@oxidezap/baileyrs 0.3.8 → 0.3.9

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
@@ -373,6 +373,7 @@ A few behaviors that differ from upstream — almost always to your advantage:
373
373
  | `DisconnectReason.loggedOut` (401) | stop; needs a fresh pairing |
374
374
  | `405` | stop; the server rejected this build, and the next one too |
375
375
  | `DisconnectReason.forbidden` (403) | wait until `lastDisconnect.error.data.expire` (unix seconds) — it is a temporary ban |
376
+ | `500` (startup failure) | inspect `lastDisconnect.error.cause` before retrying; persistent storage/setup errors will repeat |
376
377
  | anything else | reconnect, after a short delay |
377
378
 
378
379
  `Example/example.ts` implements exactly this.
@@ -429,6 +430,13 @@ A few behaviors that differ from upstream — almost always to your advantage:
429
430
 
430
431
  ### When `connecting` lasts minutes
431
432
 
433
+ Socket startup emits `connecting` before awaiting credential hydration. If
434
+ hydration, bridge construction, or client setup rejects, it emits one terminal
435
+ `close` after cleanup with `statusCode` 500. `lastDisconnect.error` preserves
436
+ the initialization failure in `cause`; pending socket methods reject with that
437
+ same error. Check the cause before replacing a socket, since a storage error can
438
+ persist across restarts. An explicit `sock.end()` during startup remains a silent shutdown.
439
+
432
440
  Upstream Baileys emits `connecting` once per socket, and it resolves to `open`
433
441
  or `close` within seconds, because upstream never retries on its own. On
434
442
  baileyrs the same value also covers every drop the engine is retrying, and the
@@ -399,6 +399,8 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
399
399
  withClient: makeWithClient(getClient)
400
400
  };
401
401
  function getClient() {
402
+ if (initError)
403
+ return Promise.reject(initError);
402
404
  // Teardown retains the client through closing to disconnect the transport.
403
405
  // Ordinary operations must stop being admitted when close() is called.
404
406
  if (owner.isClosing()) {
@@ -416,6 +418,8 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
416
418
  return Promise.resolve(wrapBridgeClient(ready));
417
419
  }
418
420
  return initPromise.then(() => {
421
+ if (initError)
422
+ throw initError;
419
423
  // Closing may have started while initialization was pending.
420
424
  // This gate does not track admitted operations. Bridge 0.21.1 tolerates
421
425
  // free() during ordinary calls, but not during disconnect(); release
@@ -423,9 +427,6 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
423
427
  if (owner.isClosing()) {
424
428
  throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
425
429
  }
426
- if (initError) {
427
- throw new Boom('Bridge client failed to initialize: ' + initError.message, { statusCode: 500 });
428
- }
429
430
  const built = owner.peek();
430
431
  if (!built)
431
432
  throw new Boom('Client not initialized', { statusCode: 500 });
@@ -514,6 +515,17 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
514
515
  clearTimeout: runtime.clearTimeout
515
516
  });
516
517
  const init = async () => {
518
+ // Announce startup before awaiting storage, and allow callers to attach
519
+ // listeners first. A slow or failed hydration still has a lifecycle.
520
+ runtime.queueMicrotask(() => {
521
+ if (owner.isClosing())
522
+ return;
523
+ ev.emit('connection.update', {
524
+ connection: 'connecting',
525
+ receivedPendingNotifications: false,
526
+ qr: undefined
527
+ });
528
+ });
517
529
  await runtime.waitForAuthState?.(auth);
518
530
  // `initWasmEngine` reads `logger.level` synchronously while installing
519
531
  // the Rust-side logger: a consumer logger without the pino shape
@@ -545,22 +557,6 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
545
557
  resetEngineInitialization();
546
558
  throw err;
547
559
  }
548
- // Defer to a microtask so callers have a turn to attach listeners
549
- // after `makeWASocket()` returns. Without this the emit fires
550
- // synchronously inside `init()` (before the function reaches its
551
- // first `await`), which is also before the caller ever sees `conn.ev`,
552
- // so any handler registered via `conn.ev.on('connection.update', …)`
553
- // or `conn.ev.process(…)` silently misses the initial 'connecting'
554
- // state. Bots like sung that drive UI off the lifecycle (spinners,
555
- // reconnection counters) end up tracking a state machine they never
556
- // got to enter, then crash when the next state ('open' / 'close')
557
- // references prerequisites that the missed event was supposed to set
558
- // up.
559
- runtime.queueMicrotask(() => ev.emit('connection.update', {
560
- connection: 'connecting',
561
- receivedPendingNotifications: false,
562
- qr: undefined
563
- }));
564
560
  // Auto-promote upstream-Baileys-style `auth: { creds, keys }` to a
565
561
  // `JsStoreCallbacks`-shaped store via `wrapLegacyStore`. The synthetic
566
562
  // `saveCreds` callback re-emits `creds.update` so the bot's existing
@@ -742,7 +738,14 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
742
738
  // becomes a `ReferenceError` inside a bridge callback, where no `try/catch`
743
739
  // of ours can reach it. Ordering it here makes the dependency structural.
744
740
  const initPromise = init().catch(err => {
745
- initError = err instanceof Error ? err : new Error(String(err));
741
+ // A failure caused by an explicit shutdown must keep its existing
742
+ // Connection Closed behavior and must not publish a second lifecycle.
743
+ if (owner.isClosing())
744
+ return owner.discard();
745
+ initError = new Boom('Bridge client failed to initialize: ' + (err instanceof Error ? err.message : String(err)), {
746
+ statusCode: 500,
747
+ decorate: { cause: err }
748
+ });
746
749
  try {
747
750
  logger.error({ err }, 'failed to initialize bridge client');
748
751
  }
@@ -751,9 +754,18 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
751
754
  // cleanup below — and an unguarded throw here surfaces as an
752
755
  // unhandled rejection on a chain the caller never sees.
753
756
  }
754
- // A client adopted before the failure outlives a read loop that never
755
- // started: `getClient()` correctly rejects, but the standalone
756
- // helpers bypass it and would keep reaching the half-built client.
757
+ // Initialization can fail before run() installs its completion observer.
758
+ // Report that failure through the same once-only lifecycle as a run exit.
759
+ // Keep this detached: the reporter joins initPromise after teardown, so
760
+ // awaiting it here would make initialization wait for itself.
761
+ if (!owner.isClosing()) {
762
+ const error = initError;
763
+ reportTerminalClose(error, () => ev.emit('connection.update', {
764
+ connection: 'close',
765
+ lastDisconnect: { error, date: new Date() }
766
+ }));
767
+ }
768
+ // Join teardown without allowing its failure to reject initPromise.
757
769
  return owner.discard();
758
770
  });
759
771
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxidezap/baileyrs",
3
3
  "type": "module",
4
- "version": "0.3.8",
4
+ "version": "0.3.9",
5
5
  "description": "A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API",
6
6
  "keywords": [
7
7
  "whatsapp",