@omnibuf/core 0.1.1 → 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, decodeZigZag32, 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
  */
@@ -243,10 +243,13 @@ export class MessageSchema {
243
243
  shortName;
244
244
  fields;
245
245
  oneofs;
246
+ nonOneofFields;
247
+ denseByNum;
246
248
  byNum = new Map();
247
249
  byKey = new Map();
248
250
  oneofByName = new Map();
249
251
  factory;
252
+ precomputedDescMap;
250
253
  generatedHooks;
251
254
  typeNameDesc;
252
255
  cachedMeta = null;
@@ -343,7 +346,107 @@ export class MessageSchema {
343
346
  // Sort fields by ascending fieldNum for deterministic output
344
347
  compiled.sort((a, b) => a.fieldNum - b.fieldNum);
345
348
  this.fields = compiled;
349
+ this.nonOneofFields = compiled.filter((f) => !f.oneof);
346
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;
347
450
  }
348
451
  /**
349
452
  * Look up a compiled field by number, `localName` (`camelCase`), `.proto` `name` (`snake_case`),
@@ -495,6 +598,26 @@ export class MessageSchema {
495
598
  return init;
496
599
  }
497
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
+ }
498
621
  const obj = hasGenCreate
499
622
  ? this.generatedHooks.create()
500
623
  : this.factory
@@ -524,69 +647,71 @@ export class MessageSchema {
524
647
  }
525
648
  }
526
649
  if (init) {
527
- for (const oneof of this.oneofs) {
528
- const localVal = oneof.localName in Object.prototype
529
- ? getOwnProp(init, oneof.localName)
530
- : init[oneof.localName];
531
- const protoVal = oneof.protoName !== oneof.localName
532
- ? oneof.protoName in Object.prototype
533
- ? getOwnProp(init, oneof.protoName)
534
- : init[oneof.protoName]
535
- : undefined;
536
- const initOneof = localVal ?? protoVal;
537
- if (initOneof && typeof initOneof === 'object' && 'case' in initOneof) {
538
- if (initOneof.case === undefined) {
539
- obj[oneof.localName] = { case: undefined };
540
- }
541
- else {
542
- const matchingField = oneof.fields.find((f) => f.localName === initOneof.case ||
543
- f.name === initOneof.case ||
544
- f.propKey === initOneof.case);
545
- if (matchingField) {
546
- obj[oneof.localName] = {
547
- case: matchingField.localName,
548
- value: initFieldValue(matchingField, initOneof.value),
549
- };
550
- }
551
- }
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 };
552
668
  }
553
- }
554
- for (const f of this.fields) {
555
- const pVal = f.inObjectProto
556
- ? getOwnProp(init, f.propKey)
557
- : init[f.propKey];
558
- const initVal = pVal !== undefined
559
- ? pVal
560
- : f.altKey !== undefined
561
- ? f.altInObjectProto
562
- ? getOwnProp(init, f.altKey)
563
- : init[f.altKey]
564
- : undefined;
565
- if (initVal !== undefined) {
566
- if (f.oneof) {
567
- obj[f.oneof] = {
568
- case: f.localName,
569
- 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),
570
677
  };
571
678
  }
572
- else {
573
- setFieldOnObj(obj, f, initFieldValue(f, initVal));
574
- }
575
679
  }
576
680
  }
577
- if (Array.isArray(init.$unknown) && init.$unknown.length > 0) {
578
- Object.defineProperty(obj, '$unknown', {
579
- value: init.$unknown.map((u) => ({
580
- no: u.no,
581
- wireType: u.wireType,
582
- data: u.data.slice(),
583
- })),
584
- enumerable: false,
585
- writable: true,
586
- configurable: true,
587
- });
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
+ }
588
701
  }
589
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
+ }
590
715
  return obj;
591
716
  }
592
717
  /**
@@ -887,7 +1012,7 @@ export class MessageSchema {
887
1012
  const writeUnknown = options?.writeUnknownFields ?? false;
888
1013
  const selfDescribing = Boolean(options?.selfDescribing);
889
1014
  if (selfDescribing) {
890
- if (deterministic && !this.isCyclicOrDeep()) {
1015
+ if (!this.isCyclicOrDeep()) {
891
1016
  enc.writeRaw(this.getCachedField0Det());
892
1017
  }
893
1018
  else {
@@ -981,8 +1106,8 @@ export class MessageSchema {
981
1106
  /**
982
1107
  * Decodes `data` into `target` (or a newly created instance if omitted).
983
1108
  */
984
- decode(data, target, depth = 0, options) {
985
- 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) {
986
1111
  return this.generatedHooks.decode(data, target, depth, options);
987
1112
  }
988
1113
  const maxDepth = options?.recursionLimit ?? MaxNestingDepth;
@@ -1028,8 +1153,8 @@ export class MessageSchema {
1028
1153
  }
1029
1154
  }
1030
1155
  }
1031
- const n = data.length;
1032
- let pos = 0;
1156
+ const n = endOffset;
1157
+ let pos = startOffset;
1033
1158
  let seenMask = 0;
1034
1159
  let seenSet = null;
1035
1160
  let unknownFields = Array.isArray(out.$unknown) ? out.$unknown : null;
@@ -1048,7 +1173,7 @@ export class MessageSchema {
1048
1173
  pos += 2;
1049
1174
  }
1050
1175
  else {
1051
- const [t64, tn] = decodeVarintBigInt(data, pos);
1176
+ const [t64, tn] = decodeVarintBigInt(data, pos, n);
1052
1177
  if (tn === 0 || t64 >> 4n > 536870911n) {
1053
1178
  throw new Error(`omnibuf: truncated or invalid multi-byte tag at ${pos}`);
1054
1179
  }
@@ -1058,20 +1183,20 @@ export class MessageSchema {
1058
1183
  const fieldNum = tag <= 0x7fffffff ? tag >>> 4 : Math.floor(tag / 16);
1059
1184
  const wt = tag & 0x0f;
1060
1185
  if (fieldNum === 0) {
1061
- if (wt !== WireSubMsg) {
1062
- 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}`);
1063
1189
  }
1064
- const [meta, nextPos] = readLenSlice(data, pos, 0);
1065
- decodeSchemaMeta(meta, depth + 1, maxDepth);
1066
1190
  pos = nextPos;
1067
1191
  continue;
1068
1192
  }
1069
- const f = this.byNum.get(fieldNum);
1193
+ const f = fieldNum <= 64 ? this.denseByNum[fieldNum] : this.byNum.get(fieldNum);
1070
1194
  if (!f ||
1071
1195
  (f.effectiveType !== 'bool' && f.wireType !== wt) ||
1072
1196
  (f.effectiveType === 'bool' && wt !== WireBoolFalse && wt !== WireBoolTrue)) {
1073
1197
  const valStart = pos;
1074
- 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);
1075
1200
  if (readUnknown) {
1076
1201
  if (!unknownFields)
1077
1202
  unknownFields = [];
@@ -1103,11 +1228,11 @@ export class MessageSchema {
1103
1228
  if (cur !== undefined) {
1104
1229
  box[f.propKey] = cur;
1105
1230
  }
1106
- pos = decodeCompiledFieldValue(data, pos, wt, f, box, alreadySeen, depth, maxDepth, options);
1231
+ pos = decodeCompiledFieldValue(data, pos, wt, f, box, alreadySeen, depth, maxDepth, options, n);
1107
1232
  setFieldOnObj(out, f, box[f.propKey]);
1108
1233
  }
1109
1234
  else {
1110
- pos = decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options);
1235
+ pos = decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options, n);
1111
1236
  }
1112
1237
  }
1113
1238
  if (unknownFields && unknownFields.length > 0 && !('$unknown' in out)) {
@@ -1205,12 +1330,18 @@ function initFieldValue(f, val) {
1205
1330
  }
1206
1331
  const out = {};
1207
1332
  for (const [k, v] of Object.entries(val)) {
1208
- Object.defineProperty(out, k, {
1209
- value: isSubMsgVal ? sub.create(v) : v,
1210
- writable: true,
1211
- enumerable: true,
1212
- configurable: true,
1213
- });
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
+ }
1214
1345
  }
1215
1346
  return out;
1216
1347
  }
@@ -1269,12 +1400,18 @@ function cloneFieldValue(f, val) {
1269
1400
  }
1270
1401
  const out = {};
1271
1402
  for (const [k, v] of Object.entries(val)) {
1272
- Object.defineProperty(out, k, {
1273
- value: isSubMsgVal ? sub.clone(v) : v,
1274
- writable: true,
1275
- enumerable: true,
1276
- configurable: true,
1277
- });
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
+ }
1278
1415
  }
1279
1416
  return out;
1280
1417
  }
@@ -1680,29 +1817,31 @@ function encodeMapField(enc, f, rawVal, deterministic, writeUnknown = false, sel
1680
1817
  }
1681
1818
  enc.endContainer();
1682
1819
  }
1683
- function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options) {
1820
+ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, maxDepth, options, endLimit = data.length) {
1684
1821
  const key = f.propKey;
1685
- const n = data.length;
1822
+ const n = endLimit;
1686
1823
  if ((wt === WireArray || wt === WireMap) && depth + 1 > maxDepth) {
1687
1824
  throw new Error(`omnibuf: nesting depth ${depth + 1} exceeds MaxNestingDepth (${maxDepth})`);
1688
1825
  }
1689
1826
  switch (f.effectiveType) {
1690
1827
  case 'uint32': {
1691
1828
  if (pos < n && (data[pos] & 7) !== 0) {
1692
- const [v, vn] = decodeVarint(data, pos);
1829
+ const [v, vn] = decodeVarint(data, pos, n);
1693
1830
  if (vn === 0)
1694
1831
  throw new Error(`omnibuf: truncated uint32 at ${pos}`);
1695
1832
  out[key] = v >>> 0;
1696
1833
  return pos + vn;
1697
1834
  }
1698
- const [v, vn] = decodeVarintBigInt(data, pos);
1835
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1699
1836
  if (vn === 0)
1700
1837
  throw new Error(`omnibuf: truncated uint32 at ${pos}`);
1701
1838
  out[key] = Number(v & 0xffffffffn) >>> 0;
1702
1839
  return pos + vn;
1703
1840
  }
1704
1841
  case 'uint64': {
1705
- 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);
1706
1845
  if (vn === 0)
1707
1846
  throw new Error(`omnibuf: truncated uint64 at ${pos}`);
1708
1847
  out[key] = v;
@@ -1712,13 +1851,13 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1712
1851
  case 'int32':
1713
1852
  case 'enum': {
1714
1853
  if (pos < n && (data[pos] & 7) !== 0) {
1715
- const [v, vn] = decodeVarint(data, pos);
1854
+ const [v, vn] = decodeVarint(data, pos, n);
1716
1855
  if (vn === 0)
1717
1856
  throw new Error(`omnibuf: truncated int32 at ${pos}`);
1718
1857
  out[key] = decodeZigZag32(v);
1719
1858
  return pos + vn;
1720
1859
  }
1721
- const [v, vn] = decodeVarintBigInt(data, pos);
1860
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1722
1861
  if (vn === 0)
1723
1862
  throw new Error(`omnibuf: truncated int32 at ${pos}`);
1724
1863
  out[key] = decodeZigZag32(v);
@@ -1726,7 +1865,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1726
1865
  }
1727
1866
  case 'sint64':
1728
1867
  case 'int64': {
1729
- const [v, vn] = decodeVarintBigInt(data, pos);
1868
+ const [v, vn] = decodeVarintBigInt(data, pos, n);
1730
1869
  if (vn === 0)
1731
1870
  throw new Error(`omnibuf: truncated int64 at ${pos}`);
1732
1871
  out[key] = f.useBigInt ? decodeZigZagBigInt(v) : decodeZigZagAuto(v);
@@ -1737,12 +1876,21 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1737
1876
  return pos;
1738
1877
  }
1739
1878
  case 'string': {
1740
- 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);
1741
1889
  out[key] = decodeUTF8(s);
1742
1890
  return nextPos;
1743
1891
  }
1744
1892
  case 'bytes': {
1745
- const [b, nextPos] = readLenSlice(data, pos, 0);
1893
+ const [b, nextPos] = readLenSlice(data, pos, 0, n);
1746
1894
  out[key] = b.slice();
1747
1895
  return nextPos;
1748
1896
  }
@@ -1798,7 +1946,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1798
1946
  return pos + 8;
1799
1947
  }
1800
1948
  case 'string[]': {
1801
- const [body, nextPos] = readLenSlice(data, pos, 2);
1949
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1802
1950
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1803
1951
  const [arr, ok] = appendStringArrBody(prev, body);
1804
1952
  if (!ok)
@@ -1807,7 +1955,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1807
1955
  return nextPos;
1808
1956
  }
1809
1957
  case 'bytes[]': {
1810
- const [body, nextPos] = readLenSlice(data, pos, 2);
1958
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1811
1959
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1812
1960
  const [arr, ok] = appendBytesArrBody(prev, body, false);
1813
1961
  if (!ok)
@@ -1816,7 +1964,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1816
1964
  return nextPos;
1817
1965
  }
1818
1966
  case 'bool[]': {
1819
- const [body, nextPos] = readLenSlice(data, pos, 2);
1967
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1820
1968
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1821
1969
  const [arr, ok] = appendBoolArrBody(prev, body);
1822
1970
  if (!ok)
@@ -1825,7 +1973,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1825
1973
  return nextPos;
1826
1974
  }
1827
1975
  case 'uint32[]': {
1828
- const [body, nextPos] = readLenSlice(data, pos, 2);
1976
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1829
1977
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1830
1978
  const [arr, ok] = appendUint32ArrBody(prev, body);
1831
1979
  if (!ok)
@@ -1834,7 +1982,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1834
1982
  return nextPos;
1835
1983
  }
1836
1984
  case 'enum[]': {
1837
- const [body, nextPos] = readLenSlice(data, pos, 2);
1985
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1838
1986
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1839
1987
  const [arr, ok] = appendEnumArrBody(prev, body);
1840
1988
  if (!ok)
@@ -1843,7 +1991,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1843
1991
  return nextPos;
1844
1992
  }
1845
1993
  case 'uint64[]': {
1846
- const [body, nextPos] = readLenSlice(data, pos, 2);
1994
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1847
1995
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1848
1996
  const startLen = prev.length;
1849
1997
  const [arr, ok] = appendUintArrAutoBody(prev, body);
@@ -1859,7 +2007,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1859
2007
  }
1860
2008
  case 'sint32[]':
1861
2009
  case 'int32[]': {
1862
- const [body, nextPos] = readLenSlice(data, pos, 2);
2010
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1863
2011
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1864
2012
  const [arr, ok] = appendEnumArrBody(prev, body);
1865
2013
  if (!ok)
@@ -1869,7 +2017,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1869
2017
  }
1870
2018
  case 'sint64[]':
1871
2019
  case 'int64[]': {
1872
- const [body, nextPos] = readLenSlice(data, pos, 2);
2020
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1873
2021
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1874
2022
  const startLen = prev.length;
1875
2023
  const [arr, ok] = appendSintArrAutoBody(prev, body);
@@ -1884,7 +2032,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1884
2032
  return nextPos;
1885
2033
  }
1886
2034
  case 'float32[]': {
1887
- const [body, nextPos] = readLenSlice(data, pos, 2);
2035
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1888
2036
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1889
2037
  const startLen = prev.length;
1890
2038
  const [arr, ok] = appendFloat32ArrBody(prev, body);
@@ -1897,7 +2045,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1897
2045
  return nextPos;
1898
2046
  }
1899
2047
  case 'fixed32[]': {
1900
- const [body, nextPos] = readLenSlice(data, pos, 2);
2048
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1901
2049
  const [elemType, c, startP, ok] = parseArrayHeader(body);
1902
2050
  if (!ok || elemType !== WireFixed32 || body.length - startP !== c * 4) {
1903
2051
  throw new Error(`omnibuf: invalid fixed32 array at ${pos}`);
@@ -1912,7 +2060,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1912
2060
  return nextPos;
1913
2061
  }
1914
2062
  case 'sfixed32[]': {
1915
- const [body, nextPos] = readLenSlice(data, pos, 2);
2063
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1916
2064
  const [elemType, c, startP, ok] = parseArrayHeader(body);
1917
2065
  if (!ok || elemType !== WireSfixed32 || body.length - startP !== c * 4) {
1918
2066
  throw new Error(`omnibuf: invalid sfixed32 array at ${pos}`);
@@ -1926,7 +2074,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1926
2074
  return nextPos;
1927
2075
  }
1928
2076
  case 'float64[]': {
1929
- const [body, nextPos] = readLenSlice(data, pos, 2);
2077
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1930
2078
  const prev = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1931
2079
  const [arr, ok] = appendFloat64ArrBody(prev, body);
1932
2080
  if (!ok)
@@ -1936,7 +2084,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1936
2084
  }
1937
2085
  case 'fixed64[]':
1938
2086
  case 'sfixed64[]': {
1939
- const [body, nextPos] = readLenSlice(data, pos, 2);
2087
+ const [body, nextPos] = readLenSlice(data, pos, 2, n);
1940
2088
  const isSigned = f.effectiveType === 'sfixed64[]';
1941
2089
  const expElemType = isSigned ? WireSfixed64 : WireFixed64;
1942
2090
  const [elemType, c, startP, ok] = parseArrayHeader(body);
@@ -1964,7 +2112,6 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1964
2112
  return nextPos;
1965
2113
  }
1966
2114
  case 'submsg': {
1967
- const [subBytes, nextPos] = readLenSlice(data, pos, 0);
1968
2115
  const subSchema = f.resolveSubSchema?.();
1969
2116
  if (!subSchema) {
1970
2117
  throw new Error(`omnibuf: missing subSchema on ${key}`);
@@ -1972,29 +2119,120 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
1972
2119
  const existing = out[key];
1973
2120
  const hasExisting = existing !== undefined && existing !== null && typeof existing === 'object';
1974
2121
  const targetSub = hasExisting ? existing : subSchema.create();
1975
- out[key] = subSchema.decode(subBytes, targetSub, depth + 1, {
1976
- ...options,
1977
- merge: f.oneof ? alreadySeen && hasExisting : alreadySeen,
1978
- });
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);
1979
2151
  return nextPos;
1980
2152
  }
1981
2153
  case 'submsg[]': {
1982
- const [arrPayload, nextPos] = readLenSlice(data, pos, 2);
1983
- const [elemCount, ok] = countSubMsgArrElems(arrPayload);
1984
- if (!ok) {
1985
- throw new Error(`omnibuf: corrupt submsg array at ${pos}`);
1986
- }
1987
2154
  const subSchema = f.resolveSubSchema?.();
1988
2155
  if (!subSchema) {
1989
2156
  throw new Error(`omnibuf: missing subSchema on ${key}`);
1990
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
+ }
1991
2229
  const elems = alreadySeen && Array.isArray(out[key]) ? out[key] : [];
1992
2230
  let [, , p] = parseArrayHeader(arrPayload);
1993
2231
  for (let i = 0; i < elemCount; i++) {
1994
2232
  const [el, en] = decodeVarintBigInt(arrPayload, p);
1995
2233
  p += en;
1996
2234
  const elNum = Number(el);
1997
- const elemObj = subSchema.decode(arrPayload.subarray(p, p + elNum), subSchema.create(), depth + 2, options);
2235
+ const elemObj = subSchema.decode(arrPayload, subSchema.create(), depth + 2, options, p, p + elNum);
1998
2236
  elems.push(elemObj);
1999
2237
  p += elNum;
2000
2238
  }
@@ -2002,7 +2240,7 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
2002
2240
  return nextPos;
2003
2241
  }
2004
2242
  case 'map': {
2005
- const [body, nextPos] = readLenSlice(data, pos, 3);
2243
+ const [body, nextPos] = readLenSlice(data, pos, 3, n);
2006
2244
  decodeMapFieldBody(f, out, body, alreadySeen, depth + 1, options);
2007
2245
  return nextPos;
2008
2246
  }
@@ -2011,6 +2249,14 @@ function decodeCompiledFieldValue(data, pos, wt, f, out, alreadySeen, depth, max
2011
2249
  function decodeMapScalarEntry(body, p, wt, subSchema, depth, options) {
2012
2250
  switch (wt) {
2013
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
+ }
2014
2260
  const [sBytes, nextP] = readLenSlice(body, p, 0);
2015
2261
  return [decodeUTF8(sBytes), nextP];
2016
2262
  }
@@ -2076,6 +2322,31 @@ function decodeMapScalarEntry(body, p, wt, subSchema, depth, options) {
2076
2322
  throw new Error(`omnibuf: invalid WireMap entry wire type ${wt}`);
2077
2323
  }
2078
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
+ }
2079
2350
  function decodeMapFieldBody(f, out, body, alreadySeen, depth, options) {
2080
2351
  const expKeyWT = f.mapKeyWT ?? WireString;
2081
2352
  const expValWT = f.mapValWT ?? WireUint;
@@ -2114,41 +2385,27 @@ function decodeMapFieldBody(f, out, body, alreadySeen, depth, options) {
2114
2385
  let p = 2 + cn;
2115
2386
  const c = Number(count);
2116
2387
  for (let i = 0; i < c; i++) {
2117
- const [kv, nextP] = decodeMapScalarEntry(body, p, f.mapKeyWT ?? WireString, undefined, depth, options);
2118
- const [rawVv, nextP2] = decodeMapScalarEntry(body, nextP, f.mapValWT ?? WireUint, subSchema, depth, options);
2119
- const convert = (v, type) => {
2120
- if (type === 'bool')
2121
- return Boolean(v);
2122
- if (type === 'float32')
2123
- return roundFloat32Shortest(float32FromBits(Number(v)));
2124
- if (type === 'float64')
2125
- return float64FromBits(BigInt(v));
2126
- if (type === 'uint32')
2127
- return Number(BigInt(v) & 0xffffffffn) >>> 0;
2128
- if (type === 'sfixed32' || type === 'int32' || type === 'sint32' || type === 'enum') {
2129
- return Number(BigInt(v) & 0xffffffffn) | 0;
2130
- }
2131
- if (type === 'sfixed64') {
2132
- const signed = BigInt.asIntN(64, BigInt(v));
2133
- return f.useBigInt || signed < -9007199254740991n || signed > 9007199254740991n
2134
- ? signed
2135
- : Number(signed);
2136
- }
2137
- return v;
2138
- };
2139
- const vv = convert(isVal64 ? BigInt(rawVv) : rawVv, f.mapValType);
2140
- 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);
2141
2392
  p = nextP2;
2142
2393
  if (targetMap instanceof Map) {
2143
2394
  targetMap.set(key, vv);
2144
2395
  }
2145
2396
  else {
2146
- Object.defineProperty(targetMap, String(key), {
2147
- value: vv,
2148
- enumerable: true,
2149
- configurable: true,
2150
- writable: true,
2151
- });
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
+ }
2152
2409
  }
2153
2410
  }
2154
2411
  if (p !== body.length) {