@oxidezap/baileyrs 0.3.6 → 0.3.7

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/README.md CHANGED
@@ -36,6 +36,25 @@ from the proto schema and compares the two libraries directly. Differences the
36
36
  fuzzers find are recorded with a reason and a review date, and known open ones
37
37
  are listed in `src/__fuzz__/harness/divergence.ts`.
38
38
 
39
+ ### Protobuf field names
40
+
41
+ The bridge and upstream Baileys generate their schemas from different sources, so a
42
+ field can keep its number and wire type and still be spelled differently. The `proto`
43
+ facade always uses the Baileys spelling:
44
+
45
+ | Type | Baileys | Bridge |
46
+ | -------------------------------------- | ------------------------ | -------------------------------- |
47
+ | `SyncActionValue.AgentAction` | `deviceID` | `deviceId` |
48
+ | `SyncActionValue.ChatAssignmentAction` | `deviceAgentID` | `deviceAgentId` |
49
+ | `Message.ExtendedTextMessage` | `faviconMMSMetadata` | `faviconMmsMetadata` |
50
+ | `Message.MessageHistoryMetadata` | `oldestMessageTimestamp` | `oldestMessageTimestampInWindow` |
51
+
52
+ Without the translation a write in the Baileys spelling is dropped by the codec and a
53
+ read never sets the public property. Both the facade and the send path translate, in
54
+ both directions, for fields nested at any depth. An own public property wins over the
55
+ bridge name, including an explicit `null` or `undefined`, and inputs are never
56
+ mutated. The bridge keeps its own names.
57
+
39
58
  ## Documentation
40
59
 
41
60
  The full API reference and guides live in the
@@ -12,6 +12,16 @@
12
12
  * absorbed, so the strict contract stays true of the bridge and the tolerant
13
13
  * one stays true of this library.
14
14
  *
15
+ * The three do not all follow the same reference, and the difference is worth
16
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
17
+ * produces, and what the client sends — while upstream protobufjs writes three
18
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
19
+ * registry folds away when it compares. The empty string becoming `0` is the other
20
+ * direction: the client never writes it and the bridge refuses it on purpose, so
21
+ * that one substitution is Baileys compatibility rather than client compliance.
22
+ * It stays because a message that used to reach the server should not start
23
+ * throwing, and it is written down here so it is a decision rather than an accident.
24
+ *
15
25
  * Repair on failure rather than check on write: the ordinary encode is exactly
16
26
  * the call it was before, with no scan of any field, and the repair runs only
17
27
  * for a message that was already going to throw. `encodeProto` returns finished
@@ -1,5 +1,5 @@
1
1
  import { encodeProto } from '@oxidezap/whatsapp-rust-bridge';
2
- import { repairProtoMessage } from './proto-runtime.js';
2
+ import { projectProtoMessage, repairProtoMessage } from './proto-runtime.js';
3
3
  /**
4
4
  * `encodeProto`, with the three inputs the bridge codec refuses put back.
5
5
  *
@@ -14,24 +14,39 @@ import { repairProtoMessage } from './proto-runtime.js';
14
14
  * absorbed, so the strict contract stays true of the bridge and the tolerant
15
15
  * one stays true of this library.
16
16
  *
17
+ * The three do not all follow the same reference, and the difference is worth
18
+ * stating. The surrogate becomes a single U+FFFD — what any UTF-8 encoder
19
+ * produces, and what the client sends — while upstream protobufjs writes three
20
+ * WTF-8 bytes instead, which is the artifact `replaceLoneSurrogates` in the fuzz
21
+ * registry folds away when it compares. The empty string becoming `0` is the other
22
+ * direction: the client never writes it and the bridge refuses it on purpose, so
23
+ * that one substitution is Baileys compatibility rather than client compliance.
24
+ * It stays because a message that used to reach the server should not start
25
+ * throwing, and it is written down here so it is a decision rather than an accident.
26
+ *
17
27
  * Repair on failure rather than check on write: the ordinary encode is exactly
18
28
  * the call it was before, with no scan of any field, and the repair runs only
19
29
  * for a message that was already going to throw. `encodeProto` returns finished
20
30
  * bytes rather than a lazy writer, so one try/catch covers it.
21
31
  */
22
32
  export const encodeProtoCompat = (path, message) => {
33
+ // The codec drops a key it does not know without throwing, so a public spelling has
34
+ // to be translated before the encode: a repair after a throw never runs. Same
35
+ // reference when nothing is aliased.
36
+ const projected = projectProtoMessage(path, message);
23
37
  try {
24
- return encodeProto(path, message);
38
+ return encodeProto(path, projected);
25
39
  }
26
40
  catch (error) {
41
+ // Repaired from the caller's message: this repair walks the schema this library
42
+ // publishes, so the projected names would not be found and the failure would
43
+ // propagate instead of being absorbed.
27
44
  const repaired = repairProtoMessage(path, message);
28
45
  // Reference equality: nothing was coerced, so the failure is something this
29
- // does not explain — an unmodelled type, a number no int64 can hold, an
30
- // unknown enum name — and it has to keep propagating rather than be
31
- // retried into a second throw.
46
+ // does not explain and it has to keep propagating rather than be retried.
32
47
  if (repaired === message)
33
48
  throw error;
34
- return encodeProto(path, repaired);
49
+ return encodeProto(path, projectProtoMessage(path, repaired));
35
50
  }
36
51
  };
37
52
  //# sourceMappingURL=encode-proto.js.map
@@ -9,6 +9,11 @@ type DynamicObject = Record<PropertyKey, unknown>;
9
9
  * repair from a failure it does not understand.
10
10
  */
11
11
  export declare const repairProtoMessage: (path: string, message: unknown) => unknown;
12
+ /**
13
+ * The projection for a caller that addresses the codec by type name. Reference
14
+ * equality means nothing needed translating.
15
+ */
16
+ export declare const projectProtoMessage: (path: string, message: unknown) => unknown;
12
17
  export interface ProtoCompatibilityFacade {
13
18
  proto: DynamicObject;
14
19
  unsupportedCodecs: readonly string[];
@@ -161,6 +161,19 @@ class LongBinaryReader extends BinaryReader {
161
161
  }
162
162
  }
163
163
  const longFromValue = (value, unsigned) => LongRuntime.fromValue(value, unsigned);
164
+ /**
165
+ * The neutral codec hands a 64-bit field back as a number while the value is exact as
166
+ * a double, and as a word split past that, where upstream declares a `Long` whose
167
+ * methods callers use. The decode reader above exists for the same reason.
168
+ */
169
+ const hydratedScalar = (kind, value) => {
170
+ if (value instanceof LongRuntime)
171
+ return value;
172
+ const split = isObject(value) && typeof value.low === 'number' && typeof value.high === 'number';
173
+ if (typeof value !== 'number' && typeof value !== 'string' && !split)
174
+ return value;
175
+ return longFromValue(value, kind === PROTO_FIELD_KIND.unsigned64);
176
+ };
164
177
  const longToBigInt = (value, unsigned) => {
165
178
  if (typeof value === 'bigint')
166
179
  return value;
@@ -279,17 +292,32 @@ const defineLazyValue = (target, key, build) => {
279
292
  });
280
293
  };
281
294
  /**
282
- * Type path to schema index, built on first use.
283
- *
284
- * Only the repair path needs it, and that path is only reached after an encode
285
- * has already failed — so an importer that never sends a refused value never
286
- * pays for the 498 entries.
295
+ * Type path to schema index, built on first use. The projection reads it per send,
296
+ * so the first encoded message builds it.
287
297
  */
288
298
  let schemaIdsByPath;
299
+ let lastSchemaPath;
300
+ let lastSchemaId;
301
+ // The send path asks for one type repeatedly, so the last answer is kept.
289
302
  const schemaIdFor = (path) => {
303
+ if (path === lastSchemaPath)
304
+ return lastSchemaId;
290
305
  schemaIdsByPath ?? (schemaIdsByPath = new Map(PROTO_MESSAGE_SCHEMAS.map(([name], index) => [name, index])));
291
- return schemaIdsByPath.get(path);
306
+ lastSchemaPath = path;
307
+ lastSchemaId = schemaIdsByPath.get(path);
308
+ return lastSchemaId;
292
309
  };
310
+ // Bridge names stay neutral. Both sides put these at the same number and wire type,
311
+ // so only the spelling differs.
312
+ const FIELD_ALIASES = {
313
+ 'SyncActionValue.AgentAction': ['deviceID', 'deviceId'],
314
+ 'SyncActionValue.ChatAssignmentAction': ['deviceAgentID', 'deviceAgentId'],
315
+ 'Message.ExtendedTextMessage': ['faviconMMSMetadata', 'faviconMmsMetadata'],
316
+ 'Message.MessageHistoryMetadata': ['oldestMessageTimestamp', 'oldestMessageTimestampInWindow']
317
+ };
318
+ // Indexed by schema id because its readers run per message.
319
+ let aliasBySchema;
320
+ const aliasFor = (schemaId) => (aliasBySchema ?? (aliasBySchema = PROTO_MESSAGE_SCHEMAS.map(([path]) => FIELD_ALIASES[path])))[schemaId];
293
321
  /**
294
322
  * Coerces the three inputs the bridge codec refuses back to what upstream
295
323
  * Baileys writes, and returns `value` itself when there was nothing to coerce.
@@ -318,10 +346,18 @@ const repairMessage = (schemaId, value, ancestors) => {
318
346
  return value;
319
347
  seen.add(value);
320
348
  let output;
349
+ const alias = aliasFor(schemaId);
321
350
  for (const field of fields) {
322
- if (!hasOwn(value, field[0]))
351
+ // Either spelling reaches the same field number, so a refused value has to be
352
+ // coerced under whichever name it arrived with.
353
+ const fieldKey = hasOwn(value, field[0])
354
+ ? field[0]
355
+ : alias !== undefined && alias[0] === field[0] && hasOwn(value, alias[1])
356
+ ? alias[1]
357
+ : undefined;
358
+ if (fieldKey === undefined)
323
359
  continue;
324
- const current = value[field[0]];
360
+ const current = value[fieldKey];
325
361
  if (current === null || current === undefined)
326
362
  continue;
327
363
  const repair = (item) => {
@@ -361,7 +397,7 @@ const repairMessage = (schemaId, value, ancestors) => {
361
397
  converted = repair(current);
362
398
  }
363
399
  if (converted !== current)
364
- (output ?? (output = { ...value }))[field[0]] = converted;
400
+ (output ?? (output = { ...value }))[fieldKey] = converted;
365
401
  }
366
402
  // The ancestor path, not everything ever visited: the same object reached
367
403
  // twice in different branches is legitimate and must still be repaired.
@@ -381,10 +417,117 @@ export const repairProtoMessage = (path, message) => {
381
417
  const schemaId = schemaIdFor(path);
382
418
  return schemaId === undefined ? message : repairMessage(schemaId, message);
383
419
  };
420
+ /**
421
+ * Message-typed fields by name, built on first use. Keyed by the message rather than
422
+ * the schema, which is what keeps the send-path walk proportional to the message.
423
+ */
424
+ const messageFieldsByNameBySchema = [];
425
+ const messageFieldsOf = (schemaId) => {
426
+ const existing = messageFieldsByNameBySchema[schemaId];
427
+ if (existing)
428
+ return existing;
429
+ const index = new Map();
430
+ for (const field of PROTO_MESSAGE_SCHEMAS[schemaId]?.[1] ?? []) {
431
+ if (field[1] === PROTO_FIELD_KIND.message)
432
+ index.set(field[0], field);
433
+ }
434
+ messageFieldsByNameBySchema[schemaId] = index;
435
+ return index;
436
+ };
437
+ /**
438
+ * Rewrites an aliased field's public spelling to the name the codec writes. The send
439
+ * path reaches `encodeProto` directly and that codec drops an unknown key without
440
+ * throwing, so this runs before the encode rather than after a failure. Copy-on-write,
441
+ * like `repairMessage`.
442
+ */
443
+ const projectAliases = (schemaId, value) => {
444
+ if (!isObject(value))
445
+ return value;
446
+ const messageFields = messageFieldsOf(schemaId);
447
+ const alias = aliasFor(schemaId);
448
+ let output;
449
+ if (alias && hasOwn(value, alias[0])) {
450
+ const moved = value[alias[0]];
451
+ // Walked, not just renamed: an aliased message type may carry one of its own.
452
+ const field = messageFields.get(alias[0]);
453
+ (output ?? (output = { ...value }))[alias[1]] =
454
+ field && moved !== null && moved !== undefined ? projectAliases(field[2], moved) : moved;
455
+ delete output[alias[0]];
456
+ }
457
+ // The message's own keys, so the cost follows the message.
458
+ for (const key of Object.keys(value)) {
459
+ if (key === alias?.[0])
460
+ continue;
461
+ const field = messageFields.get(key);
462
+ if (!field)
463
+ continue;
464
+ const current = value[key];
465
+ if (current === null || current === undefined)
466
+ continue;
467
+ let converted = current;
468
+ if (field[3] & PROTO_FIELD_FLAG.repeated) {
469
+ if (Array.isArray(current)) {
470
+ let items;
471
+ for (let index = 0; index < current.length; index++) {
472
+ const item = projectAliases(field[2], current[index]);
473
+ if (item !== current[index])
474
+ (items ?? (items = current.slice()))[index] = item;
475
+ }
476
+ converted = items ?? current;
477
+ }
478
+ }
479
+ else if (field[3] & PROTO_FIELD_FLAG.map) {
480
+ if (isObject(current)) {
481
+ let entries;
482
+ for (const entry in current) {
483
+ const item = projectAliases(field[2], current[entry]);
484
+ if (item !== current[entry])
485
+ (entries ?? (entries = { ...current }))[entry] = item;
486
+ }
487
+ converted = entries ?? current;
488
+ }
489
+ }
490
+ else {
491
+ converted = projectAliases(field[2], current);
492
+ }
493
+ if (converted !== current)
494
+ (output ?? (output = { ...value }))[key] = converted;
495
+ }
496
+ return output ?? value;
497
+ };
498
+ /**
499
+ * The projection for a caller that addresses the codec by type name. Reference
500
+ * equality means nothing needed translating.
501
+ */
502
+ export const projectProtoMessage = (path, message) => {
503
+ const schemaId = schemaIdFor(path);
504
+ return schemaId === undefined ? message : projectAliases(schemaId, message);
505
+ };
506
+ /**
507
+ * The value a field reads out of `data`, taking either spelling. `hasOwn` and not a
508
+ * null check, because an instance carries its defaults on the prototype: an absent
509
+ * public field reads as `0` there and the bridge key would never be reached.
510
+ */
511
+ const fieldValue = (data, field, alias) => !hasOwn(data, field[0]) && alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1])
512
+ ? data[alias[1]]
513
+ : data[field[0]];
514
+ /** True when either spelling is an own property, which is what keeps prototype defaults out of `toObject`. */
515
+ const hasOwnField = (data, field, alias) => hasOwn(data, field[0]) || (alias !== undefined && alias[0] === field[0] && hasOwn(data, alias[1]));
384
516
  class ProtoCompatibilityRuntime {
385
517
  constructor(sourceNamespace) {
386
518
  this.namespace = { ...sourceNamespace };
387
519
  this.enums = PROTO_ENUM_SCHEMAS.map(([, entries]) => this.makeEnum(entries));
520
+ // Only the 64-bit names are indexed: `hydrate` looks up every key a partial or a
521
+ // decode produced, and the rest of them need no conversion.
522
+ this.int64FieldsByName = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => {
523
+ const indexed = Object.create(null);
524
+ for (const field of fields) {
525
+ if (field[1] === PROTO_FIELD_KIND.signed64 || field[1] === PROTO_FIELD_KIND.unsigned64) {
526
+ indexed[field[0]] = field[1];
527
+ }
528
+ }
529
+ return indexed;
530
+ });
388
531
  this.messageFields = PROTO_MESSAGE_SCHEMAS.map(([, fields]) => fields.filter(field => field[1] === PROTO_FIELD_KIND.message));
389
532
  this.messageFieldsByName = this.messageFields.map(fields => {
390
533
  const indexed = Object.create(null);
@@ -496,7 +639,11 @@ class ProtoCompatibilityRuntime {
496
639
  constructor.toObject = (message, options) => this.toObject(schemaId, message, options);
497
640
  constructor.getTypeUrl = (prefix = 'type.googleapis.com') => `${prefix}/proto.${path}`;
498
641
  constructor.fromPartial = message => {
499
- const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(message) : message;
642
+ // A partial is not written, so it must not inherit encode's codec
643
+ // requirement: the bridge accepts holders of types it does not implement
644
+ // and simply drops them. Only the alias translation is needed here.
645
+ const projected = this.projectForEncode(schemaId, message, false);
646
+ const partial = sourceCodec?.fromPartial ? sourceCodec.fromPartial(projected) : projected;
500
647
  return this.hydrate(schemaId, isObject(partial) ? partial : {});
501
648
  };
502
649
  constructor.encode = (message, writer) => {
@@ -606,9 +753,10 @@ class ProtoCompatibilityRuntime {
606
753
  // megamorphic path, where V8 does not elide for..of iterator
607
754
  // allocations (~90 iterator results per WebMessageInfo envelope).
608
755
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
756
+ const alias = aliasFor(schemaId);
609
757
  for (let i = 0; i < fields.length; i++) {
610
758
  const field = fields[i];
611
- const value = data[field[0]];
759
+ const value = fieldValue(data, field, alias);
612
760
  if (value === null || value === undefined)
613
761
  continue;
614
762
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
@@ -668,6 +816,7 @@ class ProtoCompatibilityRuntime {
668
816
  const data = input;
669
817
  const output = {};
670
818
  const fields = PROTO_MESSAGE_SCHEMAS[schemaId][1];
819
+ const alias = aliasFor(schemaId);
671
820
  for (const field of fields) {
672
821
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
673
822
  if (options.arrays || options.defaults)
@@ -682,7 +831,7 @@ class ProtoCompatibilityRuntime {
682
831
  }
683
832
  }
684
833
  for (const field of fields) {
685
- const value = data[field[0]];
834
+ const value = fieldValue(data, field, alias);
686
835
  if (field[3] & PROTO_FIELD_FLAG.repeated) {
687
836
  if (value &&
688
837
  typeof value.length === 'number' &&
@@ -700,7 +849,7 @@ class ProtoCompatibilityRuntime {
700
849
  }
701
850
  continue;
702
851
  }
703
- if (value === null || value === undefined || !hasOwn(data, field[0]))
852
+ if (value === null || value === undefined || !hasOwnField(data, field, alias))
704
853
  continue;
705
854
  output[field[0]] = this.toObjectField(field, value, options);
706
855
  const group = oneofName(field);
@@ -788,11 +937,15 @@ class ProtoCompatibilityRuntime {
788
937
  const source = isObject(value) ? value : {};
789
938
  const instance = Object.create(this.constructorFor(schemaId).prototype);
790
939
  const messageFields = this.messageFieldsByName[schemaId];
791
- for (const key in source) {
792
- const nested = source[key];
940
+ const int64Fields = this.int64FieldsByName[schemaId];
941
+ const alias = aliasFor(schemaId);
942
+ for (const sourceKey in source) {
943
+ const key = alias && sourceKey === alias[1] ? alias[0] : sourceKey;
944
+ const nested = source[sourceKey];
793
945
  const field = messageFields[key];
794
946
  if (!field) {
795
- instance[key] = nested;
947
+ const kind = int64Fields[key];
948
+ instance[key] = kind === undefined ? nested : hydratedScalar(kind, nested);
796
949
  }
797
950
  else if (field[3] & PROTO_FIELD_FLAG.repeated) {
798
951
  if (Array.isArray(nested)) {
@@ -818,19 +971,26 @@ class ProtoCompatibilityRuntime {
818
971
  }
819
972
  return instance;
820
973
  }
821
- projectForEncode(schemaId, value) {
974
+ projectForEncode(schemaId, value, requireCodecs = true) {
822
975
  if (!isObject(value))
823
976
  return value;
824
977
  let output;
825
978
  if (typeof value[INSTANCE_SCHEMA] === 'number')
826
979
  output = { ...value };
980
+ const alias = aliasFor(schemaId);
981
+ // An own public field wins, including an explicit null or undefined.
982
+ if (alias && hasOwn(value, alias[0])) {
983
+ ;
984
+ (output ?? (output = { ...value }))[alias[1]] = value[alias[0]];
985
+ delete output[alias[0]];
986
+ }
827
987
  for (const field of this.messageFields[schemaId]) {
828
988
  if (!hasOwn(value, field[0]))
829
989
  continue;
830
990
  const nested = value[field[0]];
831
991
  if (nested === null || nested === undefined)
832
992
  continue;
833
- if (!this.sourceCodecs[field[2]]) {
993
+ if (requireCodecs && !this.sourceCodecs[field[2]]) {
834
994
  throw new Error(`protobuf codec unavailable for ${PROTO_MESSAGE_SCHEMAS[field[2]][0]}`);
835
995
  }
836
996
  let converted = nested;
@@ -838,7 +998,7 @@ class ProtoCompatibilityRuntime {
838
998
  if (Array.isArray(nested)) {
839
999
  let items;
840
1000
  for (let index = 0; index < nested.length; index++) {
841
- const item = this.projectForEncode(field[2], nested[index]);
1001
+ const item = this.projectForEncode(field[2], nested[index], requireCodecs);
842
1002
  if (item !== nested[index])
843
1003
  (items ?? (items = nested.slice()))[index] = item;
844
1004
  }
@@ -849,7 +1009,7 @@ class ProtoCompatibilityRuntime {
849
1009
  if (isObject(nested)) {
850
1010
  let entries;
851
1011
  for (const key in nested) {
852
- const item = this.projectForEncode(field[2], nested[key]);
1012
+ const item = this.projectForEncode(field[2], nested[key], requireCodecs);
853
1013
  if (item !== nested[key])
854
1014
  (entries ?? (entries = { ...nested }))[key] = item;
855
1015
  }
@@ -857,7 +1017,7 @@ class ProtoCompatibilityRuntime {
857
1017
  }
858
1018
  }
859
1019
  else {
860
- converted = this.projectForEncode(field[2], nested);
1020
+ converted = this.projectForEncode(field[2], nested, requireCodecs);
861
1021
  }
862
1022
  if (converted !== nested)
863
1023
  (output ?? (output = { ...value }))[field[0]] = converted;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxidezap/baileyrs",
3
3
  "type": "module",
4
- "version": "0.3.6",
4
+ "version": "0.3.7",
5
5
  "description": "A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API",
6
6
  "keywords": [
7
7
  "whatsapp",
@@ -93,8 +93,8 @@
93
93
  "jimp": "^1.6.0",
94
94
  "link-preview-js": "^5.0.0",
95
95
  "music-metadata": "^11.14.0",
96
- "oxfmt": "^0.66.0",
97
- "oxlint": "1.81.0",
96
+ "oxfmt": "^0.67.0",
97
+ "oxlint": "1.82.0",
98
98
  "pino": "^10.3.1",
99
99
  "pino-pretty": "^13.1.3",
100
100
  "pkg-pr-new": "^0.0.88",