grpc-dc 0.44.0 → 0.46.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,706 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Descriptor-driven struct codec (layout v1, DCS1): the
4
+ // packed struct format from SPEC.md, implemented over the
5
+ // dynamic model (dynamic.js) so browser runtimes transcode
6
+ // protobuf <-> struct without a native bridge. Byte-identical
7
+ // to the shared Rust implementation (conformance/struct).
8
+
9
+ import { FieldType, GenericMessage, parseDescriptorSet } from "./dynamic.js";
10
+ import { StatusCode, StatusError } from "./codec.js";
11
+
12
+ /** HEADERS metadata key a client sends to request the struct codec for a call. */
13
+ export const STRUCT_CODEC_HEADER = "dc-codec";
14
+ export const STRUCT_CODEC_V1 = "struct-v1";
15
+
16
+ const T = FieldType;
17
+ const FIXED32 = new Set([T.FLOAT, T.FIXED32, T.SFIXED32]);
18
+
19
+ function fingerprint(fullName) {
20
+ let h = 2166136261;
21
+ for (let i = 0; i < fullName.length; i++) {
22
+ h = Math.imul(h ^ fullName.charCodeAt(i), 16777619);
23
+ }
24
+ return h >>> 0;
25
+ }
26
+
27
+ function slotSize(field) {
28
+ return FIXED32.has(field.type) ? 4 : 8;
29
+ }
30
+
31
+ function asI64(v) {
32
+ if (typeof v === "bigint") return v;
33
+ if (typeof v === "boolean") return v ? 1n : 0n;
34
+ if (typeof v === "number") return BigInt(Math.trunc(v));
35
+ return 0n;
36
+ }
37
+
38
+ function asU64(v) {
39
+ return asI64(v) & 0xffffffffffffffffn;
40
+ }
41
+
42
+ function asF64(v) {
43
+ if (typeof v === "number") return v;
44
+ if (typeof v === "bigint") return Number(v);
45
+ if (typeof v === "boolean") return v ? 1 : 0;
46
+ return 0;
47
+ }
48
+
49
+ function bytesOf(field, value) {
50
+ if (field.type === T.STRING && typeof value === "string") return new TextEncoder().encode(value);
51
+ if (value instanceof Uint8Array) return value;
52
+ if (typeof value === "string") return new TextEncoder().encode(value);
53
+ throw StatusError.invalidArgument(`value does not match field ${field.name} type ${field.type}`);
54
+ }
55
+
56
+ function nonzero(field, value) {
57
+ switch (field.type) {
58
+ case T.STRING:
59
+ case T.BYTES:
60
+ if (typeof value === "string") return value.length > 0;
61
+ if (value instanceof Uint8Array) return value.length > 0;
62
+ return false;
63
+ case T.MESSAGE:
64
+ return value instanceof GenericMessage;
65
+ case T.BOOL:
66
+ return value === true || asI64(value) !== 0n;
67
+ case T.FLOAT:
68
+ case T.DOUBLE:
69
+ return asF64(value) !== 0;
70
+ default:
71
+ return asI64(value) !== 0n || asU64(value) !== 0n;
72
+ }
73
+ }
74
+
75
+ function sortedFields(model) {
76
+ return [...model.fields.values()].sort((a, b) => a.number - b.number);
77
+ }
78
+
79
+ function mapModel(field, fileModel) {
80
+ if (field.type !== T.MESSAGE || !field.repeated) return null;
81
+ const model = fileModel.messages.get(field.typeName);
82
+ return model && model.mapEntry ? model : null;
83
+ }
84
+
85
+ function isMap(field, fileModel) {
86
+ return mapModel(field, fileModel) !== null;
87
+ }
88
+
89
+ function defaultValue(field) {
90
+ switch (field.type) {
91
+ case T.STRING: return "";
92
+ case T.BYTES: return new Uint8Array(0);
93
+ case T.BOOL: return false;
94
+ case T.FLOAT:
95
+ case T.DOUBLE: return 0;
96
+ case T.MESSAGE: return new GenericMessage();
97
+ default: return 0n;
98
+ }
99
+ }
100
+
101
+ function keyCmp(kf, a, b) {
102
+ if (kf.type === T.STRING) {
103
+ const av = typeof a === "string" ? a : "";
104
+ const bv = typeof b === "string" ? b : "";
105
+ return av < bv ? -1 : av > bv ? 1 : 0;
106
+ }
107
+ if (kf.type === T.BOOL || kf.type === T.UINT32 || kf.type === T.UINT64 ||
108
+ kf.type === T.FIXED32 || kf.type === T.FIXED64) {
109
+ const av = asU64(a), bv = asU64(b);
110
+ return av < bv ? -1 : av > bv ? 1 : 0;
111
+ }
112
+ const av = asI64(a), bv = asI64(b);
113
+ return av < bv ? -1 : av > bv ? 1 : 0;
114
+ }
115
+
116
+ function mapEntries(field, values, entryModel) {
117
+ const kf = entryModel.fields.get(1);
118
+ const vf = entryModel.fields.get(2);
119
+ const entries = values.map((entry) => {
120
+ const key = entry.get(1);
121
+ if (key === undefined) {
122
+ throw StatusError.invalidArgument(`map field ${field.name} entry missing key`);
123
+ }
124
+ const val = entry.get(2) ?? defaultValue(vf);
125
+ return [key, val];
126
+ });
127
+ entries.sort((a, b) => keyCmp(kf, a[0], b[0]));
128
+ return entries;
129
+ }
130
+
131
+ function valueSize(field, value, fileModel) {
132
+ switch (field.type) {
133
+ case T.STRING:
134
+ case T.BYTES:
135
+ return bytesOf(field, value).length;
136
+ case T.MESSAGE: {
137
+ const nested = fileModel.messages.get(field.typeName);
138
+ return encodeStruct(nested, value, fileModel).length;
139
+ }
140
+ default:
141
+ return FIXED32.has(field.type) ? 4 : 8;
142
+ }
143
+ }
144
+
145
+ function fieldPresent(field, msg, fileModel) {
146
+ const values = msg.getAll(field.number);
147
+ if (isMap(field, fileModel) || field.repeated) return values.length > 0;
148
+ return values.length > 0 && nonzero(field, values[0]);
149
+ }
150
+
151
+ function structSize(model, msg, fileModel) {
152
+ const fields = sortedFields(model);
153
+ const words = Math.max(1, Math.floor((fields.length + 31) / 32));
154
+ let size = 12 + 4 * words;
155
+ for (const f of fields) size += slotSize(f);
156
+ for (const field of fields) {
157
+ const values = msg.getAll(field.number);
158
+ if (isMap(field, fileModel)) {
159
+ const entryModel = mapModel(field, fileModel);
160
+ const kf = entryModel.fields.get(1);
161
+ const vf = entryModel.fields.get(2);
162
+ for (const [k, v] of mapEntries(field, values, entryModel)) {
163
+ size += 8 + valueSize(kf, k, fileModel) + valueSize(vf, v, fileModel);
164
+ }
165
+ } else if (field.repeated) {
166
+ if (!values.length) continue;
167
+ if (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) {
168
+ size += 8 * values.length;
169
+ }
170
+ for (const v of values) size += valueSize(field, v, fileModel);
171
+ } else if (
172
+ (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) &&
173
+ fieldPresent(field, msg, fileModel)
174
+ ) {
175
+ size += valueSize(field, values[0], fileModel);
176
+ }
177
+ }
178
+ for (const chunk of msg.unknown ?? []) size += chunk.length;
179
+ return size;
180
+ }
181
+
182
+ function putU32(buf, off, v) {
183
+ new DataView(buf.buffer, buf.byteOffset).setUint32(off, v >>> 0, true);
184
+ }
185
+
186
+ function putU64(buf, off, v) {
187
+ new DataView(buf.buffer, buf.byteOffset).setBigUint64(off, asU64(v), true);
188
+ }
189
+
190
+ function getU32(data, off) {
191
+ if (off + 4 > data.length) throw StatusError.invalidArgument("struct codec: out of bounds");
192
+ return new DataView(data.buffer, data.byteOffset).getUint32(off, true);
193
+ }
194
+
195
+ function getU64(data, off) {
196
+ return (BigInt(getU32(data, off)) | (BigInt(getU32(data, off + 4)) << 32n)) & 0xffffffffffffffffn;
197
+ }
198
+
199
+ function writeScalar(buf, off, field, value) {
200
+ const view = new DataView(buf.buffer, buf.byteOffset);
201
+ switch (field.type) {
202
+ case T.FLOAT: view.setFloat32(off, asF64(value), true); return;
203
+ case T.FIXED32: view.setUint32(off, Number(asU64(value) & 0xffffffffn), true); return;
204
+ case T.SFIXED32: view.setInt32(off, Number(BigInt.asIntN(32, asI64(value))), true); return;
205
+ case T.DOUBLE: view.setFloat64(off, asF64(value), true); return;
206
+ case T.FIXED64: putU64(buf, off, asU64(value)); return;
207
+ case T.SFIXED64: putU64(buf, off, asI64(value)); return;
208
+ case T.BOOL: buf[off] = asI64(value) !== 0n ? 1 : 0; return;
209
+ default: putU64(buf, off, asI64(value)); return;
210
+ }
211
+ }
212
+
213
+ function writeValue(buf, off, field, value, fileModel) {
214
+ if (field.type === T.STRING || field.type === T.BYTES) {
215
+ buf.set(bytesOf(field, value), off);
216
+ return;
217
+ }
218
+ if (field.type === T.MESSAGE) {
219
+ const nested = fileModel.messages.get(field.typeName);
220
+ buf.set(encodeStruct(nested, value, fileModel), off);
221
+ return;
222
+ }
223
+ writeScalar(buf, off, field, value);
224
+ }
225
+
226
+ /** Encode `message` in the struct layout for `model`. */
227
+ export function encodeStruct(model, message, fileModel) {
228
+ const fields = sortedFields(model);
229
+ const words = Math.max(1, Math.floor((fields.length + 31) / 32));
230
+ const header = 12 + 4 * words;
231
+ const offsets = [];
232
+ let cursor = header;
233
+ for (const f of fields) {
234
+ offsets.push(cursor);
235
+ cursor += slotSize(f);
236
+ }
237
+ const fixedEnd = cursor;
238
+ const buf = new Uint8Array(structSize(model, message, fileModel));
239
+ buf.set([0x44, 0x43, 0x53, 0x31], 0); // DCS1
240
+ putU32(buf, 4, buf.length);
241
+ putU32(buf, 8, fingerprint(model.fullName));
242
+ fields.forEach((f, i) => {
243
+ if (fieldPresent(f, message, fileModel)) {
244
+ const at = 12 + 4 * Math.floor(i / 32);
245
+ putU32(buf, at, getU32(buf, at) | (1 << (i % 32)));
246
+ }
247
+ });
248
+ let vp = fixedEnd;
249
+ fields.forEach((field, i) => {
250
+ const off = offsets[i];
251
+ const values = message.getAll(field.number);
252
+ if (isMap(field, fileModel)) {
253
+ if (!values.length) return;
254
+ const entryModel = mapModel(field, fileModel);
255
+ const kf = entryModel.fields.get(1);
256
+ const vf = entryModel.fields.get(2);
257
+ putU32(buf, off, vp);
258
+ putU32(buf, off + 4, values.length);
259
+ for (const [k, v] of mapEntries(field, values, entryModel)) {
260
+ const klen = valueSize(kf, k, fileModel);
261
+ const vlen = valueSize(vf, v, fileModel);
262
+ putU32(buf, vp, klen);
263
+ putU32(buf, vp + 4, vlen);
264
+ vp += 8;
265
+ writeValue(buf, vp, kf, k, fileModel);
266
+ vp += klen;
267
+ writeValue(buf, vp, vf, v, fileModel);
268
+ vp += vlen;
269
+ }
270
+ } else if (field.repeated) {
271
+ if (!values.length) return;
272
+ putU32(buf, off, vp);
273
+ putU32(buf, off + 4, values.length);
274
+ if (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) {
275
+ let doff = vp + 8 * values.length;
276
+ for (const v of values) {
277
+ putU32(buf, vp, doff);
278
+ putU32(buf, vp + 4, valueSize(field, v, fileModel));
279
+ doff += valueSize(field, v, fileModel);
280
+ vp += 8;
281
+ }
282
+ for (const v of values) {
283
+ writeValue(buf, vp, field, v, fileModel);
284
+ vp += valueSize(field, v, fileModel);
285
+ }
286
+ } else {
287
+ for (const v of values) {
288
+ writeScalar(buf, vp, field, v);
289
+ vp += slotSize(field);
290
+ }
291
+ }
292
+ } else if (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) {
293
+ if (!fieldPresent(field, message, fileModel)) return;
294
+ putU32(buf, off, vp);
295
+ putU32(buf, off + 4, valueSize(field, values[0], fileModel));
296
+ writeValue(buf, vp, field, values[0], fileModel);
297
+ vp += valueSize(field, values[0], fileModel);
298
+ } else if (fieldPresent(field, message, fileModel)) {
299
+ writeScalar(buf, off, field, values[0]);
300
+ }
301
+ });
302
+ for (const chunk of message.unknown ?? []) {
303
+ buf.set(chunk, vp);
304
+ vp += chunk.length;
305
+ }
306
+ return buf;
307
+ }
308
+
309
+ function readScalar(data, off, field) {
310
+ const view = new DataView(data.buffer, data.byteOffset);
311
+ switch (field.type) {
312
+ case T.FLOAT: return view.getFloat32(off, true);
313
+ case T.FIXED32: return BigInt(view.getUint32(off, true));
314
+ case T.SFIXED32: return BigInt(view.getInt32(off, true));
315
+ case T.DOUBLE: return view.getFloat64(off, true);
316
+ case T.FIXED64: return getU64(data, off);
317
+ case T.SFIXED64: return BigInt.asIntN(64, getU64(data, off));
318
+ case T.BOOL: return data[off] !== 0;
319
+ case T.ENUM:
320
+ case T.INT32:
321
+ case T.SINT32:
322
+ return BigInt(BigInt.asIntN(32, getU64(data, off)));
323
+ case T.INT64:
324
+ case T.SINT64:
325
+ return BigInt.asIntN(64, getU64(data, off));
326
+ case T.UINT32:
327
+ return getU64(data, off) & 0xffffffffn;
328
+ default:
329
+ return getU64(data, off);
330
+ }
331
+ }
332
+
333
+ function readValue(data, off, len, field, fileModel) {
334
+ if (off + len > data.length) throw StatusError.invalidArgument("struct codec: out of bounds");
335
+ const slice = data.subarray(off, off + len);
336
+ if (field.type === T.STRING) return new TextDecoder().decode(slice);
337
+ if (field.type === T.BYTES) return new Uint8Array(slice);
338
+ if (field.type === T.MESSAGE) {
339
+ if (len === 0) return new GenericMessage();
340
+ const nested = fileModel.messages.get(field.typeName);
341
+ return decodeStruct(nested, slice, fileModel);
342
+ }
343
+ return readScalar(data, off, field);
344
+ }
345
+
346
+ /** Decode struct-layout bytes for `model`. */
347
+ export function decodeStruct(model, data, fileModel) {
348
+ const fields = sortedFields(model);
349
+ const words = Math.max(1, Math.floor((fields.length + 31) / 32));
350
+ const header = 12 + 4 * words;
351
+ if (data.length < header || data[0] !== 0x44 || data[1] !== 0x43 || data[2] !== 0x53 || data[3] !== 0x31) {
352
+ throw StatusError.invalidArgument("struct codec: bad header");
353
+ }
354
+ if (getU32(data, 8) !== fingerprint(model.fullName)) {
355
+ throw StatusError.invalidArgument("struct codec: schema fingerprint mismatch");
356
+ }
357
+ if (getU32(data, 4) !== data.length) {
358
+ throw StatusError.invalidArgument("struct codec: length mismatch");
359
+ }
360
+ const offsets = [];
361
+ let cursor = header;
362
+ for (const f of fields) {
363
+ offsets.push(cursor);
364
+ cursor += slotSize(f);
365
+ }
366
+ const message = new GenericMessage(model);
367
+ let vend = cursor;
368
+ fields.forEach((field, i) => {
369
+ if ((getU32(data, 12 + 4 * Math.floor(i / 32)) & (1 << (i % 32))) === 0) return;
370
+ const off = offsets[i];
371
+ if (isMap(field, fileModel)) {
372
+ const entryModel = mapModel(field, fileModel);
373
+ const kf = entryModel.fields.get(1);
374
+ const vf = entryModel.fields.get(2);
375
+ const base = getU32(data, off);
376
+ const n = getU32(data, off + 4);
377
+ let p = base;
378
+ for (let j = 0; j < n; j++) {
379
+ const kl = getU32(data, p);
380
+ const vl = getU32(data, p + 4);
381
+ p += 8;
382
+ const key = readValue(data, p, kl, kf, fileModel);
383
+ const val = readValue(data, p + kl, vl, vf, fileModel);
384
+ const entry = new GenericMessage(entryModel);
385
+ entry.set(1, key);
386
+ entry.set(2, val);
387
+ message.add(field.number, entry);
388
+ p += kl + vl;
389
+ }
390
+ vend = Math.max(vend, p);
391
+ } else if (field.repeated) {
392
+ const base = getU32(data, off);
393
+ const n = getU32(data, off + 4);
394
+ if (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) {
395
+ for (let j = 0; j < n; j++) {
396
+ const eo = getU32(data, base + 8 * j);
397
+ const el = getU32(data, base + 8 * j + 4);
398
+ if (el > 0 || field.type !== T.MESSAGE) {
399
+ message.add(field.number, readValue(data, eo, el, field, fileModel));
400
+ }
401
+ vend = Math.max(vend, eo + el);
402
+ }
403
+ } else {
404
+ for (let j = 0; j < n; j++) {
405
+ message.add(field.number, readScalar(data, base + j * slotSize(field), field));
406
+ }
407
+ vend = Math.max(vend, base + n * slotSize(field));
408
+ }
409
+ } else if (field.type === T.STRING || field.type === T.BYTES || field.type === T.MESSAGE) {
410
+ const base = getU32(data, off);
411
+ const len = getU32(data, off + 4);
412
+ message.add(field.number, readValue(data, base, len, field, fileModel));
413
+ vend = Math.max(vend, base + len);
414
+ } else {
415
+ message.add(field.number, readScalar(data, off, field));
416
+ }
417
+ });
418
+ if (vend < data.length) message.unknown.push(data.slice(vend));
419
+ return message;
420
+ }
421
+
422
+ class PbReader {
423
+ constructor(buf) {
424
+ this.buf = buf;
425
+ this.pos = 0;
426
+ }
427
+
428
+ varint() {
429
+ let result = 0n;
430
+ let shift = 0n;
431
+ for (;;) {
432
+ if (this.pos >= this.buf.length) throw StatusError.invalidArgument("truncated varint");
433
+ const b = this.buf[this.pos++];
434
+ result |= BigInt(b & 0x7f) << shift;
435
+ if ((b & 0x80) === 0) return result;
436
+ shift += 7n;
437
+ if (shift >= 70n) throw StatusError.invalidArgument("varint too long");
438
+ }
439
+ }
440
+
441
+ bytes(n) {
442
+ if (this.pos + n > this.buf.length) throw StatusError.invalidArgument("truncated field");
443
+ const out = this.buf.subarray(this.pos, this.pos + n);
444
+ this.pos += n;
445
+ return out;
446
+ }
447
+
448
+ // Yields [number, wire, value, rawChunk]; group fields yield
449
+ // their inner bytes as a LEN value.
450
+ *fields() {
451
+ while (this.pos < this.buf.length) {
452
+ const start = this.pos;
453
+ const tag = this.varint();
454
+ const number = Number(tag >> 3n);
455
+ const wire = Number(tag & 7n);
456
+ if (wire === 0) {
457
+ const v = this.varint();
458
+ yield [number, wire, v, this.buf.slice(start, this.pos)];
459
+ } else if (wire === 2) {
460
+ const len = Number(this.varint());
461
+ const v = this.bytes(len);
462
+ yield [number, wire, v, this.buf.slice(start, this.pos)];
463
+ } else if (wire === 1) {
464
+ const v = this.bytes(8);
465
+ yield [number, wire, v, this.buf.slice(start, this.pos)];
466
+ } else if (wire === 5) {
467
+ const v = this.bytes(4);
468
+ yield [number, wire, v, this.buf.slice(start, this.pos)];
469
+ } else if (wire === 3) {
470
+ const innerStart = this.pos;
471
+ let depth = 1;
472
+ let innerEnd = -1;
473
+ const scan = new PbReader(this.buf);
474
+ scan.pos = this.pos;
475
+ while (scan.pos < this.buf.length) {
476
+ const t = scan.varint();
477
+ const w = Number(t & 7n);
478
+ if (w === 0) scan.varint();
479
+ else if (w === 2) scan.bytes(Number(scan.varint()));
480
+ else if (w === 1) scan.bytes(8);
481
+ else if (w === 5) scan.bytes(4);
482
+ else if (w === 3) depth++;
483
+ else if (w === 4) {
484
+ depth--;
485
+ if (depth === 0) { innerEnd = scan.pos; break; }
486
+ } else throw StatusError.invalidArgument(`unsupported wire type ${w}`);
487
+ }
488
+ if (innerEnd < 0) throw StatusError.invalidArgument("unterminated group");
489
+ // Inner bytes exclude the end-group tag.
490
+ let end = innerEnd;
491
+ // Re-scan to find the end tag start: walk again tracking pos.
492
+ let pos = innerStart;
493
+ depth = 1;
494
+ const r2 = new PbReader(this.buf);
495
+ r2.pos = innerStart;
496
+ while (r2.pos < this.buf.length) {
497
+ const tagStart = r2.pos;
498
+ const t = r2.varint();
499
+ const w = Number(t & 7n);
500
+ if (w === 0) r2.varint();
501
+ else if (w === 2) r2.bytes(Number(r2.varint()));
502
+ else if (w === 1) r2.bytes(8);
503
+ else if (w === 5) r2.bytes(4);
504
+ else if (w === 3) depth++;
505
+ else if (w === 4) {
506
+ depth--;
507
+ if (depth === 0) { end = tagStart; break; }
508
+ }
509
+ }
510
+ const inner = this.buf.subarray(innerStart, end);
511
+ this.pos = innerEnd;
512
+ void pos;
513
+ yield [number, 2, inner, this.buf.slice(start, this.pos)];
514
+ } else if (wire === 4) {
515
+ throw StatusError.invalidArgument("unexpected end-group tag");
516
+ } else {
517
+ throw StatusError.invalidArgument(`unsupported wire type ${wire}`);
518
+ }
519
+ }
520
+ }
521
+ }
522
+
523
+ function zigzagDecode(v) {
524
+ return (v >> 1n) ^ -(v & 1n);
525
+ }
526
+
527
+ function decodeValueS(field, wire, raw, fileModel) {
528
+ if (wire === 0) {
529
+ if (field.type === T.BOOL) return raw !== 0n;
530
+ if (field.type === T.SINT32 || field.type === T.SINT64) return zigzagDecode(raw);
531
+ if (field.type === T.INT32 || field.type === T.ENUM) return BigInt(BigInt.asIntN(32, raw));
532
+ if (field.type === T.INT64) return BigInt.asIntN(64, raw);
533
+ return raw & 0xffffffffffffffffn;
534
+ }
535
+ if (wire === 1) {
536
+ const view = new DataView(raw.buffer, raw.byteOffset, 8);
537
+ if (field.type === T.DOUBLE) return view.getFloat64(0, true);
538
+ if (field.type === T.SFIXED64) return BigInt(view.getBigInt64(0, true));
539
+ return view.getBigUint64(0, true);
540
+ }
541
+ if (wire === 5) {
542
+ const view = new DataView(raw.buffer, raw.byteOffset, 4);
543
+ if (field.type === T.FLOAT) return view.getFloat32(0, true);
544
+ if (field.type === T.SFIXED32) return BigInt(view.getInt32(0, true));
545
+ return BigInt(view.getUint32(0, true));
546
+ }
547
+ if (field.type === T.STRING) return new TextDecoder().decode(raw);
548
+ if (field.type === T.MESSAGE) {
549
+ return decodeGenericS(fileModel.messages.get(field.typeName), raw, fileModel);
550
+ }
551
+ return new Uint8Array(raw);
552
+ }
553
+
554
+ function decodePackedS(field, bytes, fileModel) {
555
+ const out = [];
556
+ const wire = { 0: 0, 1: 1, 2: 5 }[
557
+ field.type === T.DOUBLE || field.type === T.FIXED64 || field.type === T.SFIXED64 ? 1
558
+ : field.type === T.FLOAT || field.type === T.FIXED32 || field.type === T.SFIXED32 ? 2 : 0];
559
+ if (wire === 0) {
560
+ const reader = new PbReader(bytes);
561
+ while (reader.pos < bytes.length) out.push(decodeValueS(field, 0, reader.varint(), fileModel));
562
+ } else if (wire === 1) {
563
+ for (let i = 0; i + 8 <= bytes.length; i += 8) out.push(decodeValueS(field, 1, bytes.subarray(i, i + 8), fileModel));
564
+ } else {
565
+ for (let i = 0; i + 4 <= bytes.length; i += 4) out.push(decodeValueS(field, 5, bytes.subarray(i, i + 4), fileModel));
566
+ }
567
+ return out;
568
+ }
569
+
570
+ /** Protobuf -> generic, mirroring the Rust dynamic decoder (packed split, BigInt-safe). */
571
+ export function decodeGenericS(model, data, fileModel) {
572
+ const message = new GenericMessage(model);
573
+ for (const [number, wire, raw, chunk] of new PbReader(data).fields()) {
574
+ const field = model.fields.get(number);
575
+ if (!field) {
576
+ message.unknown.push(chunk);
577
+ continue;
578
+ }
579
+ if (field.repeated && wire === 2 &&
580
+ field.type !== T.STRING && field.type !== T.BYTES && field.type !== T.MESSAGE && field.type !== T.GROUP) {
581
+ for (const v of decodePackedS(field, raw, fileModel)) message.add(number, v);
582
+ continue;
583
+ }
584
+ message.add(number, decodeValueS(field, wire, raw, fileModel));
585
+ }
586
+ return message;
587
+ }
588
+
589
+ function encodeVarintBytes(v) {
590
+ let x = v & 0xffffffffffffffffn;
591
+ const out = [];
592
+ while (x > 0x7fn) {
593
+ out.push(Number((x & 0x7fn) | 0x80n));
594
+ x >>= 7n;
595
+ }
596
+ out.push(Number(x));
597
+ return Uint8Array.from(out);
598
+ }
599
+
600
+ function wireTypeOf(ty) {
601
+ if ([T.INT64, T.UINT64, T.INT32, T.BOOL, T.UINT32, T.ENUM, T.SINT32, T.SINT64].includes(ty)) return 0;
602
+ if ([T.FIXED64, T.SFIXED64, T.DOUBLE].includes(ty)) return 1;
603
+ if ([T.STRING, T.MESSAGE, T.BYTES, T.GROUP].includes(ty)) return 2;
604
+ return 5; // FLOAT, FIXED32, SFIXED32
605
+ }
606
+
607
+ function encodeValueS(field, value, fileModel) {
608
+ const wire = wireTypeOf(field.type);
609
+ const parts = [encodeVarintBytes(BigInt((field.number << 3) | wire))];
610
+ if (wire === 0) {
611
+ if (field.type === T.SINT32) {
612
+ const sv = BigInt.asIntN(32, asI64(value));
613
+ parts.push(encodeVarintBytes(((sv << 1n) ^ (sv >> 31n)) & 0xffffffffn));
614
+ } else if (field.type === T.SINT64) {
615
+ const sv = asI64(value);
616
+ parts.push(encodeVarintBytes((sv << 1n) ^ (sv >> 63n)));
617
+ } else if (field.type === T.BOOL) {
618
+ parts.push(encodeVarintBytes(value === true || asI64(value) !== 0n ? 1n : 0n));
619
+ } else {
620
+ parts.push(encodeVarintBytes(asU64(value)));
621
+ }
622
+ } else if (wire === 1) {
623
+ const buf = new Uint8Array(8);
624
+ const view = new DataView(buf.buffer);
625
+ if (field.type === T.DOUBLE) view.setFloat64(0, asF64(value), true);
626
+ else view.setBigUint64(0, asU64(value), true);
627
+ parts.push(buf);
628
+ } else if (wire === 5) {
629
+ const buf = new Uint8Array(4);
630
+ const view = new DataView(buf.buffer);
631
+ if (field.type === T.FLOAT) view.setFloat32(0, asF64(value), true);
632
+ else view.setUint32(0, Number(asU64(value) & 0xffffffffn), true);
633
+ parts.push(buf);
634
+ } else {
635
+ let data;
636
+ if (field.type === T.STRING) data = new TextEncoder().encode(value);
637
+ else if (field.type === T.MESSAGE) data = encodeGenericS(fileModel.messages.get(field.typeName), value, fileModel);
638
+ else data = value instanceof Uint8Array ? value : bytesOf(field, value);
639
+ parts.push(encodeVarintBytes(BigInt(data.length)), data);
640
+ }
641
+ const total = parts.reduce((n, p) => n + p.length, 0);
642
+ const out = new Uint8Array(total);
643
+ let off = 0;
644
+ for (const p of parts) { out.set(p, off); off += p.length; }
645
+ return out;
646
+ }
647
+
648
+ /** Generic -> protobuf, mirroring the Rust dynamic encoder. */
649
+ export function encodeGenericS(model, message, fileModel) {
650
+ const parts = [];
651
+ const numbers = [...message.values.keys()].sort((a, b) => a - b);
652
+ for (const number of numbers) {
653
+ const field = model.fields.get(number);
654
+ if (!field) throw StatusError.invalidArgument(`unknown field ${number} for ${model.fullName}`);
655
+ const values = message.values.get(number);
656
+ if (field.repeated) {
657
+ for (const v of values) parts.push(encodeValueS(field, v, fileModel));
658
+ } else if (values.length) {
659
+ parts.push(encodeValueS(field, values[0], fileModel));
660
+ }
661
+ }
662
+ for (const chunk of message.unknown ?? []) parts.push(chunk);
663
+ const total = parts.reduce((n, p) => n + p.length, 0);
664
+ const out = new Uint8Array(total);
665
+ let off = 0;
666
+ for (const p of parts) { out.set(p, off); off += p.length; }
667
+ return out;
668
+ }
669
+
670
+ const descriptorCache = new Map();
671
+
672
+ /**
673
+ * Transcode between protobuf bytes and struct-layout bytes
674
+ * for `typeName` under the file descriptor set `descriptor`
675
+ * (encode=true: protobuf -> struct).
676
+ */
677
+ export function transcodeStruct(descriptor, typeName, data, encode) {
678
+ let fileModel = descriptorCache.get(descriptor);
679
+ if (!fileModel) {
680
+ fileModel = parseDescriptorSet(descriptor);
681
+ descriptorCache.set(descriptor, fileModel);
682
+ }
683
+ const model = fileModel.messages.get(typeName) ?? fileModel.messages.get("." + typeName);
684
+ if (!model) throw StatusError.invalidArgument(`unknown message type ${typeName}`);
685
+ if (encode) return encodeStruct(model, decodeGenericS(model, data, fileModel), fileModel);
686
+ return encodeGenericS(model, decodeStruct(model, data, fileModel), fileModel);
687
+ }
688
+
689
+ /** Marshal `msg` (a generated message class instance) with the call's codec. */
690
+ export function marshalForCodec(structCodec, Type, msg) {
691
+ if (!structCodec) return Type.encode(msg);
692
+ if (typeof Type.encodeStruct !== "function") {
693
+ throw StatusError.internal("message has no struct codec");
694
+ }
695
+ return Type.encodeStruct(msg);
696
+ }
697
+
698
+ /** Decode `data` with the call's codec into a new message of class `Type`. */
699
+ export function unmarshalForCodec(structCodec, Type, data) {
700
+ if (!structCodec) return Type.decode(data);
701
+ if (typeof Type.decodeStruct !== "function") {
702
+ throw StatusError.internal("message has no struct codec");
703
+ }
704
+ return Type.decodeStruct(data);
705
+ }
706
+