@omnibuf/core 0.0.8 → 0.1.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.
package/dist/schema.js CHANGED
@@ -2,10 +2,10 @@ import { validateValue, validateMapTypes } from './validation.js';
2
2
  // ============================================================================
3
3
  // Tier 3: Annotated Classes & Declarative Type Mapping for Plain Objects/Classes
4
4
  // ============================================================================
5
- import { base64ToUint8Array, decodeSchemaMeta, encodeField0SchemaMeta, mergeSchemaMeta, writeField0SchemaMeta, } from './blind.js';
5
+ import { base64ToUint8Array, encodeField0SchemaMeta, mergeSchemaMeta, writeField0SchemaMeta, } from './blind.js';
6
6
  import { Encoder } from './encoder.js';
7
7
  import { appendBoolArrBody, appendBytesArrBody, appendEnumArrBody, appendFloat32ArrBody, appendFloat64ArrBody, appendSintArrAutoBody, appendStringArrBody, appendUint32ArrBody, appendUintArrAutoBody, countSubMsgArrElems, } from './readers.js';
8
- import { MaxNestingDepth, WireArray, WireBoolFalse, WireBoolTrue, WireBytes, WireFixed32, WireFixed64, WireFloat32, WireFloat64, WireMap, WireSfixed32, WireSfixed64, WireSint, WireString, WireSubMsg, WireUint, decodeUTF8, decodeVarint, decodeVarintAuto, decodeVarintBigInt, decodeZigZag, decodeZigZagAuto, decodeZigZagBigInt, encodeZigZag, encodeZigZagNumber, float32FromBits, float64FromBits, parseArrayHeader, readFloat64At, readLenSlice, roundFloat32Shortest, } from './wire.js';
8
+ import { MaxNestingDepth, WireArray, WireBoolFalse, WireBoolTrue, WireBytes, WireFixed32, WireFixed64, WireFloat32, WireFloat64, WireMap, WireSfixed32, WireSfixed64, WireSint, WireString, WireSubMsg, WireUint, decodeUTF8, decodeVarint, decodeVarintAuto, decodeVarintBigInt, decodeZigZag32, decodeZigZagAuto, decodeZigZagBigInt, encodeZigZag, encodeZigZagNumber, float32FromBits, float64FromBits, parseArrayHeader, readFloat64At, readLenSlice, roundFloat32Shortest, validateField0At, } from './wire.js';
9
9
  /**
10
10
  * Converts `snake_case` field names to `protoCamelCase` (matching `protoc` and `@bufbuild/protobuf` v2).
11
11
  */
@@ -48,7 +48,44 @@ export function protoCamelCase(snakeCase) {
48
48
  export function protoSnakeCase(lowerCamelCase) {
49
49
  return lowerCamelCase.replace(/[A-Z]/g, (letter) => '_' + letter.toLowerCase());
50
50
  }
51
- const RESERVED_OBJECT_PROPERTIES = new Set(['constructor', 'toString', 'toJSON', 'valueOf']);
51
+ const RESERVED_OBJECT_PROPERTIES = new Set([
52
+ '__proto__',
53
+ 'constructor',
54
+ 'hasOwnProperty',
55
+ 'isPrototypeOf',
56
+ 'propertyIsEnumerable',
57
+ 'toLocaleString',
58
+ 'toString',
59
+ 'toJSON',
60
+ 'valueOf',
61
+ ]);
62
+ function getOwnProp(obj, key) {
63
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
64
+ if (!desc)
65
+ return undefined;
66
+ return desc.get ? desc.get.call(obj) : desc.value;
67
+ }
68
+ function setOwnProp(obj, key, value) {
69
+ const desc = Object.getOwnPropertyDescriptor(obj, key);
70
+ if (desc?.set) {
71
+ desc.set.call(obj, value);
72
+ return;
73
+ }
74
+ Object.defineProperty(obj, key, {
75
+ value,
76
+ writable: true,
77
+ enumerable: true,
78
+ configurable: true,
79
+ });
80
+ }
81
+ function setFieldOnObj(obj, f, value) {
82
+ if (f.isProtoKey) {
83
+ setOwnProp(obj, f.propKey, value);
84
+ }
85
+ else {
86
+ obj[f.propKey] = value;
87
+ }
88
+ }
52
89
  /**
53
90
  * Escapes field names that collide with built-in JavaScript `Object.prototype` properties.
54
91
  */
@@ -206,10 +243,13 @@ export class MessageSchema {
206
243
  shortName;
207
244
  fields;
208
245
  oneofs;
246
+ nonOneofFields;
247
+ denseByNum;
209
248
  byNum = new Map();
210
249
  byKey = new Map();
211
250
  oneofByName = new Map();
212
251
  factory;
252
+ precomputedDescMap;
213
253
  generatedHooks;
214
254
  typeNameDesc;
215
255
  cachedMeta = null;
@@ -233,6 +273,9 @@ export class MessageSchema {
233
273
  if (!Number.isInteger(spec.fieldNum) || spec.fieldNum < 1 || spec.fieldNum > 536870911) {
234
274
  throw new Error(`omnibuf: field number ${spec.fieldNum} on ${typeName}.${propKey} out of range (1..536870911)`);
235
275
  }
276
+ if (spec.fieldNum >= 19000 && spec.fieldNum <= 19999) {
277
+ throw new Error(`omnibuf: field number ${spec.fieldNum} on ${typeName}.${propKey} is in Protobuf reserved range (19000..19999)`);
278
+ }
236
279
  if (this.byNum.has(spec.fieldNum)) {
237
280
  throw new Error(`omnibuf: duplicate field number ${spec.fieldNum} on ${typeName}`);
238
281
  }
@@ -265,6 +308,10 @@ export class MessageSchema {
265
308
  oneof: oneofLocal,
266
309
  oneofProtoName: oneofProto,
267
310
  useBigInt: spec.useBigInt ?? false,
311
+ isProtoKey: propKey === '__proto__',
312
+ inObjectProto: propKey in Object.prototype,
313
+ altInObjectProto: altKey !== undefined && altKey in Object.prototype,
314
+ oneofProtoInObjectProto: oneofProto !== undefined && oneofProto in Object.prototype,
268
315
  resolveSubSchema,
269
316
  };
270
317
  if (effectiveType === 'map') {
@@ -299,7 +346,107 @@ export class MessageSchema {
299
346
  // Sort fields by ascending fieldNum for deterministic output
300
347
  compiled.sort((a, b) => a.fieldNum - b.fieldNum);
301
348
  this.fields = compiled;
349
+ this.nonOneofFields = compiled.filter((f) => !f.oneof);
302
350
  this.oneofs = Array.from(oneofMap.values());
351
+ const dense = new Array(65);
352
+ for (const cf of compiled) {
353
+ if (cf.fieldNum <= 64) {
354
+ dense[cf.fieldNum] = cf;
355
+ }
356
+ }
357
+ this.denseByNum = dense;
358
+ const canUseProtoFastPath = !factory &&
359
+ !compiled.some((f) => f.isProtoKey || f.inObjectProto || f.altKey === '__proto__') &&
360
+ !this.oneofs.some((o) => o.localName === '__proto__' ||
361
+ o.protoName === '__proto__' ||
362
+ o.localName in Object.prototype);
363
+ if (canUseProtoFastPath) {
364
+ this.precomputedDescMap = this.buildDescriptorMap();
365
+ }
366
+ else {
367
+ this.precomputedDescMap = null;
368
+ }
369
+ }
370
+ buildDescriptorMap() {
371
+ const descMap = {
372
+ $typeName: this.typeNameDesc,
373
+ };
374
+ for (const oneof of this.oneofs) {
375
+ if (oneof.protoName !== oneof.localName) {
376
+ const ln = oneof.localName;
377
+ descMap[oneof.protoName] = {
378
+ get() {
379
+ return this[ln];
380
+ },
381
+ set(v) {
382
+ this[ln] = v;
383
+ },
384
+ enumerable: false,
385
+ configurable: true,
386
+ };
387
+ }
388
+ }
389
+ for (const f of this.fields) {
390
+ if (f.oneof) {
391
+ const oneofKey = f.oneof;
392
+ const caseName = f.localName;
393
+ const altCaseName = f.name;
394
+ const propKey = f.propKey;
395
+ descMap[propKey] = {
396
+ get() {
397
+ const g = this[oneofKey];
398
+ if (g &&
399
+ typeof g === 'object' &&
400
+ (g.case === caseName || g.case === altCaseName || g.case === propKey)) {
401
+ return g.value;
402
+ }
403
+ return undefined;
404
+ },
405
+ set(v) {
406
+ if (v === undefined || v === null) {
407
+ const g = this[oneofKey];
408
+ if (g &&
409
+ typeof g === 'object' &&
410
+ (g.case === caseName || g.case === altCaseName || g.case === propKey)) {
411
+ this[oneofKey] = { case: undefined };
412
+ }
413
+ }
414
+ else {
415
+ this[oneofKey] = { case: caseName, value: v };
416
+ }
417
+ },
418
+ enumerable: false,
419
+ configurable: true,
420
+ };
421
+ if (f.altKey) {
422
+ descMap[f.altKey] = {
423
+ get() {
424
+ return this[propKey];
425
+ },
426
+ set(v) {
427
+ this[propKey] = v;
428
+ },
429
+ enumerable: false,
430
+ configurable: true,
431
+ };
432
+ }
433
+ continue;
434
+ }
435
+ if (f.altKey) {
436
+ const pk = f.propKey;
437
+ descMap[f.altKey] = {
438
+ get() {
439
+ return this[pk];
440
+ },
441
+ set(v) {
442
+ this[pk] = v;
443
+ },
444
+ enumerable: false,
445
+ configurable: true,
446
+ };
447
+ }
448
+ }
449
+ return descMap;
303
450
  }
304
451
  /**
305
452
  * Look up a compiled field by number, `localName` (`camelCase`), `.proto` `name` (`snake_case`),
@@ -326,17 +473,23 @@ export class MessageSchema {
326
473
  });
327
474
  }
328
475
  for (const oneof of this.oneofs) {
329
- if (!(oneof.localName in obj) || obj[oneof.localName] === undefined) {
330
- obj[oneof.localName] = { case: undefined };
476
+ if (!Object.hasOwn(obj, oneof.localName) || getOwnProp(obj, oneof.localName) === undefined) {
477
+ setOwnProp(obj, oneof.localName, { case: undefined });
331
478
  }
332
- if (oneof.protoName !== oneof.localName && !(oneof.protoName in obj)) {
479
+ if (oneof.protoName !== oneof.localName && !Object.hasOwn(obj, oneof.protoName)) {
333
480
  const ln = oneof.localName;
481
+ const isProtoLn = ln === '__proto__';
334
482
  Object.defineProperty(obj, oneof.protoName, {
335
483
  get() {
336
- return this[ln];
484
+ return isProtoLn ? getOwnProp(this, ln) : this[ln];
337
485
  },
338
486
  set(v) {
339
- this[ln] = v;
487
+ if (isProtoLn) {
488
+ setOwnProp(this, ln, v);
489
+ }
490
+ else {
491
+ this[ln] = v;
492
+ }
340
493
  },
341
494
  enumerable: false,
342
495
  configurable: true,
@@ -349,7 +502,7 @@ export class MessageSchema {
349
502
  const caseName = f.localName;
350
503
  const altCaseName = f.name;
351
504
  const propDesc = Object.getOwnPropertyDescriptor(obj, f.propKey);
352
- if (!(f.propKey in obj) || (propDesc && 'value' in propDesc)) {
505
+ if (!propDesc || 'value' in propDesc) {
353
506
  const initialPlainVal = propDesc?.value;
354
507
  Object.defineProperty(obj, f.propKey, {
355
508
  get() {
@@ -381,14 +534,20 @@ export class MessageSchema {
381
534
  obj[oneofKey] = { case: caseName, value: initialPlainVal };
382
535
  }
383
536
  }
384
- if (f.altKey && !(f.altKey in obj)) {
537
+ if (f.altKey && !Object.hasOwn(obj, f.altKey)) {
385
538
  const pk = f.propKey;
539
+ const isProtoPk = Boolean(f.isProtoKey);
386
540
  Object.defineProperty(obj, f.altKey, {
387
541
  get() {
388
- return this[pk];
542
+ return isProtoPk ? getOwnProp(this, pk) : this[pk];
389
543
  },
390
544
  set(v) {
391
- this[pk] = v;
545
+ if (isProtoPk) {
546
+ setOwnProp(this, pk, v);
547
+ }
548
+ else {
549
+ this[pk] = v;
550
+ }
392
551
  },
393
552
  enumerable: false,
394
553
  configurable: true,
@@ -396,14 +555,20 @@ export class MessageSchema {
396
555
  }
397
556
  continue;
398
557
  }
399
- if (f.altKey && !(f.altKey in obj)) {
558
+ if (f.altKey && !Object.hasOwn(obj, f.altKey)) {
400
559
  const pk = f.propKey;
560
+ const isProtoPk = Boolean(f.isProtoKey);
401
561
  Object.defineProperty(obj, f.altKey, {
402
562
  get() {
403
- return this[pk];
563
+ return isProtoPk ? getOwnProp(this, pk) : this[pk];
404
564
  },
405
565
  set(v) {
406
- this[pk] = v;
566
+ if (isProtoPk) {
567
+ setOwnProp(this, pk, v);
568
+ }
569
+ else {
570
+ this[pk] = v;
571
+ }
407
572
  },
408
573
  enumerable: false,
409
574
  configurable: true,
@@ -433,6 +598,26 @@ export class MessageSchema {
433
598
  return init;
434
599
  }
435
600
  const hasGenCreate = Boolean(this.generatedHooks?.create);
601
+ if (!hasGenCreate && this.precomputedDescMap !== null) {
602
+ const obj = {};
603
+ let nextCreating;
604
+ if (this.isCyclicOrDeep()) {
605
+ nextCreating = new Set(creatingAncestors);
606
+ nextCreating.add(this);
607
+ }
608
+ for (let i = 0; i < this.oneofs.length; i++) {
609
+ obj[this.oneofs[i].localName] = { case: undefined };
610
+ }
611
+ for (let i = 0; i < this.nonOneofFields.length; i++) {
612
+ const f = this.nonOneofFields[i];
613
+ obj[f.propKey] = f.explicitPresence ? undefined : defaultFieldValue(f, nextCreating);
614
+ }
615
+ Object.defineProperties(obj, this.precomputedDescMap);
616
+ if (!init) {
617
+ return obj;
618
+ }
619
+ return this.applyInitToInstance(obj, init);
620
+ }
436
621
  const obj = hasGenCreate
437
622
  ? this.generatedHooks.create()
438
623
  : this.factory
@@ -450,68 +635,83 @@ export class MessageSchema {
450
635
  if (f.oneof)
451
636
  continue;
452
637
  if (f.explicitPresence) {
453
- if (!(f.propKey in obj)) {
454
- obj[f.propKey] = undefined;
638
+ if (f.inObjectProto ? !Object.hasOwn(obj, f.propKey) : !(f.propKey in obj)) {
639
+ setFieldOnObj(obj, f, undefined);
455
640
  }
456
641
  continue;
457
642
  }
458
- if (obj[f.propKey] === undefined) {
459
- obj[f.propKey] = defaultFieldValue(f, nextCreating);
643
+ const cur = f.inObjectProto ? getOwnProp(obj, f.propKey) : obj[f.propKey];
644
+ if (cur === undefined) {
645
+ setFieldOnObj(obj, f, defaultFieldValue(f, nextCreating));
460
646
  }
461
647
  }
462
648
  }
463
649
  if (init) {
464
- for (const oneof of this.oneofs) {
465
- const initOneof = init[oneof.localName] ??
466
- (oneof.protoName !== oneof.localName ? init[oneof.protoName] : undefined);
467
- if (initOneof && typeof initOneof === 'object' && 'case' in initOneof) {
468
- if (initOneof.case === undefined) {
469
- obj[oneof.localName] = { case: undefined };
470
- }
471
- else {
472
- const matchingField = oneof.fields.find((f) => f.localName === initOneof.case ||
473
- f.name === initOneof.case ||
474
- f.propKey === initOneof.case);
475
- if (matchingField) {
476
- obj[oneof.localName] = {
477
- case: matchingField.localName,
478
- value: initFieldValue(matchingField, initOneof.value),
479
- };
480
- }
481
- }
650
+ return this.applyInitToInstance(obj, init);
651
+ }
652
+ return obj;
653
+ }
654
+ applyInitToInstance(obj, init) {
655
+ for (const oneof of this.oneofs) {
656
+ const localVal = oneof.localName in Object.prototype
657
+ ? getOwnProp(init, oneof.localName)
658
+ : init[oneof.localName];
659
+ const protoVal = oneof.protoName !== oneof.localName
660
+ ? oneof.protoName in Object.prototype
661
+ ? getOwnProp(init, oneof.protoName)
662
+ : init[oneof.protoName]
663
+ : undefined;
664
+ const initOneof = localVal ?? protoVal;
665
+ if (initOneof && typeof initOneof === 'object' && 'case' in initOneof) {
666
+ if (initOneof.case === undefined) {
667
+ obj[oneof.localName] = { case: undefined };
482
668
  }
483
- }
484
- for (const f of this.fields) {
485
- const initVal = init[f.propKey] !== undefined
486
- ? init[f.propKey]
487
- : f.altKey !== undefined
488
- ? init[f.altKey]
489
- : undefined;
490
- if (initVal !== undefined) {
491
- if (f.oneof) {
492
- obj[f.oneof] = {
493
- case: f.localName,
494
- value: initFieldValue(f, initVal),
669
+ else {
670
+ const matchingField = oneof.fields.find((f) => f.localName === initOneof.case ||
671
+ f.name === initOneof.case ||
672
+ f.propKey === initOneof.case);
673
+ if (matchingField) {
674
+ obj[oneof.localName] = {
675
+ case: matchingField.localName,
676
+ value: initFieldValue(matchingField, initOneof.value),
495
677
  };
496
678
  }
497
- else {
498
- obj[f.propKey] = initFieldValue(f, initVal);
499
- }
500
679
  }
501
680
  }
502
- if (Array.isArray(init.$unknown) && init.$unknown.length > 0) {
503
- Object.defineProperty(obj, '$unknown', {
504
- value: init.$unknown.map((u) => ({
505
- no: u.no,
506
- wireType: u.wireType,
507
- data: u.data.slice(),
508
- })),
509
- enumerable: false,
510
- writable: true,
511
- configurable: true,
512
- });
681
+ }
682
+ for (const f of this.fields) {
683
+ const pVal = f.inObjectProto ? getOwnProp(init, f.propKey) : init[f.propKey];
684
+ const initVal = pVal !== undefined
685
+ ? pVal
686
+ : f.altKey !== undefined
687
+ ? f.altInObjectProto
688
+ ? getOwnProp(init, f.altKey)
689
+ : init[f.altKey]
690
+ : undefined;
691
+ if (initVal !== undefined) {
692
+ if (f.oneof) {
693
+ obj[f.oneof] = {
694
+ case: f.localName,
695
+ value: initFieldValue(f, initVal),
696
+ };
697
+ }
698
+ else {
699
+ setFieldOnObj(obj, f, initFieldValue(f, initVal));
700
+ }
513
701
  }
514
702
  }
703
+ if (Array.isArray(init.$unknown) && init.$unknown.length > 0) {
704
+ Object.defineProperty(obj, '$unknown', {
705
+ value: init.$unknown.map((u) => ({
706
+ no: u.no,
707
+ wireType: u.wireType,
708
+ data: u.data.slice(),
709
+ })),
710
+ enumerable: false,
711
+ writable: true,
712
+ configurable: true,
713
+ });
714
+ }
515
715
  return obj;
516
716
  }
517
717
  /**
@@ -539,10 +739,10 @@ export class MessageSchema {
539
739
  return;
540
740
  }
541
741
  if (f.explicitPresence) {
542
- msg[f.propKey] = undefined;
742
+ setFieldOnObj(msg, f, undefined);
543
743
  return;
544
744
  }
545
- msg[f.propKey] = defaultFieldValue(f);
745
+ setFieldOnObj(msg, f, defaultFieldValue(f));
546
746
  }
547
747
  /**
548
748
  * Deep-clones `msg`, including nested messages, arrays, maps, `oneof` groups, `Uint8Array` buffers, and `$unknown` fields.
@@ -561,10 +761,10 @@ export class MessageSchema {
561
761
  }
562
762
  }
563
763
  else if (f.explicitPresence) {
564
- out[f.propKey] = val === undefined ? undefined : cloneFieldValue(f, val);
764
+ setFieldOnObj(out, f, val === undefined ? undefined : cloneFieldValue(f, val));
565
765
  }
566
766
  else {
567
- out[f.propKey] = cloneFieldValue(f, val);
767
+ setFieldOnObj(out, f, cloneFieldValue(f, val));
568
768
  }
569
769
  }
570
770
  if (Array.isArray(src.$unknown) && src.$unknown.length > 0) {
@@ -650,7 +850,7 @@ export class MessageSchema {
650
850
  const visiting = new Set();
651
851
  const visited = new Set();
652
852
  const dfs = (node, depth) => {
653
- if (depth > MaxNestingDepth)
853
+ if (1 + depth * 2 > MaxNestingDepth)
654
854
  return true;
655
855
  if (visiting.has(node))
656
856
  return true;
@@ -677,11 +877,15 @@ export class MessageSchema {
677
877
  * For recursive schemas, follows the actual populated structure of `msg` when provided,
678
878
  * and terminates static cycle edges cleanly without exponential expansion.
679
879
  */
680
- getSchemaMeta(depth = 0, msg, ancestors) {
681
- if (depth === 0 && !msg && this.cachedMeta) {
880
+ getSchemaMeta(depth = 0, msg, ancestors, baseContainerDepth = 1) {
881
+ if (depth === 0 && baseContainerDepth === 1 && !msg && this.cachedMeta) {
682
882
  return this.cachedMeta;
683
883
  }
684
- if (depth === 0 && msg && !this.isCyclicOrDeep() && this.cachedMeta) {
884
+ if (depth === 0 &&
885
+ baseContainerDepth === 1 &&
886
+ msg &&
887
+ !this.isCyclicOrDeep() &&
888
+ this.cachedMeta) {
685
889
  return this.cachedMeta;
686
890
  }
687
891
  const fieldsMap = {};
@@ -689,9 +893,10 @@ export class MessageSchema {
689
893
  const pathAncestors = ancestors ?? new Set();
690
894
  const nextAncestors = new Set(pathAncestors);
691
895
  nextAncestors.add(this);
896
+ const schemaDepth = baseContainerDepth + depth * 2;
692
897
  for (const f of this.fields) {
693
898
  fieldsMap[f.fieldNum] = f.name;
694
- if (f.resolveSubSchema && depth < MaxNestingDepth) {
899
+ if (f.resolveSubSchema && schemaDepth + 3 <= MaxNestingDepth) {
695
900
  const sub = f.resolveSubSchema();
696
901
  if (!sub)
697
902
  continue;
@@ -699,10 +904,10 @@ export class MessageSchema {
699
904
  const rawVal = getFieldFromMsg(msg, f);
700
905
  if (f.effectiveType === 'submsg') {
701
906
  if (rawVal && typeof rawVal === 'object') {
702
- childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, rawVal, nextAncestors);
907
+ childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, rawVal, nextAncestors, baseContainerDepth);
703
908
  }
704
909
  else if (!pathAncestors.has(sub)) {
705
- childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors);
910
+ childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors, baseContainerDepth);
706
911
  }
707
912
  }
708
913
  else if (f.effectiveType === 'submsg[]') {
@@ -711,7 +916,7 @@ export class MessageSchema {
711
916
  for (let i = 0; i < rawVal.length; i++) {
712
917
  const elem = rawVal[i];
713
918
  if (elem && typeof elem === 'object') {
714
- merged = mergeSchemaMeta(merged, sub.getSchemaMeta(depth + 1, elem, nextAncestors));
919
+ merged = mergeSchemaMeta(merged, sub.getSchemaMeta(depth + 1, elem, nextAncestors, baseContainerDepth));
715
920
  }
716
921
  }
717
922
  if (merged) {
@@ -719,7 +924,7 @@ export class MessageSchema {
719
924
  }
720
925
  }
721
926
  else if (!pathAncestors.has(sub)) {
722
- childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors);
927
+ childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors, baseContainerDepth);
723
928
  }
724
929
  }
725
930
  else if (f.effectiveType === 'map' && f.mapValType === 'submsg') {
@@ -733,7 +938,7 @@ export class MessageSchema {
733
938
  for (let i = 0; i < vals.length; i++) {
734
939
  const v = vals[i];
735
940
  if (v && typeof v === 'object') {
736
- merged = mergeSchemaMeta(merged, sub.getSchemaMeta(depth + 1, v, nextAncestors));
941
+ merged = mergeSchemaMeta(merged, sub.getSchemaMeta(depth + 1, v, nextAncestors, baseContainerDepth));
737
942
  }
738
943
  }
739
944
  if (merged) {
@@ -741,12 +946,12 @@ export class MessageSchema {
741
946
  }
742
947
  }
743
948
  else if (!pathAncestors.has(sub)) {
744
- childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors);
949
+ childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors, baseContainerDepth);
745
950
  }
746
951
  }
747
952
  }
748
953
  else if (!pathAncestors.has(sub)) {
749
- childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors);
954
+ childrenMap[f.fieldNum] = sub.getSchemaMeta(depth + 1, undefined, nextAncestors, baseContainerDepth);
750
955
  }
751
956
  else {
752
957
  childrenMap[f.fieldNum] = sub.getShallowSchemaMeta();
@@ -760,23 +965,25 @@ export class MessageSchema {
760
965
  if (Object.keys(childrenMap).length > 0) {
761
966
  meta.children = childrenMap;
762
967
  }
763
- if (depth === 0 && !msg) {
968
+ if (depth === 0 && baseContainerDepth === 1 && !msg) {
764
969
  this.cachedMeta = meta;
765
970
  }
766
971
  return meta;
767
972
  }
973
+ getCachedField0Det() {
974
+ if (!this.cachedField0Det) {
975
+ this.cachedField0Det = encodeField0SchemaMeta(this.getSchemaMeta(0), true);
976
+ }
977
+ return this.cachedField0Det;
978
+ }
768
979
  /**
769
980
  * Returns pre-encoded deterministic Field #0 bytes.
770
981
  */
771
982
  getField0Bytes(deterministic = true) {
772
- if (deterministic && this.cachedField0Det) {
773
- return this.cachedField0Det;
774
- }
775
- const bytes = encodeField0SchemaMeta(this.getSchemaMeta(0), deterministic);
776
983
  if (deterministic) {
777
- this.cachedField0Det = bytes;
984
+ return this.getCachedField0Det().slice();
778
985
  }
779
- return bytes;
986
+ return encodeField0SchemaMeta(this.getSchemaMeta(0), false);
780
987
  }
781
988
  /**
782
989
  * Encodes `msg` into a new `Uint8Array`.
@@ -803,25 +1010,33 @@ export class MessageSchema {
803
1010
  encodeInto(enc, msg, options) {
804
1011
  const deterministic = options?.deterministic ?? false;
805
1012
  const writeUnknown = options?.writeUnknownFields ?? false;
806
- if (options?.selfDescribing) {
807
- if (deterministic && !this.isCyclicOrDeep()) {
808
- enc.writeRaw(this.getField0Bytes(true));
1013
+ const selfDescribing = Boolean(options?.selfDescribing);
1014
+ if (selfDescribing) {
1015
+ if (!this.isCyclicOrDeep()) {
1016
+ enc.writeRaw(this.getCachedField0Det());
809
1017
  }
810
1018
  else {
811
- writeField0SchemaMeta(enc, this.getSchemaMeta(0, msg), deterministic);
1019
+ writeField0SchemaMeta(enc, this.getSchemaMeta(0, msg, undefined, 1), deterministic);
812
1020
  }
813
1021
  }
814
- if (this.generatedHooks?.encode) {
1022
+ if (this.generatedHooks?.encode && (!selfDescribing || !this.isCyclicOrDeep())) {
815
1023
  this.generatedHooks.encode(enc, msg, options);
816
1024
  return;
817
1025
  }
818
- this.encodeBody(enc, msg, deterministic, writeUnknown);
1026
+ const rootCoveredHops = Math.floor((MaxNestingDepth - 2) / 2);
1027
+ this.encodeBody(enc, msg, deterministic, writeUnknown, selfDescribing, 0, rootCoveredHops);
819
1028
  }
820
1029
  /**
821
1030
  * Internal single-pass body encoder (used for root and nested sub-messages).
822
1031
  */
823
- encodeBody(enc, msg, deterministic, writeUnknown = false) {
824
- if (this.generatedHooks?.encode) {
1032
+ encodeBody(enc, msg, deterministic, writeUnknown = false, selfDescribing = false, msgDepth = 0, coveredHops = 0) {
1033
+ let activeCovered = coveredHops;
1034
+ if (selfDescribing && activeCovered < 0 && msgDepth + 2 <= MaxNestingDepth) {
1035
+ const baseDepth = msgDepth + 1;
1036
+ writeField0SchemaMeta(enc, this.getSchemaMeta(0, msg, undefined, baseDepth), deterministic);
1037
+ activeCovered = Math.floor((MaxNestingDepth - baseDepth - 1) / 2);
1038
+ }
1039
+ if (this.generatedHooks?.encode && (!selfDescribing || !this.isCyclicOrDeep())) {
825
1040
  this.generatedHooks.encode(enc, msg, {
826
1041
  deterministic,
827
1042
  writeUnknownFields: writeUnknown,
@@ -850,10 +1065,10 @@ export class MessageSchema {
850
1065
  }
851
1066
  enc.beginSubMsg(f.fieldNum);
852
1067
  if (rawVal) {
853
- subSchema.encodeBody(enc, rawVal, deterministic, writeUnknown);
1068
+ subSchema.encodeBody(enc, rawVal, deterministic, writeUnknown, selfDescribing, msgDepth + 1, activeCovered - 1);
854
1069
  }
855
1070
  else if (!f.optional) {
856
- subSchema.encodeBody(enc, subSchema.create(), deterministic, writeUnknown);
1071
+ subSchema.encodeBody(enc, subSchema.create(), deterministic, writeUnknown, selfDescribing, msgDepth + 1, activeCovered - 1);
857
1072
  }
858
1073
  enc.endSubMsg();
859
1074
  continue;
@@ -861,7 +1076,7 @@ export class MessageSchema {
861
1076
  if (f.omitEmpty && !f.oneof && !f.explicitPresence && isFieldValueEmpty(f, rawVal)) {
862
1077
  continue;
863
1078
  }
864
- encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown);
1079
+ encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown, selfDescribing, msgDepth, activeCovered);
865
1080
  }
866
1081
  if (writeUnknown && msg && Array.isArray(msg.$unknown)) {
867
1082
  const unknown = msg.$unknown;
@@ -891,8 +1106,8 @@ export class MessageSchema {
891
1106
  /**
892
1107
  * Decodes `data` into `target` (or a newly created instance if omitted).
893
1108
  */
894
- decode(data, target, depth = 0, options) {
895
- if (this.generatedHooks?.decode) {
1109
+ decode(data, target, depth = 0, options, startOffset = 0, endOffset = data.length) {
1110
+ if (this.generatedHooks?.decode && startOffset === 0 && endOffset === data.length) {
896
1111
  return this.generatedHooks.decode(data, target, depth, options);
897
1112
  }
898
1113
  const maxDepth = options?.recursionLimit ?? MaxNestingDepth;
@@ -918,20 +1133,28 @@ export class MessageSchema {
918
1133
  }
919
1134
  for (let i = 0; i < this.fields.length; i++) {
920
1135
  const f = this.fields[i];
1136
+ if (f.altKey && !f.altInObjectProto && Object.hasOwn(out, f.altKey)) {
1137
+ const desc = Object.getOwnPropertyDescriptor(out, f.altKey);
1138
+ if (desc && 'value' in desc) {
1139
+ delete out[f.altKey];
1140
+ }
1141
+ }
921
1142
  if (f.oneof)
922
1143
  continue;
923
1144
  if (f.explicitPresence) {
924
- out[f.propKey] = undefined;
1145
+ setFieldOnObj(out, f, undefined);
925
1146
  }
926
1147
  else {
927
- out[f.propKey] = defaultFieldValue(f, nextCreating);
1148
+ setFieldOnObj(out, f, defaultFieldValue(f, nextCreating));
928
1149
  }
929
1150
  }
930
- delete out.$unknown;
1151
+ if (Object.hasOwn(out, '$unknown')) {
1152
+ delete out.$unknown;
1153
+ }
931
1154
  }
932
1155
  }
933
- const n = data.length;
934
- let pos = 0;
1156
+ const n = endOffset;
1157
+ let pos = startOffset;
935
1158
  let seenMask = 0;
936
1159
  let seenSet = null;
937
1160
  let unknownFields = Array.isArray(out.$unknown) ? out.$unknown : null;
@@ -950,7 +1173,7 @@ export class MessageSchema {
950
1173
  pos += 2;
951
1174
  }
952
1175
  else {
953
- const [t64, tn] = decodeVarintBigInt(data, pos);
1176
+ const [t64, tn] = decodeVarintBigInt(data, pos, n);
954
1177
  if (tn === 0 || t64 >> 4n > 536870911n) {
955
1178
  throw new Error(`omnibuf: truncated or invalid multi-byte tag at ${pos}`);
956
1179
  }
@@ -960,20 +1183,20 @@ export class MessageSchema {
960
1183
  const fieldNum = tag <= 0x7fffffff ? tag >>> 4 : Math.floor(tag / 16);
961
1184
  const wt = tag & 0x0f;
962
1185
  if (fieldNum === 0) {
963
- if (wt !== WireSubMsg) {
964
- throw new Error(`omnibuf: invalid Field #0 wire type ${wt}`);
1186
+ const nextPos = validateField0At(data, pos, wt, depth, maxDepth, n);
1187
+ if (nextPos < 0) {
1188
+ throw new Error(`omnibuf: invalid Field #0 at ${pos}`);
965
1189
  }
966
- const [meta, nextPos] = readLenSlice(data, pos, 0);
967
- decodeSchemaMeta(meta, depth + 1, maxDepth);
968
1190
  pos = nextPos;
969
1191
  continue;
970
1192
  }
971
- const f = this.byNum.get(fieldNum);
1193
+ const f = fieldNum <= 64 ? this.denseByNum[fieldNum] : this.byNum.get(fieldNum);
972
1194
  if (!f ||
973
1195
  (f.effectiveType !== 'bool' && f.wireType !== wt) ||
974
1196
  (f.effectiveType === 'bool' && wt !== WireBoolFalse && wt !== WireBoolTrue)) {
975
1197
  const valStart = pos;
976
- pos = validateValue(data, pos, wt, depth, maxDepth);
1198
+ const valBuf = n === data.length ? data : data.subarray(0, n);
1199
+ pos = validateValue(valBuf, pos, wt, depth, maxDepth);
977
1200
  if (readUnknown) {
978
1201
  if (!unknownFields)
979
1202
  unknownFields = [];
@@ -999,7 +1222,18 @@ export class MessageSchema {
999
1222
  alreadySeen = true;
1000
1223
  seenSet.add(fieldNum);
1001
1224
  }
1002
- pos = decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, options);
1225
+ if (f.inObjectProto) {
1226
+ const box = Object.create(null);
1227
+ const cur = getOwnProp(out, f.propKey);
1228
+ if (cur !== undefined) {
1229
+ box[f.propKey] = cur;
1230
+ }
1231
+ pos = decodeCompiledFieldValue(data, pos, wt, f, box, alreadySeen, depth, maxDepth, options, n);
1232
+ setFieldOnObj(out, f, box[f.propKey]);
1233
+ }
1234
+ else {
1235
+ pos = decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options, n);
1236
+ }
1003
1237
  }
1004
1238
  if (unknownFields && unknownFields.length > 0 && !('$unknown' in out)) {
1005
1239
  Object.defineProperty(out, '$unknown', {
@@ -1016,7 +1250,12 @@ function getFieldFromMsg(msg, f) {
1016
1250
  if (!msg)
1017
1251
  return undefined;
1018
1252
  if (f.oneof) {
1019
- const group = msg[f.oneof] ?? (f.oneofProtoName ? msg[f.oneofProtoName] : undefined);
1253
+ const group = msg[f.oneof] ??
1254
+ (f.oneofProtoName
1255
+ ? f.oneofProtoInObjectProto
1256
+ ? getOwnProp(msg, f.oneofProtoName)
1257
+ : msg[f.oneofProtoName]
1258
+ : undefined);
1020
1259
  if (group && typeof group === 'object' && 'case' in group) {
1021
1260
  if (group.case === f.localName || group.case === f.name || group.case === f.propKey) {
1022
1261
  return group.value;
@@ -1024,11 +1263,12 @@ function getFieldFromMsg(msg, f) {
1024
1263
  return undefined;
1025
1264
  }
1026
1265
  }
1027
- const v = msg[f.propKey];
1266
+ const v = f.inObjectProto ? getOwnProp(msg, f.propKey) : msg[f.propKey];
1028
1267
  if (v !== undefined)
1029
1268
  return v;
1030
- if (f.altKey !== undefined)
1031
- return msg[f.altKey];
1269
+ if (f.altKey !== undefined) {
1270
+ return f.altInObjectProto ? getOwnProp(msg, f.altKey) : msg[f.altKey];
1271
+ }
1032
1272
  return undefined;
1033
1273
  }
1034
1274
  function coerce64(val, useBigInt, unsigned) {
@@ -1090,12 +1330,18 @@ function initFieldValue(f, val) {
1090
1330
  }
1091
1331
  const out = {};
1092
1332
  for (const [k, v] of Object.entries(val)) {
1093
- Object.defineProperty(out, k, {
1094
- value: isSubMsgVal ? sub.create(v) : v,
1095
- writable: true,
1096
- enumerable: true,
1097
- configurable: true,
1098
- });
1333
+ const mapped = isSubMsgVal ? sub.create(v) : v;
1334
+ if (k === '__proto__') {
1335
+ Object.defineProperty(out, k, {
1336
+ value: mapped,
1337
+ writable: true,
1338
+ enumerable: true,
1339
+ configurable: true,
1340
+ });
1341
+ }
1342
+ else {
1343
+ out[k] = mapped;
1344
+ }
1099
1345
  }
1100
1346
  return out;
1101
1347
  }
@@ -1154,12 +1400,18 @@ function cloneFieldValue(f, val) {
1154
1400
  }
1155
1401
  const out = {};
1156
1402
  for (const [k, v] of Object.entries(val)) {
1157
- Object.defineProperty(out, k, {
1158
- value: isSubMsgVal ? sub.clone(v) : v,
1159
- writable: true,
1160
- enumerable: true,
1161
- configurable: true,
1162
- });
1403
+ const cloned = isSubMsgVal ? sub.clone(v) : v;
1404
+ if (k === '__proto__') {
1405
+ Object.defineProperty(out, k, {
1406
+ value: cloned,
1407
+ writable: true,
1408
+ enumerable: true,
1409
+ configurable: true,
1410
+ });
1411
+ }
1412
+ else {
1413
+ out[k] = cloned;
1414
+ }
1163
1415
  }
1164
1416
  return out;
1165
1417
  }
@@ -1177,6 +1429,8 @@ function bytesEqual(a, b) {
1177
1429
  function scalarValuesEqual(a, b) {
1178
1430
  if (a === b)
1179
1431
  return true;
1432
+ if (Number.isNaN(a) && Number.isNaN(b))
1433
+ return true;
1180
1434
  if ((typeof a === 'number' || typeof a === 'bigint') &&
1181
1435
  (typeof b === 'number' || typeof b === 'bigint')) {
1182
1436
  try {
@@ -1329,11 +1583,14 @@ function isFieldValueEmpty(f, val) {
1329
1583
  const sub = f.resolveSubSchema?.();
1330
1584
  return sub ? sub.isEmptyInstance(val) : true;
1331
1585
  }
1586
+ case 'float32':
1587
+ case 'float64':
1588
+ return Object.is(val, 0);
1332
1589
  default:
1333
1590
  return val === 0 || val === 0n;
1334
1591
  }
1335
1592
  }
1336
- function encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown = false) {
1593
+ function encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown = false, selfDescribing = false, msgDepth = 0, coveredHops = 0) {
1337
1594
  const fnum = f.fieldNum;
1338
1595
  switch (f.effectiveType) {
1339
1596
  case 'uint32':
@@ -1433,7 +1690,7 @@ function encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown = false) {
1433
1690
  for (let i = 0; i < items.length; i++) {
1434
1691
  enc.beginSubMsgElem();
1435
1692
  if (items[i] !== null && items[i] !== undefined) {
1436
- subSchema.encodeBody(enc, items[i], deterministic, writeUnknown);
1693
+ subSchema.encodeBody(enc, items[i], deterministic, writeUnknown, selfDescribing, msgDepth + 2, coveredHops - 1);
1437
1694
  }
1438
1695
  enc.endSubMsgElem();
1439
1696
  }
@@ -1441,7 +1698,7 @@ function encodeFieldValue(enc, f, rawVal, deterministic, writeUnknown = false) {
1441
1698
  break;
1442
1699
  }
1443
1700
  case 'map': {
1444
- encodeMapField(enc, f, rawVal, deterministic, writeUnknown);
1701
+ encodeMapField(enc, f, rawVal, deterministic, writeUnknown, selfDescribing, msgDepth, coveredHops);
1445
1702
  break;
1446
1703
  }
1447
1704
  }
@@ -1525,7 +1782,7 @@ function compareMapKeys(keyType, a, b) {
1525
1782
  }
1526
1783
  }
1527
1784
  }
1528
- function encodeMapField(enc, f, rawVal, deterministic, writeUnknown = false) {
1785
+ function encodeMapField(enc, f, rawVal, deterministic, writeUnknown = false, selfDescribing = false, msgDepth = 0, coveredHops = 0) {
1529
1786
  const keyWT = f.mapKeyWT ?? WireString;
1530
1787
  const valWT = f.mapValWT ?? WireUint;
1531
1788
  const keyType = f.mapKeyType ?? 'string';
@@ -1550,7 +1807,7 @@ function encodeMapField(enc, f, rawVal, deterministic, writeUnknown = false) {
1550
1807
  if (valType === 'submsg') {
1551
1808
  enc.beginContainer();
1552
1809
  if (v && subSchema) {
1553
- subSchema.encodeBody(enc, v, deterministic, writeUnknown);
1810
+ subSchema.encodeBody(enc, v, deterministic, writeUnknown, selfDescribing, msgDepth + 2, coveredHops - 1);
1554
1811
  }
1555
1812
  enc.endContainer();
1556
1813
  }
@@ -1560,26 +1817,31 @@ function encodeMapField(enc, f, rawVal, deterministic, writeUnknown = false) {
1560
1817
  }
1561
1818
  enc.endContainer();
1562
1819
  }
1563
- function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, options) {
1820
+ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options, endLimit = data.length) {
1564
1821
  const key = f.propKey;
1565
- const n = data.length;
1822
+ const n = endLimit;
1823
+ if ((wt === WireArray || wt === WireMap) && depth + 1 > maxDepth) {
1824
+ throw new Error(`omnibuf: nesting depth ${depth + 1} exceeds MaxNestingDepth (${maxDepth})`);
1825
+ }
1566
1826
  switch (f.effectiveType) {
1567
1827
  case 'uint32': {
1568
1828
  if (pos < n && (data[pos] & 7) !== 0) {
1569
- const [v, vn] = decodeVarint(data, pos);
1829
+ const [v, vn] = decodeVarint(data, pos, n);
1570
1830
  if (vn === 0)
1571
1831
  throw new Error(`omnibuf: truncated uint32 at ${pos}`);
1572
1832
  out[key] = v >>> 0;
1573
1833
  return pos + vn;
1574
1834
  }
1575
- const [v, vn] = decodeVarintBigInt(data, pos);
1835
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1576
1836
  if (vn === 0)
1577
1837
  throw new Error(`omnibuf: truncated uint32 at ${pos}`);
1578
1838
  out[key] = Number(v & 0xffffffffn) >>> 0;
1579
1839
  return pos + vn;
1580
1840
  }
1581
1841
  case 'uint64': {
1582
- const [v, vn] = f.useBigInt ? decodeVarintBigInt(data, pos) : decodeVarintAuto(data, pos);
1842
+ const [v, vn] = f.useBigInt
1843
+ ? decodeVarintBigInt(data, pos, n)
1844
+ : decodeVarintAuto(data, pos, n);
1583
1845
  if (vn === 0)
1584
1846
  throw new Error(`omnibuf: truncated uint64 at ${pos}`);
1585
1847
  out[key] = v;
@@ -1589,21 +1851,21 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1589
1851
  case 'int32':
1590
1852
  case 'enum': {
1591
1853
  if (pos < n && (data[pos] & 7) !== 0) {
1592
- const [v, vn] = decodeVarint(data, pos);
1854
+ const [v, vn] = decodeVarint(data, pos, n);
1593
1855
  if (vn === 0)
1594
1856
  throw new Error(`omnibuf: truncated int32 at ${pos}`);
1595
- out[key] = decodeZigZag(v) | 0;
1857
+ out[key] = decodeZigZag32(v);
1596
1858
  return pos + vn;
1597
1859
  }
1598
- const [v, vn] = decodeVarintBigInt(data, pos);
1860
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1599
1861
  if (vn === 0)
1600
1862
  throw new Error(`omnibuf: truncated int32 at ${pos}`);
1601
- out[key] = decodeZigZag(v) | 0;
1863
+ out[key] = decodeZigZag32(v);
1602
1864
  return pos + vn;
1603
1865
  }
1604
1866
  case 'sint64':
1605
1867
  case 'int64': {
1606
- const [v, vn] = decodeVarintBigInt(data, pos);
1868
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1607
1869
  if (vn === 0)
1608
1870
  throw new Error(`omnibuf: truncated int64 at ${pos}`);
1609
1871
  out[key] = f.useBigInt ? decodeZigZagBigInt(v) : decodeZigZagAuto(v);
@@ -1614,12 +1876,21 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1614
1876
  return pos;
1615
1877
  }
1616
1878
  case 'string': {
1617
- const [s, nextPos] = readLenSlice(data, pos, 0);
1879
+ if (pos < n && (data[pos] & 1) !== 0) {
1880
+ const sLen = data[pos] >>> 1;
1881
+ const sStart = pos + 1;
1882
+ const sEnd = sStart + sLen;
1883
+ if (sEnd <= n) {
1884
+ out[key] = decodeUTF8(data, sStart, sEnd);
1885
+ return sEnd;
1886
+ }
1887
+ }
1888
+ const [s, nextPos] = readLenSlice(data, pos, 0, n);
1618
1889
  out[key] = decodeUTF8(s);
1619
1890
  return nextPos;
1620
1891
  }
1621
1892
  case 'bytes': {
1622
- const [b, nextPos] = readLenSlice(data, pos, 0);
1893
+ const [b, nextPos] = readLenSlice(data, pos, 0, n);
1623
1894
  out[key] = b.slice();
1624
1895
  return nextPos;
1625
1896
  }
@@ -1675,7 +1946,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1675
1946
  return pos + 8;
1676
1947
  }
1677
1948
  case 'string[]': {
1678
- const [body, nextPos] = readLenSlice(data, pos, 2);
1949
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1679
1950
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1680
1951
  const [arr, ok] = appendStringArrBody(prev, body);
1681
1952
  if (!ok)
@@ -1684,7 +1955,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1684
1955
  return nextPos;
1685
1956
  }
1686
1957
  case 'bytes[]': {
1687
- const [body, nextPos] = readLenSlice(data, pos, 2);
1958
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1688
1959
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1689
1960
  const [arr, ok] = appendBytesArrBody(prev, body, false);
1690
1961
  if (!ok)
@@ -1693,7 +1964,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1693
1964
  return nextPos;
1694
1965
  }
1695
1966
  case 'bool[]': {
1696
- const [body, nextPos] = readLenSlice(data, pos, 2);
1967
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1697
1968
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1698
1969
  const [arr, ok] = appendBoolArrBody(prev, body);
1699
1970
  if (!ok)
@@ -1702,7 +1973,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1702
1973
  return nextPos;
1703
1974
  }
1704
1975
  case 'uint32[]': {
1705
- const [body, nextPos] = readLenSlice(data, pos, 2);
1976
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1706
1977
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1707
1978
  const [arr, ok] = appendUint32ArrBody(prev, body);
1708
1979
  if (!ok)
@@ -1711,7 +1982,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1711
1982
  return nextPos;
1712
1983
  }
1713
1984
  case 'enum[]': {
1714
- const [body, nextPos] = readLenSlice(data, pos, 2);
1985
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1715
1986
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1716
1987
  const [arr, ok] = appendEnumArrBody(prev, body);
1717
1988
  if (!ok)
@@ -1720,7 +1991,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1720
1991
  return nextPos;
1721
1992
  }
1722
1993
  case 'uint64[]': {
1723
- const [body, nextPos] = readLenSlice(data, pos, 2);
1994
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1724
1995
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1725
1996
  const startLen = prev.length;
1726
1997
  const [arr, ok] = appendUintArrAutoBody(prev, body);
@@ -1736,7 +2007,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1736
2007
  }
1737
2008
  case 'sint32[]':
1738
2009
  case 'int32[]': {
1739
- const [body, nextPos] = readLenSlice(data, pos, 2);
2010
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1740
2011
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1741
2012
  const [arr, ok] = appendEnumArrBody(prev, body);
1742
2013
  if (!ok)
@@ -1746,7 +2017,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1746
2017
  }
1747
2018
  case 'sint64[]':
1748
2019
  case 'int64[]': {
1749
- const [body, nextPos] = readLenSlice(data, pos, 2);
2020
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1750
2021
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1751
2022
  const startLen = prev.length;
1752
2023
  const [arr, ok] = appendSintArrAutoBody(prev, body);
@@ -1761,7 +2032,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1761
2032
  return nextPos;
1762
2033
  }
1763
2034
  case 'float32[]': {
1764
- const [body, nextPos] = readLenSlice(data, pos, 2);
2035
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1765
2036
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1766
2037
  const startLen = prev.length;
1767
2038
  const [arr, ok] = appendFloat32ArrBody(prev, body);
@@ -1774,7 +2045,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1774
2045
  return nextPos;
1775
2046
  }
1776
2047
  case 'fixed32[]': {
1777
- const [body, nextPos] = readLenSlice(data, pos, 2);
2048
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1778
2049
  const [elemType, c, startP, ok] = parseArrayHeader(body);
1779
2050
  if (!ok || elemType !== WireFixed32 || body.length - startP !== c * 4) {
1780
2051
  throw new Error(`omnibuf: invalid fixed32 array at ${pos}`);
@@ -1789,7 +2060,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1789
2060
  return nextPos;
1790
2061
  }
1791
2062
  case 'sfixed32[]': {
1792
- const [body, nextPos] = readLenSlice(data, pos, 2);
2063
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1793
2064
  const [elemType, c, startP, ok] = parseArrayHeader(body);
1794
2065
  if (!ok || elemType !== WireSfixed32 || body.length - startP !== c * 4) {
1795
2066
  throw new Error(`omnibuf: invalid sfixed32 array at ${pos}`);
@@ -1803,7 +2074,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1803
2074
  return nextPos;
1804
2075
  }
1805
2076
  case 'float64[]': {
1806
- const [body, nextPos] = readLenSlice(data, pos, 2);
2077
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1807
2078
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1808
2079
  const [arr, ok] = appendFloat64ArrBody(prev, body);
1809
2080
  if (!ok)
@@ -1813,7 +2084,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1813
2084
  }
1814
2085
  case 'fixed64[]':
1815
2086
  case 'sfixed64[]': {
1816
- const [body, nextPos] = readLenSlice(data, pos, 2);
2087
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1817
2088
  const isSigned = f.effectiveType === 'sfixed64[]';
1818
2089
  const expElemType = isSigned ? WireSfixed64 : WireFixed64;
1819
2090
  const [elemType, c, startP, ok] = parseArrayHeader(body);
@@ -1841,7 +2112,6 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1841
2112
  return nextPos;
1842
2113
  }
1843
2114
  case 'submsg': {
1844
- const [subBytes, nextPos] = readLenSlice(data, pos, 0);
1845
2115
  const subSchema = f.resolveSubSchema?.();
1846
2116
  if (!subSchema) {
1847
2117
  throw new Error(`omnibuf: missing subSchema on ${key}`);
@@ -1849,29 +2119,120 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1849
2119
  const existing = out[key];
1850
2120
  const hasExisting = existing !== undefined && existing !== null && typeof existing === 'object';
1851
2121
  const targetSub = hasExisting ? existing : subSchema.create();
1852
- out[key] = subSchema.decode(subBytes, targetSub, depth + 1, {
1853
- ...options,
1854
- merge: f.oneof ? alreadySeen && hasExisting : alreadySeen,
1855
- });
2122
+ const shouldMerge = f.oneof ? alreadySeen && hasExisting : alreadySeen;
2123
+ const subOpts = shouldMerge
2124
+ ? { ...options, merge: true }
2125
+ : options?.merge
2126
+ ? { ...options, merge: false }
2127
+ : options;
2128
+ if (pos < n) {
2129
+ const lb = data[pos];
2130
+ if ((lb & 1) !== 0) {
2131
+ const subLen = lb >>> 1;
2132
+ const sStart = pos + 1;
2133
+ const sEnd = sStart + subLen;
2134
+ if (sEnd <= n) {
2135
+ out[key] = subSchema.decode(data, targetSub, depth + 1, subOpts, sStart, sEnd);
2136
+ return sEnd;
2137
+ }
2138
+ }
2139
+ else if ((lb & 2) !== 0 && pos + 2 <= n) {
2140
+ const subLen = (lb | (data[pos + 1] << 8)) >>> 2;
2141
+ const sStart = pos + 2;
2142
+ const sEnd = sStart + subLen;
2143
+ if (sEnd <= n) {
2144
+ out[key] = subSchema.decode(data, targetSub, depth + 1, subOpts, sStart, sEnd);
2145
+ return sEnd;
2146
+ }
2147
+ }
2148
+ }
2149
+ const [subBytes, nextPos] = readLenSlice(data, pos, 0, n);
2150
+ out[key] = subSchema.decode(subBytes, targetSub, depth + 1, subOpts);
1856
2151
  return nextPos;
1857
2152
  }
1858
2153
  case 'submsg[]': {
1859
- const [arrPayload, nextPos] = readLenSlice(data, pos, 2);
1860
- const [elemCount, ok] = countSubMsgArrElems(arrPayload);
1861
- if (!ok) {
1862
- throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
1863
- }
1864
2154
  const subSchema = f.resolveSubSchema?.();
1865
2155
  if (!subSchema) {
1866
2156
  throw new Error(`omnibuf: missing subSchema on ${key}`);
1867
2157
  }
2158
+ if (pos < n) {
2159
+ let arrLen = -1;
2160
+ let arrStart = pos;
2161
+ const lb = data[pos];
2162
+ if ((lb & 1) !== 0) {
2163
+ arrLen = lb >>> 1;
2164
+ arrStart = pos + 1;
2165
+ }
2166
+ else if ((lb & 2) !== 0 && pos + 2 <= n) {
2167
+ arrLen = (lb | (data[pos + 1] << 8)) >>> 2;
2168
+ arrStart = pos + 2;
2169
+ }
2170
+ const arrEnd = arrStart + arrLen;
2171
+ if (arrLen >= 2 &&
2172
+ arrEnd <= n &&
2173
+ data[arrStart] === WireSubMsg &&
2174
+ (data[arrStart + 1] & 1) !== 0) {
2175
+ const elemCount = data[arrStart + 1] >>> 1;
2176
+ let p = arrStart + 2;
2177
+ if (elemCount <= arrEnd - p && (elemCount > 0 || p === arrEnd)) {
2178
+ const elems = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
2179
+ const origLen = elems.length;
2180
+ for (let i = 0; i < elemCount; i++) {
2181
+ if (p >= arrEnd) {
2182
+ elems.length = origLen;
2183
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2184
+ }
2185
+ let elNum = 0;
2186
+ const eb0 = data[p];
2187
+ if ((eb0 & 1) !== 0) {
2188
+ elNum = eb0 >>> 1;
2189
+ p += 1;
2190
+ }
2191
+ else if ((eb0 & 2) !== 0) {
2192
+ if (p + 2 > arrEnd) {
2193
+ elems.length = origLen;
2194
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2195
+ }
2196
+ elNum = (eb0 | (data[p + 1] << 8)) >>> 2;
2197
+ p += 2;
2198
+ }
2199
+ else {
2200
+ const [el, en] = decodeVarintBigInt(data, p, arrEnd);
2201
+ if (en === 0 || el > BigInt(arrEnd - (p + en))) {
2202
+ elems.length = origLen;
2203
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2204
+ }
2205
+ p += en;
2206
+ elNum = Number(el);
2207
+ }
2208
+ if (p + elNum > arrEnd) {
2209
+ elems.length = origLen;
2210
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2211
+ }
2212
+ elems.push(subSchema.decode(data, subSchema.create(), depth + 2, options, p, p + elNum));
2213
+ p += elNum;
2214
+ }
2215
+ if (p !== arrEnd) {
2216
+ elems.length = origLen;
2217
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2218
+ }
2219
+ out[key] = elems;
2220
+ return arrEnd;
2221
+ }
2222
+ }
2223
+ }
2224
+ const [arrPayload, nextPos] = readLenSlice(data, pos, 2, n);
2225
+ const [elemCount, ok] = countSubMsgArrElems(arrPayload);
2226
+ if (!ok) {
2227
+ throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
2228
+ }
1868
2229
  const elems = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1869
2230
  let [, , p] = parseArrayHeader(arrPayload);
1870
2231
  for (let i = 0; i < elemCount; i++) {
1871
2232
  const [el, en] = decodeVarintBigInt(arrPayload, p);
1872
2233
  p += en;
1873
2234
  const elNum = Number(el);
1874
- const elemObj = subSchema.decode(arrPayload.subarray(p, p + elNum), subSchema.create(), depth + 1, options);
2235
+ const elemObj = subSchema.decode(arrPayload, subSchema.create(), depth + 2, options, p, p + elNum);
1875
2236
  elems.push(elemObj);
1876
2237
  p += elNum;
1877
2238
  }
@@ -1879,8 +2240,8 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1879
2240
  return nextPos;
1880
2241
  }
1881
2242
  case 'map': {
1882
- const [body, nextPos] = readLenSlice(data, pos, 3);
1883
- decodeMapFieldBody(f, out, body, alreadySeen, depth, options);
2243
+ const [body, nextPos] = readLenSlice(data, pos, 3, n);
2244
+ decodeMapFieldBody(f, out, body, alreadySeen, depth + 1, options);
1884
2245
  return nextPos;
1885
2246
  }
1886
2247
  }
@@ -1888,6 +2249,14 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, opt
1888
2249
  function decodeMapScalarEntry(body, p, wt, subSchema, depth, options) {
1889
2250
  switch (wt) {
1890
2251
  case WireString: {
2252
+ if (p < body.length && (body[p] & 1) !== 0) {
2253
+ const sLen = body[p] >>> 1;
2254
+ const sStart = p + 1;
2255
+ const sEnd = sStart + sLen;
2256
+ if (sEnd <= body.length) {
2257
+ return [decodeUTF8(body, sStart, sEnd), sEnd];
2258
+ }
2259
+ }
1891
2260
  const [sBytes, nextP] = readLenSlice(body, p, 0);
1892
2261
  return [decodeUTF8(sBytes), nextP];
1893
2262
  }
@@ -1953,6 +2322,31 @@ function decodeMapScalarEntry(body, p, wt, subSchema, depth, options) {
1953
2322
  throw new Error(`omnibuf: invalid WireMap entry wire type ${wt}`);
1954
2323
  }
1955
2324
  }
2325
+ function convertMapScalarValue(v, type, useBigInt) {
2326
+ switch (type) {
2327
+ case 'bool':
2328
+ return Boolean(v);
2329
+ case 'float32':
2330
+ return roundFloat32Shortest(float32FromBits(Number(v)));
2331
+ case 'float64':
2332
+ return float64FromBits(BigInt(v));
2333
+ case 'uint32':
2334
+ return typeof v === 'number' ? v >>> 0 : Number(BigInt(v) & 0xffffffffn) >>> 0;
2335
+ case 'sfixed32':
2336
+ case 'int32':
2337
+ case 'sint32':
2338
+ case 'enum':
2339
+ return typeof v === 'number' ? v | 0 : Number(BigInt(v) & 0xffffffffn) | 0;
2340
+ case 'sfixed64': {
2341
+ const signed = BigInt.asIntN(64, BigInt(v));
2342
+ return useBigInt || signed < -9007199254740991n || signed > 9007199254740991n
2343
+ ? signed
2344
+ : Number(signed);
2345
+ }
2346
+ default:
2347
+ return v;
2348
+ }
2349
+ }
1956
2350
  function decodeMapFieldBody(f, out, body, alreadySeen, depth, options) {
1957
2351
  const expKeyWT = f.mapKeyWT ?? WireString;
1958
2352
  const expValWT = f.mapValWT ?? WireUint;
@@ -1991,41 +2385,27 @@ function decodeMapFieldBody(f, out, body, alreadySeen, depth, options) {
1991
2385
  let p = 2 + cn;
1992
2386
  const c = Number(count);
1993
2387
  for (let i = 0; i < c; i++) {
1994
- const [kv, nextP] = decodeMapScalarEntry(body, p, f.mapKeyWT ?? WireString, undefined, depth, options);
1995
- const [rawVv, nextP2] = decodeMapScalarEntry(body, nextP, f.mapValWT ?? WireUint, subSchema, depth, options);
1996
- const convert = (v, type) => {
1997
- if (type === 'bool')
1998
- return Boolean(v);
1999
- if (type === 'float32')
2000
- return roundFloat32Shortest(float32FromBits(Number(v)));
2001
- if (type === 'float64')
2002
- return float64FromBits(BigInt(v));
2003
- if (type === 'uint32')
2004
- return Number(BigInt(v) & 0xffffffffn) >>> 0;
2005
- if (type === 'sfixed32' || type === 'int32' || type === 'sint32' || type === 'enum') {
2006
- return Number(BigInt(v) & 0xffffffffn) | 0;
2007
- }
2008
- if (type === 'sfixed64') {
2009
- const signed = BigInt.asIntN(64, BigInt(v));
2010
- return f.useBigInt || signed < -9007199254740991n || signed > 9007199254740991n
2011
- ? signed
2012
- : Number(signed);
2013
- }
2014
- return v;
2015
- };
2016
- const vv = convert(isVal64 ? BigInt(rawVv) : rawVv, f.mapValType);
2017
- const key = convert(isKey64 ? BigInt(kv) : kv, f.mapKeyType);
2388
+ const [kv, nextP] = decodeMapScalarEntry(body, p, expKeyWT, undefined, depth, options);
2389
+ const [rawVv, nextP2] = decodeMapScalarEntry(body, nextP, expValWT, subSchema, depth, options);
2390
+ const vv = convertMapScalarValue(isVal64 ? BigInt(rawVv) : rawVv, f.mapValType, f.useBigInt);
2391
+ const key = convertMapScalarValue(isKey64 ? BigInt(kv) : kv, f.mapKeyType, f.useBigInt);
2018
2392
  p = nextP2;
2019
2393
  if (targetMap instanceof Map) {
2020
2394
  targetMap.set(key, vv);
2021
2395
  }
2022
2396
  else {
2023
- Object.defineProperty(targetMap, String(key), {
2024
- value: vv,
2025
- enumerable: true,
2026
- configurable: true,
2027
- writable: true,
2028
- });
2397
+ const kStr = String(key);
2398
+ if (kStr === '__proto__') {
2399
+ Object.defineProperty(targetMap, kStr, {
2400
+ value: vv,
2401
+ enumerable: true,
2402
+ configurable: true,
2403
+ writable: true,
2404
+ });
2405
+ }
2406
+ else {
2407
+ targetMap[kStr] = vv;
2408
+ }
2029
2409
  }
2030
2410
  }
2031
2411
  if (p !== body.length) {
@@ -2069,7 +2449,7 @@ export function omnibufField(fieldNum, options = {}) {
2069
2449
  if (contextOrPropKey.metadata) {
2070
2450
  const metaObj = contextOrPropKey.metadata;
2071
2451
  if (!metaObj[PENDING_FIELDS_SYMBOL]) {
2072
- metaObj[PENDING_FIELDS_SYMBOL] = {};
2452
+ metaObj[PENDING_FIELDS_SYMBOL] = Object.create(null);
2073
2453
  }
2074
2454
  metaObj[PENDING_FIELDS_SYMBOL][propKey] = spec;
2075
2455
  }
@@ -2080,7 +2460,7 @@ export function omnibufField(fieldNum, options = {}) {
2080
2460
  if (ctor) {
2081
2461
  let map = classPendingFields.get(ctor);
2082
2462
  if (!map) {
2083
- map = {};
2463
+ map = Object.create(null);
2084
2464
  classPendingFields.set(ctor, map);
2085
2465
  }
2086
2466
  map[propKey] = spec;
@@ -2095,7 +2475,7 @@ export function omnibufField(fieldNum, options = {}) {
2095
2475
  if (ctor) {
2096
2476
  let map = classPendingFields.get(ctor);
2097
2477
  if (!map) {
2098
- map = {};
2478
+ map = Object.create(null);
2099
2479
  classPendingFields.set(ctor, map);
2100
2480
  }
2101
2481
  map[propKey] = spec;
@@ -2117,7 +2497,7 @@ export function omnibufMessage(typeName) {
2117
2497
  if (metadataFields) {
2118
2498
  let map = classPendingFields.get(target);
2119
2499
  if (!map) {
2120
- map = {};
2500
+ map = Object.create(null);
2121
2501
  classPendingFields.set(target, map);
2122
2502
  }
2123
2503
  Object.assign(map, metadataFields);