@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.
- package/CONTRIBUTING.md +82 -0
- package/LICENSE +201 -0
- package/README.md +232 -0
- package/README.zh-CN.md +231 -0
- package/dist/client.cjs +462 -0
- package/dist/client.d.cts +247 -0
- package/dist/client.d.ts +247 -0
- package/dist/client.es.js +442 -0
- package/dist/http.cjs +69 -0
- package/dist/http.d.cts +100 -0
- package/dist/http.d.ts +100 -0
- package/dist/http.es.js +64 -0
- package/dist/request-options-2HZzkj4w.cjs +353 -0
- package/dist/request-options-disym648.js +288 -0
- package/docs/guides/axios.md +115 -0
- package/docs/guides/usage.md +259 -0
- package/docs/maintainers/architecture.md +47 -0
- package/docs/maintainers/protocol.md +135 -0
- package/docs/maintainers/releasing.md +92 -0
- package/package.json +65 -0
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
import { c as HTTP_TIMEOUT_ERROR_CODE, d as VrpcInvokeError, i as createFetchTransport, l as HttpInvokeError, n as splitVrpcRequestOptions, o as buildRequestUrl, r as createClientCore, s as mergeHeaders, u as HttpTimeoutError } from "./request-options-disym648.js";
|
|
2
|
+
//#region src/protocol/id.ts
|
|
3
|
+
var DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY = "vrpc-client-instance-id";
|
|
4
|
+
function getRandomByteArray(length) {
|
|
5
|
+
const array = new Uint8Array(length);
|
|
6
|
+
if (globalThis.crypto?.getRandomValues) {
|
|
7
|
+
globalThis.crypto.getRandomValues(array);
|
|
8
|
+
return array;
|
|
9
|
+
}
|
|
10
|
+
for (let i = 0; i < length; i++) array[i] = Math.floor(Math.random() * 256);
|
|
11
|
+
return array;
|
|
12
|
+
}
|
|
13
|
+
function toHex(bytes) {
|
|
14
|
+
return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
|
|
15
|
+
}
|
|
16
|
+
function newNonZeroHex(bytesLength, zeroValue) {
|
|
17
|
+
for (;;) {
|
|
18
|
+
const value = toHex(getRandomByteArray(bytesLength));
|
|
19
|
+
if (value !== zeroValue) return value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function generateVrpcId() {
|
|
23
|
+
return newNonZeroHex(16, "00000000000000000000000000000000");
|
|
24
|
+
}
|
|
25
|
+
function generateVrpcSpan() {
|
|
26
|
+
return newNonZeroHex(8, "0000000000000000");
|
|
27
|
+
}
|
|
28
|
+
function generateClientInstanceId() {
|
|
29
|
+
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().toLowerCase();
|
|
30
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
|
|
31
|
+
const value = Math.floor(Math.random() * 16);
|
|
32
|
+
return (char === "x" ? value : value & 3 | 8).toString(16);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
function getClientInstanceId({ key } = {}) {
|
|
36
|
+
const storageKey = key?.trim() || "vrpc-client-instance-id";
|
|
37
|
+
try {
|
|
38
|
+
const existingClientInstanceId = globalThis.localStorage.getItem(storageKey);
|
|
39
|
+
if (existingClientInstanceId) return existingClientInstanceId;
|
|
40
|
+
const clientInstanceId = generateClientInstanceId();
|
|
41
|
+
globalThis.localStorage.setItem(storageKey, clientInstanceId);
|
|
42
|
+
return clientInstanceId;
|
|
43
|
+
} catch {
|
|
44
|
+
return generateClientInstanceId();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/protocol/headers.ts
|
|
49
|
+
var VRPC_JSON_CONTENT_TYPE = "application/vrpc+json";
|
|
50
|
+
var VRPC_CBOR_CONTENT_TYPE = "application/vrpc+cbor";
|
|
51
|
+
var CLIENT_NAME_PATTERN = /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/;
|
|
52
|
+
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-]+)*)?$/;
|
|
53
|
+
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}$/;
|
|
54
|
+
var TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
|
|
55
|
+
var TRACE_SPAN_PATTERN = /^[0-9a-f]{16}$/;
|
|
56
|
+
function assertClientInfo(clientInfo, scope = "client") {
|
|
57
|
+
if (!CLIENT_NAME_PATTERN.test(clientInfo.clientName)) throw new Error(`Invalid vRPC ${scope} name: ${clientInfo.clientName}`);
|
|
58
|
+
if (!SEMVER_PATTERN.test(clientInfo.clientVersion)) throw new Error(`Invalid vRPC ${scope} version: ${clientInfo.clientVersion}`);
|
|
59
|
+
if (!UUID_PATTERN.test(clientInfo.clientInstanceId)) throw new Error(`Invalid vRPC ${scope} instanceId: ${clientInfo.clientInstanceId}`);
|
|
60
|
+
}
|
|
61
|
+
function decodeDelimitedAppInfo(value) {
|
|
62
|
+
const fields = {};
|
|
63
|
+
for (const entry of value.split(",")) {
|
|
64
|
+
const separator = entry.indexOf("=");
|
|
65
|
+
if (separator <= 0) return null;
|
|
66
|
+
const key = entry.slice(0, separator).trim();
|
|
67
|
+
const fieldValue = entry.slice(separator + 1).trim();
|
|
68
|
+
if (!key || !fieldValue || key in fields) return null;
|
|
69
|
+
fields[key] = fieldValue;
|
|
70
|
+
}
|
|
71
|
+
if (Object.keys(fields).length !== 3) return null;
|
|
72
|
+
const name = fields.name;
|
|
73
|
+
const version = fields.version;
|
|
74
|
+
const instanceId = fields.instanceId;
|
|
75
|
+
if (!name || !version || !instanceId) return null;
|
|
76
|
+
return {
|
|
77
|
+
clientName: name,
|
|
78
|
+
clientVersion: version,
|
|
79
|
+
clientInstanceId: instanceId
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function assertValidVrpcServerHeader(value) {
|
|
83
|
+
if (!value) throw new Error("Invalid vRPC response: missing vrpc-server header.");
|
|
84
|
+
const serverInfo = decodeDelimitedAppInfo(value);
|
|
85
|
+
if (!serverInfo) throw new Error("Invalid vRPC response: invalid vrpc-server header.");
|
|
86
|
+
try {
|
|
87
|
+
assertClientInfo(serverInfo, "server");
|
|
88
|
+
} catch {
|
|
89
|
+
throw new Error("Invalid vRPC response: invalid vrpc-server header.");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function assertValidVrpcTrace(trace) {
|
|
93
|
+
if (!TRACE_ID_PATTERN.test(trace.id)) throw new Error(`Invalid vRPC trace id: ${trace.id}`);
|
|
94
|
+
if (trace.span !== void 0 && !TRACE_SPAN_PATTERN.test(trace.span)) throw new Error(`Invalid vRPC trace span: ${trace.span}`);
|
|
95
|
+
}
|
|
96
|
+
function assertValidVrpcTimeout(timeoutMs) {
|
|
97
|
+
if (timeoutMs !== void 0 && (!Number.isSafeInteger(timeoutMs) || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new Error(`Invalid vRPC timeoutMs: ${timeoutMs}`);
|
|
98
|
+
}
|
|
99
|
+
function isReservedVrpcHeader(name) {
|
|
100
|
+
const normalized = name.toLowerCase();
|
|
101
|
+
return normalized === "accept" || normalized === "content-type" || normalized.startsWith("vrpc-");
|
|
102
|
+
}
|
|
103
|
+
function assertNoReservedVrpcHeaders(...values) {
|
|
104
|
+
for (const value of values) {
|
|
105
|
+
if (!value) continue;
|
|
106
|
+
const headers = new Headers(value);
|
|
107
|
+
for (const name of headers.keys()) if (isReservedVrpcHeader(name)) throw new Error(`vRPC protocol header cannot be overridden: ${name}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function mediaTypeOf(value) {
|
|
111
|
+
return value?.split(";", 1)[0]?.trim().toLowerCase() || "";
|
|
112
|
+
}
|
|
113
|
+
function buildVrpcHeaders({ clientInfo, trace, timeoutMs, requestUsesCbor = false, responseUsesCbor = false }) {
|
|
114
|
+
assertClientInfo(clientInfo);
|
|
115
|
+
assertValidVrpcTrace(trace);
|
|
116
|
+
assertValidVrpcTimeout(timeoutMs);
|
|
117
|
+
const headers = new Headers();
|
|
118
|
+
headers.set("content-type", requestUsesCbor ? VRPC_CBOR_CONTENT_TYPE : VRPC_JSON_CONTENT_TYPE);
|
|
119
|
+
headers.set("accept", responseUsesCbor ? `${VRPC_CBOR_CONTENT_TYPE}, ${VRPC_JSON_CONTENT_TYPE}` : VRPC_JSON_CONTENT_TYPE);
|
|
120
|
+
headers.set("vrpc-client", `name=${clientInfo.clientName},version=${clientInfo.clientVersion},instanceId=${clientInfo.clientInstanceId}`);
|
|
121
|
+
headers.set("vrpc-trace", trace.span ? `id=${trace.id},span=${trace.span}` : `id=${trace.id}`);
|
|
122
|
+
if (timeoutMs !== void 0) headers.set("vrpc-options", `timeout=${timeoutMs}ms`);
|
|
123
|
+
return headers;
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/protocol/wire.ts
|
|
127
|
+
function resolveFields(schema) {
|
|
128
|
+
return typeof schema.fields === "function" ? schema.fields() : schema.fields;
|
|
129
|
+
}
|
|
130
|
+
function entriesOf(value) {
|
|
131
|
+
if (value instanceof Map) return Array.from(value.entries());
|
|
132
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return Object.entries(value);
|
|
133
|
+
throw new Error("vRPC wire map value must be a Record or Map.");
|
|
134
|
+
}
|
|
135
|
+
function objectOf(value) {
|
|
136
|
+
if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), item]));
|
|
137
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
138
|
+
throw new Error("vRPC wire object value must be an object.");
|
|
139
|
+
}
|
|
140
|
+
function toIntegerKey(value) {
|
|
141
|
+
const integer = typeof value === "number" ? value : Number(value);
|
|
142
|
+
if (!Number.isSafeInteger(integer)) throw new Error(`vRPC wire map key must be an integer: ${String(value)}`);
|
|
143
|
+
return integer;
|
|
144
|
+
}
|
|
145
|
+
function normalizeBinary(value) {
|
|
146
|
+
if (value instanceof Uint8Array) return value;
|
|
147
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
148
|
+
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
149
|
+
throw new Error("vRPC Binary value must be a Uint8Array.");
|
|
150
|
+
}
|
|
151
|
+
function toCborWireValue(value, schema) {
|
|
152
|
+
if (value == null) return value;
|
|
153
|
+
switch (schema.kind) {
|
|
154
|
+
case "value": return value;
|
|
155
|
+
case "binary": return normalizeBinary(value);
|
|
156
|
+
case "list":
|
|
157
|
+
if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
|
|
158
|
+
return value.map((item) => toCborWireValue(item, schema.value));
|
|
159
|
+
case "map": {
|
|
160
|
+
const entries = entriesOf(value);
|
|
161
|
+
if (schema.key === "int") return new Map(entries.map(([key, item]) => [toIntegerKey(key), toCborWireValue(item, schema.value)]));
|
|
162
|
+
return Object.fromEntries(entries.map(([key, item]) => [String(key), toCborWireValue(item, schema.value)]));
|
|
163
|
+
}
|
|
164
|
+
case "object": {
|
|
165
|
+
const input = objectOf(value);
|
|
166
|
+
const output = { ...input };
|
|
167
|
+
for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = toCborWireValue(input[field], fieldSchema);
|
|
168
|
+
return output;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function fromCborWireValue(value, schema) {
|
|
173
|
+
if (value == null) return value;
|
|
174
|
+
switch (schema.kind) {
|
|
175
|
+
case "value": return value;
|
|
176
|
+
case "binary": return normalizeBinary(value);
|
|
177
|
+
case "list":
|
|
178
|
+
if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
|
|
179
|
+
return value.map((item) => fromCborWireValue(item, schema.value));
|
|
180
|
+
case "map": return Object.fromEntries(entriesOf(value).map(([key, item]) => {
|
|
181
|
+
const normalizedKey = schema.key === "int" ? toIntegerKey(key) : String(key);
|
|
182
|
+
return [String(normalizedKey), fromCborWireValue(item, schema.value)];
|
|
183
|
+
}));
|
|
184
|
+
case "object": {
|
|
185
|
+
const input = objectOf(value);
|
|
186
|
+
const output = { ...input };
|
|
187
|
+
for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = fromCborWireValue(input[field], fieldSchema);
|
|
188
|
+
return output;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function normalizeCborValue(value) {
|
|
193
|
+
if (value instanceof Uint8Array) return value;
|
|
194
|
+
if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), normalizeCborValue(item)]));
|
|
195
|
+
if (Array.isArray(value)) return value.map(normalizeCborValue);
|
|
196
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeCborValue(item)]));
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/protocol/request.ts
|
|
201
|
+
function buildVrpcPath(serviceName, methodName) {
|
|
202
|
+
return `${encodeURIComponent(serviceName)}/${encodeURIComponent(methodName)}`;
|
|
203
|
+
}
|
|
204
|
+
function buildVrpcRequestBody(params) {
|
|
205
|
+
return JSON.stringify({ params: params ?? null });
|
|
206
|
+
}
|
|
207
|
+
async function encodeVrpcRequestBody(params, schema, cborCodec) {
|
|
208
|
+
if (!schema) return buildVrpcRequestBody(params);
|
|
209
|
+
if (!cborCodec) throw new Error("A cborCodec is required to encode a CBOR vRPC request.");
|
|
210
|
+
const bytes = await cborCodec.encode({ params: toCborWireValue(params, schema) });
|
|
211
|
+
if (!(bytes instanceof Uint8Array)) throw new Error("cborCodec.encode() must return a Uint8Array.");
|
|
212
|
+
const body = new Uint8Array(bytes.byteLength);
|
|
213
|
+
body.set(bytes);
|
|
214
|
+
return body.buffer;
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/protocol/response.ts
|
|
218
|
+
function readEnvelopeError(payload) {
|
|
219
|
+
if (!payload || typeof payload !== "object") return payload;
|
|
220
|
+
return payload.error ?? payload;
|
|
221
|
+
}
|
|
222
|
+
function readEnvelopeResult(payload) {
|
|
223
|
+
if (!payload || typeof payload !== "object") return;
|
|
224
|
+
return payload.result;
|
|
225
|
+
}
|
|
226
|
+
function requireResponseHeader(headers, name) {
|
|
227
|
+
const value = headers.get(name);
|
|
228
|
+
if (!value) throw new Error(`Invalid vRPC response: missing ${name} header.`);
|
|
229
|
+
return value;
|
|
230
|
+
}
|
|
231
|
+
function readDecodedEnvelopeField(payload, field) {
|
|
232
|
+
if (payload instanceof Map) return payload.get(field);
|
|
233
|
+
if (payload && typeof payload === "object") return payload[field];
|
|
234
|
+
}
|
|
235
|
+
async function decodeVrpcResponsePayload(response, cborCodec, resultSchema) {
|
|
236
|
+
requireResponseHeader(response.headers, "vrpc-status");
|
|
237
|
+
assertValidVrpcServerHeader(response.headers.get("vrpc-server"));
|
|
238
|
+
const contentType = mediaTypeOf(requireResponseHeader(response.headers, "content-type"));
|
|
239
|
+
if (contentType === "application/vrpc+json") {
|
|
240
|
+
const text = await response.text();
|
|
241
|
+
if (!text) throw new Error("Invalid vRPC response: empty response body.");
|
|
242
|
+
try {
|
|
243
|
+
return JSON.parse(text);
|
|
244
|
+
} catch {
|
|
245
|
+
throw new Error("Invalid vRPC response: JSON body cannot be parsed.");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (contentType !== "application/vrpc+cbor") throw new Error(`Invalid vRPC response content-type: ${contentType || "empty"}.`);
|
|
249
|
+
if (!resultSchema) throw new Error("Invalid vRPC response: unexpected CBOR body for a JSON method.");
|
|
250
|
+
if (!cborCodec) throw new Error("A cborCodec is required to decode a CBOR vRPC response.");
|
|
251
|
+
const decoded = await cborCodec.decode(new Uint8Array(await response.arrayBuffer()));
|
|
252
|
+
const result = readDecodedEnvelopeField(decoded, "result");
|
|
253
|
+
const error = readDecodedEnvelopeField(decoded, "error");
|
|
254
|
+
return {
|
|
255
|
+
result: fromCborWireValue(result, resultSchema),
|
|
256
|
+
error: normalizeCborValue(error)
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
function normalizeResponseHeaders(headers) {
|
|
260
|
+
if (!headers) return new Headers();
|
|
261
|
+
if (headers instanceof Headers) return new Headers(headers);
|
|
262
|
+
if (Array.isArray(headers)) return new Headers(headers.map(([key, value]) => [key, String(value)]));
|
|
263
|
+
const normalized = new Headers();
|
|
264
|
+
for (const [key, rawValue] of Object.entries(headers)) {
|
|
265
|
+
if (rawValue == null) continue;
|
|
266
|
+
const values = Array.isArray(rawValue) ? rawValue : [rawValue];
|
|
267
|
+
for (const value of values) normalized.append(key, String(value));
|
|
268
|
+
}
|
|
269
|
+
return normalized;
|
|
270
|
+
}
|
|
271
|
+
function buildResponse(responseLike) {
|
|
272
|
+
const response = new Response(null, {
|
|
273
|
+
status: responseLike.status,
|
|
274
|
+
statusText: responseLike.statusText,
|
|
275
|
+
headers: normalizeResponseHeaders(responseLike.headers)
|
|
276
|
+
});
|
|
277
|
+
try {
|
|
278
|
+
Object.defineProperty(response, "url", {
|
|
279
|
+
value: responseLike.url || "",
|
|
280
|
+
configurable: true
|
|
281
|
+
});
|
|
282
|
+
} catch {}
|
|
283
|
+
return response;
|
|
284
|
+
}
|
|
285
|
+
function resolveVrpcResponse(responseLike, payload) {
|
|
286
|
+
const response = buildResponse(responseLike);
|
|
287
|
+
const vrpcStatus = response.headers.get("vrpc-status");
|
|
288
|
+
const statusText = response.statusText || "";
|
|
289
|
+
const url = responseLike.url || response.url || "";
|
|
290
|
+
const method = responseLike.method || "POST";
|
|
291
|
+
if (response.ok && vrpcStatus === "OK") return {
|
|
292
|
+
response,
|
|
293
|
+
parsed: {
|
|
294
|
+
ok: true,
|
|
295
|
+
status: response.status,
|
|
296
|
+
statusText,
|
|
297
|
+
vrpcStatus: "OK",
|
|
298
|
+
headers: response.headers,
|
|
299
|
+
url,
|
|
300
|
+
method,
|
|
301
|
+
payload,
|
|
302
|
+
result: payload.result,
|
|
303
|
+
error: null
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
return {
|
|
307
|
+
response,
|
|
308
|
+
parsed: {
|
|
309
|
+
ok: false,
|
|
310
|
+
status: response.status,
|
|
311
|
+
statusText,
|
|
312
|
+
vrpcStatus,
|
|
313
|
+
headers: response.headers,
|
|
314
|
+
url,
|
|
315
|
+
method,
|
|
316
|
+
payload,
|
|
317
|
+
result: readEnvelopeResult(payload),
|
|
318
|
+
error: readEnvelopeError(payload)
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function parseVrpcResponse(responseLike, payload) {
|
|
323
|
+
return resolveVrpcResponse(responseLike, payload).parsed;
|
|
324
|
+
}
|
|
325
|
+
function unwrapVrpcResponse(responseLike, payload) {
|
|
326
|
+
const { response, parsed } = resolveVrpcResponse(responseLike, payload);
|
|
327
|
+
if (!parsed.ok) throw new VrpcInvokeError(response, parsed.error, {
|
|
328
|
+
url: parsed.url,
|
|
329
|
+
method: parsed.method
|
|
330
|
+
});
|
|
331
|
+
return parsed.result;
|
|
332
|
+
}
|
|
333
|
+
//#endregion
|
|
334
|
+
//#region src/core/invoke-args.ts
|
|
335
|
+
function normalizeInvokeRequest(request) {
|
|
336
|
+
return {
|
|
337
|
+
serviceName: request.serviceName,
|
|
338
|
+
methodName: request.methodName,
|
|
339
|
+
params: request.params ?? null,
|
|
340
|
+
options: request.options
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/core/create-vrpc-client.ts
|
|
345
|
+
function buildDefaultTrace(traceMode) {
|
|
346
|
+
const trace = { id: generateVrpcId() };
|
|
347
|
+
if (traceMode === "direct") trace.span = generateVrpcSpan();
|
|
348
|
+
return trace;
|
|
349
|
+
}
|
|
350
|
+
function assertWireSpec(serviceName, methodName, wire) {
|
|
351
|
+
if (!wire) return;
|
|
352
|
+
if (!wire.arguments && !wire.result) throw new Error(`Invalid vRPC wire spec for ${serviceName}/${methodName}: wire is empty.`);
|
|
353
|
+
}
|
|
354
|
+
function requireCborCodec(serviceName, methodName, wire, cborCodec) {
|
|
355
|
+
if (wire && !cborCodec) throw new Error(`CBOR is required for ${serviceName}/${methodName}, but no cborCodec was configured. Pass cborCodec to createVrpcClient().`);
|
|
356
|
+
}
|
|
357
|
+
function createVrpcClient(options) {
|
|
358
|
+
const { prefixUrl, clientInfo, traceMode = "portal", cborCodec, fetchImpl, transport, interceptors, ...baseOptions } = options;
|
|
359
|
+
const core = createClientCore({
|
|
360
|
+
prefixUrl,
|
|
361
|
+
baseOptions,
|
|
362
|
+
fetchImpl,
|
|
363
|
+
transport,
|
|
364
|
+
interceptors,
|
|
365
|
+
splitRequestOptions: splitVrpcRequestOptions,
|
|
366
|
+
prepareRequest: async (request, helpers) => {
|
|
367
|
+
const resolvedRequest = normalizeInvokeRequest(request);
|
|
368
|
+
const requestOptions = helpers.splitRequestOptions(resolvedRequest.options);
|
|
369
|
+
const wire = requestOptions.wire;
|
|
370
|
+
assertWireSpec(resolvedRequest.serviceName, resolvedRequest.methodName, wire);
|
|
371
|
+
requireCborCodec(resolvedRequest.serviceName, resolvedRequest.methodName, wire, cborCodec);
|
|
372
|
+
assertNoReservedVrpcHeaders(helpers.baseOptions.headers, requestOptions.headers);
|
|
373
|
+
const timeoutMs = requestOptions.timeoutMs ?? helpers.baseOptions.timeoutMs;
|
|
374
|
+
const trace = requestOptions.trace ?? buildDefaultTrace(traceMode);
|
|
375
|
+
const requestUsesCbor = Boolean(wire?.arguments);
|
|
376
|
+
const responseUsesCbor = Boolean(wire?.result);
|
|
377
|
+
const protocolHeaders = buildVrpcHeaders({
|
|
378
|
+
clientInfo,
|
|
379
|
+
trace,
|
|
380
|
+
timeoutMs,
|
|
381
|
+
requestUsesCbor,
|
|
382
|
+
responseUsesCbor
|
|
383
|
+
});
|
|
384
|
+
const finalHeaders = mergeHeaders(helpers.baseOptions.headers, requestOptions.headers, protocolHeaders);
|
|
385
|
+
const body = await encodeVrpcRequestBody(resolvedRequest.params, wire?.arguments, cborCodec);
|
|
386
|
+
const path = buildVrpcPath(resolvedRequest.serviceName, resolvedRequest.methodName);
|
|
387
|
+
const url = buildRequestUrl(helpers.prefixUrl, path);
|
|
388
|
+
const resolvedRequestInit = {
|
|
389
|
+
credentials: "omit",
|
|
390
|
+
...helpers.baseOptions.requestInit,
|
|
391
|
+
...requestOptions.requestInit
|
|
392
|
+
};
|
|
393
|
+
const resolvedOptions = {
|
|
394
|
+
headers: finalHeaders,
|
|
395
|
+
timeoutMs,
|
|
396
|
+
requestInit: resolvedRequestInit,
|
|
397
|
+
suppressGlobalToast: requestOptions.suppressGlobalToast ?? helpers.baseOptions.suppressGlobalToast,
|
|
398
|
+
trace,
|
|
399
|
+
wire
|
|
400
|
+
};
|
|
401
|
+
return {
|
|
402
|
+
timeoutMs,
|
|
403
|
+
fallbackMethod: "POST",
|
|
404
|
+
fallbackHeaders: finalHeaders,
|
|
405
|
+
fallbackBody: body,
|
|
406
|
+
context: {
|
|
407
|
+
url,
|
|
408
|
+
init: {
|
|
409
|
+
...resolvedRequestInit,
|
|
410
|
+
method: "POST",
|
|
411
|
+
headers: finalHeaders,
|
|
412
|
+
body
|
|
413
|
+
},
|
|
414
|
+
request: resolvedRequest,
|
|
415
|
+
options: resolvedOptions
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
},
|
|
419
|
+
parseResponse: (response, context) => decodeVrpcResponsePayload(response, cborCodec, context.options.wire?.result),
|
|
420
|
+
validateRequest: (_context, requestMeta) => {
|
|
421
|
+
if (requestMeta.method !== "POST") throw new Error(`Unsupported method: ${requestMeta.method}, only POST is allowed.`);
|
|
422
|
+
},
|
|
423
|
+
assertResponse: (response, payload, _context, requestMeta) => {
|
|
424
|
+
unwrapVrpcResponse({
|
|
425
|
+
status: response.status,
|
|
426
|
+
statusText: response.statusText,
|
|
427
|
+
headers: response.headers,
|
|
428
|
+
url: requestMeta.url,
|
|
429
|
+
method: requestMeta.method
|
|
430
|
+
}, payload);
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
async function invoke(request) {
|
|
434
|
+
return (await core.execute(request)).result;
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
invoke,
|
|
438
|
+
use: core.use
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
//#endregion
|
|
442
|
+
export { DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY, HTTP_TIMEOUT_ERROR_CODE, HttpInvokeError, HttpTimeoutError, VRPC_CBOR_CONTENT_TYPE, VRPC_JSON_CONTENT_TYPE, VrpcInvokeError, buildVrpcHeaders, buildVrpcPath, buildVrpcRequestBody, createFetchTransport, createVrpcClient, decodeVrpcResponsePayload, encodeVrpcRequestBody, generateClientInstanceId, generateVrpcId, generateVrpcSpan, getClientInstanceId, parseVrpcResponse, unwrapVrpcResponse };
|
package/dist/http.cjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_request_options = require("./request-options-2HZzkj4w.cjs");
|
|
3
|
+
//#region src/core/create-http-client.ts
|
|
4
|
+
function resolveJsonBody(request) {
|
|
5
|
+
if (request.json !== void 0 && request.body !== void 0) throw new Error("Request json and body cannot be used together.");
|
|
6
|
+
if (request.json !== void 0) return JSON.stringify(request.json);
|
|
7
|
+
return request.body;
|
|
8
|
+
}
|
|
9
|
+
function createHttpClient(options) {
|
|
10
|
+
const { prefixUrl, fetchImpl, transport, interceptors, ...baseOptions } = options;
|
|
11
|
+
const core = require_request_options.createClientCore({
|
|
12
|
+
prefixUrl,
|
|
13
|
+
baseOptions,
|
|
14
|
+
fetchImpl,
|
|
15
|
+
transport,
|
|
16
|
+
interceptors,
|
|
17
|
+
splitRequestOptions: require_request_options.splitHttpRequestOptions,
|
|
18
|
+
prepareRequest: (request, helpers) => {
|
|
19
|
+
const requestOptions = helpers.splitRequestOptions(request.options);
|
|
20
|
+
const method = String(request.method || "GET").toUpperCase();
|
|
21
|
+
const url = require_request_options.appendQueryToUrl(require_request_options.buildRequestUrl(helpers.prefixUrl, request.path), request.query);
|
|
22
|
+
const finalHeaders = require_request_options.mergeHeaders(helpers.baseOptions.headers, requestOptions.headers);
|
|
23
|
+
const body = resolveJsonBody(request);
|
|
24
|
+
if (request.json !== void 0 && !finalHeaders.has("content-type")) finalHeaders.set("content-type", "application/json");
|
|
25
|
+
const resolvedRequestInit = {
|
|
26
|
+
...helpers.baseOptions.requestInit,
|
|
27
|
+
...requestOptions.requestInit
|
|
28
|
+
};
|
|
29
|
+
const timeoutMs = requestOptions.timeoutMs ?? helpers.baseOptions.timeoutMs;
|
|
30
|
+
const resolvedOptions = {
|
|
31
|
+
headers: finalHeaders,
|
|
32
|
+
timeoutMs,
|
|
33
|
+
requestInit: resolvedRequestInit,
|
|
34
|
+
suppressGlobalToast: requestOptions.suppressGlobalToast ?? helpers.baseOptions.suppressGlobalToast
|
|
35
|
+
};
|
|
36
|
+
const init = {
|
|
37
|
+
...resolvedRequestInit,
|
|
38
|
+
method,
|
|
39
|
+
headers: finalHeaders
|
|
40
|
+
};
|
|
41
|
+
if (body !== void 0) init.body = body;
|
|
42
|
+
return {
|
|
43
|
+
timeoutMs,
|
|
44
|
+
fallbackMethod: method,
|
|
45
|
+
fallbackHeaders: finalHeaders,
|
|
46
|
+
fallbackBody: body,
|
|
47
|
+
context: {
|
|
48
|
+
url,
|
|
49
|
+
init,
|
|
50
|
+
request,
|
|
51
|
+
options: resolvedOptions
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
assertResponse: (response, payload, _context, requestMeta) => {
|
|
56
|
+
if (!response.ok) throw new require_request_options.HttpInvokeError(response, payload, requestMeta);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
return {
|
|
60
|
+
request: core.execute,
|
|
61
|
+
use: core.use
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
exports.HTTP_TIMEOUT_ERROR_CODE = require_request_options.HTTP_TIMEOUT_ERROR_CODE;
|
|
66
|
+
exports.HttpInvokeError = require_request_options.HttpInvokeError;
|
|
67
|
+
exports.HttpTimeoutError = require_request_options.HttpTimeoutError;
|
|
68
|
+
exports.createFetchTransport = require_request_options.createFetchTransport;
|
|
69
|
+
exports.createHttpClient = createHttpClient;
|
package/dist/http.d.cts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
//#region src/contracts/types.d.ts
|
|
2
|
+
type HttpRequestInit = Omit<RequestInit, "method" | "body" | "headers">;
|
|
3
|
+
type HttpQueryPrimitive = string | number | boolean;
|
|
4
|
+
type HttpQueryValue = HttpQueryPrimitive | HttpQueryPrimitive[] | null | undefined;
|
|
5
|
+
type HttpQueryParams = Record<string, HttpQueryValue>;
|
|
6
|
+
type HttpRequestOptions = {
|
|
7
|
+
headers?: HeadersInit;
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
requestInit?: HttpRequestInit;
|
|
10
|
+
suppressGlobalToast?: boolean;
|
|
11
|
+
};
|
|
12
|
+
type HttpRequestConfig = {
|
|
13
|
+
path: string;
|
|
14
|
+
method?: string;
|
|
15
|
+
query?: HttpQueryParams | URLSearchParams;
|
|
16
|
+
json?: unknown;
|
|
17
|
+
body?: BodyInit | null;
|
|
18
|
+
options?: HttpRequestOptions;
|
|
19
|
+
};
|
|
20
|
+
type HttpClientOptions = HttpRequestOptions & {
|
|
21
|
+
prefixUrl: string | URL;
|
|
22
|
+
fetchImpl?: typeof fetch;
|
|
23
|
+
transport?: HttpTransport;
|
|
24
|
+
interceptors?: HttpInterceptor[];
|
|
25
|
+
};
|
|
26
|
+
type HttpInvokeContext = {
|
|
27
|
+
url: string;
|
|
28
|
+
init: RequestInit;
|
|
29
|
+
request: HttpRequestConfig;
|
|
30
|
+
options: HttpRequestOptions;
|
|
31
|
+
};
|
|
32
|
+
type HttpInterceptor = {
|
|
33
|
+
beforeRequest?: (context: HttpInvokeContext) => void | Promise<void>;
|
|
34
|
+
afterResponse?: (response: Response, context: HttpInvokeContext) => void | Promise<void>;
|
|
35
|
+
onError?: (error: unknown, context: HttpInvokeContext) => void | Promise<void>;
|
|
36
|
+
};
|
|
37
|
+
type HttpTransportRequest = {
|
|
38
|
+
url: string;
|
|
39
|
+
init: RequestInit;
|
|
40
|
+
method: string;
|
|
41
|
+
headers: HeadersInit;
|
|
42
|
+
body?: BodyInit | null;
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
signal?: AbortSignal | null;
|
|
45
|
+
};
|
|
46
|
+
type HttpTransportResponse = {
|
|
47
|
+
status: number;
|
|
48
|
+
statusText?: string;
|
|
49
|
+
headers: Headers;
|
|
50
|
+
body: Uint8Array | null;
|
|
51
|
+
url: string;
|
|
52
|
+
};
|
|
53
|
+
type HttpTransport = {
|
|
54
|
+
request: (request: HttpTransportRequest) => Promise<HttpTransportResponse>;
|
|
55
|
+
close?: () => Promise<void> | void;
|
|
56
|
+
};
|
|
57
|
+
type HttpClient = {
|
|
58
|
+
request: <TResponse = unknown>(request: HttpRequestConfig) => Promise<TResponse>;
|
|
59
|
+
use: (interceptor: HttpInterceptor) => void;
|
|
60
|
+
};
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/contracts/errors.d.ts
|
|
63
|
+
type HttpErrorPayload = {
|
|
64
|
+
type?: string;
|
|
65
|
+
code?: string;
|
|
66
|
+
message?: string;
|
|
67
|
+
reason?: string;
|
|
68
|
+
detail?: string;
|
|
69
|
+
};
|
|
70
|
+
type HttpErrorRequestMeta = {
|
|
71
|
+
url?: string;
|
|
72
|
+
method?: string;
|
|
73
|
+
};
|
|
74
|
+
declare const HTTP_TIMEOUT_ERROR_CODE: "HTTP_TIMEOUT";
|
|
75
|
+
declare class HttpTimeoutError extends Error {
|
|
76
|
+
code: typeof HTTP_TIMEOUT_ERROR_CODE;
|
|
77
|
+
timeoutMs: number;
|
|
78
|
+
constructor(timeoutMs: number);
|
|
79
|
+
}
|
|
80
|
+
declare class HttpInvokeError extends Error {
|
|
81
|
+
type?: string;
|
|
82
|
+
code?: string;
|
|
83
|
+
reason?: string;
|
|
84
|
+
detail?: string;
|
|
85
|
+
status: number;
|
|
86
|
+
statusText: string;
|
|
87
|
+
responseHeaders: Headers;
|
|
88
|
+
payload: unknown;
|
|
89
|
+
url: string;
|
|
90
|
+
method: string;
|
|
91
|
+
constructor(response: Response, payload: unknown, requestMeta?: HttpErrorRequestMeta);
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/core/create-http-client.d.ts
|
|
95
|
+
declare function createHttpClient(options: HttpClientOptions): HttpClient;
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/transports/fetch-transport.d.ts
|
|
98
|
+
declare function createFetchTransport(fetchImpl?: typeof fetch): HttpTransport;
|
|
99
|
+
//#endregion
|
|
100
|
+
export { HTTP_TIMEOUT_ERROR_CODE, type HttpClient, type HttpClientOptions, type HttpErrorPayload, type HttpInterceptor, type HttpInvokeContext, HttpInvokeError, type HttpQueryParams, type HttpQueryPrimitive, type HttpQueryValue, type HttpRequestConfig, type HttpRequestInit, type HttpRequestOptions, HttpTimeoutError, type HttpTransport, type HttpTransportRequest, type HttpTransportResponse, createFetchTransport, createHttpClient };
|