@graphql-mesh/transport-protobuf 0.0.0-stage → 0.7.2

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,429 @@
1
+ import { resolveBind, type MappingField, type ProtoType } from './mapping.js';
2
+
3
+ const WIRE_VARINT = 0;
4
+ const WIRE_64 = 1;
5
+ const WIRE_LEN = 2;
6
+ const WIRE_32 = 5;
7
+
8
+ export function encodeMessage(
9
+ fields: MappingField[],
10
+ args: Record<string, any>,
11
+ localRoot: Record<string, any> = args,
12
+ thisRoot?: Record<string, any>,
13
+ ): Uint8Array {
14
+ const chunks: Uint8Array[] = [];
15
+ for (const field of fields) {
16
+ writeField(chunks, field, args, localRoot, thisRoot);
17
+ }
18
+ return concat(chunks);
19
+ }
20
+
21
+ function resolveFieldValue(
22
+ bind: string | undefined,
23
+ args: Record<string, any>,
24
+ localRoot: Record<string, any>,
25
+ thisRoot?: Record<string, any>,
26
+ ): any {
27
+ if (bind == null || bind === '') return undefined;
28
+ if (bind.startsWith('$args') || bind.startsWith('$this')) {
29
+ return resolveBind(bind, args, thisRoot);
30
+ }
31
+ return resolveBind(bind, localRoot, thisRoot);
32
+ }
33
+
34
+ function writeField(
35
+ chunks: Uint8Array[],
36
+ field: MappingField,
37
+ args: Record<string, any>,
38
+ localRoot: Record<string, any>,
39
+ thisRoot?: Record<string, any>,
40
+ ) {
41
+ const type = field.type;
42
+ if (type.kind === 'message') {
43
+ let childRoot = localRoot;
44
+ if (field.bind != null && !field.bind.startsWith('$args') && !field.bind.startsWith('$this')) {
45
+ const fromLocal = resolveBind(field.bind, localRoot, thisRoot);
46
+ if (fromLocal != null && typeof fromLocal === 'object') {
47
+ childRoot = fromLocal;
48
+ }
49
+ }
50
+ const nestedFields = field.fields ?? type.fields;
51
+ const nested = encodeMessage(nestedFields, args, childRoot, thisRoot);
52
+ if (nested.length === 0) return;
53
+ writeTag(chunks, field.id, WIRE_LEN);
54
+ writeVarint(chunks, nested.length);
55
+ chunks.push(nested);
56
+ return;
57
+ }
58
+
59
+ if (type.kind === 'repeated') {
60
+ const list = resolveFieldValue(field.bind, args, localRoot, thisRoot);
61
+ if (!Array.isArray(list)) return;
62
+ const elementType: ProtoType =
63
+ type.element.kind === 'message' && field.fields?.length
64
+ ? { kind: 'message', fields: field.fields }
65
+ : type.element;
66
+ for (const item of list) {
67
+ writeValue(chunks, field.id, elementType, item);
68
+ }
69
+ return;
70
+ }
71
+
72
+ const value = resolveFieldValue(field.bind, args, localRoot, thisRoot);
73
+ if (value === undefined || value === null) return;
74
+ writeValue(chunks, field.id, type, value);
75
+ }
76
+
77
+ function writeValue(chunks: Uint8Array[], id: number, type: ProtoType, value: any) {
78
+ if (type.kind === 'scalar') {
79
+ switch (type.name) {
80
+ case 'bool':
81
+ writeTag(chunks, id, WIRE_VARINT);
82
+ writeVarint(chunks, value ? 1 : 0);
83
+ return;
84
+ case 'int32':
85
+ case 'uint32':
86
+ case 'int64':
87
+ case 'uint64':
88
+ writeTag(chunks, id, WIRE_VARINT);
89
+ writeVarint(chunks, toLongish(value));
90
+ return;
91
+ case 'sint32':
92
+ writeTag(chunks, id, WIRE_VARINT);
93
+ writeVarint(chunks, zigzag32(Number(value)));
94
+ return;
95
+ case 'sint64':
96
+ writeTag(chunks, id, WIRE_VARINT);
97
+ writeVarint(chunks, zigzag64(toLongish(value)));
98
+ return;
99
+ case 'fixed32':
100
+ case 'sfixed32':
101
+ writeTag(chunks, id, WIRE_32);
102
+ writeFixed32(chunks, Number(value) >>> 0);
103
+ return;
104
+ case 'fixed64':
105
+ case 'sfixed64':
106
+ writeTag(chunks, id, WIRE_64);
107
+ writeFixed64(chunks, toLongish(value));
108
+ return;
109
+ case 'float':
110
+ writeTag(chunks, id, WIRE_32);
111
+ writeFloat32(chunks, Number(value));
112
+ return;
113
+ case 'double':
114
+ writeTag(chunks, id, WIRE_64);
115
+ writeFloat64(chunks, Number(value));
116
+ return;
117
+ case 'string': {
118
+ const bytes = new TextEncoder().encode(String(value));
119
+ writeTag(chunks, id, WIRE_LEN);
120
+ writeVarint(chunks, bytes.length);
121
+ chunks.push(bytes);
122
+ return;
123
+ }
124
+ case 'bytes': {
125
+ const bytes =
126
+ value instanceof Uint8Array
127
+ ? value
128
+ : typeof value === 'string'
129
+ ? new TextEncoder().encode(value)
130
+ : new Uint8Array(value);
131
+ writeTag(chunks, id, WIRE_LEN);
132
+ writeVarint(chunks, bytes.length);
133
+ chunks.push(bytes);
134
+ return;
135
+ }
136
+ default:
137
+ throw new Error(`Unsupported scalar ${type.name}`);
138
+ }
139
+ }
140
+ if (type.kind === 'enum') {
141
+ const num =
142
+ typeof value === 'number'
143
+ ? value
144
+ : (type.values[String(value)] ?? type.values[String(value).toUpperCase()]);
145
+ if (num == null) {
146
+ throw new Error(`Unknown enum value ${value}`);
147
+ }
148
+ writeTag(chunks, id, WIRE_VARINT);
149
+ writeVarint(chunks, num);
150
+ return;
151
+ }
152
+ if (type.kind === 'message') {
153
+ const nested = encodeMessage(type.fields, value ?? {});
154
+ writeTag(chunks, id, WIRE_LEN);
155
+ writeVarint(chunks, nested.length);
156
+ chunks.push(nested);
157
+ return;
158
+ }
159
+ if (type.kind === 'map') {
160
+ // value should be object; each entry is a synthetic message key=1 value=2
161
+ const obj = value ?? {};
162
+ for (const [k, v] of Object.entries(obj)) {
163
+ const entry = encodeMessage(
164
+ [
165
+ { id: 1, type: type.key, bind: 'key' },
166
+ { id: 2, type: type.value, bind: 'value' },
167
+ ],
168
+ { key: k, value: v },
169
+ );
170
+ writeTag(chunks, id, WIRE_LEN);
171
+ writeVarint(chunks, entry.length);
172
+ chunks.push(entry);
173
+ }
174
+ }
175
+ }
176
+
177
+ export function decodeMessage(fields: MappingField[], data: Uint8Array): Record<string, any> {
178
+ const byId = new Map(fields.map(f => [f.id, f]));
179
+ const out: Record<string, any> = {};
180
+ // Absent repeated/map fields are empty collections in protobuf wire format.
181
+ for (const field of fields) {
182
+ const key = field.bind && !field.bind.startsWith('$') ? field.bind : `_${field.id}`;
183
+ if (field.type.kind === 'repeated') out[key] = [];
184
+ else if (field.type.kind === 'map') out[key] = {};
185
+ }
186
+ let i = 0;
187
+ while (i < data.length) {
188
+ const tag = readVarint(data, i);
189
+ i = tag.next;
190
+ const tagNum = Number(tag.value);
191
+ const id = tagNum >>> 3;
192
+ const wire = tagNum & 7;
193
+ const field = byId.get(id);
194
+ if (!field) {
195
+ i = skipWire(data, i, wire);
196
+ continue;
197
+ }
198
+ let typeForRead: ProtoType = field.type;
199
+ if (field.type.kind === 'message' && field.fields?.length) {
200
+ typeForRead = { kind: 'message', fields: field.fields };
201
+ } else if (
202
+ field.type.kind === 'repeated' &&
203
+ field.type.element.kind === 'message' &&
204
+ field.fields?.length
205
+ ) {
206
+ typeForRead = {
207
+ kind: 'repeated',
208
+ element: { kind: 'message', fields: field.fields },
209
+ };
210
+ }
211
+ const decoded = readValue(data, i, wire, typeForRead);
212
+ i = decoded.next;
213
+ const key = field.bind && !field.bind.startsWith('$') ? field.bind : `_${id}`;
214
+ if (field.type.kind === 'map') {
215
+ const entry = decoded.value as { key: any; value: any };
216
+ out[key] = out[key] ?? {};
217
+ out[key][entry.key] = entry.value;
218
+ } else if (field.type.kind === 'repeated') {
219
+ out[key] = out[key] ?? [];
220
+ out[key].push(decoded.value);
221
+ } else {
222
+ out[key] = decoded.value;
223
+ }
224
+ }
225
+ // Map enum numbers back to names when bind keys used
226
+ for (const field of fields) {
227
+ const key = field.bind && !field.bind.startsWith('$') ? field.bind : `_${field.id}`;
228
+ if (field.type.kind === 'enum' && out[key] != null && typeof out[key] === 'number') {
229
+ const name = Object.entries(field.type.values).find(([, n]) => n === out[key])?.[0];
230
+ if (name) out[key] = name;
231
+ }
232
+ if (
233
+ field.type.kind === 'repeated' &&
234
+ field.type.element.kind === 'enum' &&
235
+ Array.isArray(out[key])
236
+ ) {
237
+ const enumValues = field.type.element.values;
238
+ out[key] = out[key].map((n: any) => {
239
+ if (typeof n !== 'number') return n;
240
+ return Object.entries(enumValues).find(([, v]) => v === n)?.[0] ?? n;
241
+ });
242
+ }
243
+ }
244
+ return out;
245
+ }
246
+
247
+ function readValue(
248
+ data: Uint8Array,
249
+ i: number,
250
+ wire: number,
251
+ type: ProtoType,
252
+ ): { value: any; next: number; raw?: Uint8Array } {
253
+ if (type.kind === 'repeated') {
254
+ // element fields carried on parent MappingField are applied by caller via typeForRead
255
+ return readValue(data, i, wire, type.element);
256
+ }
257
+ if (type.kind === 'map') {
258
+ const len = readVarint(data, i);
259
+ const end = len.next + Number(len.value);
260
+ const raw = data.subarray(len.next, end);
261
+ const entry = decodeMessage(
262
+ [
263
+ { id: 1, type: type.key, bind: 'key' },
264
+ { id: 2, type: type.value, bind: 'value' },
265
+ ],
266
+ raw,
267
+ );
268
+ return { value: entry, next: end, raw };
269
+ }
270
+ if (
271
+ type.kind === 'message' ||
272
+ (type.kind === 'scalar' && (type.name === 'string' || type.name === 'bytes'))
273
+ ) {
274
+ const len = readVarint(data, i);
275
+ const end = len.next + Number(len.value);
276
+ const raw = data.subarray(len.next, end);
277
+ if (type.kind === 'scalar' && type.name === 'string') {
278
+ return { value: new TextDecoder().decode(raw), next: end, raw };
279
+ }
280
+ if (type.kind === 'scalar' && type.name === 'bytes') {
281
+ // graphql-scalars `Byte` validates `Buffer` instances (not bare Uint8Array).
282
+ return { value: Buffer.from(raw), next: end, raw };
283
+ }
284
+ if (type.kind !== 'message') {
285
+ throw new Error('Expected message type after length-delimited scalar branch');
286
+ }
287
+ return { value: decodeMessage(type.fields, raw), next: end, raw };
288
+ }
289
+ if (wire === WIRE_VARINT) {
290
+ const v = readVarint(data, i);
291
+ let value: number | bigint | boolean = v.value;
292
+ if (type.kind === 'scalar' && type.name === 'sint32') value = unzigzag32(Number(v.value));
293
+ else if (type.kind === 'scalar' && type.name === 'sint64') value = unzigzag64(v.value);
294
+ else if (type.kind === 'scalar' && type.name === 'bool') value = Number(v.value) !== 0;
295
+ else if (type.kind === 'enum') value = Number(v.value);
296
+ else if (
297
+ type.kind === 'scalar' &&
298
+ (type.name === 'int32' ||
299
+ type.name === 'uint32' ||
300
+ type.name === 'int64' ||
301
+ type.name === 'uint64')
302
+ ) {
303
+ // Prefer Number when safe for GraphQL Int / Float paths
304
+ const asNum = Number(v.value);
305
+ value = BigInt(asNum) === v.value && Number.isSafeInteger(asNum) ? asNum : v.value;
306
+ }
307
+ return { value, next: v.next };
308
+ }
309
+ if (wire === WIRE_32) {
310
+ const view = new DataView(data.buffer, data.byteOffset + i, 4);
311
+ let value: number;
312
+ if (type.kind === 'scalar' && type.name === 'float') value = view.getFloat32(0, true);
313
+ else value = view.getUint32(0, true);
314
+ return { value, next: i + 4 };
315
+ }
316
+ if (wire === WIRE_64) {
317
+ const view = new DataView(data.buffer, data.byteOffset + i, 8);
318
+ let value: number | bigint;
319
+ if (type.kind === 'scalar' && type.name === 'double') value = view.getFloat64(0, true);
320
+ else value = view.getBigUint64(0, true);
321
+ return { value, next: i + 8 };
322
+ }
323
+ if (wire === WIRE_LEN) {
324
+ const len = readVarint(data, i);
325
+ const n = Number(len.value);
326
+ return { value: data.subarray(len.next, len.next + n), next: len.next + n };
327
+ }
328
+ throw new Error(`Unsupported wire type ${wire}`);
329
+ }
330
+
331
+ function skipWire(data: Uint8Array, i: number, wire: number): number {
332
+ if (wire === WIRE_VARINT) return readVarint(data, i).next;
333
+ if (wire === WIRE_64) return i + 8;
334
+ if (wire === WIRE_32) return i + 4;
335
+ if (wire === WIRE_LEN) {
336
+ const len = readVarint(data, i);
337
+ return len.next + Number(len.value);
338
+ }
339
+ throw new Error(`Cannot skip wire type ${wire}`);
340
+ }
341
+
342
+ function writeTag(chunks: Uint8Array[], id: number, wire: number) {
343
+ writeVarint(chunks, (id << 3) | wire);
344
+ }
345
+
346
+ function writeVarint(chunks: Uint8Array[], value: number | bigint) {
347
+ let n = typeof value === 'bigint' ? value : BigInt(Math.trunc(Number(value)));
348
+ if (n < 0n) {
349
+ n = (1n << 64n) + n;
350
+ }
351
+ const out: number[] = [];
352
+ while (n > 0x7fn) {
353
+ out.push(Number((n & 0x7fn) | 0x80n));
354
+ n >>= 7n;
355
+ }
356
+ out.push(Number(n));
357
+ chunks.push(Uint8Array.from(out));
358
+ }
359
+
360
+ function readVarint(data: Uint8Array, i: number): { value: bigint; next: number } {
361
+ let result = 0n;
362
+ let shift = 0n;
363
+ let pos = i;
364
+ while (pos < data.length) {
365
+ const b = data[pos++];
366
+ result |= BigInt(b & 0x7f) << shift;
367
+ if ((b & 0x80) === 0) break;
368
+ shift += 7n;
369
+ }
370
+ return { value: result, next: pos };
371
+ }
372
+
373
+ function writeFixed32(chunks: Uint8Array[], value: number) {
374
+ const buf = new Uint8Array(4);
375
+ new DataView(buf.buffer).setUint32(0, value, true);
376
+ chunks.push(buf);
377
+ }
378
+
379
+ function writeFixed64(chunks: Uint8Array[], value: number | bigint) {
380
+ const buf = new Uint8Array(8);
381
+ new DataView(buf.buffer).setBigUint64(0, BigInt(value), true);
382
+ chunks.push(buf);
383
+ }
384
+
385
+ function writeFloat32(chunks: Uint8Array[], value: number) {
386
+ const buf = new Uint8Array(4);
387
+ new DataView(buf.buffer).setFloat32(0, value, true);
388
+ chunks.push(buf);
389
+ }
390
+
391
+ function writeFloat64(chunks: Uint8Array[], value: number) {
392
+ const buf = new Uint8Array(8);
393
+ new DataView(buf.buffer).setFloat64(0, value, true);
394
+ chunks.push(buf);
395
+ }
396
+
397
+ function zigzag32(n: number): number {
398
+ return (n << 1) ^ (n >> 31);
399
+ }
400
+
401
+ function zigzag64(n: number | bigint): bigint {
402
+ const v = BigInt(n);
403
+ return (v << 1n) ^ (v >> 63n);
404
+ }
405
+
406
+ function unzigzag32(n: number): number {
407
+ return (n >>> 1) ^ -(n & 1);
408
+ }
409
+
410
+ function unzigzag64(n: bigint): bigint {
411
+ return (n >> 1n) ^ -(n & 1n);
412
+ }
413
+
414
+ function toLongish(value: any): number | bigint {
415
+ if (typeof value === 'bigint') return value;
416
+ if (typeof value === 'string') return BigInt(value);
417
+ return Math.trunc(Number(value));
418
+ }
419
+
420
+ function concat(chunks: Uint8Array[]): Uint8Array {
421
+ const len = chunks.reduce((a, c) => a + c.length, 0);
422
+ const out = new Uint8Array(len);
423
+ let o = 0;
424
+ for (const c of chunks) {
425
+ out.set(c, o);
426
+ o += c.length;
427
+ }
428
+ return out;
429
+ }
@@ -0,0 +1,56 @@
1
+ import type { GraphQLResolveInfo } from 'graphql';
2
+ import type { MeshFetch } from '@graphql-mesh/types';
3
+ import { fetch as defaultFetch } from '@whatwg-node/fetch';
4
+
5
+ export function isHttpLocation(location: string): boolean {
6
+ return /^https?:\/\//i.test(location);
7
+ }
8
+
9
+ export function buildRpcPath(service: string | undefined, method: string): string {
10
+ const svc = service?.replace(/^\//, '') || '';
11
+ if (!svc) return `/${method}`;
12
+ return `/${svc}/${method}`;
13
+ }
14
+
15
+ export function resolveHttpUrl(
16
+ location: string,
17
+ service: string | undefined,
18
+ method: string,
19
+ ): string {
20
+ const base = location.replace(/\/$/, '');
21
+ return `${base}${buildRpcPath(service, method)}`;
22
+ }
23
+
24
+ /** Default Connect unary binary content type; override via `@transport(headers:)` (e.g. Twirp `application/protobuf`). */
25
+ export const DEFAULT_PROTOBUF_HTTP_CONTENT_TYPE = 'application/proto';
26
+
27
+ export async function httpProtobufUnary(opts: {
28
+ url: string;
29
+ body: Uint8Array;
30
+ headers?: Record<string, string>;
31
+ signal?: AbortSignal;
32
+ fetchFn?: MeshFetch;
33
+ context?: any;
34
+ info?: GraphQLResolveInfo;
35
+ }): Promise<Uint8Array> {
36
+ const fetchFn = opts.fetchFn || defaultFetch;
37
+ const res = await fetchFn(
38
+ opts.url,
39
+ {
40
+ method: 'POST',
41
+ headers: {
42
+ 'content-type': DEFAULT_PROTOBUF_HTTP_CONTENT_TYPE,
43
+ ...opts.headers,
44
+ },
45
+ body: opts.body as any,
46
+ signal: opts.signal,
47
+ },
48
+ opts.context,
49
+ opts.info as any,
50
+ );
51
+ if (!res.ok) {
52
+ const text = await res.text().catch(() => '');
53
+ throw new Error(`Protobuf HTTP ${res.status}: ${text || res.statusText}`);
54
+ }
55
+ return new Uint8Array(await res.arrayBuffer());
56
+ }