@yorun-ai/vrpc 0.9.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.
@@ -0,0 +1,231 @@
1
+ # @yorun-ai/vrpc
2
+
3
+ [English](README.md) | **简体中文**
4
+
5
+ 用于 Vine vRPC 与通用 HTTP 请求的客户端运行时。
6
+
7
+ 项目仓库:[github.com/yorun-ai/vrpc-ts](https://github.com/yorun-ai/vrpc-ts)
8
+
9
+ ## 稳定性
10
+
11
+ 本包从 `0.9.0` 开始发布,已经可以使用,但 `1.0.0` 之前暂不承诺公开 API 稳定。不兼容的 API 变更可以随新的 `0.x` minor 版本发布,并会提供迁移说明;`1.0.0` 将作为稳定 API 承诺的起点。
12
+
13
+ ## 安装
14
+
15
+ ```bash
16
+ pnpm add @yorun-ai/vrpc
17
+ ```
18
+
19
+ ## 入口
20
+
21
+ - `@yorun-ai/vrpc` / `@yorun-ai/vrpc/client`:vRPC client、协议 helper、共享 transport 和类型。
22
+ - `@yorun-ai/vrpc/http`:通用 HTTP client。
23
+
24
+ ## vRPC 快速开始
25
+
26
+ ```ts
27
+ import { VrpcInvokeError, createVrpcClient, getClientInstanceId } from "@yorun-ai/vrpc";
28
+
29
+ const client = createVrpcClient({
30
+ prefixUrl: "https://api.example.com/invoke",
31
+ timeoutMs: 15_000,
32
+ suppressGlobalToast: false,
33
+ clientInfo: {
34
+ clientName: "demo.browser",
35
+ clientVersion: "1.0.0",
36
+ clientInstanceId: getClientInstanceId(),
37
+ },
38
+ });
39
+
40
+ client.use({
41
+ onError(error, context) {
42
+ if (context.options.suppressGlobalToast) {
43
+ return;
44
+ }
45
+ console.error(error);
46
+ },
47
+ });
48
+
49
+ const profile = await client.invoke<{ id: number; name: string }>({
50
+ serviceName: "user.UserService",
51
+ methodName: "getProfile",
52
+ params: { userId: 1 },
53
+ options: {
54
+ timeoutMs: 3_000,
55
+ suppressGlobalToast: true,
56
+ },
57
+ });
58
+
59
+ // 无参 method 可以传 null 或空对象。
60
+ await client.invoke({
61
+ serviceName: "user.UserService",
62
+ methodName: "ping",
63
+ params: null,
64
+ });
65
+
66
+ try {
67
+ await client.invoke({
68
+ serviceName: "user.UserService",
69
+ methodName: "missing",
70
+ params: {},
71
+ });
72
+ } catch (error) {
73
+ if (error instanceof VrpcInvokeError) {
74
+ console.error(error.status, error.vrpcStatus, error.code, error.reason);
75
+ }
76
+ }
77
+ ```
78
+
79
+ `traceMode` 只控制 runtime 自动生成的 `vrpc-trace` Header,不改变请求路由或 `prefixUrl`。经过 Vine Portal 时使用默认的 `"portal"` 模式,Header 只包含 id;应用直连 vRPC 服务时设置 `traceMode: "direct"`,runtime 同时生成 id 和 span。单次调用的 `options.trace` 会覆盖自动生成结果。
80
+
81
+ ### 请求配置
82
+
83
+ ```ts
84
+ type VrpcRequestOptions = {
85
+ headers?: HeadersInit;
86
+ timeoutMs?: number;
87
+ requestInit?: Omit<RequestInit, "method" | "body" | "headers">;
88
+ suppressGlobalToast?: boolean;
89
+ trace?: { id: string; span?: string };
90
+ wire?: VrpcMethodWireSpec;
91
+ };
92
+ ```
93
+
94
+ - create 时的 `suppressGlobalToast` 是默认值,单次调用的 `true` 或 `false` 会覆盖它。
95
+ - `timeoutMs` 默认不启用;未配置时内置 transport 不创建本地 timeout,也不发送 `vrpc-options`。
96
+ - `wire` 只能用于单次调用,并且不会进入 HTTP payload。
97
+ - 无参 method 兼容 `params: null` 和 `params: {}`。
98
+ - 浏览器 transport 默认 `credentials: "omit"`;需要 cookie 时使用 `requestInit.credentials`。
99
+
100
+ ## 自动 CBOR
101
+
102
+ runtime 不内置 CBOR 依赖。没有 `wire` 的 method 始终使用 JSON,也不需要 codec。生成的 client 会在 method 的 arguments 或 result 含 Binary 时附加稀疏 wire schema:
103
+
104
+ ```ts
105
+ import type { VrpcCborCodec, VrpcWireSchema } from "@yorun-ai/vrpc";
106
+
107
+ const uploadArguments: VrpcWireSchema = {
108
+ kind: "object",
109
+ fields: {
110
+ content: { kind: "binary" },
111
+ },
112
+ };
113
+
114
+ const cborCodec: VrpcCborCodec = {
115
+ encode: (value) => yourCborLibrary.encode(value),
116
+ decode: (bytes) => yourCborLibrary.decode(bytes),
117
+ };
118
+
119
+ const client = createVrpcClient({
120
+ prefixUrl: "https://api.example.com/invoke",
121
+ clientInfo: {
122
+ clientName: "demo.browser",
123
+ clientVersion: "1.0.0",
124
+ clientInstanceId: getClientInstanceId(),
125
+ },
126
+ cborCodec,
127
+ });
128
+
129
+ await client.invoke({
130
+ serviceName: "file.FileService",
131
+ methodName: "upload",
132
+ params: { content: new Uint8Array([1, 2, 3]) },
133
+ options: {
134
+ wire: { arguments: uploadArguments },
135
+ },
136
+ });
137
+ ```
138
+
139
+ 自动选择规则
140
+
141
+ - `wire.arguments`:请求 `content-type` 使用 `application/vrpc+cbor`。
142
+ - `wire.result`:`accept` 使用 `application/vrpc+cbor, application/vrpc+json`。
143
+ - 两者都没有:JSON。
144
+ - wire 存在但没有 `cborCodec`:在网络请求前抛出配置错误。
145
+
146
+ `VrpcWireSchema` 支持 Binary、nullable、list、object 和 `Map<Int|string, T>`。CBOR 中 Binary 保持原始 bytes;整数键 `Record` 转换为真正的整数键 CBOR Map。
147
+
148
+ ## Vine Header
149
+
150
+ runtime 自动生成
151
+
152
+ ```text
153
+ content-type: application/vrpc+json
154
+ accept: application/vrpc+json
155
+ vrpc-trace: id=<32hex>
156
+ vrpc-client: name=demo.browser,version=1.0.0,instanceId=<uuid>
157
+ vrpc-options: timeout=3000ms
158
+ ```
159
+
160
+ 自定义 `headers` 不能覆盖 `accept`、`content-type` 或任何 `vrpc-*` Header。显式配置 `timeoutMs` 时,它同时控制本地 `AbortController` 和 `vrpc-options`。
161
+
162
+ ## 通用 HTTP client
163
+
164
+ ```ts
165
+ import { createHttpClient } from "@yorun-ai/vrpc/http";
166
+
167
+ const http = createHttpClient({
168
+ prefixUrl: "https://api.example.com",
169
+ timeoutMs: 5_000,
170
+ });
171
+
172
+ const profile = await http.request<{ id: number }>({
173
+ path: "/users/me",
174
+ query: { withProfile: true },
175
+ options: {
176
+ requestInit: { credentials: "include" },
177
+ suppressGlobalToast: true,
178
+ },
179
+ });
180
+
181
+ await http.request({
182
+ path: "/users",
183
+ method: "POST",
184
+ json: { name: "Vine" },
185
+ });
186
+ ```
187
+
188
+ HTTP interceptor 通过 `context.options` 读取合并后的请求配置。`json` 和 `body` 互斥,空响应返回 `null`。
189
+
190
+ ## 协议 helper
191
+
192
+ ```ts
193
+ import {
194
+ buildVrpcHeaders,
195
+ buildVrpcPath,
196
+ buildVrpcRequestBody,
197
+ generateVrpcId,
198
+ } from "@yorun-ai/vrpc";
199
+
200
+ const headers = buildVrpcHeaders({
201
+ clientInfo: {
202
+ clientName: "demo.browser",
203
+ clientVersion: "1.0.0",
204
+ clientInstanceId: getClientInstanceId(),
205
+ },
206
+ trace: { id: generateVrpcId() },
207
+ timeoutMs: 3_000,
208
+ });
209
+
210
+ const path = buildVrpcPath("user.UserService", "getProfile");
211
+ const body = buildVrpcRequestBody({ userId: 1 });
212
+ ```
213
+
214
+ ## 文档
215
+
216
+ 使用指南:
217
+
218
+ - [Usage(English)](./docs/guides/usage.md):HTTP/vRPC client 配置与扩展点。
219
+ - [Axios integration(English)](./docs/guides/axios.md):自定义 Axios transport 与 JSON 协议 helper。
220
+
221
+ 维护者文档:
222
+
223
+ - [Architecture(English)](./docs/maintainers/architecture.md):模块边界与请求数据流。
224
+ - [vRPC protocol(English)](./docs/maintainers/protocol.md):path、envelope、Header、内容协商、wire schema 与生成 client 的要求。
225
+ - [Releasing(English)](./docs/maintainers/releasing.md):版本管理与 npm 发布流程。
226
+
227
+ 根 README 与 `docs/guides/` 面向包使用者;`docs/maintainers/` 面向仓库维护者,以及需要实现 transport 或 codegen 的接入方。公开导出、类型、默认值、Header、错误或请求行为变化时,必须同步更新面向使用者和维护者的文档。
228
+
229
+ ## License
230
+
231
+ 本项目使用 [Apache License 2.0](./LICENSE)。
@@ -0,0 +1,462 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_request_options = require("./request-options-2HZzkj4w.cjs");
3
+ //#region src/protocol/id.ts
4
+ var DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY = "vrpc-client-instance-id";
5
+ function getRandomByteArray(length) {
6
+ const array = new Uint8Array(length);
7
+ if (globalThis.crypto?.getRandomValues) {
8
+ globalThis.crypto.getRandomValues(array);
9
+ return array;
10
+ }
11
+ for (let i = 0; i < length; i++) array[i] = Math.floor(Math.random() * 256);
12
+ return array;
13
+ }
14
+ function toHex(bytes) {
15
+ return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
16
+ }
17
+ function newNonZeroHex(bytesLength, zeroValue) {
18
+ for (;;) {
19
+ const value = toHex(getRandomByteArray(bytesLength));
20
+ if (value !== zeroValue) return value;
21
+ }
22
+ }
23
+ function generateVrpcId() {
24
+ return newNonZeroHex(16, "00000000000000000000000000000000");
25
+ }
26
+ function generateVrpcSpan() {
27
+ return newNonZeroHex(8, "0000000000000000");
28
+ }
29
+ function generateClientInstanceId() {
30
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().toLowerCase();
31
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
32
+ const value = Math.floor(Math.random() * 16);
33
+ return (char === "x" ? value : value & 3 | 8).toString(16);
34
+ });
35
+ }
36
+ function getClientInstanceId({ key } = {}) {
37
+ const storageKey = key?.trim() || "vrpc-client-instance-id";
38
+ try {
39
+ const existingClientInstanceId = globalThis.localStorage.getItem(storageKey);
40
+ if (existingClientInstanceId) return existingClientInstanceId;
41
+ const clientInstanceId = generateClientInstanceId();
42
+ globalThis.localStorage.setItem(storageKey, clientInstanceId);
43
+ return clientInstanceId;
44
+ } catch {
45
+ return generateClientInstanceId();
46
+ }
47
+ }
48
+ //#endregion
49
+ //#region src/protocol/headers.ts
50
+ var VRPC_JSON_CONTENT_TYPE = "application/vrpc+json";
51
+ var VRPC_CBOR_CONTENT_TYPE = "application/vrpc+cbor";
52
+ var CLIENT_NAME_PATTERN = /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/;
53
+ var SEMVER_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
54
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
55
+ var TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
56
+ var TRACE_SPAN_PATTERN = /^[0-9a-f]{16}$/;
57
+ function assertClientInfo(clientInfo, scope = "client") {
58
+ if (!CLIENT_NAME_PATTERN.test(clientInfo.clientName)) throw new Error(`Invalid vRPC ${scope} name: ${clientInfo.clientName}`);
59
+ if (!SEMVER_PATTERN.test(clientInfo.clientVersion)) throw new Error(`Invalid vRPC ${scope} version: ${clientInfo.clientVersion}`);
60
+ if (!UUID_PATTERN.test(clientInfo.clientInstanceId)) throw new Error(`Invalid vRPC ${scope} instanceId: ${clientInfo.clientInstanceId}`);
61
+ }
62
+ function decodeDelimitedAppInfo(value) {
63
+ const fields = {};
64
+ for (const entry of value.split(",")) {
65
+ const separator = entry.indexOf("=");
66
+ if (separator <= 0) return null;
67
+ const key = entry.slice(0, separator).trim();
68
+ const fieldValue = entry.slice(separator + 1).trim();
69
+ if (!key || !fieldValue || key in fields) return null;
70
+ fields[key] = fieldValue;
71
+ }
72
+ if (Object.keys(fields).length !== 3) return null;
73
+ const name = fields.name;
74
+ const version = fields.version;
75
+ const instanceId = fields.instanceId;
76
+ if (!name || !version || !instanceId) return null;
77
+ return {
78
+ clientName: name,
79
+ clientVersion: version,
80
+ clientInstanceId: instanceId
81
+ };
82
+ }
83
+ function assertValidVrpcServerHeader(value) {
84
+ if (!value) throw new Error("Invalid vRPC response: missing vrpc-server header.");
85
+ const serverInfo = decodeDelimitedAppInfo(value);
86
+ if (!serverInfo) throw new Error("Invalid vRPC response: invalid vrpc-server header.");
87
+ try {
88
+ assertClientInfo(serverInfo, "server");
89
+ } catch {
90
+ throw new Error("Invalid vRPC response: invalid vrpc-server header.");
91
+ }
92
+ }
93
+ function assertValidVrpcTrace(trace) {
94
+ if (!TRACE_ID_PATTERN.test(trace.id)) throw new Error(`Invalid vRPC trace id: ${trace.id}`);
95
+ if (trace.span !== void 0 && !TRACE_SPAN_PATTERN.test(trace.span)) throw new Error(`Invalid vRPC trace span: ${trace.span}`);
96
+ }
97
+ function assertValidVrpcTimeout(timeoutMs) {
98
+ if (timeoutMs !== void 0 && (!Number.isSafeInteger(timeoutMs) || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new Error(`Invalid vRPC timeoutMs: ${timeoutMs}`);
99
+ }
100
+ function isReservedVrpcHeader(name) {
101
+ const normalized = name.toLowerCase();
102
+ return normalized === "accept" || normalized === "content-type" || normalized.startsWith("vrpc-");
103
+ }
104
+ function assertNoReservedVrpcHeaders(...values) {
105
+ for (const value of values) {
106
+ if (!value) continue;
107
+ const headers = new Headers(value);
108
+ for (const name of headers.keys()) if (isReservedVrpcHeader(name)) throw new Error(`vRPC protocol header cannot be overridden: ${name}`);
109
+ }
110
+ }
111
+ function mediaTypeOf(value) {
112
+ return value?.split(";", 1)[0]?.trim().toLowerCase() || "";
113
+ }
114
+ function buildVrpcHeaders({ clientInfo, trace, timeoutMs, requestUsesCbor = false, responseUsesCbor = false }) {
115
+ assertClientInfo(clientInfo);
116
+ assertValidVrpcTrace(trace);
117
+ assertValidVrpcTimeout(timeoutMs);
118
+ const headers = new Headers();
119
+ headers.set("content-type", requestUsesCbor ? VRPC_CBOR_CONTENT_TYPE : VRPC_JSON_CONTENT_TYPE);
120
+ headers.set("accept", responseUsesCbor ? `${VRPC_CBOR_CONTENT_TYPE}, ${VRPC_JSON_CONTENT_TYPE}` : VRPC_JSON_CONTENT_TYPE);
121
+ headers.set("vrpc-client", `name=${clientInfo.clientName},version=${clientInfo.clientVersion},instanceId=${clientInfo.clientInstanceId}`);
122
+ headers.set("vrpc-trace", trace.span ? `id=${trace.id},span=${trace.span}` : `id=${trace.id}`);
123
+ if (timeoutMs !== void 0) headers.set("vrpc-options", `timeout=${timeoutMs}ms`);
124
+ return headers;
125
+ }
126
+ //#endregion
127
+ //#region src/protocol/wire.ts
128
+ function resolveFields(schema) {
129
+ return typeof schema.fields === "function" ? schema.fields() : schema.fields;
130
+ }
131
+ function entriesOf(value) {
132
+ if (value instanceof Map) return Array.from(value.entries());
133
+ if (value && typeof value === "object" && !Array.isArray(value)) return Object.entries(value);
134
+ throw new Error("vRPC wire map value must be a Record or Map.");
135
+ }
136
+ function objectOf(value) {
137
+ if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), item]));
138
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
139
+ throw new Error("vRPC wire object value must be an object.");
140
+ }
141
+ function toIntegerKey(value) {
142
+ const integer = typeof value === "number" ? value : Number(value);
143
+ if (!Number.isSafeInteger(integer)) throw new Error(`vRPC wire map key must be an integer: ${String(value)}`);
144
+ return integer;
145
+ }
146
+ function normalizeBinary(value) {
147
+ if (value instanceof Uint8Array) return value;
148
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
149
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
150
+ throw new Error("vRPC Binary value must be a Uint8Array.");
151
+ }
152
+ function toCborWireValue(value, schema) {
153
+ if (value == null) return value;
154
+ switch (schema.kind) {
155
+ case "value": return value;
156
+ case "binary": return normalizeBinary(value);
157
+ case "list":
158
+ if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
159
+ return value.map((item) => toCborWireValue(item, schema.value));
160
+ case "map": {
161
+ const entries = entriesOf(value);
162
+ if (schema.key === "int") return new Map(entries.map(([key, item]) => [toIntegerKey(key), toCborWireValue(item, schema.value)]));
163
+ return Object.fromEntries(entries.map(([key, item]) => [String(key), toCborWireValue(item, schema.value)]));
164
+ }
165
+ case "object": {
166
+ const input = objectOf(value);
167
+ const output = { ...input };
168
+ for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = toCborWireValue(input[field], fieldSchema);
169
+ return output;
170
+ }
171
+ }
172
+ }
173
+ function fromCborWireValue(value, schema) {
174
+ if (value == null) return value;
175
+ switch (schema.kind) {
176
+ case "value": return value;
177
+ case "binary": return normalizeBinary(value);
178
+ case "list":
179
+ if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
180
+ return value.map((item) => fromCborWireValue(item, schema.value));
181
+ case "map": return Object.fromEntries(entriesOf(value).map(([key, item]) => {
182
+ const normalizedKey = schema.key === "int" ? toIntegerKey(key) : String(key);
183
+ return [String(normalizedKey), fromCborWireValue(item, schema.value)];
184
+ }));
185
+ case "object": {
186
+ const input = objectOf(value);
187
+ const output = { ...input };
188
+ for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = fromCborWireValue(input[field], fieldSchema);
189
+ return output;
190
+ }
191
+ }
192
+ }
193
+ function normalizeCborValue(value) {
194
+ if (value instanceof Uint8Array) return value;
195
+ if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), normalizeCborValue(item)]));
196
+ if (Array.isArray(value)) return value.map(normalizeCborValue);
197
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeCborValue(item)]));
198
+ return value;
199
+ }
200
+ //#endregion
201
+ //#region src/protocol/request.ts
202
+ function buildVrpcPath(serviceName, methodName) {
203
+ return `${encodeURIComponent(serviceName)}/${encodeURIComponent(methodName)}`;
204
+ }
205
+ function buildVrpcRequestBody(params) {
206
+ return JSON.stringify({ params: params ?? null });
207
+ }
208
+ async function encodeVrpcRequestBody(params, schema, cborCodec) {
209
+ if (!schema) return buildVrpcRequestBody(params);
210
+ if (!cborCodec) throw new Error("A cborCodec is required to encode a CBOR vRPC request.");
211
+ const bytes = await cborCodec.encode({ params: toCborWireValue(params, schema) });
212
+ if (!(bytes instanceof Uint8Array)) throw new Error("cborCodec.encode() must return a Uint8Array.");
213
+ const body = new Uint8Array(bytes.byteLength);
214
+ body.set(bytes);
215
+ return body.buffer;
216
+ }
217
+ //#endregion
218
+ //#region src/protocol/response.ts
219
+ function readEnvelopeError(payload) {
220
+ if (!payload || typeof payload !== "object") return payload;
221
+ return payload.error ?? payload;
222
+ }
223
+ function readEnvelopeResult(payload) {
224
+ if (!payload || typeof payload !== "object") return;
225
+ return payload.result;
226
+ }
227
+ function requireResponseHeader(headers, name) {
228
+ const value = headers.get(name);
229
+ if (!value) throw new Error(`Invalid vRPC response: missing ${name} header.`);
230
+ return value;
231
+ }
232
+ function readDecodedEnvelopeField(payload, field) {
233
+ if (payload instanceof Map) return payload.get(field);
234
+ if (payload && typeof payload === "object") return payload[field];
235
+ }
236
+ async function decodeVrpcResponsePayload(response, cborCodec, resultSchema) {
237
+ requireResponseHeader(response.headers, "vrpc-status");
238
+ assertValidVrpcServerHeader(response.headers.get("vrpc-server"));
239
+ const contentType = mediaTypeOf(requireResponseHeader(response.headers, "content-type"));
240
+ if (contentType === "application/vrpc+json") {
241
+ const text = await response.text();
242
+ if (!text) throw new Error("Invalid vRPC response: empty response body.");
243
+ try {
244
+ return JSON.parse(text);
245
+ } catch {
246
+ throw new Error("Invalid vRPC response: JSON body cannot be parsed.");
247
+ }
248
+ }
249
+ if (contentType !== "application/vrpc+cbor") throw new Error(`Invalid vRPC response content-type: ${contentType || "empty"}.`);
250
+ if (!resultSchema) throw new Error("Invalid vRPC response: unexpected CBOR body for a JSON method.");
251
+ if (!cborCodec) throw new Error("A cborCodec is required to decode a CBOR vRPC response.");
252
+ const decoded = await cborCodec.decode(new Uint8Array(await response.arrayBuffer()));
253
+ const result = readDecodedEnvelopeField(decoded, "result");
254
+ const error = readDecodedEnvelopeField(decoded, "error");
255
+ return {
256
+ result: fromCborWireValue(result, resultSchema),
257
+ error: normalizeCborValue(error)
258
+ };
259
+ }
260
+ function normalizeResponseHeaders(headers) {
261
+ if (!headers) return new Headers();
262
+ if (headers instanceof Headers) return new Headers(headers);
263
+ if (Array.isArray(headers)) return new Headers(headers.map(([key, value]) => [key, String(value)]));
264
+ const normalized = new Headers();
265
+ for (const [key, rawValue] of Object.entries(headers)) {
266
+ if (rawValue == null) continue;
267
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
268
+ for (const value of values) normalized.append(key, String(value));
269
+ }
270
+ return normalized;
271
+ }
272
+ function buildResponse(responseLike) {
273
+ const response = new Response(null, {
274
+ status: responseLike.status,
275
+ statusText: responseLike.statusText,
276
+ headers: normalizeResponseHeaders(responseLike.headers)
277
+ });
278
+ try {
279
+ Object.defineProperty(response, "url", {
280
+ value: responseLike.url || "",
281
+ configurable: true
282
+ });
283
+ } catch {}
284
+ return response;
285
+ }
286
+ function resolveVrpcResponse(responseLike, payload) {
287
+ const response = buildResponse(responseLike);
288
+ const vrpcStatus = response.headers.get("vrpc-status");
289
+ const statusText = response.statusText || "";
290
+ const url = responseLike.url || response.url || "";
291
+ const method = responseLike.method || "POST";
292
+ if (response.ok && vrpcStatus === "OK") return {
293
+ response,
294
+ parsed: {
295
+ ok: true,
296
+ status: response.status,
297
+ statusText,
298
+ vrpcStatus: "OK",
299
+ headers: response.headers,
300
+ url,
301
+ method,
302
+ payload,
303
+ result: payload.result,
304
+ error: null
305
+ }
306
+ };
307
+ return {
308
+ response,
309
+ parsed: {
310
+ ok: false,
311
+ status: response.status,
312
+ statusText,
313
+ vrpcStatus,
314
+ headers: response.headers,
315
+ url,
316
+ method,
317
+ payload,
318
+ result: readEnvelopeResult(payload),
319
+ error: readEnvelopeError(payload)
320
+ }
321
+ };
322
+ }
323
+ function parseVrpcResponse(responseLike, payload) {
324
+ return resolveVrpcResponse(responseLike, payload).parsed;
325
+ }
326
+ function unwrapVrpcResponse(responseLike, payload) {
327
+ const { response, parsed } = resolveVrpcResponse(responseLike, payload);
328
+ if (!parsed.ok) throw new require_request_options.VrpcInvokeError(response, parsed.error, {
329
+ url: parsed.url,
330
+ method: parsed.method
331
+ });
332
+ return parsed.result;
333
+ }
334
+ //#endregion
335
+ //#region src/core/invoke-args.ts
336
+ function normalizeInvokeRequest(request) {
337
+ return {
338
+ serviceName: request.serviceName,
339
+ methodName: request.methodName,
340
+ params: request.params ?? null,
341
+ options: request.options
342
+ };
343
+ }
344
+ //#endregion
345
+ //#region src/core/create-vrpc-client.ts
346
+ function buildDefaultTrace(traceMode) {
347
+ const trace = { id: generateVrpcId() };
348
+ if (traceMode === "direct") trace.span = generateVrpcSpan();
349
+ return trace;
350
+ }
351
+ function assertWireSpec(serviceName, methodName, wire) {
352
+ if (!wire) return;
353
+ if (!wire.arguments && !wire.result) throw new Error(`Invalid vRPC wire spec for ${serviceName}/${methodName}: wire is empty.`);
354
+ }
355
+ function requireCborCodec(serviceName, methodName, wire, cborCodec) {
356
+ if (wire && !cborCodec) throw new Error(`CBOR is required for ${serviceName}/${methodName}, but no cborCodec was configured. Pass cborCodec to createVrpcClient().`);
357
+ }
358
+ function createVrpcClient(options) {
359
+ const { prefixUrl, clientInfo, traceMode = "portal", cborCodec, fetchImpl, transport, interceptors, ...baseOptions } = options;
360
+ const core = require_request_options.createClientCore({
361
+ prefixUrl,
362
+ baseOptions,
363
+ fetchImpl,
364
+ transport,
365
+ interceptors,
366
+ splitRequestOptions: require_request_options.splitVrpcRequestOptions,
367
+ prepareRequest: async (request, helpers) => {
368
+ const resolvedRequest = normalizeInvokeRequest(request);
369
+ const requestOptions = helpers.splitRequestOptions(resolvedRequest.options);
370
+ const wire = requestOptions.wire;
371
+ assertWireSpec(resolvedRequest.serviceName, resolvedRequest.methodName, wire);
372
+ requireCborCodec(resolvedRequest.serviceName, resolvedRequest.methodName, wire, cborCodec);
373
+ assertNoReservedVrpcHeaders(helpers.baseOptions.headers, requestOptions.headers);
374
+ const timeoutMs = requestOptions.timeoutMs ?? helpers.baseOptions.timeoutMs;
375
+ const trace = requestOptions.trace ?? buildDefaultTrace(traceMode);
376
+ const requestUsesCbor = Boolean(wire?.arguments);
377
+ const responseUsesCbor = Boolean(wire?.result);
378
+ const protocolHeaders = buildVrpcHeaders({
379
+ clientInfo,
380
+ trace,
381
+ timeoutMs,
382
+ requestUsesCbor,
383
+ responseUsesCbor
384
+ });
385
+ const finalHeaders = require_request_options.mergeHeaders(helpers.baseOptions.headers, requestOptions.headers, protocolHeaders);
386
+ const body = await encodeVrpcRequestBody(resolvedRequest.params, wire?.arguments, cborCodec);
387
+ const path = buildVrpcPath(resolvedRequest.serviceName, resolvedRequest.methodName);
388
+ const url = require_request_options.buildRequestUrl(helpers.prefixUrl, path);
389
+ const resolvedRequestInit = {
390
+ credentials: "omit",
391
+ ...helpers.baseOptions.requestInit,
392
+ ...requestOptions.requestInit
393
+ };
394
+ const resolvedOptions = {
395
+ headers: finalHeaders,
396
+ timeoutMs,
397
+ requestInit: resolvedRequestInit,
398
+ suppressGlobalToast: requestOptions.suppressGlobalToast ?? helpers.baseOptions.suppressGlobalToast,
399
+ trace,
400
+ wire
401
+ };
402
+ return {
403
+ timeoutMs,
404
+ fallbackMethod: "POST",
405
+ fallbackHeaders: finalHeaders,
406
+ fallbackBody: body,
407
+ context: {
408
+ url,
409
+ init: {
410
+ ...resolvedRequestInit,
411
+ method: "POST",
412
+ headers: finalHeaders,
413
+ body
414
+ },
415
+ request: resolvedRequest,
416
+ options: resolvedOptions
417
+ }
418
+ };
419
+ },
420
+ parseResponse: (response, context) => decodeVrpcResponsePayload(response, cborCodec, context.options.wire?.result),
421
+ validateRequest: (_context, requestMeta) => {
422
+ if (requestMeta.method !== "POST") throw new Error(`Unsupported method: ${requestMeta.method}, only POST is allowed.`);
423
+ },
424
+ assertResponse: (response, payload, _context, requestMeta) => {
425
+ unwrapVrpcResponse({
426
+ status: response.status,
427
+ statusText: response.statusText,
428
+ headers: response.headers,
429
+ url: requestMeta.url,
430
+ method: requestMeta.method
431
+ }, payload);
432
+ }
433
+ });
434
+ async function invoke(request) {
435
+ return (await core.execute(request)).result;
436
+ }
437
+ return {
438
+ invoke,
439
+ use: core.use
440
+ };
441
+ }
442
+ //#endregion
443
+ exports.DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY = DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY;
444
+ exports.HTTP_TIMEOUT_ERROR_CODE = require_request_options.HTTP_TIMEOUT_ERROR_CODE;
445
+ exports.HttpInvokeError = require_request_options.HttpInvokeError;
446
+ exports.HttpTimeoutError = require_request_options.HttpTimeoutError;
447
+ exports.VRPC_CBOR_CONTENT_TYPE = VRPC_CBOR_CONTENT_TYPE;
448
+ exports.VRPC_JSON_CONTENT_TYPE = VRPC_JSON_CONTENT_TYPE;
449
+ exports.VrpcInvokeError = require_request_options.VrpcInvokeError;
450
+ exports.buildVrpcHeaders = buildVrpcHeaders;
451
+ exports.buildVrpcPath = buildVrpcPath;
452
+ exports.buildVrpcRequestBody = buildVrpcRequestBody;
453
+ exports.createFetchTransport = require_request_options.createFetchTransport;
454
+ exports.createVrpcClient = createVrpcClient;
455
+ exports.decodeVrpcResponsePayload = decodeVrpcResponsePayload;
456
+ exports.encodeVrpcRequestBody = encodeVrpcRequestBody;
457
+ exports.generateClientInstanceId = generateClientInstanceId;
458
+ exports.generateVrpcId = generateVrpcId;
459
+ exports.generateVrpcSpan = generateVrpcSpan;
460
+ exports.getClientInstanceId = getClientInstanceId;
461
+ exports.parseVrpcResponse = parseVrpcResponse;
462
+ exports.unwrapVrpcResponse = unwrapVrpcResponse;