@replit/river 0.215.0 → 0.216.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/dist/adapter-BXCk-dmy.d.ts +29 -0
- package/dist/adapter-D5X11kmP.d.cts +29 -0
- package/dist/{chunk-VXRAFUA3.js → chunk-75ZMPCKC.js} +26 -6
- package/dist/{chunk-VXRAFUA3.js.map → chunk-75ZMPCKC.js.map} +1 -1
- package/dist/chunk-SHND2JG6.js +86 -0
- package/dist/chunk-SHND2JG6.js.map +1 -0
- package/dist/{chunk-RDTQZ7HO.js → chunk-ZLMQQI43.js} +12 -2
- package/dist/chunk-ZLMQQI43.js.map +1 -0
- package/dist/{client-BhwlY0-L.d.ts → client-BNc5Pj_4.d.ts} +2 -2
- package/dist/{client-Dk4H7qeg.d.cts → client-BZUvFL6B.d.cts} +2 -2
- package/dist/codec/index.cjs.map +1 -1
- package/dist/codec/index.d.cts +3 -3
- package/dist/codec/index.d.ts +3 -3
- package/dist/codec/index.js +2 -2
- package/dist/{connection-DU9v3y8a.d.ts → connection-ou9w2dSY.d.ts} +3 -3
- package/dist/{connection-CS00EWuS.d.cts → connection-xxgJHs2o.d.cts} +3 -3
- package/dist/{index-CHCzvZ9D.d.cts → index-BAGGleT3.d.cts} +1 -1
- package/dist/{index-uF0cBM7z.d.ts → index-ZWkoesQD.d.ts} +1 -1
- package/dist/logging/index.d.cts +2 -2
- package/dist/logging/index.d.ts +2 -2
- package/dist/{message-aABg0s5M.d.cts → message-CpXWqmJw.d.cts} +1 -1
- package/dist/{message-aABg0s5M.d.ts → message-CpXWqmJw.d.ts} +1 -1
- package/dist/protobuf/codec.cjs +107 -0
- package/dist/protobuf/codec.cjs.map +1 -0
- package/dist/protobuf/codec.d.cts +13 -0
- package/dist/protobuf/codec.d.ts +13 -0
- package/dist/protobuf/codec.js +7 -0
- package/dist/protobuf/codec.js.map +1 -0
- package/dist/protobuf/index.cjs +1877 -0
- package/dist/protobuf/index.cjs.map +1 -0
- package/dist/protobuf/index.d.cts +488 -0
- package/dist/protobuf/index.d.ts +488 -0
- package/dist/protobuf/index.js +1260 -0
- package/dist/protobuf/index.js.map +1 -0
- package/dist/router/index.cjs +1 -1
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +12 -11
- package/dist/router/index.d.ts +12 -11
- package/dist/router/index.js +1 -1
- package/dist/{server-uNzkzIRh.d.ts → server-BPu7Td80.d.ts} +4 -4
- package/dist/{server-BR0DZaWi.d.cts → server-JdnoVO11.d.cts} +4 -4
- package/dist/{services-B5SY771g.d.ts → services-BrTFTO5Q.d.ts} +104 -93
- package/dist/{services-DBv2nmly.d.cts → services-cwGAC2rB.d.cts} +104 -93
- package/dist/testUtil/index.cjs +25 -5
- package/dist/testUtil/index.cjs.map +1 -1
- package/dist/testUtil/index.d.cts +8 -7
- package/dist/testUtil/index.d.ts +8 -7
- package/dist/testUtil/index.js +2 -2
- package/dist/transport/impls/ws/client.cjs +5 -1
- package/dist/transport/impls/ws/client.cjs.map +1 -1
- package/dist/transport/impls/ws/client.d.cts +7 -6
- package/dist/transport/impls/ws/client.d.ts +7 -6
- package/dist/transport/impls/ws/client.js +2 -2
- package/dist/transport/impls/ws/server.cjs +21 -5
- package/dist/transport/impls/ws/server.cjs.map +1 -1
- package/dist/transport/impls/ws/server.d.cts +7 -6
- package/dist/transport/impls/ws/server.d.ts +7 -6
- package/dist/transport/impls/ws/server.js +2 -2
- package/dist/transport/index.cjs +25 -5
- package/dist/transport/index.cjs.map +1 -1
- package/dist/transport/index.d.cts +8 -7
- package/dist/transport/index.d.ts +8 -7
- package/dist/transport/index.js +2 -2
- package/dist/{transport-BOL2p5s-.d.ts → transport-B1MUtXL7.d.ts} +7 -5
- package/dist/{transport-D3jzhFSi.d.cts → transport-BnU3Zb0Q.d.cts} +7 -5
- package/dist/types-BGGvYIJM.d.cts +20 -0
- package/dist/types-BGGvYIJM.d.ts +20 -0
- package/package.json +12 -1
- package/dist/adapter-CgF7vQPu.d.ts +0 -47
- package/dist/adapter-IGrG4KLL.d.cts +0 -47
- package/dist/chunk-RDTQZ7HO.js.map +0 -1
package/dist/codec/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../codec/index.ts","../../codec/binary.ts","../../codec/json.ts","../../codec/adapter.ts","../../transport/message.ts","../../transport/stringifyError.ts"],"sourcesContent":["export { BinaryCodec } from './binary';\nexport { NaiveJsonCodec } from './json';\nexport type { Codec } from './types';\nexport { CodecMessageAdapter } from './adapter';\n","import { DecodeError, ExtensionCodec, decode, encode } from '@msgpack/msgpack';\nimport { Codec } from './types';\n\nconst BIGINT_EXT_TYPE = 0;\nconst extensionCodec = new ExtensionCodec();\nextensionCodec.register({\n type: BIGINT_EXT_TYPE,\n encode(input: unknown): Uint8Array | null {\n if (typeof input === 'bigint') {\n if (\n input <= Number.MAX_SAFE_INTEGER &&\n input >= Number.MIN_SAFE_INTEGER\n ) {\n return encode(Number(input));\n } else {\n return encode(String(input));\n }\n } else {\n return null;\n }\n },\n decode(data: Uint8Array): bigint {\n const val = decode(data);\n if (!(typeof val === 'string' || typeof val === 'number')) {\n throw new DecodeError(`unexpected BigInt source: ${typeof val}`);\n }\n\n return BigInt(val);\n },\n});\n\n/**\n * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood\n * @type {Codec}\n */\nexport const BinaryCodec: Codec = {\n toBuffer(obj) {\n return encode(obj, {\n ignoreUndefined: true,\n initialBufferSize: 512,\n extensionCodec,\n });\n },\n fromBuffer: (buff: Uint8Array) => {\n const res = decode(buff, { extensionCodec });\n if (typeof res !== 'object' || res === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return res;\n },\n};\n","import { Codec } from './types';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n// Convert Uint8Array to base64\nfunction uint8ArrayToBase64(uint8Array: Uint8Array) {\n let binary = '';\n uint8Array.forEach((byte) => {\n binary += String.fromCharCode(byte);\n });\n\n return btoa(binary);\n}\n\n// Convert base64 to Uint8Array\nfunction base64ToUint8Array(base64: string) {\n const binaryString = atob(base64);\n const uint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n uint8Array[i] = binaryString.charCodeAt(i);\n }\n\n return uint8Array;\n}\n\ninterface Base64EncodedValue {\n $t: string;\n}\n\ninterface BigIntEncodedValue {\n $b: string;\n}\n\n/**\n * Naive JSON codec implementation using JSON.stringify and JSON.parse.\n * @type {Codec}\n */\nexport const NaiveJsonCodec: Codec = {\n toBuffer: (obj: object) => {\n return encoder.encode(\n JSON.stringify(obj, function replacer<\n T extends object,\n >(this: T, key: keyof T) {\n const val = this[key];\n if (val instanceof Uint8Array) {\n return { $t: uint8ArrayToBase64(val) } satisfies Base64EncodedValue;\n } else if (typeof val === 'bigint') {\n return { $b: val.toString() } satisfies BigIntEncodedValue;\n } else {\n return val;\n }\n }),\n );\n },\n fromBuffer: (buff: Uint8Array) => {\n const parsed = JSON.parse(\n decoder.decode(buff),\n function reviver(_key, val: unknown) {\n if ((val as Base64EncodedValue | undefined)?.$t !== undefined) {\n return base64ToUint8Array((val as Base64EncodedValue).$t);\n } else if ((val as BigIntEncodedValue | undefined)?.$b !== undefined) {\n return BigInt((val as BigIntEncodedValue).$b);\n } else {\n return val;\n }\n },\n ) as unknown;\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return parsed;\n },\n};\n","import { Value } from '@sinclair/typebox/value';\nimport {\n OpaqueTransportMessage,\n OpaqueTransportMessageSchema,\n} from '../transport';\nimport { Codec } from './types';\nimport { DeserializeResult, SerializeResult } from '../transport/results';\nimport { coerceErrorString } from '../transport/stringifyError';\n\n/**\n * Adapts a {@link Codec} to the {@link OpaqueTransportMessage} format,\n * accounting for fallibility of toBuffer and fromBuffer and wrapping\n * it with a Result type.\n */\nexport class CodecMessageAdapter {\n constructor(private readonly codec: Codec) {}\n\n toBuffer(msg: OpaqueTransportMessage): SerializeResult {\n try {\n return {\n ok: true,\n value: this.codec.toBuffer(msg),\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n\n fromBuffer(buf: Uint8Array): DeserializeResult {\n try {\n const parsedMsg = this.codec.fromBuffer(buf);\n if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {\n return {\n ok: false,\n reason: 'transport message schema mismatch',\n };\n }\n\n return {\n ok: true,\n value: parsedMsg,\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n}\n","import { Type, TSchema, Static } from '@sinclair/typebox';\nimport { PropagationContext } from '../tracing';\nimport { generateId } from './id';\nimport { ErrResult, ReaderErrorSchema } from '../router';\n\n/**\n * Control flags for transport messages.\n */\nexport const enum ControlFlags {\n /**\n * Used in heartbeat messages.\n */\n AckBit = 0b00001,\n /**\n * Used in stream open requests.\n */\n StreamOpenBit = 0b00010,\n /**\n * Used when a stream is cancelled due errors or to explicit cancellation\n */\n StreamCancelBit = 0b00100,\n /**\n * Used when writer closes the stream.\n */\n StreamClosedBit = 0b01000,\n}\n\n/**\n * Generic Typebox schema for a transport message.\n * @template T The type of the payload.\n * @param {T} t The payload schema.\n * @returns The transport message schema.\n */\nexport const TransportMessageSchema = <T extends TSchema>(t: T) =>\n Type.Object({\n id: Type.String(),\n from: Type.String(),\n to: Type.String(),\n seq: Type.Integer(),\n ack: Type.Integer(),\n serviceName: Type.Optional(Type.String()),\n procedureName: Type.Optional(Type.String()),\n streamId: Type.String(),\n controlFlags: Type.Integer(),\n tracing: Type.Optional(\n Type.Object({\n traceparent: Type.String(),\n tracestate: Type.String(),\n }),\n ),\n payload: t,\n });\n\n/**\n * Defines the schema for a transport acknowledgement message. This is never constructed manually\n * and is only used internally by the library for tracking inflight messages.\n * @returns The transport message schema.\n */\nexport const ControlMessageAckSchema = Type.Object({\n type: Type.Literal('ACK'),\n});\n\n/**\n * Defines the schema for a transport close message. This is never constructed manually and is only\n * used internally by the library for closing and cleaning up streams.\n */\nexport const ControlMessageCloseSchema = Type.Object({\n type: Type.Literal('CLOSE'),\n});\n\nexport type ProtocolVersion = 'v1.1' | 'v2.0';\nexport const currentProtocolVersion = 'v2.0' satisfies ProtocolVersion;\nexport const acceptedProtocolVersions = ['v1.1', currentProtocolVersion];\nexport function isAcceptedProtocolVersion(\n version: string,\n): version is ProtocolVersion {\n return acceptedProtocolVersions.includes(version);\n}\n\nexport const ControlMessageHandshakeRequestSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_REQ'),\n protocolVersion: Type.String(),\n sessionId: Type.String(),\n /**\n * Specifies what the server's expected session state (from the pov of the client). This can be\n * used by the server to know whether this is a new or a reestablished connection, and whether it\n * is compatible with what it already has.\n */\n expectedSessionState: Type.Object({\n // what the client expects the server to send next\n nextExpectedSeq: Type.Integer(),\n nextSentSeq: Type.Integer(),\n }),\n\n metadata: Type.Optional(Type.Unknown()),\n});\n\nexport const HandshakeErrorRetriableResponseCodes = Type.Union([\n Type.Literal('SESSION_STATE_MISMATCH'),\n]);\n\nexport const HandshakeErrorCustomHandlerFatalResponseCodes = Type.Union([\n // The custom validation handler rejected the handler because the client is unsupported.\n Type.Literal('REJECTED_UNSUPPORTED_CLIENT'),\n // The custom validation handler rejected the handshake.\n Type.Literal('REJECTED_BY_CUSTOM_HANDLER'),\n]);\n\nexport const HandshakeErrorFatalResponseCodes = Type.Union([\n HandshakeErrorCustomHandlerFatalResponseCodes,\n // The ciient sent a handshake that doesn't comply with the extended handshake metadata.\n Type.Literal('MALFORMED_HANDSHAKE_META'),\n // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.\n Type.Literal('MALFORMED_HANDSHAKE'),\n // The client's protocol version does not match the server's.\n Type.Literal('PROTOCOL_VERSION_MISMATCH'),\n]);\n\nexport const HandshakeErrorResponseCodes = Type.Union([\n HandshakeErrorRetriableResponseCodes,\n HandshakeErrorFatalResponseCodes,\n]);\n\nexport const ControlMessageHandshakeResponseSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_RESP'),\n status: Type.Union([\n Type.Object({\n ok: Type.Literal(true),\n sessionId: Type.String(),\n }),\n Type.Object({\n ok: Type.Literal(false),\n reason: Type.String(),\n code: HandshakeErrorResponseCodes,\n }),\n ]),\n});\n\nexport const ControlMessagePayloadSchema = Type.Union([\n ControlMessageCloseSchema,\n ControlMessageAckSchema,\n ControlMessageHandshakeRequestSchema,\n ControlMessageHandshakeResponseSchema,\n]);\n\n/**\n * Defines the schema for an opaque transport message that is agnostic to any\n * procedure/service.\n * @returns The transport message schema.\n */\nexport const OpaqueTransportMessageSchema = TransportMessageSchema(\n Type.Unknown(),\n);\n\n/**\n * Represents a transport message. This is the same type as {@link TransportMessageSchema} but\n * we can't statically infer generics from generic Typebox schemas so we have to define it again here.\n *\n * TypeScript can't enforce types when a bitmask is involved, so these are the semantics of\n * `controlFlags`:\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `streamId` must be set to a unique value\n * (suggestion: use `nanoid`).\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `serviceName` and `procedureName` must be set.\n * * If `controlFlags & StreamClosedBit == StreamClosedBit` and the kind is `stream` or `subscription`,\n * `payload` should be discarded (usually contains a control message).\n * * If `controlFlags & AckBit == AckBit`, the message is an explicit acknowledgement message and doesn't\n * contain any payload that is relevant to the application so should not be delivered.\n * @template Payload The type of the payload.\n */\nexport interface TransportMessage<Payload = unknown> {\n id: string;\n from: TransportClientId;\n to: TransportClientId;\n seq: number;\n ack: number;\n serviceName?: string;\n procedureName?: string;\n streamId: string;\n controlFlags: number;\n tracing?: PropagationContext;\n payload: Payload;\n}\n\nexport type PartialTransportMessage<Payload = unknown> = Omit<\n TransportMessage<Payload>,\n 'id' | 'from' | 'to' | 'seq' | 'ack'\n>;\n\nexport function handshakeRequestMessage({\n from,\n to,\n sessionId,\n expectedSessionState,\n metadata,\n tracing,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n sessionId: string;\n expectedSessionState: Static<\n typeof ControlMessageHandshakeRequestSchema\n >['expectedSessionState'];\n metadata?: unknown;\n tracing?: PropagationContext;\n}): TransportMessage<Static<typeof ControlMessageHandshakeRequestSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n tracing,\n payload: {\n type: 'HANDSHAKE_REQ',\n protocolVersion: currentProtocolVersion,\n sessionId,\n expectedSessionState,\n metadata,\n } satisfies Static<typeof ControlMessageHandshakeRequestSchema>,\n };\n}\n\n/**\n * This is a reason that can be given during the handshake to indicate that the peer has the wrong\n * session state.\n */\nexport const SESSION_STATE_MISMATCH = 'session state mismatch';\n\nexport function handshakeResponseMessage({\n from,\n to,\n status,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n status: Static<typeof ControlMessageHandshakeResponseSchema>['status'];\n}): TransportMessage<Static<typeof ControlMessageHandshakeResponseSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n payload: {\n type: 'HANDSHAKE_RESP',\n status,\n } satisfies Static<typeof ControlMessageHandshakeResponseSchema>,\n };\n}\n\nexport function closeStreamMessage(streamId: string): PartialTransportMessage {\n return {\n streamId,\n controlFlags: ControlFlags.StreamClosedBit,\n payload: {\n type: 'CLOSE' as const,\n } satisfies Static<typeof ControlMessagePayloadSchema>,\n };\n}\n\nexport function cancelMessage(\n streamId: string,\n payload: ErrResult<Static<typeof ReaderErrorSchema>>,\n) {\n return {\n streamId,\n controlFlags: ControlFlags.StreamCancelBit,\n payload,\n };\n}\n\n/**\n * A type alias for a transport message with an opaque payload.\n * @template T - The type of the opaque payload.\n */\nexport type OpaqueTransportMessage = TransportMessage;\nexport type TransportClientId = string;\n\n/**\n * An encoded message that is ready to be sent over the transport.\n * The seq number is kept to track which messages have been\n * acked by the peer and can be dropped from the send buffer.\n */\nexport interface EncodedTransportMessage {\n id: string;\n seq: number;\n msg: PartialTransportMessage;\n data: Uint8Array;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an ack message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the AckBit, false otherwise.\n */\nexport function isAck(controlFlag: number): boolean {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n return (controlFlag & ControlFlags.AckBit) === ControlFlags.AckBit;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream open message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamOpenBit, false otherwise.\n */\nexport function isStreamOpen(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamOpenBit) === ControlFlags.StreamOpenBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream close message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamCloseBit, false otherwise.\n */\nexport function isStreamClose(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamClosedBit) ===\n ControlFlags.StreamClosedBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an cancel message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the CancelBit, false otherwise\n */\nexport function isStreamCancel(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamCancelBit) ===\n ControlFlags.StreamCancelBit\n );\n}\n","export function coerceErrorString(err: unknown): string {\n if (err instanceof Error) {\n return err.message || 'unknown reason';\n }\n\n return `[coerced to error] ${String(err)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA4D;AAG5D,IAAM,kBAAkB;AACxB,IAAM,iBAAiB,IAAI,8BAAe;AAC1C,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;AAAA,IACF,SAAS,GAAG;AACV,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ,kBAAkB,CAAC;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../codec/index.ts","../../codec/binary.ts","../../codec/json.ts","../../codec/adapter.ts","../../transport/message.ts","../../transport/stringifyError.ts"],"sourcesContent":["export { BinaryCodec } from './binary';\nexport { NaiveJsonCodec } from './json';\nexport type { Codec } from './types';\nexport { CodecMessageAdapter } from './adapter';\n","import { DecodeError, ExtensionCodec, decode, encode } from '@msgpack/msgpack';\nimport { Codec } from './types';\n\nconst BIGINT_EXT_TYPE = 0;\nconst extensionCodec = new ExtensionCodec();\nextensionCodec.register({\n type: BIGINT_EXT_TYPE,\n encode(input: unknown): Uint8Array | null {\n if (typeof input === 'bigint') {\n if (\n input <= Number.MAX_SAFE_INTEGER &&\n input >= Number.MIN_SAFE_INTEGER\n ) {\n return encode(Number(input));\n } else {\n return encode(String(input));\n }\n } else {\n return null;\n }\n },\n decode(data: Uint8Array): bigint {\n const val = decode(data);\n if (!(typeof val === 'string' || typeof val === 'number')) {\n throw new DecodeError(`unexpected BigInt source: ${typeof val}`);\n }\n\n return BigInt(val);\n },\n});\n\n/**\n * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood\n * @type {Codec}\n */\nexport const BinaryCodec: Codec = {\n toBuffer(obj) {\n return encode(obj, {\n ignoreUndefined: true,\n initialBufferSize: 512,\n extensionCodec,\n });\n },\n fromBuffer: (buff: Uint8Array) => {\n const res = decode(buff, { extensionCodec });\n if (typeof res !== 'object' || res === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return res;\n },\n};\n","import { Codec } from './types';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n// Convert Uint8Array to base64\nfunction uint8ArrayToBase64(uint8Array: Uint8Array) {\n let binary = '';\n uint8Array.forEach((byte) => {\n binary += String.fromCharCode(byte);\n });\n\n return btoa(binary);\n}\n\n// Convert base64 to Uint8Array\nfunction base64ToUint8Array(base64: string) {\n const binaryString = atob(base64);\n const uint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n uint8Array[i] = binaryString.charCodeAt(i);\n }\n\n return uint8Array;\n}\n\ninterface Base64EncodedValue {\n $t: string;\n}\n\ninterface BigIntEncodedValue {\n $b: string;\n}\n\n/**\n * Naive JSON codec implementation using JSON.stringify and JSON.parse.\n * @type {Codec}\n */\nexport const NaiveJsonCodec: Codec = {\n toBuffer: (obj: object) => {\n return encoder.encode(\n JSON.stringify(obj, function replacer<\n T extends object,\n >(this: T, key: keyof T) {\n const val = this[key];\n if (val instanceof Uint8Array) {\n return { $t: uint8ArrayToBase64(val) } satisfies Base64EncodedValue;\n } else if (typeof val === 'bigint') {\n return { $b: val.toString() } satisfies BigIntEncodedValue;\n } else {\n return val;\n }\n }),\n );\n },\n fromBuffer: (buff: Uint8Array) => {\n const parsed = JSON.parse(\n decoder.decode(buff),\n function reviver(_key, val: unknown) {\n if ((val as Base64EncodedValue | undefined)?.$t !== undefined) {\n return base64ToUint8Array((val as Base64EncodedValue).$t);\n } else if ((val as BigIntEncodedValue | undefined)?.$b !== undefined) {\n return BigInt((val as BigIntEncodedValue).$b);\n } else {\n return val;\n }\n },\n ) as unknown;\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return parsed;\n },\n};\n","import { Value } from '@sinclair/typebox/value';\nimport {\n OpaqueTransportMessage,\n OpaqueTransportMessageSchema,\n} from '../transport';\nimport { Codec } from './types';\nimport { DeserializeResult, SerializeResult } from '../transport/results';\nimport { coerceErrorString } from '../transport/stringifyError';\n\n/**\n * Adapts a {@link Codec} to the {@link OpaqueTransportMessage} format,\n * accounting for fallibility of toBuffer and fromBuffer and wrapping\n * it with a Result type.\n */\nexport class CodecMessageAdapter {\n constructor(private readonly codec: Codec) {}\n\n toBuffer(msg: OpaqueTransportMessage): SerializeResult {\n try {\n return {\n ok: true,\n value: this.codec.toBuffer(msg),\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n\n fromBuffer(buf: Uint8Array): DeserializeResult {\n try {\n const parsedMsg = this.codec.fromBuffer(buf);\n if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {\n return {\n ok: false,\n reason: 'transport message schema mismatch',\n };\n }\n\n return {\n ok: true,\n value: parsedMsg,\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n}\n","import { Type, TSchema, Static } from '@sinclair/typebox';\nimport { PropagationContext } from '../tracing';\nimport { generateId } from './id';\nimport { ErrResult } from '../router';\nimport type { ErrorPayload } from '../router/result';\n\n/**\n * Control flags for transport messages.\n */\nexport const enum ControlFlags {\n /**\n * Used in heartbeat messages.\n */\n AckBit = 0b00001,\n /**\n * Used in stream open requests.\n */\n StreamOpenBit = 0b00010,\n /**\n * Used when a stream is cancelled due errors or to explicit cancellation\n */\n StreamCancelBit = 0b00100,\n /**\n * Used when writer closes the stream.\n */\n StreamClosedBit = 0b01000,\n}\n\n/**\n * Generic Typebox schema for a transport message.\n * @template T The type of the payload.\n * @param {T} t The payload schema.\n * @returns The transport message schema.\n */\nexport const TransportMessageSchema = <T extends TSchema>(t: T) =>\n Type.Object({\n id: Type.String(),\n from: Type.String(),\n to: Type.String(),\n seq: Type.Integer(),\n ack: Type.Integer(),\n serviceName: Type.Optional(Type.String()),\n procedureName: Type.Optional(Type.String()),\n streamId: Type.String(),\n controlFlags: Type.Integer(),\n tracing: Type.Optional(\n Type.Object({\n traceparent: Type.String(),\n tracestate: Type.String(),\n }),\n ),\n payload: t,\n });\n\n/**\n * Defines the schema for a transport acknowledgement message. This is never constructed manually\n * and is only used internally by the library for tracking inflight messages.\n * @returns The transport message schema.\n */\nexport const ControlMessageAckSchema = Type.Object({\n type: Type.Literal('ACK'),\n});\n\n/**\n * Defines the schema for a transport close message. This is never constructed manually and is only\n * used internally by the library for closing and cleaning up streams.\n */\nexport const ControlMessageCloseSchema = Type.Object({\n type: Type.Literal('CLOSE'),\n});\n\nexport type ProtocolVersion = 'v1.1' | 'v2.0';\nexport const currentProtocolVersion = 'v2.0' satisfies ProtocolVersion;\nexport const acceptedProtocolVersions = ['v1.1', currentProtocolVersion];\nexport function isAcceptedProtocolVersion(\n version: string,\n): version is ProtocolVersion {\n return acceptedProtocolVersions.includes(version);\n}\n\nexport const ControlMessageHandshakeRequestSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_REQ'),\n protocolVersion: Type.String(),\n sessionId: Type.String(),\n /**\n * Specifies what the server's expected session state (from the pov of the client). This can be\n * used by the server to know whether this is a new or a reestablished connection, and whether it\n * is compatible with what it already has.\n */\n expectedSessionState: Type.Object({\n // what the client expects the server to send next\n nextExpectedSeq: Type.Integer(),\n nextSentSeq: Type.Integer(),\n }),\n\n metadata: Type.Optional(Type.Unknown()),\n});\n\nexport const HandshakeErrorRetriableResponseCodes = Type.Union([\n Type.Literal('SESSION_STATE_MISMATCH'),\n]);\n\nexport const HandshakeErrorCustomHandlerFatalResponseCodes = Type.Union([\n // The custom validation handler rejected the handler because the client is unsupported.\n Type.Literal('REJECTED_UNSUPPORTED_CLIENT'),\n // The custom validation handler rejected the handshake.\n Type.Literal('REJECTED_BY_CUSTOM_HANDLER'),\n]);\n\nexport const HandshakeErrorFatalResponseCodes = Type.Union([\n HandshakeErrorCustomHandlerFatalResponseCodes,\n // The ciient sent a handshake that doesn't comply with the extended handshake metadata.\n Type.Literal('MALFORMED_HANDSHAKE_META'),\n // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.\n Type.Literal('MALFORMED_HANDSHAKE'),\n // The client's protocol version does not match the server's.\n Type.Literal('PROTOCOL_VERSION_MISMATCH'),\n]);\n\nexport const HandshakeErrorResponseCodes = Type.Union([\n HandshakeErrorRetriableResponseCodes,\n HandshakeErrorFatalResponseCodes,\n]);\n\nexport const ControlMessageHandshakeResponseSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_RESP'),\n status: Type.Union([\n Type.Object({\n ok: Type.Literal(true),\n sessionId: Type.String(),\n }),\n Type.Object({\n ok: Type.Literal(false),\n reason: Type.String(),\n code: HandshakeErrorResponseCodes,\n }),\n ]),\n});\n\nexport const ControlMessagePayloadSchema = Type.Union([\n ControlMessageCloseSchema,\n ControlMessageAckSchema,\n ControlMessageHandshakeRequestSchema,\n ControlMessageHandshakeResponseSchema,\n]);\n\n/**\n * Defines the schema for an opaque transport message that is agnostic to any\n * procedure/service.\n * @returns The transport message schema.\n */\nexport const OpaqueTransportMessageSchema = TransportMessageSchema(\n Type.Unknown(),\n);\n\n/**\n * Represents a transport message. This is the same type as {@link TransportMessageSchema} but\n * we can't statically infer generics from generic Typebox schemas so we have to define it again here.\n *\n * TypeScript can't enforce types when a bitmask is involved, so these are the semantics of\n * `controlFlags`:\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `streamId` must be set to a unique value\n * (suggestion: use `nanoid`).\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `serviceName` and `procedureName` must be set.\n * * If `controlFlags & StreamClosedBit == StreamClosedBit` and the kind is `stream` or `subscription`,\n * `payload` should be discarded (usually contains a control message).\n * * If `controlFlags & AckBit == AckBit`, the message is an explicit acknowledgement message and doesn't\n * contain any payload that is relevant to the application so should not be delivered.\n * @template Payload The type of the payload.\n */\nexport interface TransportMessage<Payload = unknown> {\n id: string;\n from: TransportClientId;\n to: TransportClientId;\n seq: number;\n ack: number;\n serviceName?: string;\n procedureName?: string;\n streamId: string;\n controlFlags: number;\n tracing?: PropagationContext;\n payload: Payload;\n}\n\nexport type PartialTransportMessage<Payload = unknown> = Omit<\n TransportMessage<Payload>,\n 'id' | 'from' | 'to' | 'seq' | 'ack'\n>;\n\nexport function handshakeRequestMessage({\n from,\n to,\n sessionId,\n expectedSessionState,\n metadata,\n tracing,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n sessionId: string;\n expectedSessionState: Static<\n typeof ControlMessageHandshakeRequestSchema\n >['expectedSessionState'];\n metadata?: unknown;\n tracing?: PropagationContext;\n}): TransportMessage<Static<typeof ControlMessageHandshakeRequestSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n tracing,\n payload: {\n type: 'HANDSHAKE_REQ',\n protocolVersion: currentProtocolVersion,\n sessionId,\n expectedSessionState,\n metadata,\n } satisfies Static<typeof ControlMessageHandshakeRequestSchema>,\n };\n}\n\n/**\n * This is a reason that can be given during the handshake to indicate that the peer has the wrong\n * session state.\n */\nexport const SESSION_STATE_MISMATCH = 'session state mismatch';\n\nexport function handshakeResponseMessage({\n from,\n to,\n status,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n status: Static<typeof ControlMessageHandshakeResponseSchema>['status'];\n}): TransportMessage<Static<typeof ControlMessageHandshakeResponseSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n payload: {\n type: 'HANDSHAKE_RESP',\n status,\n } satisfies Static<typeof ControlMessageHandshakeResponseSchema>,\n };\n}\n\nexport function closeStreamMessage(streamId: string): PartialTransportMessage {\n return {\n streamId,\n controlFlags: ControlFlags.StreamClosedBit,\n payload: {\n type: 'CLOSE' as const,\n } satisfies Static<typeof ControlMessagePayloadSchema>,\n };\n}\n\nexport function cancelMessage(\n streamId: string,\n payload: ErrResult<ErrorPayload>,\n) {\n return {\n streamId,\n controlFlags: ControlFlags.StreamCancelBit,\n payload,\n };\n}\n\n/**\n * A type alias for a transport message with an opaque payload.\n * @template T - The type of the opaque payload.\n */\nexport type OpaqueTransportMessage = TransportMessage;\nexport type TransportClientId = string;\n\n/**\n * An encoded message that is ready to be sent over the transport.\n * The seq number is kept to track which messages have been\n * acked by the peer and can be dropped from the send buffer.\n */\nexport interface EncodedTransportMessage {\n id: string;\n seq: number;\n msg: PartialTransportMessage;\n data: Uint8Array;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an ack message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the AckBit, false otherwise.\n */\nexport function isAck(controlFlag: number): boolean {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n return (controlFlag & ControlFlags.AckBit) === ControlFlags.AckBit;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream open message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamOpenBit, false otherwise.\n */\nexport function isStreamOpen(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamOpenBit) === ControlFlags.StreamOpenBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream close message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamCloseBit, false otherwise.\n */\nexport function isStreamClose(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamClosedBit) ===\n ControlFlags.StreamClosedBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an cancel message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the CancelBit, false otherwise\n */\nexport function isStreamCancel(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamCancelBit) ===\n ControlFlags.StreamCancelBit\n );\n}\n","export function coerceErrorString(err: unknown): string {\n if (err instanceof Error) {\n return err.message || 'unknown reason';\n }\n\n return `[coerced to error] ${String(err)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA4D;AAG5D,IAAM,kBAAkB;AACxB,IAAM,iBAAiB,IAAI,8BAAe;AAC1C,eAAe,SAAS;AAAA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,GAAG;AACV,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ,kBAAkB,CAAC;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/codec/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as Codec } from '../
|
|
2
|
-
export {
|
|
3
|
-
import '../message-
|
|
1
|
+
import { C as Codec } from '../types-BGGvYIJM.cjs';
|
|
2
|
+
export { C as CodecMessageAdapter } from '../adapter-D5X11kmP.cjs';
|
|
3
|
+
import '../message-CpXWqmJw.cjs';
|
|
4
4
|
import '@sinclair/typebox';
|
|
5
5
|
import '@opentelemetry/api';
|
|
6
6
|
|
package/dist/codec/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as Codec } from '../
|
|
2
|
-
export {
|
|
3
|
-
import '../message-
|
|
1
|
+
import { C as Codec } from '../types-BGGvYIJM.js';
|
|
2
|
+
export { C as CodecMessageAdapter } from '../adapter-BXCk-dmy.js';
|
|
3
|
+
import '../message-CpXWqmJw.js';
|
|
4
4
|
import '@sinclair/typebox';
|
|
5
5
|
import '@opentelemetry/api';
|
|
6
6
|
|
package/dist/codec/index.js
CHANGED
|
@@ -2,9 +2,9 @@ import {
|
|
|
2
2
|
BinaryCodec,
|
|
3
3
|
CodecMessageAdapter,
|
|
4
4
|
NaiveJsonCodec
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-75ZMPCKC.js";
|
|
6
6
|
import "../chunk-CC7RN7GI.js";
|
|
7
|
-
import "../chunk-
|
|
7
|
+
import "../chunk-ZLMQQI43.js";
|
|
8
8
|
export {
|
|
9
9
|
BinaryCodec,
|
|
10
10
|
CodecMessageAdapter,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { T as Tags } from './index-
|
|
2
|
-
import { P as ProtocolVersion,
|
|
3
|
-
import { C as Connection } from './transport-
|
|
1
|
+
import { T as Tags } from './index-ZWkoesQD.js';
|
|
2
|
+
import { P as ProtocolVersion, O as OpaqueTransportMessage } from './message-CpXWqmJw.js';
|
|
3
|
+
import { C as Connection } from './transport-B1MUtXL7.js';
|
|
4
4
|
import { W as WsLike } from './wslike-Dng9H1C7.js';
|
|
5
5
|
|
|
6
6
|
interface ConnectionInfoExtras extends Record<string, unknown> {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { T as Tags } from './index-
|
|
2
|
-
import { P as ProtocolVersion,
|
|
3
|
-
import { C as Connection } from './transport-
|
|
1
|
+
import { T as Tags } from './index-BAGGleT3.cjs';
|
|
2
|
+
import { P as ProtocolVersion, O as OpaqueTransportMessage } from './message-CpXWqmJw.cjs';
|
|
3
|
+
import { C as Connection } from './transport-BnU3Zb0Q.cjs';
|
|
4
4
|
import { W as WsLike } from './wslike-Dng9H1C7.cjs';
|
|
5
5
|
|
|
6
6
|
interface ConnectionInfoExtras extends Record<string, unknown> {
|
package/dist/logging/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as LogFn, L as Logger, M as MessageMetadata, c as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../index-
|
|
2
|
-
import '../message-
|
|
1
|
+
export { a as LogFn, L as Logger, M as MessageMetadata, c as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../index-BAGGleT3.cjs';
|
|
2
|
+
import '../message-CpXWqmJw.cjs';
|
|
3
3
|
import '@sinclair/typebox';
|
|
4
4
|
import '@opentelemetry/api';
|
package/dist/logging/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as LogFn, L as Logger, M as MessageMetadata, c as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../index-
|
|
2
|
-
import '../message-
|
|
1
|
+
export { a as LogFn, L as Logger, M as MessageMetadata, c as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../index-ZWkoesQD.js';
|
|
2
|
+
import '../message-CpXWqmJw.js';
|
|
3
3
|
import '@sinclair/typebox';
|
|
4
4
|
import '@opentelemetry/api';
|
|
@@ -116,4 +116,4 @@ declare function isStreamOpen(controlFlag: number): boolean;
|
|
|
116
116
|
*/
|
|
117
117
|
declare function isStreamClose(controlFlag: number): boolean;
|
|
118
118
|
|
|
119
|
-
export { type EncodedTransportMessage as E, HandshakeErrorResponseCodes as H,
|
|
119
|
+
export { type EncodedTransportMessage as E, HandshakeErrorResponseCodes as H, type OpaqueTransportMessage as O, type ProtocolVersion as P, type TransportClientId as T, OpaqueTransportMessageSchema as a, type TransportMessage as b, TransportMessageSchema as c, isStreamOpen as d, type PartialTransportMessage as e, HandshakeErrorCustomHandlerFatalResponseCodes as f, type TelemetryInfo as g, isStreamClose as i };
|
|
@@ -116,4 +116,4 @@ declare function isStreamOpen(controlFlag: number): boolean;
|
|
|
116
116
|
*/
|
|
117
117
|
declare function isStreamClose(controlFlag: number): boolean;
|
|
118
118
|
|
|
119
|
-
export { type EncodedTransportMessage as E, HandshakeErrorResponseCodes as H,
|
|
119
|
+
export { type EncodedTransportMessage as E, HandshakeErrorResponseCodes as H, type OpaqueTransportMessage as O, type ProtocolVersion as P, type TransportClientId as T, OpaqueTransportMessageSchema as a, type TransportMessage as b, TransportMessageSchema as c, isStreamOpen as d, type PartialTransportMessage as e, HandshakeErrorCustomHandlerFatalResponseCodes as f, type TelemetryInfo as g, isStreamClose as i };
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// protobuf/codec.ts
|
|
21
|
+
var codec_exports = {};
|
|
22
|
+
__export(codec_exports, {
|
|
23
|
+
ProtoCodec: () => ProtoCodec
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(codec_exports);
|
|
26
|
+
var import_protobuf = require("@bufbuild/protobuf");
|
|
27
|
+
var import_msgpack = require("@msgpack/msgpack");
|
|
28
|
+
|
|
29
|
+
// protobuf/gen/transport_pb.ts
|
|
30
|
+
var import_codegenv2 = require("@bufbuild/protobuf/codegenv2");
|
|
31
|
+
var file_transport = /* @__PURE__ */ (0, import_codegenv2.fileDesc)("Cg90cmFuc3BvcnQucHJvdG8SGHJlcGxpdC5yaXZlci5pbnRlcm5hbC52MSI9ChJQcm9wYWdhdGlvbkNvbnRleHQSEwoLdHJhY2VwYXJlbnQYASABKAkSEgoKdHJhY2VzdGF0ZRgCIAEoCSKuAgoRVHJhbnNwb3J0RW52ZWxvcGUSCgoCaWQYASABKAkSDAoEZnJvbRgCIAEoCRIKCgJ0bxgDIAEoCRILCgNzZXEYBCABKA0SCwoDYWNrGAUgASgNEhEKCXN0cmVhbV9pZBgGIAEoCRIVCg1jb250cm9sX2ZsYWdzGAcgASgNEhQKDHNlcnZpY2VfbmFtZRgIIAEoCRIWCg5wcm9jZWR1cmVfbmFtZRgJIAEoCRI9Cgd0cmFjaW5nGAogASgLMiwucmVwbGl0LnJpdmVyLmludGVybmFsLnYxLlByb3BhZ2F0aW9uQ29udGV4dBIXCg1wYXlsb2FkX2J5dGVzGAsgASgMSAASGQoPcGF5bG9hZF9tc2dwYWNrGAwgASgMSABCDgoMcGF5bG9hZF9raW5kYgZwcm90bzM");
|
|
32
|
+
var TransportEnvelopeSchema = /* @__PURE__ */ (0, import_codegenv2.messageDesc)(file_transport, 1);
|
|
33
|
+
|
|
34
|
+
// protobuf/codec.ts
|
|
35
|
+
var ProtoCodec = {
|
|
36
|
+
toBuffer(obj) {
|
|
37
|
+
const message = coerceTransportMessage(obj);
|
|
38
|
+
return (0, import_protobuf.toBinary)(
|
|
39
|
+
TransportEnvelopeSchema,
|
|
40
|
+
(0, import_protobuf.create)(TransportEnvelopeSchema, toEnvelopeInit(message))
|
|
41
|
+
);
|
|
42
|
+
},
|
|
43
|
+
fromBuffer(buff) {
|
|
44
|
+
const bytes = buff instanceof Uint8Array ? buff : new Uint8Array(buff);
|
|
45
|
+
return fromEnvelope((0, import_protobuf.fromBinary)(TransportEnvelopeSchema, bytes));
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
function coerceTransportMessage(obj) {
|
|
49
|
+
const candidate = obj;
|
|
50
|
+
if (typeof candidate.id !== "string" || typeof candidate.from !== "string" || typeof candidate.to !== "string" || typeof candidate.seq !== "number" || typeof candidate.ack !== "number" || typeof candidate.streamId !== "string" || typeof candidate.controlFlags !== "number" || !("payload" in candidate)) {
|
|
51
|
+
throw new Error("ProtoCodec expects an opaque transport message");
|
|
52
|
+
}
|
|
53
|
+
return candidate;
|
|
54
|
+
}
|
|
55
|
+
function toEnvelopeInit(message) {
|
|
56
|
+
return {
|
|
57
|
+
id: message.id,
|
|
58
|
+
from: message.from,
|
|
59
|
+
to: message.to,
|
|
60
|
+
seq: message.seq,
|
|
61
|
+
ack: message.ack,
|
|
62
|
+
streamId: message.streamId,
|
|
63
|
+
controlFlags: message.controlFlags,
|
|
64
|
+
serviceName: message.serviceName ?? "",
|
|
65
|
+
procedureName: message.procedureName ?? "",
|
|
66
|
+
tracing: message.tracing ? {
|
|
67
|
+
traceparent: message.tracing.traceparent,
|
|
68
|
+
tracestate: message.tracing.tracestate
|
|
69
|
+
} : void 0,
|
|
70
|
+
payloadKind: message.payload instanceof Uint8Array ? { case: "payloadBytes", value: message.payload } : { case: "payloadMsgpack", value: (0, import_msgpack.encode)(message.payload) }
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function fromEnvelope(envelope) {
|
|
74
|
+
return {
|
|
75
|
+
id: envelope.id,
|
|
76
|
+
from: envelope.from,
|
|
77
|
+
to: envelope.to,
|
|
78
|
+
seq: envelope.seq,
|
|
79
|
+
ack: envelope.ack,
|
|
80
|
+
streamId: envelope.streamId,
|
|
81
|
+
controlFlags: envelope.controlFlags,
|
|
82
|
+
payload: decodePayloadKind(envelope),
|
|
83
|
+
...envelope.serviceName === "" ? {} : { serviceName: envelope.serviceName },
|
|
84
|
+
...envelope.procedureName === "" ? {} : { procedureName: envelope.procedureName },
|
|
85
|
+
...envelope.tracing ? {
|
|
86
|
+
tracing: {
|
|
87
|
+
traceparent: envelope.tracing.traceparent,
|
|
88
|
+
tracestate: envelope.tracing.tracestate
|
|
89
|
+
}
|
|
90
|
+
} : {}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function decodePayloadKind(envelope) {
|
|
94
|
+
switch (envelope.payloadKind.case) {
|
|
95
|
+
case "payloadBytes":
|
|
96
|
+
return envelope.payloadKind.value;
|
|
97
|
+
case "payloadMsgpack":
|
|
98
|
+
return (0, import_msgpack.decode)(envelope.payloadKind.value);
|
|
99
|
+
default:
|
|
100
|
+
throw new Error("invalid protobuf transport envelope: missing payload");
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
104
|
+
0 && (module.exports = {
|
|
105
|
+
ProtoCodec
|
|
106
|
+
});
|
|
107
|
+
//# sourceMappingURL=codec.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../protobuf/codec.ts","../../protobuf/gen/transport_pb.ts"],"sourcesContent":["import { create, fromBinary, toBinary } from '@bufbuild/protobuf';\nimport type { MessageInitShape, MessageShape } from '@bufbuild/protobuf';\nimport {\n decode as msgpackDecode,\n encode as msgpackEncode,\n} from '@msgpack/msgpack';\nimport type { OpaqueTransportMessage } from '../transport/message';\nimport { Codec } from '../codec/types';\nimport { TransportEnvelopeSchema } from './gen/transport_pb';\n\n/**\n * A protobuf-native transport envelope codec.\n *\n * The envelope schema is defined in `proto/transport.proto` and generated via\n * `buf generate`. Handler payloads that are already raw protobuf bytes use\n * `payload_bytes`. Non-protobuf payloads (error results, control messages)\n * are msgpack-encoded into `payload_msgpack`.\n */\nexport const ProtoCodec: Codec = {\n toBuffer(obj) {\n const message = coerceTransportMessage(obj);\n\n return toBinary(\n TransportEnvelopeSchema,\n create(TransportEnvelopeSchema, toEnvelopeInit(message)),\n ) as Uint8Array;\n },\n\n fromBuffer(buff: Uint8Array) {\n // WebSocketConnection sets binaryType='arraybuffer', so the buffer\n // arriving here is actually an ArrayBuffer despite the Uint8Array\n // signature on Codec.fromBuffer. The JSON and msgpack codecs happen\n // to tolerate this because TextDecoder.decode() and msgpack.decode()\n // accept ArrayBuffer, but protobuf's fromBinary() requires a real\n // Uint8Array (it uses indexed access). The proper fix is to have the\n // connection hand out Uint8Array in the first place.\n const bytes =\n buff instanceof Uint8Array ? buff : new Uint8Array(buff as ArrayBuffer);\n\n return fromEnvelope(fromBinary(TransportEnvelopeSchema, bytes));\n },\n};\n\nfunction coerceTransportMessage(obj: object): OpaqueTransportMessage {\n const candidate = obj as Partial<OpaqueTransportMessage>;\n\n if (\n typeof candidate.id !== 'string' ||\n typeof candidate.from !== 'string' ||\n typeof candidate.to !== 'string' ||\n typeof candidate.seq !== 'number' ||\n typeof candidate.ack !== 'number' ||\n typeof candidate.streamId !== 'string' ||\n typeof candidate.controlFlags !== 'number' ||\n !('payload' in candidate)\n ) {\n throw new Error('ProtoCodec expects an opaque transport message');\n }\n\n return candidate as OpaqueTransportMessage;\n}\n\nfunction toEnvelopeInit(\n message: OpaqueTransportMessage,\n): MessageInitShape<typeof TransportEnvelopeSchema> {\n return {\n id: message.id,\n from: message.from,\n to: message.to,\n seq: message.seq,\n ack: message.ack,\n streamId: message.streamId,\n controlFlags: message.controlFlags,\n serviceName: message.serviceName ?? '',\n procedureName: message.procedureName ?? '',\n tracing: message.tracing\n ? {\n traceparent: message.tracing.traceparent,\n tracestate: message.tracing.tracestate,\n }\n : undefined,\n payloadKind:\n message.payload instanceof Uint8Array\n ? { case: 'payloadBytes', value: message.payload }\n : { case: 'payloadMsgpack', value: msgpackEncode(message.payload) },\n };\n}\n\nfunction fromEnvelope(\n envelope: MessageShape<typeof TransportEnvelopeSchema>,\n): OpaqueTransportMessage {\n return {\n id: envelope.id,\n from: envelope.from,\n to: envelope.to,\n seq: envelope.seq,\n ack: envelope.ack,\n streamId: envelope.streamId,\n controlFlags: envelope.controlFlags,\n payload: decodePayloadKind(envelope),\n ...(envelope.serviceName === ''\n ? {}\n : { serviceName: envelope.serviceName }),\n ...(envelope.procedureName === ''\n ? {}\n : { procedureName: envelope.procedureName }),\n ...(envelope.tracing\n ? {\n tracing: {\n traceparent: envelope.tracing.traceparent,\n tracestate: envelope.tracing.tracestate,\n },\n }\n : {}),\n };\n}\n\nfunction decodePayloadKind(\n envelope: MessageShape<typeof TransportEnvelopeSchema>,\n): unknown {\n switch (envelope.payloadKind.case) {\n case 'payloadBytes':\n return envelope.payloadKind.value;\n case 'payloadMsgpack':\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return msgpackDecode(envelope.payloadKind.value);\n default:\n throw new Error('invalid protobuf transport envelope: missing payload');\n }\n}\n","// @generated by protoc-gen-es v2.11.0 with parameter \"target=ts,import_extension=none\"\n// @generated from file transport.proto (package replit.river.internal.v1, syntax proto3)\n/* eslint-disable */\n\nimport type { GenFile, GenMessage } from \"@bufbuild/protobuf/codegenv2\";\nimport { fileDesc, messageDesc } from \"@bufbuild/protobuf/codegenv2\";\nimport type { Message } from \"@bufbuild/protobuf\";\n\n/**\n * Describes the file transport.proto.\n */\nexport const file_transport: GenFile = /*@__PURE__*/\n fileDesc(\"Cg90cmFuc3BvcnQucHJvdG8SGHJlcGxpdC5yaXZlci5pbnRlcm5hbC52MSI9ChJQcm9wYWdhdGlvbkNvbnRleHQSEwoLdHJhY2VwYXJlbnQYASABKAkSEgoKdHJhY2VzdGF0ZRgCIAEoCSKuAgoRVHJhbnNwb3J0RW52ZWxvcGUSCgoCaWQYASABKAkSDAoEZnJvbRgCIAEoCRIKCgJ0bxgDIAEoCRILCgNzZXEYBCABKA0SCwoDYWNrGAUgASgNEhEKCXN0cmVhbV9pZBgGIAEoCRIVCg1jb250cm9sX2ZsYWdzGAcgASgNEhQKDHNlcnZpY2VfbmFtZRgIIAEoCRIWCg5wcm9jZWR1cmVfbmFtZRgJIAEoCRI9Cgd0cmFjaW5nGAogASgLMiwucmVwbGl0LnJpdmVyLmludGVybmFsLnYxLlByb3BhZ2F0aW9uQ29udGV4dBIXCg1wYXlsb2FkX2J5dGVzGAsgASgMSAASGQoPcGF5bG9hZF9tc2dwYWNrGAwgASgMSABCDgoMcGF5bG9hZF9raW5kYgZwcm90bzM\");\n\n/**\n * *\n * OpenTelemetry propagation context forwarded between peers.\n *\n * @generated from message replit.river.internal.v1.PropagationContext\n */\nexport type PropagationContext = Message<\"replit.river.internal.v1.PropagationContext\"> & {\n /**\n * @generated from field: string traceparent = 1;\n */\n traceparent: string;\n\n /**\n * @generated from field: string tracestate = 2;\n */\n tracestate: string;\n};\n\n/**\n * Describes the message replit.river.internal.v1.PropagationContext.\n * Use `create(PropagationContextSchema)` to create a new message.\n */\nexport const PropagationContextSchema: GenMessage<PropagationContext> = /*@__PURE__*/\n messageDesc(file_transport, 0);\n\n/**\n * *\n * Internal protobuf envelope used by the proto codec to carry River transport\n * messages.\n *\n * @generated from message replit.river.internal.v1.TransportEnvelope\n */\nexport type TransportEnvelope = Message<\"replit.river.internal.v1.TransportEnvelope\"> & {\n /**\n * @generated from field: string id = 1;\n */\n id: string;\n\n /**\n * @generated from field: string from = 2;\n */\n from: string;\n\n /**\n * @generated from field: string to = 3;\n */\n to: string;\n\n /**\n * @generated from field: uint32 seq = 4;\n */\n seq: number;\n\n /**\n * @generated from field: uint32 ack = 5;\n */\n ack: number;\n\n /**\n * @generated from field: string stream_id = 6;\n */\n streamId: string;\n\n /**\n * @generated from field: uint32 control_flags = 7;\n */\n controlFlags: number;\n\n /**\n * @generated from field: string service_name = 8;\n */\n serviceName: string;\n\n /**\n * @generated from field: string procedure_name = 9;\n */\n procedureName: string;\n\n /**\n * @generated from field: replit.river.internal.v1.PropagationContext tracing = 10;\n */\n tracing?: PropagationContext;\n\n /**\n * @generated from oneof replit.river.internal.v1.TransportEnvelope.payload_kind\n */\n payloadKind: {\n /**\n * @generated from field: bytes payload_bytes = 11;\n */\n value: Uint8Array;\n case: \"payloadBytes\";\n } | {\n /**\n * @generated from field: bytes payload_msgpack = 12;\n */\n value: Uint8Array;\n case: \"payloadMsgpack\";\n } | { case: undefined; value?: undefined };\n};\n\n/**\n * Describes the message replit.river.internal.v1.TransportEnvelope.\n * Use `create(TransportEnvelopeSchema)` to create a new message.\n */\nexport const TransportEnvelopeSchema: GenMessage<TransportEnvelope> = /*@__PURE__*/\n messageDesc(file_transport, 1);\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAA6C;AAE7C,qBAGO;;;ACAP,uBAAsC;AAM/B,IAAM,iBACX,+CAAS,ijBAAijB;AA2GrjB,IAAM,0BACX,kDAAY,gBAAgB,CAAC;;;ADtGxB,IAAM,aAAoB;AAAA,EAC/B,SAAS,KAAK;AACZ,UAAM,UAAU,uBAAuB,GAAG;AAE1C,eAAO;AAAA,MACL;AAAA,UACA,wBAAO,yBAAyB,eAAe,OAAO,CAAC;AAAA,IACzD;AAAA,EACF;AAAA,EAEA,WAAW,MAAkB;AAQ3B,UAAM,QACJ,gBAAgB,aAAa,OAAO,IAAI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YAAY;AAAA,IACxC,GAAI,SAAS,kBAAkB,KAC3B,CAAC,IACD,EAAE,eAAe,SAAS,cAAc;AAAA,IAC5C,GAAI,SAAS,UACT;AAAA,MACE,SAAS;AAAA,QACP,aAAa,SAAS,QAAQ;AAAA,QAC9B,YAAY,SAAS,QAAQ;AAAA,MAC/B;AAAA,IACF,IACA,CAAC;AAAA,EACP;AACF;AAEA,SAAS,kBACP,UACS;AACT,UAAQ,SAAS,YAAY,MAAM;AAAA,IACjC,KAAK;AACH,aAAO,SAAS,YAAY;AAAA,IAC9B,KAAK;AAEH,iBAAO,eAAAC,QAAc,SAAS,YAAY,KAAK;AAAA,IACjD;AACE,YAAM,IAAI,MAAM,sDAAsD;AAAA,EAC1E;AACF;","names":["msgpackEncode","msgpackDecode"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { C as Codec } from '../types-BGGvYIJM.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A protobuf-native transport envelope codec.
|
|
5
|
+
*
|
|
6
|
+
* The envelope schema is defined in `proto/transport.proto` and generated via
|
|
7
|
+
* `buf generate`. Handler payloads that are already raw protobuf bytes use
|
|
8
|
+
* `payload_bytes`. Non-protobuf payloads (error results, control messages)
|
|
9
|
+
* are msgpack-encoded into `payload_msgpack`.
|
|
10
|
+
*/
|
|
11
|
+
declare const ProtoCodec: Codec;
|
|
12
|
+
|
|
13
|
+
export { ProtoCodec };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { C as Codec } from '../types-BGGvYIJM.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A protobuf-native transport envelope codec.
|
|
5
|
+
*
|
|
6
|
+
* The envelope schema is defined in `proto/transport.proto` and generated via
|
|
7
|
+
* `buf generate`. Handler payloads that are already raw protobuf bytes use
|
|
8
|
+
* `payload_bytes`. Non-protobuf payloads (error results, control messages)
|
|
9
|
+
* are msgpack-encoded into `payload_msgpack`.
|
|
10
|
+
*/
|
|
11
|
+
declare const ProtoCodec: Codec;
|
|
12
|
+
|
|
13
|
+
export { ProtoCodec };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|