@distilled.cloud/core 1.0.0-rc.18 → 1.0.0-rc.19

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.
Files changed (112) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/grpc.js +2 -0
  6. package/lib/_bundle/grpc.js.map +1 -0
  7. package/lib/_bundle/rest.js +1 -1
  8. package/lib/_bundle/rest.js.map +1 -1
  9. package/lib/_bundle/xml.js +1 -1
  10. package/lib/_bundle/xml.js.map +1 -1
  11. package/lib/annotations.d.ts +2 -0
  12. package/lib/annotations.d.ts.map +1 -1
  13. package/lib/annotations.js +1 -1
  14. package/lib/annotations.js.map +1 -1
  15. package/lib/api.d.ts +37 -1
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -1
  18. package/lib/errors.d.ts +1 -0
  19. package/lib/errors.d.ts.map +1 -1
  20. package/lib/errors.js +1 -1
  21. package/lib/graphql.d.ts +12 -5
  22. package/lib/graphql.d.ts.map +1 -1
  23. package/lib/graphql.types.d.ts.map +1 -1
  24. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  25. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  26. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  27. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  28. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  29. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  30. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  31. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  32. package/lib/grpc-transport-node-http2.d.ts +19 -0
  33. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  34. package/lib/grpc-transport-node-http2.js +2 -0
  35. package/lib/grpc-transport-node-http2.js.map +1 -0
  36. package/lib/grpc-transport.d.ts +76 -0
  37. package/lib/grpc-transport.d.ts.map +1 -0
  38. package/lib/grpc-transport.js +1 -0
  39. package/lib/hpack.d.ts +34 -0
  40. package/lib/hpack.d.ts.map +1 -0
  41. package/lib/hpack.js +2 -0
  42. package/lib/hpack.js.map +1 -0
  43. package/lib/index.d.ts +3 -0
  44. package/lib/index.d.ts.map +1 -1
  45. package/lib/index.js +3 -0
  46. package/lib/pagination.d.ts +22 -2
  47. package/lib/pagination.d.ts.map +1 -1
  48. package/lib/pagination.js +1 -1
  49. package/lib/protobuf.d.ts +92 -0
  50. package/lib/protobuf.d.ts.map +1 -0
  51. package/lib/protobuf.js +1 -0
  52. package/lib/protocol-grpc.d.ts +86 -0
  53. package/lib/protocol-grpc.d.ts.map +1 -0
  54. package/lib/protocol-grpc.js +1 -0
  55. package/lib/protocol-http.d.ts +11 -6
  56. package/lib/protocol-http.d.ts.map +1 -1
  57. package/lib/protocol-rest.d.ts +12 -8
  58. package/lib/protocol-rest.d.ts.map +1 -1
  59. package/lib/response-validation.d.ts +1 -1
  60. package/lib/response-validation.d.ts.map +1 -1
  61. package/lib/sdk-error.d.ts +27 -0
  62. package/lib/sdk-error.d.ts.map +1 -0
  63. package/lib/sdk-error.js +1 -0
  64. package/lib/sensitive.d.ts +28 -0
  65. package/lib/sensitive.d.ts.map +1 -0
  66. package/lib/sensitive.js +2 -0
  67. package/lib/sensitive.js.map +1 -0
  68. package/lib/telemetry-debug.d.ts +2 -10
  69. package/lib/telemetry-debug.d.ts.map +1 -1
  70. package/lib/telemetry-debug.js +1 -1
  71. package/lib/telemetry-debug.js.map +1 -1
  72. package/lib/telemetry-stream.d.ts +3 -1
  73. package/lib/telemetry-stream.d.ts.map +1 -1
  74. package/lib/telemetry-stream.js +1 -1
  75. package/lib/telemetry-stream.js.map +1 -1
  76. package/lib/telemetry.d.ts +23 -4
  77. package/lib/telemetry.d.ts.map +1 -1
  78. package/lib/telemetry.js +2 -2
  79. package/lib/telemetry.js.map +1 -1
  80. package/lib/trait.d.ts +7 -0
  81. package/lib/trait.d.ts.map +1 -1
  82. package/lib/trait.js +1 -1
  83. package/lib/xml.d.ts.map +1 -1
  84. package/package.json +3 -3
  85. package/src/annotations.ts +16 -0
  86. package/src/api.ts +199 -25
  87. package/src/errors.ts +4 -0
  88. package/src/graphql.ts +68 -45
  89. package/src/graphql.types.ts +5 -1
  90. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  91. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  92. package/src/grpc-transport-node-http2.ts +234 -0
  93. package/src/grpc-transport.ts +118 -0
  94. package/src/hpack.ts +331 -0
  95. package/src/index.ts +3 -0
  96. package/src/pagination.ts +75 -3
  97. package/src/protobuf.ts +1332 -0
  98. package/src/protocol-grpc.ts +641 -0
  99. package/src/protocol-http.ts +30 -30
  100. package/src/protocol-rest.ts +49 -118
  101. package/src/response-validation.ts +4 -2
  102. package/src/sdk-error.ts +33 -0
  103. package/src/sensitive.ts +154 -0
  104. package/src/telemetry-debug.ts +65 -21
  105. package/src/telemetry-stream.ts +16 -7
  106. package/src/telemetry.ts +91 -27
  107. package/src/trait.ts +10 -0
  108. package/src/xml.ts +10 -1
  109. package/lib/debug.d.ts +0 -2
  110. package/lib/debug.d.ts.map +0 -1
  111. package/lib/debug.js +0 -1
  112. package/src/debug.ts +0 -11
@@ -0,0 +1,1332 @@
1
+ /**
2
+ * Protobuf binary wire codec over generated descriptors.
3
+ *
4
+ * Proto-sourced SDKs keep their schemas in proto3 JSON shape (camelCase wire
5
+ * names, 64-bit integers as strings, bytes as base64, enums by name,
6
+ * `google.protobuf.Timestamp` as RFC 3339). Servers that only speak binary
7
+ * gRPC need the same values as protobuf bytes, so this module transcodes
8
+ * between the two using a descriptor table the converter emits next to the
9
+ * services (`src/descriptors.ts`): field numbers, scalar kinds, message and
10
+ * enum references.
11
+ *
12
+ * Decoding follows proto3: a field without presence (a plain scalar, enum,
13
+ * `repeated` or `map` field) reads as its default when the wire omits it
14
+ * (`""`, `0`, `"0"` for 64-bit integers, `false`, the enum's zero value,
15
+ * `[]`, `{}`), so the JSON always carries it. Fields with presence (marked
16
+ * `optional`, message fields and `oneof` members) are omitted when absent.
17
+ * Enum numbers map back to names, and unknown fields are skipped.
18
+ */
19
+
20
+ /** A scalar or composite field kind. */
21
+ export type FieldKind =
22
+ | "double"
23
+ | "float"
24
+ | "int32"
25
+ | "int64"
26
+ | "uint32"
27
+ | "uint64"
28
+ | "sint32"
29
+ | "sint64"
30
+ | "fixed32"
31
+ | "fixed64"
32
+ | "sfixed32"
33
+ | "sfixed64"
34
+ | "bool"
35
+ | "string"
36
+ | "bytes"
37
+ | "enum"
38
+ | "message"
39
+ | "map";
40
+
41
+ /** `[keyKind, valueKind, valueRef?]` for a `map<K, V>` field. */
42
+ export type MapRef = readonly [key: FieldKind, value: FieldKind, ref?: string];
43
+
44
+ /**
45
+ * One field: `[number, jsonName, kind, ref?, repeated?, presence?]`. `ref`
46
+ * names the message or enum for `message`/`enum` kinds and is a
47
+ * {@link MapRef} for `map`; `repeated` is `1` for repeated fields. `presence`
48
+ * is set for a field whose absence is observable: `1` for a proto3
49
+ * `optional` field, and `n >= 2` for the members of the message's oneof `n`
50
+ * (setting one member clears the others). Message fields always have
51
+ * presence.
52
+ */
53
+ export type FieldDescriptor = readonly [
54
+ number: number,
55
+ jsonName: string,
56
+ kind: FieldKind,
57
+ ref?: string | MapRef | 0,
58
+ repeated?: 0 | 1,
59
+ presence?: number,
60
+ ];
61
+
62
+ export interface ProtoDescriptors {
63
+ /** Message full name -> fields. */
64
+ readonly messages: Readonly<Record<string, ReadonlyArray<FieldDescriptor>>>;
65
+ /** Enum full name -> value name -> number. */
66
+ readonly enums: Readonly<Record<string, Readonly<Record<string, number>>>>;
67
+ /**
68
+ * gRPC method path (`/<package>.<Service>/<Method>`) ->
69
+ * `[requestMessage, responseMessage, serverStream?]`. A server-streaming
70
+ * method's JSON output is `{ items: [response, ...] }`.
71
+ */
72
+ readonly methods: Readonly<
73
+ Record<string, readonly [request: string, response: string, serverStream?: 0 | 1]>
74
+ >;
75
+ }
76
+
77
+ /** A value the descriptors can't encode (a wrong type for its field). */
78
+ export class ProtobufEncodeError extends Error {
79
+ readonly _tag = "ProtobufEncodeError";
80
+ }
81
+
82
+ /** Bytes that aren't valid protobuf for the expected message. */
83
+ export class ProtobufDecodeError extends Error {
84
+ readonly _tag: string = "ProtobufDecodeError";
85
+ }
86
+
87
+ /**
88
+ * Valid protobuf whose value proto3 JSON can't represent: a Timestamp
89
+ * outside years 0001 to 9999, or a Duration beyond 10,000 years.
90
+ */
91
+ export class ProtobufJsonRangeError extends ProtobufDecodeError {
92
+ override readonly _tag = "ProtobufJsonRangeError";
93
+ }
94
+
95
+ // ============================================================================
96
+ // Writer
97
+ // ============================================================================
98
+
99
+ class Writer {
100
+ buf = new Uint8Array(64);
101
+ pos = 0;
102
+
103
+ ensure(n: number): void {
104
+ if (this.pos + n <= this.buf.length) return;
105
+ let size = this.buf.length * 2;
106
+ while (size < this.pos + n) size *= 2;
107
+ const next = new Uint8Array(size);
108
+ next.set(this.buf.subarray(0, this.pos));
109
+ this.buf = next;
110
+ }
111
+
112
+ byte(b: number): void {
113
+ this.ensure(1);
114
+ this.buf[this.pos++] = b;
115
+ }
116
+
117
+ bytes(b: Uint8Array): void {
118
+ this.ensure(b.length);
119
+ this.buf.set(b, this.pos);
120
+ this.pos += b.length;
121
+ }
122
+
123
+ /** Unsigned varint of a non-negative number below 2^53. */
124
+ uvarint(n: number): void {
125
+ while (n > 0x7f) {
126
+ this.byte((n % 0x80) | 0x80);
127
+ n = Math.floor(n / 0x80);
128
+ }
129
+ this.byte(n);
130
+ }
131
+
132
+ /** Varint of a 64-bit value (two's complement for negatives). */
133
+ varint64(n: bigint): void {
134
+ let v = BigInt.asUintN(64, n);
135
+ while (v > 0x7fn) {
136
+ this.byte(Number(v & 0x7fn) | 0x80);
137
+ v >>= 7n;
138
+ }
139
+ this.byte(Number(v));
140
+ }
141
+
142
+ tag(field: number, wire: number): void {
143
+ this.uvarint(field * 8 + wire);
144
+ }
145
+
146
+ fixed32(n: number): void {
147
+ this.ensure(4);
148
+ new DataView(this.buf.buffer, this.buf.byteOffset).setUint32(this.pos, n >>> 0, true);
149
+ this.pos += 4;
150
+ }
151
+
152
+ fixed64(n: bigint): void {
153
+ this.ensure(8);
154
+ new DataView(this.buf.buffer, this.buf.byteOffset).setBigUint64(
155
+ this.pos,
156
+ BigInt.asUintN(64, n),
157
+ true,
158
+ );
159
+ this.pos += 8;
160
+ }
161
+
162
+ float(n: number): void {
163
+ this.ensure(4);
164
+ new DataView(this.buf.buffer, this.buf.byteOffset).setFloat32(this.pos, n, true);
165
+ this.pos += 4;
166
+ }
167
+
168
+ double(n: number): void {
169
+ this.ensure(8);
170
+ new DataView(this.buf.buffer, this.buf.byteOffset).setFloat64(this.pos, n, true);
171
+ this.pos += 8;
172
+ }
173
+
174
+ /** Length-delimited payload written by `f` (length-prefixed afterwards). */
175
+ delimited(f: (w: Writer) => void): void {
176
+ const inner = new Writer();
177
+ f(inner);
178
+ this.uvarint(inner.pos);
179
+ this.bytes(inner.finish());
180
+ }
181
+
182
+ finish(): Uint8Array {
183
+ return this.buf.subarray(0, this.pos);
184
+ }
185
+ }
186
+
187
+ // ============================================================================
188
+ // Reader
189
+ // ============================================================================
190
+
191
+ class Reader {
192
+ pos = 0;
193
+ readonly view: DataView;
194
+ constructor(readonly buf: Uint8Array) {
195
+ this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
196
+ }
197
+
198
+ get done(): boolean {
199
+ return this.pos >= this.buf.length;
200
+ }
201
+
202
+ /** A varint of at most ten bytes, truncated to 64 bits. */
203
+ varint64(): bigint {
204
+ let result = 0n;
205
+ let shift = 0n;
206
+ for (let i = 0; i < 10; i++) {
207
+ if (this.pos >= this.buf.length) throw new ProtobufDecodeError("truncated varint");
208
+ const b = this.buf[this.pos++]!;
209
+ result |= BigInt(b & 0x7f) << shift;
210
+ if ((b & 0x80) === 0) return BigInt.asUintN(64, result);
211
+ shift += 7n;
212
+ }
213
+ throw new ProtobufDecodeError("varint longer than ten bytes");
214
+ }
215
+
216
+ uvarint(): number {
217
+ // Fast path for small values (tags, lengths).
218
+ let result = 0;
219
+ let mul = 1;
220
+ for (let i = 0; i < 8; i++) {
221
+ if (this.pos >= this.buf.length) throw new ProtobufDecodeError("truncated varint");
222
+ const b = this.buf[this.pos++]!;
223
+ result += (b & 0x7f) * mul;
224
+ if ((b & 0x80) === 0) return result;
225
+ mul *= 0x80;
226
+ }
227
+ this.pos -= 8;
228
+ return Number(this.varint64());
229
+ }
230
+
231
+ take(n: number): Uint8Array {
232
+ if (this.pos + n > this.buf.length) throw new ProtobufDecodeError("truncated field");
233
+ const out = this.buf.subarray(this.pos, this.pos + n);
234
+ this.pos += n;
235
+ return out;
236
+ }
237
+
238
+ delimited(): Uint8Array {
239
+ return this.take(this.uvarint());
240
+ }
241
+
242
+ fixed32(): number {
243
+ const v = this.view.getUint32(this.take(4).byteOffset - this.buf.byteOffset, true);
244
+ return v;
245
+ }
246
+
247
+ fixed64(): bigint {
248
+ return this.view.getBigUint64(this.take(8).byteOffset - this.buf.byteOffset, true);
249
+ }
250
+
251
+ float(): number {
252
+ return this.view.getFloat32(this.take(4).byteOffset - this.buf.byteOffset, true);
253
+ }
254
+
255
+ double(): number {
256
+ return this.view.getFloat64(this.take(8).byteOffset - this.buf.byteOffset, true);
257
+ }
258
+
259
+ /** A field tag: its number (1 to 2^29 - 1) and wire type (0 to 5). */
260
+ tag(): readonly [num: number, wire: number] {
261
+ const start = this.pos;
262
+ const tag = Number(this.varint64());
263
+ // A tag is a 32-bit varint: at most five bytes.
264
+ if (this.pos - start > 5) throw new ProtobufDecodeError("overlong field tag");
265
+ const num = Math.floor(tag / 8);
266
+ const wire = tag & 7;
267
+ if (num < 1 || num > MAX_FIELD_NUMBER) {
268
+ throw new ProtobufDecodeError(`invalid field number ${num}`);
269
+ }
270
+ if (wire > 5) throw new ProtobufDecodeError(`invalid wire type ${wire}`);
271
+ return [num, wire];
272
+ }
273
+
274
+ /** Skip an unknown field's value; a group is skipped to its end tag. */
275
+ skip(wire: number, num: number): void {
276
+ switch (wire) {
277
+ case 0:
278
+ this.varint64();
279
+ return;
280
+ case 1:
281
+ this.take(8);
282
+ return;
283
+ case 2:
284
+ this.take(this.uvarint());
285
+ return;
286
+ case 3:
287
+ for (;;) {
288
+ if (this.done) throw new ProtobufDecodeError("unterminated group");
289
+ const [n, w] = this.tag();
290
+ if (w === 4) {
291
+ if (n !== num) throw new ProtobufDecodeError("mismatched end group");
292
+ return;
293
+ }
294
+ this.skip(w, n);
295
+ }
296
+ case 4:
297
+ throw new ProtobufDecodeError("unexpected end group");
298
+ case 5:
299
+ this.take(4);
300
+ return;
301
+ default:
302
+ throw new ProtobufDecodeError(`invalid wire type ${wire}`);
303
+ }
304
+ }
305
+ }
306
+
307
+ const MAX_FIELD_NUMBER = 536_870_911;
308
+
309
+ // ============================================================================
310
+ // Shared helpers
311
+ // ============================================================================
312
+
313
+ const textEncoder = /*@__PURE__*/ new TextEncoder();
314
+ const textDecoder = /*@__PURE__*/ new TextDecoder();
315
+
316
+ const wireTypeOf = (kind: FieldKind): number => {
317
+ switch (kind) {
318
+ case "double":
319
+ case "fixed64":
320
+ case "sfixed64":
321
+ return 1;
322
+ case "float":
323
+ case "fixed32":
324
+ case "sfixed32":
325
+ return 5;
326
+ case "string":
327
+ case "bytes":
328
+ case "message":
329
+ case "map":
330
+ return 2;
331
+ default:
332
+ return 0;
333
+ }
334
+ };
335
+
336
+ const isPackable = (kind: FieldKind): boolean =>
337
+ kind !== "string" && kind !== "bytes" && kind !== "message" && kind !== "map";
338
+
339
+ /** A JSON number's text: what a quoted number may be. */
340
+ const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
341
+
342
+ const INT_RANGES: Partial<Record<FieldKind | "enum", readonly [bigint, bigint]>> = {
343
+ int32: [-(2n ** 31n), 2n ** 31n - 1n],
344
+ sint32: [-(2n ** 31n), 2n ** 31n - 1n],
345
+ sfixed32: [-(2n ** 31n), 2n ** 31n - 1n],
346
+ enum: [-(2n ** 31n), 2n ** 31n - 1n],
347
+ uint32: [0n, 2n ** 32n - 1n],
348
+ fixed32: [0n, 2n ** 32n - 1n],
349
+ int64: [-(2n ** 63n), 2n ** 63n - 1n],
350
+ sint64: [-(2n ** 63n), 2n ** 63n - 1n],
351
+ sfixed64: [-(2n ** 63n), 2n ** 63n - 1n],
352
+ uint64: [0n, 2n ** 64n - 1n],
353
+ fixed64: [0n, 2n ** 64n - 1n],
354
+ };
355
+
356
+ /**
357
+ * An integer field's value: a bigint, an integral number, or a string of
358
+ * one (proto3 JSON quotes 64-bit integers, and allows `"1e5"`). Fails when
359
+ * it isn't an integer or is out of the kind's range.
360
+ */
361
+ const toBigInt = (value: unknown, field: string, kind: FieldKind | "enum"): bigint => {
362
+ let n: bigint | undefined;
363
+ if (typeof value === "bigint") n = value;
364
+ else if (typeof value === "number" && Number.isInteger(value)) n = BigInt(value);
365
+ else if (typeof value === "string" && /^-?\d+$/.test(value)) n = BigInt(value);
366
+ else if (
367
+ typeof value === "string" &&
368
+ JSON_NUMBER.test(value) &&
369
+ Number.isInteger(Number(value))
370
+ ) {
371
+ n = BigInt(Number(value));
372
+ }
373
+ if (n === undefined) {
374
+ throw new ProtobufEncodeError(`${field}: expected an integer, got ${JSON.stringify(value)}`);
375
+ }
376
+ const range = INT_RANGES[kind];
377
+ if (range && (n < range[0] || n > range[1])) {
378
+ throw new ProtobufEncodeError(`${field}: ${n} is out of range for ${kind}`);
379
+ }
380
+ return n;
381
+ };
382
+
383
+ const FLOAT_MAX = 3.4028234663852886e38;
384
+
385
+ /**
386
+ * A float or double field's value: a number, a JSON number's text, or
387
+ * `"NaN"` / `"Infinity"` / `"-Infinity"`. Fails for a finite value too large
388
+ * for the kind.
389
+ */
390
+ const toNumber = (value: unknown, field: string, kind: "float" | "double"): number => {
391
+ let n: number | undefined;
392
+ if (typeof value === "number") n = value;
393
+ else if (value === "NaN") n = Number.NaN;
394
+ else if (value === "Infinity") n = Number.POSITIVE_INFINITY;
395
+ else if (value === "-Infinity") n = Number.NEGATIVE_INFINITY;
396
+ else if (typeof value === "string" && JSON_NUMBER.test(value)) {
397
+ n = Number(value);
398
+ if (!Number.isFinite(n)) {
399
+ throw new ProtobufEncodeError(`${field}: ${value} is out of range for ${kind}`);
400
+ }
401
+ }
402
+ if (n === undefined) {
403
+ throw new ProtobufEncodeError(`${field}: expected a number, got ${JSON.stringify(value)}`);
404
+ }
405
+ if (kind === "float" && Number.isFinite(n) && Math.abs(n) > FLOAT_MAX) {
406
+ throw new ProtobufEncodeError(`${field}: ${n} is out of range for float`);
407
+ }
408
+ return n;
409
+ };
410
+
411
+ const base64ToBytes = (value: string): Uint8Array => {
412
+ const normal = value.replace(/-/g, "+").replace(/_/g, "/");
413
+ const bin = atob(normal);
414
+ const out = new Uint8Array(bin.length);
415
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
416
+ return out;
417
+ };
418
+
419
+ const bytesToBase64 = (bytes: Uint8Array): string => {
420
+ let bin = "";
421
+ for (let i = 0; i < bytes.length; i += 0x8000) {
422
+ bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
423
+ }
424
+ return btoa(bin);
425
+ };
426
+
427
+ const toBytes = (value: unknown, field: string): Uint8Array => {
428
+ if (value instanceof Uint8Array) return value;
429
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
430
+ if (typeof value === "string") return base64ToBytes(value);
431
+ throw new ProtobufEncodeError(`${field}: expected bytes (base64 string or Uint8Array)`);
432
+ };
433
+
434
+ // ============================================================================
435
+ // Encode (proto3 JSON -> binary)
436
+ // ============================================================================
437
+
438
+ const writeScalar = (
439
+ d: ProtoDescriptors,
440
+ w: Writer,
441
+ kind: FieldKind,
442
+ ref: string | undefined,
443
+ value: unknown,
444
+ field: string,
445
+ ): void => {
446
+ switch (kind) {
447
+ case "double":
448
+ case "float":
449
+ return kind === "double"
450
+ ? w.double(toNumber(value, field, kind))
451
+ : w.float(toNumber(value, field, kind));
452
+ case "int32":
453
+ case "int64":
454
+ case "uint32":
455
+ case "uint64":
456
+ return w.varint64(toBigInt(value, field, kind));
457
+ case "sint32":
458
+ case "sint64": {
459
+ const n = toBigInt(value, field, kind);
460
+ return w.varint64(n >= 0n ? n << 1n : (-n << 1n) - 1n);
461
+ }
462
+ case "fixed32":
463
+ case "sfixed32":
464
+ return w.fixed32(Number(BigInt.asUintN(32, toBigInt(value, field, kind))));
465
+ case "fixed64":
466
+ case "sfixed64":
467
+ return w.fixed64(toBigInt(value, field, kind));
468
+ case "bool":
469
+ if (typeof value !== "boolean") {
470
+ throw new ProtobufEncodeError(`${field}: expected a boolean, got ${JSON.stringify(value)}`);
471
+ }
472
+ return w.byte(value ? 1 : 0);
473
+ case "enum": {
474
+ if (typeof value === "number") return w.varint64(toBigInt(value, field, "enum"));
475
+ const values = ref ? d.enums[ref] : undefined;
476
+ const n = typeof value === "string" ? values?.[value] : undefined;
477
+ if (n === undefined) {
478
+ throw new ProtobufEncodeError(`${field}: unknown enum value ${JSON.stringify(value)}`);
479
+ }
480
+ return w.varint64(BigInt(n));
481
+ }
482
+ default:
483
+ throw new ProtobufEncodeError(`${field}: ${kind} is not a scalar`);
484
+ }
485
+ };
486
+
487
+ const writeValue = (
488
+ d: ProtoDescriptors,
489
+ w: Writer,
490
+ num: number,
491
+ kind: FieldKind,
492
+ ref: string | MapRef | 0 | undefined,
493
+ value: unknown,
494
+ field: string,
495
+ ): void => {
496
+ switch (kind) {
497
+ case "string":
498
+ if (typeof value !== "string") {
499
+ throw new ProtobufEncodeError(`${field}: expected a string, got ${JSON.stringify(value)}`);
500
+ }
501
+ w.tag(num, 2);
502
+ return w.delimited((inner) => inner.bytes(textEncoder.encode(value)));
503
+ case "bytes":
504
+ w.tag(num, 2);
505
+ return w.delimited((inner) => inner.bytes(toBytes(value, field)));
506
+ case "message":
507
+ w.tag(num, 2);
508
+ return w.delimited((inner) => writeMessageInto(d, inner, ref as string, value, field));
509
+ default:
510
+ w.tag(num, wireTypeOf(kind));
511
+ return writeScalar(d, w, kind, typeof ref === "string" ? ref : undefined, value, field);
512
+ }
513
+ };
514
+
515
+ // --- well-known types --------------------------------------------------------
516
+
517
+ /** Timestamp range: 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. */
518
+ const MIN_TIMESTAMP = -62_135_596_800n;
519
+ const MAX_TIMESTAMP = 253_402_300_799n;
520
+ /** Duration range: +/-10,000 years. */
521
+ const MAX_DURATION = 315_576_000_000n;
522
+
523
+ const RFC3339 =
524
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
525
+
526
+ const parseTimestamp = (value: unknown, field: string): { seconds: bigint; nanos: number } => {
527
+ if (value instanceof Date) {
528
+ const ms = value.getTime();
529
+ return { seconds: BigInt(Math.floor(ms / 1000)), nanos: (((ms % 1000) + 1000) % 1000) * 1e6 };
530
+ }
531
+ const m = typeof value === "string" ? RFC3339.exec(value) : null;
532
+ if (!m)
533
+ throw new ProtobufEncodeError(
534
+ `${field}: expected an RFC 3339 timestamp, got ${JSON.stringify(value)}`,
535
+ );
536
+ const [, y, mo, dd, hh, mi, ss, frac, sign, oh, om] = m;
537
+ const date = new Date(0);
538
+ date.setUTCFullYear(Number(y), Number(mo) - 1, Number(dd));
539
+ date.setUTCHours(Number(hh), Number(mi), Number(ss), 0);
540
+ if (
541
+ date.getUTCFullYear() !== Number(y) ||
542
+ date.getUTCMonth() !== Number(mo) - 1 ||
543
+ date.getUTCDate() !== Number(dd) ||
544
+ Number(hh) > 23 ||
545
+ Number(mi) > 59 ||
546
+ Number(ss) > 59
547
+ ) {
548
+ throw new ProtobufEncodeError(`${field}: invalid timestamp ${JSON.stringify(value)}`);
549
+ }
550
+ const offset = sign ? (sign === "-" ? -1 : 1) * (Number(oh) * 3600 + Number(om) * 60) : 0;
551
+ const seconds = BigInt(Math.floor(date.getTime() / 1000) - offset);
552
+ if (seconds < MIN_TIMESTAMP || seconds > MAX_TIMESTAMP) {
553
+ throw new ProtobufEncodeError(`${field}: timestamp ${value} is out of range`);
554
+ }
555
+ return { seconds, nanos: frac ? Number(frac.padEnd(9, "0")) : 0 };
556
+ };
557
+
558
+ const formatTimestamp = (seconds: bigint, nanos: number): string => {
559
+ const date = new Date(Number(seconds) * 1000);
560
+ const year = String(date.getUTCFullYear()).padStart(4, "0");
561
+ const iso = date
562
+ .toISOString()
563
+ .replace(/^[+-]?\d+/, year)
564
+ .replace(/\.\d{3}Z$/, "");
565
+ return `${iso}${fraction(nanos)}Z`;
566
+ };
567
+
568
+ /** A Duration's proto3 JSON (`"-1.5s"`), or a number of seconds. */
569
+ const parseDuration = (value: unknown, field: string): { seconds: bigint; nanos: number } => {
570
+ if (typeof value === "number" && Number.isFinite(value)) {
571
+ const whole = Math.trunc(value);
572
+ return { seconds: BigInt(whole), nanos: Math.round((value - whole) * 1e9) };
573
+ }
574
+ const m = typeof value === "string" ? /^(-)?(\d+)(?:\.(\d{1,9}))?s$/.exec(value) : null;
575
+ if (!m)
576
+ throw new ProtobufEncodeError(
577
+ `${field}: expected a duration like "1.5s", got ${JSON.stringify(value)}`,
578
+ );
579
+ const sign = m[1] ? -1n : 1n;
580
+ const seconds = sign * BigInt(m[2]!);
581
+ if (seconds > MAX_DURATION || seconds < -MAX_DURATION) {
582
+ throw new ProtobufEncodeError(`${field}: duration ${value} is out of range`);
583
+ }
584
+ const nanos = m[3] ? Number(m[3].padEnd(9, "0")) : 0;
585
+ return { seconds, nanos: m[1] ? -nanos : nanos };
586
+ };
587
+
588
+ const writeStructValue = (w: Writer, value: unknown): void => {
589
+ // google.protobuf.Value: null_value=1 (enum), number_value=2, string_value=3,
590
+ // bool_value=4, struct_value=5, list_value=6.
591
+ if (value === null || value === undefined) {
592
+ w.tag(1, 0);
593
+ w.byte(0);
594
+ } else if (typeof value === "number") {
595
+ w.tag(2, 1);
596
+ w.double(value);
597
+ } else if (typeof value === "string") {
598
+ w.tag(3, 2);
599
+ w.delimited((inner) => inner.bytes(textEncoder.encode(value)));
600
+ } else if (typeof value === "boolean") {
601
+ w.tag(4, 0);
602
+ w.byte(value ? 1 : 0);
603
+ } else if (Array.isArray(value)) {
604
+ w.tag(6, 2);
605
+ w.delimited((list) => {
606
+ for (const item of value) {
607
+ list.tag(1, 2);
608
+ list.delimited((inner) => writeStructValue(inner, item));
609
+ }
610
+ });
611
+ } else {
612
+ w.tag(5, 2);
613
+ w.delimited((inner) => writeStruct(inner, value as Record<string, unknown>));
614
+ }
615
+ };
616
+
617
+ const writeStruct = (w: Writer, value: Record<string, unknown>): void => {
618
+ // google.protobuf.Struct: map<string, Value> fields = 1.
619
+ for (const [key, item] of Object.entries(value)) {
620
+ w.tag(1, 2);
621
+ w.delimited((entry) => {
622
+ entry.tag(1, 2);
623
+ entry.delimited((inner) => inner.bytes(textEncoder.encode(key)));
624
+ entry.tag(2, 2);
625
+ entry.delimited((inner) => writeStructValue(inner, item));
626
+ });
627
+ }
628
+ };
629
+
630
+ const WRAPPER_KINDS: Record<string, FieldKind> = {
631
+ "google.protobuf.DoubleValue": "double",
632
+ "google.protobuf.FloatValue": "float",
633
+ "google.protobuf.Int64Value": "int64",
634
+ "google.protobuf.UInt64Value": "uint64",
635
+ "google.protobuf.Int32Value": "int32",
636
+ "google.protobuf.UInt32Value": "uint32",
637
+ "google.protobuf.BoolValue": "bool",
638
+ "google.protobuf.StringValue": "string",
639
+ "google.protobuf.BytesValue": "bytes",
640
+ };
641
+
642
+ /** Write a well-known type's fields; `false` when `name` isn't one. */
643
+ const writeWellKnown = (
644
+ d: ProtoDescriptors,
645
+ w: Writer,
646
+ name: string,
647
+ value: unknown,
648
+ field: string,
649
+ ): boolean => {
650
+ if (!name.startsWith("google.protobuf.")) return false;
651
+ switch (name) {
652
+ case "google.protobuf.Empty":
653
+ return true;
654
+ case "google.protobuf.Timestamp":
655
+ case "google.protobuf.Duration": {
656
+ const { seconds, nanos } =
657
+ name === "google.protobuf.Timestamp"
658
+ ? parseTimestamp(value, field)
659
+ : parseDuration(value, field);
660
+ if (seconds !== 0n) {
661
+ w.tag(1, 0);
662
+ w.varint64(seconds);
663
+ }
664
+ if (nanos !== 0) {
665
+ w.tag(2, 0);
666
+ w.varint64(BigInt(nanos));
667
+ }
668
+ return true;
669
+ }
670
+ case "google.protobuf.Struct":
671
+ writeStruct(w, (value ?? {}) as Record<string, unknown>);
672
+ return true;
673
+ case "google.protobuf.Value":
674
+ writeStructValue(w, value);
675
+ return true;
676
+ case "google.protobuf.ListValue":
677
+ for (const item of (value ?? []) as unknown[]) {
678
+ w.tag(1, 2);
679
+ w.delimited((inner) => writeStructValue(inner, item));
680
+ }
681
+ return true;
682
+ case "google.protobuf.FieldMask": {
683
+ if (typeof value !== "string") {
684
+ throw new ProtobufEncodeError(
685
+ `${field}: expected a FieldMask string, got ${JSON.stringify(value)}`,
686
+ );
687
+ }
688
+ for (const path of value === "" ? [] : value.split(",")) {
689
+ w.tag(1, 2);
690
+ w.delimited((inner) => inner.bytes(textEncoder.encode(pathFromJson(path, field))));
691
+ }
692
+ return true;
693
+ }
694
+ case "google.protobuf.Any": {
695
+ // proto3 JSON: `{ "@type": url, ...fields }`, or `{ "@type": url, value }`
696
+ // for a well-known type with its own JSON. A type the descriptors don't
697
+ // know is `{ "@type": url, value: <base64 bytes> }`.
698
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
699
+ throw new ProtobufEncodeError(`${field}: expected an Any object`);
700
+ }
701
+ const { "@type": typeUrl, ...rest } = value as Record<string, unknown>;
702
+ if (typeUrl === undefined && Object.keys(rest).length === 0) return true;
703
+ if (typeof typeUrl !== "string" || !typeUrl.includes("/")) {
704
+ throw new ProtobufEncodeError(`${field}: an Any needs an "@type" type URL`);
705
+ }
706
+ const type = typeNameOf(typeUrl);
707
+ let inner: Uint8Array;
708
+ if (!isKnownMessage(d, type)) {
709
+ if (typeof rest.value !== "string") {
710
+ throw new ProtobufEncodeError(`${field}: unknown Any type ${typeUrl}`);
711
+ }
712
+ inner = toBytes(rest.value, field);
713
+ } else {
714
+ inner = encodeMessage(d, type, CUSTOM_JSON.has(type) ? rest.value : rest);
715
+ }
716
+ w.tag(1, 2);
717
+ w.delimited((out) => out.bytes(textEncoder.encode(typeUrl)));
718
+ if (inner.length > 0) {
719
+ w.tag(2, 2);
720
+ w.delimited((out) => out.bytes(inner));
721
+ }
722
+ return true;
723
+ }
724
+ default: {
725
+ const kind = WRAPPER_KINDS[name];
726
+ if (!kind) return false;
727
+ writeValue(d, w, 1, kind, undefined, value, field);
728
+ return true;
729
+ }
730
+ }
731
+ };
732
+
733
+ const writeMessageInto = (
734
+ d: ProtoDescriptors,
735
+ w: Writer,
736
+ name: string,
737
+ value: unknown,
738
+ path: string,
739
+ ): void => {
740
+ if (writeWellKnown(d, w, name, value, path)) return;
741
+ const fields = d.messages[name];
742
+ if (!fields) throw new ProtobufEncodeError(`${path}: unknown message ${name}`);
743
+ if (value === null || value === undefined) return;
744
+ if (typeof value !== "object") {
745
+ throw new ProtobufEncodeError(`${path}: expected an object for ${name}`);
746
+ }
747
+ const obj = value as Record<string, unknown>;
748
+ const set = new Map<number, string>();
749
+ for (const [num, json, kind, ref, repeated, presence] of fields) {
750
+ const v = obj[json];
751
+ // `null` is "not set", except in a google.protobuf.Value, where it is NullValue.
752
+ if (v === undefined || (v === null && ref !== "google.protobuf.Value")) continue;
753
+ if (presence !== undefined && presence >= 2) {
754
+ const other = set.get(presence);
755
+ if (other !== undefined) {
756
+ throw new ProtobufEncodeError(`${path}: ${other} and ${json} are members of one oneof`);
757
+ }
758
+ set.set(presence, json);
759
+ }
760
+ // proto3: a field without presence is not written at its default.
761
+ if (
762
+ !repeated &&
763
+ !presence &&
764
+ kind !== "message" &&
765
+ kind !== "map" &&
766
+ isDefault(d, kind, ref, v)
767
+ ) {
768
+ continue;
769
+ }
770
+ const field = `${path}.${json}`;
771
+ if (kind === "map") {
772
+ const [kk, vk, vr] = ref as MapRef;
773
+ for (const [k, item] of Object.entries(v as Record<string, unknown>)) {
774
+ if (item === undefined) continue;
775
+ w.tag(num, 2);
776
+ w.delimited((entry) => {
777
+ writeValue(d, entry, 1, kk, undefined, kk === "bool" ? k === "true" : k, `${field}.key`);
778
+ writeValue(d, entry, 2, vk, vr, item, `${field}[${k}]`);
779
+ });
780
+ }
781
+ continue;
782
+ }
783
+ if (repeated) {
784
+ if (!Array.isArray(v)) throw new ProtobufEncodeError(`${field}: expected an array`);
785
+ if (v.length === 0) continue;
786
+ if (isPackable(kind)) {
787
+ w.tag(num, 2);
788
+ w.delimited((inner) => {
789
+ for (const item of v) writeScalar(d, inner, kind, ref as string, item, field);
790
+ });
791
+ } else {
792
+ for (const item of v) writeValue(d, w, num, kind, ref, item, field);
793
+ }
794
+ continue;
795
+ }
796
+ writeValue(d, w, num, kind, ref, v, field);
797
+ }
798
+ };
799
+
800
+ /** Whether `v` is the proto3 default of a scalar or enum field (`-0.0` is not). */
801
+ const isDefault = (
802
+ d: ProtoDescriptors,
803
+ kind: FieldKind,
804
+ ref: string | MapRef | 0 | undefined,
805
+ v: unknown,
806
+ ): boolean => {
807
+ switch (kind) {
808
+ case "string":
809
+ case "bytes":
810
+ return v === "";
811
+ case "bool":
812
+ return v === false;
813
+ case "enum":
814
+ return (
815
+ v === 0 || (typeof ref === "string" && typeof v === "string" && d.enums[ref]?.[v] === 0)
816
+ );
817
+ default:
818
+ return (v === 0 && !Object.is(v, -0)) || v === "0" || v === 0n;
819
+ }
820
+ };
821
+
822
+ /** Encode a proto3 JSON value of message `name` to protobuf bytes. */
823
+ export const encodeMessage = (d: ProtoDescriptors, name: string, value: unknown): Uint8Array => {
824
+ if (value === null && name !== "google.protobuf.Value") {
825
+ throw new ProtobufEncodeError(`${name}: expected a message, got null`);
826
+ }
827
+ const w = new Writer();
828
+ writeMessageInto(d, w, name, value, name);
829
+ return w.finish();
830
+ };
831
+
832
+ // ============================================================================
833
+ // Decode (binary -> proto3 JSON)
834
+ // ============================================================================
835
+
836
+ const readScalar = (
837
+ d: ProtoDescriptors,
838
+ r: Reader,
839
+ kind: FieldKind,
840
+ ref: string | undefined,
841
+ ): unknown => {
842
+ switch (kind) {
843
+ case "double":
844
+ return r.double();
845
+ case "float":
846
+ return r.float();
847
+ case "int32":
848
+ return Number(BigInt.asIntN(32, r.varint64()));
849
+ case "uint32":
850
+ return Number(BigInt.asUintN(32, r.varint64()));
851
+ case "int64":
852
+ return BigInt.asIntN(64, r.varint64()).toString();
853
+ case "uint64":
854
+ return BigInt.asUintN(64, r.varint64()).toString();
855
+ case "sint32":
856
+ case "sint64": {
857
+ // Zigzag over the kind's width: a sint32 is the low 32 bits of the varint.
858
+ const n = kind === "sint32" ? BigInt.asUintN(32, r.varint64()) : r.varint64();
859
+ const v = (n >> 1n) ^ -(n & 1n);
860
+ return kind === "sint32" ? Number(v) : BigInt.asIntN(64, v).toString();
861
+ }
862
+ case "fixed32":
863
+ return r.fixed32();
864
+ case "sfixed32":
865
+ return r.fixed32() | 0;
866
+ case "fixed64":
867
+ return r.fixed64().toString();
868
+ case "sfixed64":
869
+ return BigInt.asIntN(64, r.fixed64()).toString();
870
+ case "bool":
871
+ return r.varint64() !== 0n;
872
+ case "enum": {
873
+ const n = Number(BigInt.asIntN(32, r.varint64()));
874
+ const values = ref ? d.enums[ref] : undefined;
875
+ if (values) {
876
+ for (const key in values) if (values[key] === n) return key;
877
+ }
878
+ return n;
879
+ }
880
+ default:
881
+ throw new ProtobufDecodeError(`${kind} is not a scalar`);
882
+ }
883
+ };
884
+
885
+ const readValue = (
886
+ d: ProtoDescriptors,
887
+ r: Reader,
888
+ wire: number,
889
+ kind: FieldKind,
890
+ ref: string | MapRef | 0 | undefined,
891
+ ): unknown => {
892
+ switch (kind) {
893
+ case "string":
894
+ return textDecoder.decode(r.delimited());
895
+ case "bytes":
896
+ return bytesToBase64(r.delimited());
897
+ case "message":
898
+ return decodeMessage(d, ref as string, r.delimited());
899
+ default:
900
+ if (wire === 2) throw new ProtobufDecodeError("unexpected length-delimited scalar");
901
+ return readScalar(d, r, kind, typeof ref === "string" ? ref : undefined);
902
+ }
903
+ };
904
+
905
+ const readStructValue = (bytes: Uint8Array): unknown => {
906
+ const r = new Reader(bytes);
907
+ let out: unknown = null;
908
+ while (!r.done) {
909
+ const [num, wire] = r.tag();
910
+ switch (num) {
911
+ case 1:
912
+ r.varint64();
913
+ out = null;
914
+ break;
915
+ case 2:
916
+ out = r.double();
917
+ break;
918
+ case 3:
919
+ out = textDecoder.decode(r.delimited());
920
+ break;
921
+ case 4:
922
+ out = r.varint64() !== 0n;
923
+ break;
924
+ case 5:
925
+ out = readStruct(r.delimited());
926
+ break;
927
+ case 6:
928
+ out = readList(r.delimited());
929
+ break;
930
+ default:
931
+ r.skip(wire, num);
932
+ }
933
+ }
934
+ return out;
935
+ };
936
+
937
+ const readList = (bytes: Uint8Array): unknown[] => {
938
+ const r = new Reader(bytes);
939
+ const items: unknown[] = [];
940
+ while (!r.done) {
941
+ const [num, wire] = r.tag();
942
+ if (num === 1 && wire === 2) items.push(readStructValue(r.delimited()));
943
+ else r.skip(wire, num);
944
+ }
945
+ return items;
946
+ };
947
+
948
+ const readStruct = (bytes: Uint8Array): Record<string, unknown> => {
949
+ const r = new Reader(bytes);
950
+ const out: Record<string, unknown> = {};
951
+ while (!r.done) {
952
+ const [num, wire] = r.tag();
953
+ if (num !== 1 || wire !== 2) {
954
+ r.skip(wire, num);
955
+ continue;
956
+ }
957
+ const entry = new Reader(r.delimited());
958
+ let key = "";
959
+ let value: unknown = null;
960
+ while (!entry.done) {
961
+ const [n, w] = entry.tag();
962
+ if (n === 1 && w === 2) key = textDecoder.decode(entry.delimited());
963
+ else if (n === 2 && w === 2) value = readStructValue(entry.delimited());
964
+ else entry.skip(w, n);
965
+ }
966
+ out[key] = value;
967
+ }
968
+ return out;
969
+ };
970
+
971
+ /** `seconds` and `nanos` of a Timestamp or Duration. */
972
+ const readSecondsNanos = (bytes: Uint8Array): { seconds: bigint; nanos: number } => {
973
+ const r = new Reader(bytes);
974
+ let seconds = 0n;
975
+ let nanos = 0;
976
+ while (!r.done) {
977
+ const [n, wire] = r.tag();
978
+ if (n === 1 && wire === 0) seconds = BigInt.asIntN(64, r.varint64());
979
+ else if (n === 2 && wire === 0) nanos = Number(BigInt.asIntN(32, r.varint64()));
980
+ else r.skip(wire, n);
981
+ }
982
+ return { seconds, nanos };
983
+ };
984
+
985
+ /** Fractional seconds as proto3 JSON writes them: 0, 3, 6 or 9 digits. */
986
+ const fraction = (nanos: number): string =>
987
+ nanos === 0
988
+ ? ""
989
+ : nanos % 1_000_000 === 0
990
+ ? `.${String(nanos / 1_000_000).padStart(3, "0")}`
991
+ : nanos % 1_000 === 0
992
+ ? `.${String(nanos / 1_000).padStart(6, "0")}`
993
+ : `.${String(nanos).padStart(9, "0")}`;
994
+
995
+ const formatDuration = (seconds: bigint, nanos: number): string => {
996
+ const negative = seconds < 0n || nanos < 0;
997
+ const abs = seconds < 0n ? -seconds : seconds;
998
+ return `${negative ? "-" : ""}${abs}${fraction(Math.abs(nanos))}s`;
999
+ };
1000
+
1001
+ /** A FieldMask path in proto3 JSON: `foo_bar.baz` -> `fooBar.baz`. */
1002
+ const pathToJson = (path: string): string =>
1003
+ path.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
1004
+
1005
+ /** A FieldMask path from proto3 JSON: `fooBar.baz` -> `foo_bar.baz`. */
1006
+ const pathFromJson = (path: string, field: string): string => {
1007
+ if (/_/.test(path) || !/^[A-Za-z0-9.]*$/.test(path)) {
1008
+ throw new ProtobufEncodeError(`${field}: invalid FieldMask path ${JSON.stringify(path)}`);
1009
+ }
1010
+ return path.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
1011
+ };
1012
+
1013
+ /** Well-known types whose proto3 JSON isn't an object of their fields. */
1014
+ const CUSTOM_JSON = new Set([
1015
+ "google.protobuf.Any",
1016
+ "google.protobuf.Timestamp",
1017
+ "google.protobuf.Duration",
1018
+ "google.protobuf.FieldMask",
1019
+ "google.protobuf.Struct",
1020
+ "google.protobuf.Value",
1021
+ "google.protobuf.ListValue",
1022
+ "google.protobuf.DoubleValue",
1023
+ "google.protobuf.FloatValue",
1024
+ "google.protobuf.Int64Value",
1025
+ "google.protobuf.UInt64Value",
1026
+ "google.protobuf.Int32Value",
1027
+ "google.protobuf.UInt32Value",
1028
+ "google.protobuf.BoolValue",
1029
+ "google.protobuf.StringValue",
1030
+ "google.protobuf.BytesValue",
1031
+ ]);
1032
+
1033
+ /** The message name a type URL names (`type.googleapis.com/a.B` -> `a.B`). */
1034
+ const typeNameOf = (url: string): string => url.slice(url.lastIndexOf("/") + 1);
1035
+
1036
+ const isKnownMessage = (d: ProtoDescriptors, name: string): boolean =>
1037
+ CUSTOM_JSON.has(name) || name === "google.protobuf.Empty" || d.messages[name] !== undefined;
1038
+
1039
+ const readWellKnown = (
1040
+ d: ProtoDescriptors,
1041
+ name: string,
1042
+ bytes: Uint8Array,
1043
+ ): { value: unknown } | undefined => {
1044
+ if (!name.startsWith("google.protobuf.")) return undefined;
1045
+ switch (name) {
1046
+ case "google.protobuf.Empty":
1047
+ return { value: {} };
1048
+ case "google.protobuf.Timestamp": {
1049
+ // proto3 JSON can't write a Timestamp outside 0001 to 9999.
1050
+ const { seconds, nanos } = readSecondsNanos(bytes);
1051
+ if (seconds < MIN_TIMESTAMP || seconds > MAX_TIMESTAMP || nanos < 0 || nanos > 999_999_999) {
1052
+ throw new ProtobufJsonRangeError(`Timestamp ${seconds}s ${nanos}ns is out of range`);
1053
+ }
1054
+ return { value: formatTimestamp(seconds, nanos) };
1055
+ }
1056
+ case "google.protobuf.Duration": {
1057
+ // Nor a Duration beyond 10,000 years, or whose parts differ in sign.
1058
+ const { seconds, nanos } = readSecondsNanos(bytes);
1059
+ if (
1060
+ seconds > MAX_DURATION ||
1061
+ seconds < -MAX_DURATION ||
1062
+ Math.abs(nanos) > 999_999_999 ||
1063
+ (seconds > 0n && nanos < 0) ||
1064
+ (seconds < 0n && nanos > 0)
1065
+ ) {
1066
+ throw new ProtobufJsonRangeError(`Duration ${seconds}s ${nanos}ns is out of range`);
1067
+ }
1068
+ return { value: formatDuration(seconds, nanos) };
1069
+ }
1070
+ case "google.protobuf.FieldMask": {
1071
+ const r = new Reader(bytes);
1072
+ const paths: string[] = [];
1073
+ while (!r.done) {
1074
+ const [n, wire] = r.tag();
1075
+ if (n === 1 && wire === 2) paths.push(pathToJson(textDecoder.decode(r.delimited())));
1076
+ else r.skip(wire, n);
1077
+ }
1078
+ return { value: paths.join(",") };
1079
+ }
1080
+ case "google.protobuf.Struct":
1081
+ return { value: readStruct(bytes) };
1082
+ case "google.protobuf.Value":
1083
+ return { value: readStructValue(bytes) };
1084
+ case "google.protobuf.ListValue":
1085
+ return { value: readList(bytes) };
1086
+ case "google.protobuf.Any": {
1087
+ const r = new Reader(bytes);
1088
+ let typeUrl = "";
1089
+ let inner: Uint8Array = new Uint8Array(0);
1090
+ while (!r.done) {
1091
+ const [n, wire] = r.tag();
1092
+ if (n === 1 && wire === 2) typeUrl = textDecoder.decode(r.delimited());
1093
+ else if (n === 2 && wire === 2) inner = r.delimited();
1094
+ else r.skip(wire, n);
1095
+ }
1096
+ if (typeUrl === "") return { value: {} };
1097
+ const type = typeNameOf(typeUrl);
1098
+ // A type the descriptors don't know stays opaque: its bytes, base64.
1099
+ if (!isKnownMessage(d, type))
1100
+ return { value: { "@type": typeUrl, value: bytesToBase64(inner) } };
1101
+ const message = decodeMessage(d, type, inner);
1102
+ return {
1103
+ value: CUSTOM_JSON.has(type)
1104
+ ? { "@type": typeUrl, value: message }
1105
+ : { "@type": typeUrl, ...(message as Record<string, unknown>) },
1106
+ };
1107
+ }
1108
+ default: {
1109
+ const kind = WRAPPER_KINDS[name];
1110
+ if (!kind) return undefined;
1111
+ const r = new Reader(bytes);
1112
+ let value: unknown = defaultOf(d, kind, undefined);
1113
+ while (!r.done) {
1114
+ const [n, wire] = r.tag();
1115
+ if (n === 1 && wire === wireTypeOf(kind)) value = readValue(d, r, wire, kind, undefined);
1116
+ else r.skip(wire, n);
1117
+ }
1118
+ return { value };
1119
+ }
1120
+ }
1121
+ };
1122
+
1123
+ const concatBytes = (chunks: ReadonlyArray<Uint8Array>): Uint8Array => {
1124
+ if (chunks.length === 1) return chunks[0]!;
1125
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
1126
+ let at = 0;
1127
+ for (const c of chunks) {
1128
+ out.set(c, at);
1129
+ at += c.length;
1130
+ }
1131
+ return out;
1132
+ };
1133
+
1134
+ /** The JSON names of each oneof's members, by presence group. */
1135
+ const oneofCache = /*@__PURE__*/ new WeakMap<
1136
+ ReadonlyArray<FieldDescriptor>,
1137
+ Map<number, string[]>
1138
+ >();
1139
+
1140
+ const oneofsOf = (fields: ReadonlyArray<FieldDescriptor>): Map<number, string[]> => {
1141
+ let groups = oneofCache.get(fields);
1142
+ if (!groups) {
1143
+ groups = new Map();
1144
+ for (const [, json, , , , presence] of fields) {
1145
+ if (presence !== undefined && presence >= 2) {
1146
+ groups.set(presence, [...(groups.get(presence) ?? []), json]);
1147
+ }
1148
+ }
1149
+ oneofCache.set(fields, groups);
1150
+ }
1151
+ return groups;
1152
+ };
1153
+
1154
+ /**
1155
+ * Decode protobuf bytes of message `name` to a proto3 JSON value. As in any
1156
+ * proto3 parser, the last value of a singular field wins, a message field
1157
+ * seen more than once is merged, setting a oneof member clears the others,
1158
+ * a field whose wire type doesn't match its kind is skipped as unknown, and
1159
+ * unknown fields are dropped.
1160
+ */
1161
+ export const decodeMessage = (d: ProtoDescriptors, name: string, bytes: Uint8Array): unknown => {
1162
+ const wk = readWellKnown(d, name, bytes);
1163
+ if (wk) return wk.value;
1164
+ const fields = d.messages[name];
1165
+ if (!fields) throw new ProtobufDecodeError(`unknown message ${name}`);
1166
+ const byNumber = fieldIndex(fields);
1167
+ const oneofs = oneofsOf(fields);
1168
+ const out: Record<string, unknown> = {};
1169
+ // A singular message field's occurrences, merged by decoding them as one.
1170
+ const messages = new Map<string, { ref: string; chunks: Uint8Array[] }>();
1171
+ const r = new Reader(bytes);
1172
+ while (!r.done) {
1173
+ const [num, wire] = r.tag();
1174
+ const f = byNumber.get(num);
1175
+ if (!f) {
1176
+ r.skip(wire, num);
1177
+ continue;
1178
+ }
1179
+ const [, json, kind, ref, repeated, presence] = f;
1180
+ const packed = repeated && wire === 2 && isPackable(kind);
1181
+ if (wire !== wireTypeOf(kind) && !packed) {
1182
+ r.skip(wire, num);
1183
+ continue;
1184
+ }
1185
+ if (presence !== undefined && presence >= 2) {
1186
+ for (const other of oneofs.get(presence) ?? []) {
1187
+ if (other === json) continue;
1188
+ delete out[other];
1189
+ messages.delete(other);
1190
+ }
1191
+ }
1192
+ if (kind === "map") {
1193
+ const [kk, vk, vr] = ref as MapRef;
1194
+ const entry = new Reader(r.delimited());
1195
+ let key: unknown = defaultOf(d, kk, undefined);
1196
+ let value: unknown =
1197
+ vk === "message" ? decodeMessage(d, vr as string, new Uint8Array(0)) : defaultOf(d, vk, vr);
1198
+ while (!entry.done) {
1199
+ const [n, w] = entry.tag();
1200
+ if (n === 1 && w === wireTypeOf(kk)) key = readValue(d, entry, w, kk, undefined);
1201
+ else if (n === 2 && w === wireTypeOf(vk)) value = readValue(d, entry, w, vk, vr);
1202
+ else entry.skip(w, n);
1203
+ }
1204
+ const map = (out[json] ??= {}) as Record<string, unknown>;
1205
+ map[String(key)] = value;
1206
+ continue;
1207
+ }
1208
+ if (repeated) {
1209
+ const list = (out[json] ??= []) as unknown[];
1210
+ if (packed) {
1211
+ const items = new Reader(r.delimited());
1212
+ while (!items.done) list.push(readScalar(d, items, kind, ref as string));
1213
+ } else {
1214
+ list.push(readValue(d, r, wire, kind, ref));
1215
+ }
1216
+ continue;
1217
+ }
1218
+ if (kind === "message") {
1219
+ const seen = messages.get(json);
1220
+ if (seen) seen.chunks.push(r.delimited());
1221
+ else messages.set(json, { ref: ref as string, chunks: [r.delimited()] });
1222
+ continue;
1223
+ }
1224
+ out[json] = readValue(d, r, wire, kind, ref);
1225
+ }
1226
+ for (const [json, { ref, chunks }] of messages) {
1227
+ out[json] = decodeMessage(d, ref, concatBytes(chunks));
1228
+ }
1229
+ for (const [, json, kind, ref, repeated, presence] of fields) {
1230
+ // A singular message field has presence; a repeated one reads as [].
1231
+ if (presence || (kind === "message" && !repeated) || json in out) continue;
1232
+ out[json] = repeated ? [] : kind === "map" ? {} : defaultOf(d, kind, ref);
1233
+ }
1234
+ return out;
1235
+ };
1236
+
1237
+ /** The proto3 default of a scalar or enum field. */
1238
+ const defaultOf = (d: ProtoDescriptors, kind: FieldKind, ref: string | MapRef | 0 | undefined) => {
1239
+ switch (kind) {
1240
+ case "string":
1241
+ case "bytes":
1242
+ return "";
1243
+ case "bool":
1244
+ return false;
1245
+ case "int64":
1246
+ case "uint64":
1247
+ case "sint64":
1248
+ case "fixed64":
1249
+ case "sfixed64":
1250
+ return "0";
1251
+ case "enum": {
1252
+ const values = typeof ref === "string" ? d.enums[ref] : undefined;
1253
+ if (values) for (const key in values) if (values[key] === 0) return key;
1254
+ return 0;
1255
+ }
1256
+ default:
1257
+ return 0;
1258
+ }
1259
+ };
1260
+
1261
+ const indexCache = /*@__PURE__*/ new WeakMap<
1262
+ ReadonlyArray<FieldDescriptor>,
1263
+ Map<number, FieldDescriptor>
1264
+ >();
1265
+
1266
+ const fieldIndex = (fields: ReadonlyArray<FieldDescriptor>): Map<number, FieldDescriptor> => {
1267
+ let index = indexCache.get(fields);
1268
+ if (!index) {
1269
+ index = new Map(fields.map((f) => [f[0], f]));
1270
+ indexCache.set(fields, index);
1271
+ }
1272
+ return index;
1273
+ };
1274
+
1275
+ // ============================================================================
1276
+ // gRPC length-prefixed framing
1277
+ // ============================================================================
1278
+
1279
+ /** One gRPC message frame: `[flag=0][u32 length BE][payload]`. */
1280
+ export const frame = (payload: Uint8Array): Uint8Array => {
1281
+ const out = new Uint8Array(5 + payload.length);
1282
+ new DataView(out.buffer).setUint32(1, payload.length, false);
1283
+ out.set(payload, 5);
1284
+ return out;
1285
+ };
1286
+
1287
+ /**
1288
+ * Reads gRPC message frames from a body that arrives in chunks: `push` each
1289
+ * chunk and get back the messages it completed. `rest` is the number of
1290
+ * bytes held for an incomplete frame (`0` once a body ends cleanly).
1291
+ * Compressed frames are rejected; gRPC-Web trailer frames are skipped.
1292
+ */
1293
+ export class FrameReader {
1294
+ private buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
1295
+
1296
+ get rest(): number {
1297
+ return this.buf.length;
1298
+ }
1299
+
1300
+ push(chunk: Uint8Array): Uint8Array[] {
1301
+ if (this.buf.length === 0) this.buf = chunk;
1302
+ else {
1303
+ const next = new Uint8Array(this.buf.length + chunk.length);
1304
+ next.set(this.buf);
1305
+ next.set(chunk, this.buf.length);
1306
+ this.buf = next;
1307
+ }
1308
+ const out: Uint8Array[] = [];
1309
+ let pos = 0;
1310
+ const view = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);
1311
+ while (pos + 5 <= this.buf.length) {
1312
+ const flag = this.buf[pos]!;
1313
+ const len = view.getUint32(pos + 1, false);
1314
+ if (pos + 5 + len > this.buf.length) break;
1315
+ if (flag & 1 && !(flag & 0x80)) {
1316
+ throw new ProtobufDecodeError("compressed gRPC frames are not supported");
1317
+ }
1318
+ if (!(flag & 0x80)) out.push(this.buf.slice(pos + 5, pos + 5 + len));
1319
+ pos += 5 + len;
1320
+ }
1321
+ this.buf = this.buf.subarray(pos);
1322
+ return out;
1323
+ }
1324
+ }
1325
+
1326
+ /** Split a whole gRPC body into message payloads. */
1327
+ export const unframe = (body: Uint8Array): Uint8Array[] => {
1328
+ const reader = new FrameReader();
1329
+ const out = reader.push(body);
1330
+ if (reader.rest !== 0) throw new ProtobufDecodeError("truncated gRPC frame");
1331
+ return out;
1332
+ };