@johnhenry/browsermesh-apps 0.5.0 → 0.7.1

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
@@ -1,7 +1,29 @@
1
1
  # browsermesh-apps
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/%40johnhenry%2Fbrowsermesh-apps.svg)](https://www.npmjs.com/package/@johnhenry/browsermesh-apps)
4
+ [![license](https://img.shields.io/npm/l/%40johnhenry%2Fbrowsermesh-apps.svg)](LICENSE)
5
+
3
6
  Application layer for BrowserMesh: marketplace, chat, payments, compute orchestration, and agent tools.
4
7
 
8
+ ## Contents
9
+
10
+ - [Provenance](#provenance)
11
+ - [Modules](#modules)
12
+ - [GPU compute](#gpu-compute)
13
+ - [Install](#install)
14
+ - [Usage](#usage)
15
+ - [Connecting a real mesh node: `createMeshNode()`](#connecting-a-real-mesh-node-createmeshnode)
16
+ - [TURN server configuration](#turn-server-configuration)
17
+ - [Sharing a `VirtualNetwork` with specific peers: mesh relay](#sharing-a-virtualnetwork-with-specific-peers-mesh-relay)
18
+ - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
+ - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
+ - [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
21
+ - [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
22
+ - [`browserMeshFetch`](#browsermeshfetch)
23
+ - [`BrowserMeshWebSocket`](#browsermeshwebsocket)
24
+ - [LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`](#llm-tool-calling-browsertoolregistry-and-createagentruntime)
25
+ - [License](#license)
26
+
5
27
  ## Provenance
6
28
 
7
29
  Extracted from the private `clawser` monorepo (previously `packages/browsermesh-apps`), where it was manually published to npm, unscoped, as `browsermesh-apps@0.1.0` (2026-07-17) with no CI ever automating that publish. This is its first release as part of the `@johnhenry/browsermesh` monorepo; the version restarts at `0.0.0` per family convention.
@@ -49,9 +71,9 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
49
71
  | peer-verification | `VerificationQuorum`, `Attestation` |
50
72
  | marketplace-ui | `SkillMarketplace` |
51
73
  | mesh-relay-host | `MeshRelayHost` |
52
- | mesh-relay-backend | `MeshRelayBackend` |
74
+ | mesh-relay-backend | `createMeshRelayBackend` |
53
75
  | mesh-service | `attachService`, `MeshService` (attach convention) |
54
- | cloud-storage-backend | `CloudStorageBackend` |
76
+ | cloud-storage-backend | `createCloudStorageBackend` |
55
77
  | grant-log | `GrantLog`, `createGrantLogService` |
56
78
  | key-distribution | `createKeyDistributionService` |
57
79
  | manifest-sync | `createManifestSyncService` |
@@ -133,7 +155,7 @@ npm install @johnhenry/browsermesh-apps @johnhenry/browsermesh-primitives @johnh
133
155
  ## Usage
134
156
 
135
157
  ```js
136
- import { MeshChat, AppRegistry, MeshOrchestrator } from 'browsermesh-apps';
158
+ import { MeshChat, AppRegistry, MeshOrchestrator } from '@johnhenry/browsermesh-apps';
137
159
  ```
138
160
 
139
161
  ## Connecting a real mesh node: `createMeshNode()`
@@ -232,17 +254,17 @@ alice.registry.grantCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
232
254
  alice.registry.revokeCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
233
255
  ```
234
256
 
235
- On the client side (the peer being granted access), `MeshRelayBackend` is a
236
- `browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
257
+ On the client side (the peer being granted access), `createMeshRelayBackend()`
258
+ builds a `browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
237
259
  under any scheme you like, and connect through the normal API, treating the
238
260
  service name as the "host":
239
261
 
240
262
  ```js
241
- import { MeshRelayBackend } from '@johnhenry/browsermesh-apps';
263
+ import { createMeshRelayBackend } from '@johnhenry/browsermesh-apps';
242
264
  import { VirtualNetwork } from '@johnhenry/browsermesh-netway';
243
265
 
244
266
  const bobNetwork = new VirtualNetwork();
245
- bobNetwork.addBackend('via-alice', new MeshRelayBackend({ node: bob, relayPeerPubKey: alice.podId }));
267
+ bobNetwork.addBackend('via-alice', createMeshRelayBackend({ node: bob, relayPeerPubKey: alice.podId }));
246
268
 
247
269
  const socket = await bobNetwork.connect('via-alice://s3-local'); // refused (ConnectionRefusedError) until granted
248
270
  ```
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.5.0",
3
+ "version": "0.7.1",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
8
- ".": "./src/index.mjs",
8
+ ".": {
9
+ "browser": "./src/index.mjs",
10
+ "default": "./src/index.mjs"
11
+ },
9
12
  "./compat": "./src/compat.mjs",
10
13
  "./mesh-rpc": "./src/mesh-rpc.mjs",
11
14
  "./mesh-fetch": "./src/mesh-fetch.mjs",
@@ -66,6 +69,6 @@
66
69
  },
67
70
  "homepage": "https://opensource.johnhenry.me/browsermesh/",
68
71
  "engines": {
69
- "node": ">=24.0.0"
72
+ "node": ">=26.0.0"
70
73
  }
71
74
  }
@@ -140,9 +140,36 @@
140
140
  * is byte-for-byte identical to before this phase existed.
141
141
  *
142
142
  * No browser-only imports at module level.
143
+ *
144
+ * `@johnhenry/browsermesh-netway` (an optional peerDependency) is lazily
145
+ * resolved via `createLazyRequire(import.meta.url)`
146
+ * (`./internal/lazy-node-require.mjs`, using
147
+ * `process.getBuiltinModule('module')` rather than a static
148
+ * `import ... from 'node:module'`, so no Node-only code runs merely from
149
+ * importing this file -- see issue #183). `Backend` is used as a
150
+ * `extends` clause is evaluated at class-DECLARATION time, and a
151
+ * `class ... extends ... {}` statement written at module top level always
152
+ * runs at module-LOAD time, no matter how the `Backend` reference feeding
153
+ * it is obtained -- there is no way to defer that with a plain lazy
154
+ * import, sync or async. The fix here instead moves the class declaration
155
+ * itself out of module-top-level scope, into a function that resolves
156
+ * `Backend` via `require()` and builds+memoizes the class on first call, so
157
+ * it still only runs once, lazily, the first time this file is actually
158
+ * used, not merely imported. (`@johnhenry/browsermesh-sync` and
159
+ * `@johnhenry/browsermesh-primitives`, imported below, are both REQUIRED
160
+ * -- not optional -- peerDependencies of this package, so they stay
161
+ * imported eagerly; only `browsermesh-netway` needed this treatment.)
162
+ *
163
+ * **BREAKING CHANGE**: `CloudStorageBackend` is no longer exported as a
164
+ * class. Replace `new CloudStorageBackend(opts)` with
165
+ * `createCloudStorageBackend(opts)` (same `opts` shape, still returns a
166
+ * real `CloudStorageBackend` instance with the exact same instance API) --
167
+ * see the CHANGELOG entry documenting this fix across the package for the
168
+ * full rationale and the sibling `mesh-relay-backend.mjs` fix.
143
169
  */
144
170
 
145
- import { Backend, StreamSocket } from '@johnhenry/browsermesh-netway'
171
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
172
+
146
173
  import { IndexedDBChunkStore, IndexedDBSyncStorage, TRANSFER_DEFAULTS } from '@johnhenry/browsermesh-sync'
147
174
  import { LWWMap } from '@johnhenry/browsermesh-primitives'
148
175
 
@@ -286,13 +313,27 @@ function bytesEqual(a, b) {
286
313
  // CloudStorageBackend
287
314
  // ---------------------------------------------------------------------------
288
315
 
316
+ let _CloudStorageBackendClass = null
317
+
289
318
  /**
290
- * A `Backend` exposing a durable, encrypted-at-rest, single-peer S3-like
291
- * object store over a JSON-command-over-socket protocol.
292
- *
293
- * @extends Backend
319
+ * Lazily builds (and memoizes) the `CloudStorageBackend` class, deferring
320
+ * resolution of `@johnhenry/browsermesh-netway`'s `Backend`/`StreamSocket`
321
+ * past module-load time -- see module doc comment. Only ever runs once per
322
+ * process; every later call returns the same class reference.
323
+ * @returns {typeof CloudStorageBackend}
294
324
  */
295
- export class CloudStorageBackend extends Backend {
325
+ function resolveCloudStorageBackendClass() {
326
+ if (_CloudStorageBackendClass) return _CloudStorageBackendClass
327
+ const require = createLazyRequire(import.meta.url)
328
+ const { Backend, StreamSocket } = require('@johnhenry/browsermesh-netway')
329
+
330
+ /**
331
+ * A `Backend` exposing a durable, encrypted-at-rest, single-peer S3-like
332
+ * object store over a JSON-command-over-socket protocol.
333
+ *
334
+ * @extends Backend
335
+ */
336
+ class CloudStorageBackend extends Backend {
296
337
  /** @type {string} */
297
338
  #bucket
298
339
 
@@ -929,4 +970,22 @@ export class CloudStorageBackend extends Backend {
929
970
  this.#manifestStorage.close?.()
930
971
  this.#keyStorage.close?.()
931
972
  }
973
+ }
974
+
975
+ _CloudStorageBackendClass = CloudStorageBackend
976
+ return CloudStorageBackend
977
+ }
978
+
979
+ /**
980
+ * Construct a `CloudStorageBackend` -- the class itself is no longer
981
+ * exported directly (see module doc comment's "BREAKING CHANGE" note).
982
+ *
983
+ * @param {object} opts - Same shape as `CloudStorageBackend`'s constructor:
984
+ * `{bucket, dbName?, chunkStore?, manifestStorage?, keyStorage?, nodeId?, onLog?}`.
985
+ * @returns {import('@johnhenry/browsermesh-netway').Backend} A real
986
+ * `CloudStorageBackend` instance (the full instance API is unchanged).
987
+ */
988
+ export function createCloudStorageBackend(opts) {
989
+ const CloudStorageBackend = resolveCloudStorageBackendClass()
990
+ return new CloudStorageBackend(opts)
932
991
  }
@@ -198,7 +198,7 @@
198
198
  */
199
199
 
200
200
  import { attachService, createEventBus } from './mesh-service.mjs'
201
- import { CloudStorageBackend } from './cloud-storage-backend.mjs'
201
+ import { createCloudStorageBackend } from './cloud-storage-backend.mjs'
202
202
  import { createGrantLogService } from './grant-log.mjs'
203
203
  import { createKeyDistributionService } from './key-distribution.mjs'
204
204
  import { createManifestSyncService } from './manifest-sync.mjs'
@@ -304,7 +304,7 @@ export class CloudStorage {
304
304
  /** @type {import('@johnhenry/browsermesh-netway').VirtualNetwork|null} */
305
305
  #network
306
306
 
307
- /** @type {CloudStorageBackend} */
307
+ /** @type {import('./cloud-storage-backend.mjs').CloudStorageBackend} */
308
308
  #backend
309
309
 
310
310
  /** @type {import('@johnhenry/browsermesh-netway').StreamSocket|null} lazily-opened private local socket to `#backend` */
@@ -415,7 +415,7 @@ export class CloudStorage {
415
415
  })
416
416
  }
417
417
 
418
- this.#backend = new CloudStorageBackend({
418
+ this.#backend = createCloudStorageBackend({
419
419
  bucket,
420
420
  dbName,
421
421
  chunkStore,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A Node-only, browser-safe way to obtain a CommonJS-style `require()`
3
+ * bound to a given module URL -- WITHOUT ever writing
4
+ * `import { createRequire } from 'node:module'` at a file's top level.
5
+ *
6
+ * Why this exists: several files in this package resolve an optional
7
+ * peerDependency lazily via `require()` rather than a dynamic `import()`,
8
+ * because the call site is synchronous (a constructor, or a factory whose
9
+ * validation throw is directly tested with `assert.throws()`) and a
10
+ * dynamic `import()` is inherently async. `createRequire()` itself is
11
+ * fine to call lazily, inside the function that needs it -- the bug this
12
+ * file fixes is that a *static* `import ... from 'node:module'` at a
13
+ * file's top level is unconditionally resolved when that file is loaded,
14
+ * before any function runs. In a browser (no bundler, or a bundler that
15
+ * doesn't polyfill Node builtins) that static import fails immediately,
16
+ * which broke importing this package's root entry at all -- even for
17
+ * callers who never touch the optional-peer code path.
18
+ *
19
+ * `process.getBuiltinModule('module')` (Node >=22.3) returns the same
20
+ * `node:module` export without any `import`/`require` of its own, so
21
+ * referencing it only from inside a function -- guarded by
22
+ * `typeof process !== 'undefined'` -- means nothing Node-only executes,
23
+ * and no unresolvable specifier is ever touched, just from importing a
24
+ * file that uses this helper.
25
+ *
26
+ * @param {string} url - Pass `import.meta.url` from the calling module.
27
+ * @returns {NodeRequire} A `require()` bound to `url`.
28
+ * @throws {Error} If called outside Node.js (e.g. in a browser), but only
29
+ * when a caller actually invokes this -- never merely from importing a
30
+ * module that references it.
31
+ */
32
+ export function createLazyRequire(url) {
33
+ const getBuiltinModule = typeof process !== 'undefined' && process.getBuiltinModule
34
+ if (!getBuiltinModule) {
35
+ throw new Error(
36
+ 'createLazyRequire() requires Node.js (process.getBuiltinModule is unavailable) -- ' +
37
+ 'this code path is not supported in a browser environment.',
38
+ )
39
+ }
40
+ const { createRequire } = getBuiltinModule('module')
41
+ return createRequire(url)
42
+ }
@@ -29,11 +29,10 @@
29
29
  * with no adapter code needed -- this module's only real job is making that
30
30
  * dependency direction, and the one-import convenience, explicit.
31
31
  *
32
- * No browser-only imports at module level.
32
+ * No browser-only imports at module level -- @johnhenry/browsermesh-kernel
33
+ * is imported lazily inside createMeshKernel() (see below).
33
34
  */
34
35
 
35
- import { Kernel } from '@johnhenry/browsermesh-kernel'
36
-
37
36
  /**
38
37
  * Construct a Kernel whose MESH capability is backed by a real, connected
39
38
  * `PeerNode`. Any tenant created via the returned kernel with
@@ -49,8 +48,15 @@ import { Kernel } from '@johnhenry/browsermesh-kernel'
49
48
  * `new Kernel()`.
50
49
  * @param {object} [opts.kernelOpts] - Passed through to the Kernel
51
50
  * constructor (`clock`, `rng`, `tracerOpts`, `loggerOpts`, `resourceOpts`).
52
- * @returns {Kernel}
51
+ * @returns {Promise<Kernel>}
53
52
  */
54
- export function createMeshKernel({ peerNode, kernelOpts = {} } = {}) {
53
+ export async function createMeshKernel({ peerNode, kernelOpts = {} } = {}) {
54
+ // Lazily imported so this module doesn't force @johnhenry/browsermesh-kernel
55
+ // (an optional peerDependency) on every consumer of this package's
56
+ // top-level `.` entrypoint, which `export *`s from this file among 70+
57
+ // others -- see the CHANGELOG entry documenting this fix for the full
58
+ // rationale. BREAKING: this function is now async (was sync); the only
59
+ // in-repo caller (test/real-peer/kernel-mesh.test.mjs) is updated to match.
60
+ const { Kernel } = await import('@johnhenry/browsermesh-kernel')
55
61
  return new Kernel({ ...kernelOpts, mesh: peerNode || null })
56
62
  }
@@ -168,7 +168,13 @@
168
168
  */
169
169
 
170
170
  import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
171
- import { generateEncryptionKeyPair, wrapKeyForMember, unwrapKeyForMember } from '@johnhenry/browsermesh-core'
171
+ // @johnhenry/browsermesh-core (an optional peerDependency) is imported
172
+ // lazily, at each of the three call sites below, rather than eagerly here
173
+ // -- so this module doesn't force it on every consumer of this package's
174
+ // top-level `.` entrypoint. Dynamic import() is cached by the module
175
+ // system after the first real resolution, so this costs nothing on repeat
176
+ // calls. See the CHANGELOG entry documenting this fix for the full
177
+ // rationale.
172
178
 
173
179
  /** Default `envelope.type` used to route key-distribution payloads on the shared `onIncomingData()` bus. */
174
180
  const DEFAULT_ENVELOPE_TYPE = 'bucket-key'
@@ -315,11 +321,13 @@ export function createKeyDistributionService({
315
321
 
316
322
  function ensureKeyPair() {
317
323
  if (!keyPairPromise) {
318
- keyPairPromise = generateEncryptionKeyPair().then(async (kp) => {
319
- const raw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
320
- localPublicKeyB64 = toBase64(raw)
321
- return kp
322
- })
324
+ keyPairPromise = import('@johnhenry/browsermesh-core')
325
+ .then(({ generateEncryptionKeyPair }) => generateEncryptionKeyPair())
326
+ .then(async (kp) => {
327
+ const raw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
328
+ localPublicKeyB64 = toBase64(raw)
329
+ return kp
330
+ })
323
331
  }
324
332
  return keyPairPromise
325
333
  }
@@ -330,6 +338,7 @@ export function createKeyDistributionService({
330
338
 
331
339
  /** Wrap `rawKeyBytes` for `recipientPublicKey` and sign a `deliver` record over the result. */
332
340
  async function buildDeliverRecord(rawKeyBytes, recipientPublicKey) {
341
+ const { wrapKeyForMember } = await import('@johnhenry/browsermesh-core')
333
342
  const importable = await crypto.subtle.importKey('raw', rawKeyBytes, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
334
343
  const envelope = await wrapKeyForMember(importable, recipientPublicKey)
335
344
 
@@ -464,6 +473,7 @@ export function createKeyDistributionService({
464
473
 
465
474
  let rawKeyBytes
466
475
  try {
476
+ const { unwrapKeyForMember } = await import('@johnhenry/browsermesh-core')
467
477
  const keyPair = await ensureKeyPair()
468
478
  const unwrapped = await unwrapKeyForMember(envelope, keyPair.privateKey)
469
479
  rawKeyBytes = new Uint8Array(await crypto.subtle.exportKey('raw', unwrapped))
@@ -53,7 +53,7 @@
53
53
  * e.g. one with a `GatewayBackend` reaching a real local service), attached
54
54
  * as `node.relayHost`. This is the "share my `VirtualNetwork` access with
55
55
  * specific peers" side; the client side is `mesh-relay-backend.mjs`'s
56
- * `MeshRelayBackend`, constructed directly (not via this function) and
56
+ * `createMeshRelayBackend()`, called directly (not via this function) and
57
57
  * registered on the *client's own* `VirtualNetwork`.
58
58
  *
59
59
  * **Transport hardening is opt-in via `{ enableHardening: true,
@@ -300,29 +300,12 @@
300
300
  * detection). Attached to the returned node as `node.swarm` (the
301
301
  * `attachService()` handle -- also reachable via `node.services.get('swarm')`).
302
302
  *
303
- * No browser-only imports at module level.
303
+ * No browser-only imports at module level. @johnhenry/browsermesh-core/
304
+ * -discovery/-transport (all optional peerDependencies) are imported
305
+ * lazily inside createMeshNode() itself, not here -- see that function's
306
+ * own comment and the CHANGELOG entry documenting this fix.
304
307
  */
305
308
 
306
- import {
307
- IdentityWallet,
308
- MeshIdentityManager,
309
- MeshPeerManager,
310
- TrustGraph,
311
- MeshACL,
312
- CapabilityValidator,
313
- CapabilityToken,
314
- } from '@johnhenry/browsermesh-core'
315
- import {
316
- DiscoveryManager,
317
- DiscoveryRecord,
318
- BroadcastChannelStrategy,
319
- } from '@johnhenry/browsermesh-discovery'
320
- import {
321
- MeshTransportNegotiator,
322
- WebRTCMeshManager,
323
- mergeIceServers,
324
- } from '@johnhenry/browsermesh-transport'
325
-
326
309
  import { PeerNode } from './peer-node.mjs'
327
310
  import { PeerRegistry } from './peer-registry.mjs'
328
311
  import { MeshSignalingChannel } from './signaling.mjs'
@@ -876,6 +859,22 @@ export async function createMeshNode(options = {}) {
876
859
  )
877
860
  }
878
861
 
862
+ // @johnhenry/browsermesh-core/-discovery/-transport (all optional
863
+ // peerDependencies) are imported lazily here, not eagerly at module
864
+ // top-level, so this module doesn't force them on every consumer of
865
+ // this package's top-level `.` entrypoint -- see the CHANGELOG entry
866
+ // documenting this fix. createMeshNode() was already async, so this
867
+ // adds no signature change.
868
+ const [
869
+ { IdentityWallet, MeshIdentityManager, MeshPeerManager, TrustGraph, MeshACL, CapabilityValidator, CapabilityToken },
870
+ { DiscoveryManager, DiscoveryRecord, BroadcastChannelStrategy },
871
+ { MeshTransportNegotiator, WebRTCMeshManager, mergeIceServers },
872
+ ] = await Promise.all([
873
+ import('@johnhenry/browsermesh-core'),
874
+ import('@johnhenry/browsermesh-discovery'),
875
+ import('@johnhenry/browsermesh-transport'),
876
+ ])
877
+
879
878
  // -- Identity ---------------------------------------------------------
880
879
  const identityManager = providedIdentityManager || new MeshIdentityManager({ onLog })
881
880
  const wallet = new IdentityWallet({ identityManager, onLog })
@@ -980,7 +979,7 @@ export async function createMeshNode(options = {}) {
980
979
  // same `transportNegotiator` reference, so it sees adapters registered on
981
980
  // it regardless of when registration happens relative to wrapping.
982
981
  const hardening = enableHardening
983
- ? createHardenedNegotiator({
982
+ ? await createHardenedNegotiator({
984
983
  negotiator: transportNegotiator,
985
984
  retryOptions: hardeningOptions?.retry,
986
985
  onLog,
package/src/mesh-dht.mjs CHANGED
@@ -49,9 +49,25 @@
49
49
  * supplying that out-of-band knowledge yourself.
50
50
  *
51
51
  * No browser-only imports at module level.
52
+ *
53
+ * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
54
+ * lazily resolved via `createLazyRequire(import.meta.url)`
55
+ * (`./internal/lazy-node-require.mjs`, using
56
+ * `process.getBuiltinModule('module')` rather than a static
57
+ * `import ... from 'node:module'`, so no Node-only code runs merely from
58
+ * importing this file -- see issue #183), not a dynamic `import()`.
59
+ * `createMeshDht()` is synchronous, has a directly-tested synchronous
60
+ * validation-throw contract (`test/mesh-dht.test.mjs`'s
61
+ * `assert.throws(...)`), and returns `{strategy, dhtNode, teardown}`
62
+ * directly to ~11 synchronous call sites in its own test file -- an async
63
+ * `import()` would have broken all of that (see the CHANGELOG entry
64
+ * documenting this fix across the package). `require()` resolves lazily
65
+ * (only when `createMeshDht()` is actually called, after its own
66
+ * validation throws) while staying fully synchronous, so none of that
67
+ * changes.
52
68
  */
53
69
 
54
- import { DhtDiscoveryStrategy } from '@johnhenry/browsermesh-discovery'
70
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
55
71
 
56
72
  /** Default `type` tag for DHT wire messages multiplexed onto a shared transport. */
57
73
  const DEFAULT_MESSAGE_TYPE = 'dht-relay'
@@ -146,6 +162,11 @@ export function createMeshDht({
146
162
  throw new Error('createMeshDht: options.transport is required and must implement send(msg)/onMessage(cb)')
147
163
  }
148
164
 
165
+ // Lazy, synchronous (see module doc comment) -- only reached once
166
+ // validation above has already passed.
167
+ const require = createLazyRequire(import.meta.url)
168
+ const { DhtDiscoveryStrategy } = require('@johnhenry/browsermesh-discovery')
169
+
149
170
  const sendFn = (targetId, msg) => {
150
171
  transport.send({ type: messageType, from: localPodId, to: targetId, payload: msg })
151
172
  }
@@ -91,10 +91,37 @@
91
91
  * server ever answered, which is exactly what a `mesh-rpc` timeout or
92
92
  * send failure represents.
93
93
  *
94
- * No browser-only imports at module level.
94
+ * No browser-only imports at module level, and -- as of the fix for
95
+ * issue #183 -- no Node-only imports at module level either:
96
+ * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
97
+ * lazily resolved via `createLazyRequire(import.meta.url)`
98
+ * (`./internal/lazy-node-require.mjs`), which itself gets Node's
99
+ * `require()` from `process.getBuiltinModule('module')` rather than a
100
+ * static `import ... from 'node:module'`. This matters for two reasons:
101
+ * first, `browserMeshFetch(url, init)` below is deliberately NOT async
102
+ * (see "ERROR-VS-REJECT SEMANTICS" above -- it must throw a `TypeError`
103
+ * *synchronously* for a malformed URL, matching real `fetch()`), and
104
+ * `createBrowserMeshFetch()`'s own synchronous meshRpcApi-validation throw
105
+ * is directly tested (`test/mesh-fetch.test.mjs`'s
106
+ * `assert.throws(() => createBrowserMeshFetch(...))`) -- a dynamic
107
+ * `import()` is inherently async and would have broken both of those.
108
+ * Second, and the reason it's `createLazyRequire()` and not a top-level
109
+ * `createRequire(import.meta.url)`: a *static* `import` of `node:module`
110
+ * at this file's top level would fail immediately when this file is
111
+ * loaded in a browser, even for callers who never call
112
+ * `createBrowserMeshFetch()` at all -- since this file is re-exported from
113
+ * the package root. `createLazyRequire()` resolves the module lazily
114
+ * (only when `createBrowserMeshFetch()` is actually called, not at this
115
+ * module's own load time) while staying fully synchronous, so neither
116
+ * function's signature or throw semantics change at all. See the
117
+ * CHANGELOG entry documenting this fix across the package for the sibling
118
+ * files that use the same technique, and `mesh-websocket.mjs`'s module doc
119
+ * comment for the one case (a constructor) where a dynamic `import()`
120
+ * genuinely could not have worked even with an async rewrite, which is
121
+ * what led to trying `require()` here in the first place.
95
122
  */
96
123
 
97
- import { parseMeshRequest } from '@johnhenry/browsermesh-discovery'
124
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
98
125
 
99
126
  /**
100
127
  * @typedef {object} MeshRpcApi
@@ -121,6 +148,12 @@ export function createBrowserMeshFetch(meshRpcApi) {
121
148
  )
122
149
  }
123
150
 
151
+ // Lazy, synchronous (see module doc comment) -- only resolved once a
152
+ // caller actually builds a browserMeshFetch, and cached by require()'s
153
+ // own module cache for every subsequent call.
154
+ const require = createLazyRequire(import.meta.url)
155
+ const { parseMeshRequest } = require('@johnhenry/browsermesh-discovery')
156
+
124
157
  /**
125
158
  * `browserMeshFetch()` itself -- deliberately NOT an `async function` (see
126
159
  * the module doc comment's "ERROR-VS-REJECT SEMANTICS" section for why: a
@@ -85,7 +85,10 @@
85
85
  * No browser-only imports at module level.
86
86
  */
87
87
 
88
- import { RetryWithBackoff, TransportFailover, MetricsRegistry } from '@johnhenry/browsermesh-core'
88
+ // @johnhenry/browsermesh-core (an optional peerDependency) is imported
89
+ // lazily inside createHardenedNegotiator() below, not eagerly here -- so
90
+ // this module doesn't force it on every consumer of this package's
91
+ // top-level `.` entrypoint. See the CHANGELOG entry documenting this fix.
89
92
 
90
93
  const DEFAULT_METRICS_KEY = 'unknown'
91
94
 
@@ -192,17 +195,21 @@ function instrumentTransport(transport, metrics) {
192
195
  * `new RetryWithBackoff()` (maxRetries/baseDelayMs/maxDelayMs/jitterFactor/
193
196
  * resetTimeoutMs -- see hardening.mjs).
194
197
  * @param {Function} [opts.onLog]
195
- * @returns {{
198
+ * @returns {Promise<{
196
199
  * negotiate: (endpoints: object, auth?: object) => Promise<object>,
197
200
  * metrics: import('@johnhenry/browsermesh-core').MetricsRegistry,
198
201
  * failovers: Map<string, import('@johnhenry/browsermesh-core').TransportFailover>,
199
202
  * retries: Map<string, import('@johnhenry/browsermesh-core').RetryWithBackoff>,
200
- * }}
203
+ * }>}
201
204
  */
202
- export function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
205
+ export async function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
203
206
  if (!negotiator) {
204
207
  throw new Error('createHardenedNegotiator: options.negotiator is required')
205
208
  }
209
+ // Lazily imported (an optional peerDependency) -- see the CHANGELOG entry
210
+ // documenting this fix. BREAKING: this function is now async (was sync);
211
+ // its one in-repo caller (mesh-bootstrap.mjs) is updated to match.
212
+ const { RetryWithBackoff, TransportFailover, MetricsRegistry } = await import('@johnhenry/browsermesh-core')
206
213
  const log = onLog || (() => {})
207
214
  const metrics = new MetricsRegistry()
208
215
  const failovers = new Map()
@@ -117,9 +117,27 @@
117
117
  * instance was found -- see "HARDENING INTEGRATION" above).
118
118
  *
119
119
  * No browser-only imports at module level.
120
+ *
121
+ * `@johnhenry/browsermesh-core` (an optional peerDependency) is lazily
122
+ * imported inside `startCheckFor()`, guarded by a reservation/cancellation
123
+ * scheme rather than a bare `checks.has(pubKey)` de-dup: `startCheckFor()`
124
+ * is called both from a synchronous event handler and synchronously inside
125
+ * `attach()`'s initial peer-scan loop, so a naive lazy import would open a
126
+ * real race (two rapid calls for the same peer both passing the de-dup
127
+ * check before the first call's import resolves, leaking an orphaned,
128
+ * un-stoppable `TransportHealthCheck`). The fix: `checks.set(pubKey, {
129
+ * pending: true, cancelled: false })` happens SYNCHRONOUSLY, before the
130
+ * `await import()` -- so the de-dup guard (`checks.has(pubKey)`) is
131
+ * correct the instant `startCheckFor()` returns, regardless of how long
132
+ * the import takes. A concurrent `stopCheckFor()` arriving while pending
133
+ * flips `cancelled` and removes the map entry immediately; when the import
134
+ * later resolves, a cancelled reservation is a no-op (no orphaned check
135
+ * gets installed). Every other `checks.get(pubKey)` read site (the pong
136
+ * handler, `handleTransportClose`/`handleTransportError`,
137
+ * `getStatus()`/`getCheck()`) is reservation-aware -- see each site's own
138
+ * comment. See `test/mesh-keepalive.test.mjs`'s dedicated race tests.
120
139
  */
121
140
 
122
- import { TransportHealthCheck } from '@johnhenry/browsermesh-core'
123
141
  import { endpointsKey } from './mesh-hardening.mjs'
124
142
 
125
143
  /** Envelope type for the outbound liveness probe. */
@@ -172,9 +190,19 @@ export function createMeshKeepaliveService({
172
190
  )
173
191
  }
174
192
 
175
- /** @type {Map<string, import('@johnhenry/browsermesh-core').TransportHealthCheck>} pubKey -> health check */
193
+ /**
194
+ * pubKey -> either a real health check, or a pending reservation
195
+ * (`{pending: true, cancelled: boolean}`) while `TransportHealthCheck`
196
+ * is being lazily imported -- see module doc comment.
197
+ * @type {Map<string, import('@johnhenry/browsermesh-core').TransportHealthCheck | {pending: true, cancelled: boolean}>}
198
+ */
176
199
  const checks = new Map()
177
200
 
201
+ /** @param {*} entry @returns {boolean} */
202
+ function isReservation(entry) {
203
+ return !!entry && entry.pending === true
204
+ }
205
+
178
206
  /**
179
207
  * Best-effort lookup of the `TransportFailover` instance
180
208
  * `mesh-hardening.mjs` scoped to this peer -- see module doc comment's
@@ -204,10 +232,33 @@ export function createMeshKeepaliveService({
204
232
  }
205
233
  }
206
234
 
207
- /** @param {string} pubKey */
235
+ /**
236
+ * Claims the `pubKey` slot synchronously (closing the lazy-import
237
+ * race -- see module doc comment), then lazily imports
238
+ * `TransportHealthCheck` and installs a real check, unless the
239
+ * reservation was cancelled (via `stopCheckFor()`) in the meantime.
240
+ * @param {string} pubKey
241
+ */
208
242
  function startCheckFor(pubKey) {
209
243
  if (!pubKey || checks.has(pubKey)) return
210
244
 
245
+ const reservation = { pending: true, cancelled: false }
246
+ checks.set(pubKey, reservation)
247
+
248
+ buildCheck(pubKey, reservation).catch((err) => {
249
+ if (checks.get(pubKey) === reservation) checks.delete(pubKey)
250
+ log('mesh-keepalive:start-check-failed', { pubKey, error: err?.message || String(err) })
251
+ })
252
+ }
253
+
254
+ /**
255
+ * @param {string} pubKey
256
+ * @param {{pending: true, cancelled: boolean}} reservation
257
+ */
258
+ async function buildCheck(pubKey, reservation) {
259
+ const { TransportHealthCheck } = await import('@johnhenry/browsermesh-core')
260
+ if (reservation.cancelled) return
261
+
211
262
  const check = new TransportHealthCheck({
212
263
  // TransportHealthCheck requires a truthy `transport` but only
213
264
  // threads it through to pingFn/its own emitted event payloads --
@@ -242,12 +293,21 @@ export function createMeshKeepaliveService({
242
293
  check.start()
243
294
  }
244
295
 
245
- /** @param {string} pubKey */
296
+ /**
297
+ * If `pubKey` is still a pending reservation, cancels it (the
298
+ * in-flight lazy import will no-op when it resolves). Otherwise stops
299
+ * and removes the real check.
300
+ * @param {string} pubKey
301
+ */
246
302
  function stopCheckFor(pubKey) {
247
- const check = checks.get(pubKey)
248
- if (!check) return
249
- check.stop()
303
+ const entry = checks.get(pubKey)
304
+ if (!entry) return
250
305
  checks.delete(pubKey)
306
+ if (isReservation(entry)) {
307
+ entry.cancelled = true
308
+ return
309
+ }
310
+ entry.stop()
251
311
  }
252
312
 
253
313
  // -----------------------------------------------------------------
@@ -264,15 +324,19 @@ export function createMeshKeepaliveService({
264
324
  // NATIVE-TRANSPORT-CLOSE WIRING". A stronger, immediate signal than
265
325
  // waiting out maxMissed ping/pong cycles.
266
326
  function handleTransportClose({ pubKey } = {}) {
267
- if (!pubKey || !checks.has(pubKey)) return
268
- ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: checks.get(pubKey).missedCount, reason: 'transport-close' })
327
+ const entry = checks.get(pubKey)
328
+ if (!pubKey || !entry) return
329
+ // A pending reservation has 0 missed pings so far -- matches
330
+ // TransportHealthCheck's own #missedCount = 0 default (hardening.mjs).
331
+ ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: isReservation(entry) ? 0 : entry.missedCount, reason: 'transport-close' })
269
332
  triggerFailover(pubKey, 'keepalive:transport-close').catch((err) => {
270
333
  log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
271
334
  })
272
335
  }
273
336
  function handleTransportError({ pubKey, error } = {}) {
274
- if (!pubKey || !checks.has(pubKey)) return
275
- ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: checks.get(pubKey).missedCount, reason: 'transport-error' })
337
+ const entry = checks.get(pubKey)
338
+ if (!pubKey || !entry) return
339
+ ctx.emit('keepalive:peer-unhealthy', { pubKey, missedCount: isReservation(entry) ? 0 : entry.missedCount, reason: 'transport-error' })
276
340
  log('mesh-keepalive:transport-error', { pubKey, error })
277
341
  triggerFailover(pubKey, 'keepalive:transport-error').catch((err) => {
278
342
  log('mesh-keepalive:trigger-failover-error', { pubKey, error: err?.message || String(err) })
@@ -307,8 +371,12 @@ export function createMeshKeepaliveService({
307
371
  log('mesh-keepalive:pong-send-failed', { to: fromPubKey, error: err?.message || String(err) })
308
372
  })
309
373
  } else if (msg.type === PONG_TYPE) {
310
- const check = checks.get(fromPubKey)
311
- if (check) check.recordPong()
374
+ const entry = checks.get(fromPubKey)
375
+ // A pong arriving while still a pending reservation would be a
376
+ // stray/duplicate from a prior connection -- this file can't have
377
+ // sent a ping for this peer yet (check.start() hasn't run), so
378
+ // it's safe to drop.
379
+ if (entry && !isReservation(entry)) entry.recordPong()
312
380
  }
313
381
  })
314
382
 
@@ -316,18 +384,29 @@ export function createMeshKeepaliveService({
316
384
  /**
317
385
  * @param {string} pubKey
318
386
  * @returns {'healthy'|'degraded'|'unhealthy'|null} `null` if this
319
- * peer is not currently tracked (never connected, or already
320
- * disconnected).
387
+ * peer is not currently tracked (never connected or already
388
+ * disconnected). A pending reservation (lazy import still in
389
+ * flight) reports `'healthy'` -- matching `TransportHealthCheck`'s
390
+ * own `#status = 'healthy'` default at construction, before
391
+ * `start()` runs (`hardening.mjs`) -- not `null`, so callers see
392
+ * the exact same synchronous-default behavior as before this file
393
+ * lazy-loaded the class.
321
394
  */
322
395
  getStatus(pubKey) {
323
- return checks.get(pubKey)?.status ?? null
396
+ const entry = checks.get(pubKey)
397
+ if (!entry) return null
398
+ return isReservation(entry) ? 'healthy' : entry.status
324
399
  },
325
400
  /**
326
401
  * @param {string} pubKey
327
402
  * @returns {import('@johnhenry/browsermesh-core').TransportHealthCheck|null}
403
+ * `null` also while a pending reservation hasn't finished
404
+ * installing yet -- never returns the internal reservation shape.
328
405
  */
329
406
  getCheck(pubKey) {
330
- return checks.get(pubKey) || null
407
+ const entry = checks.get(pubKey)
408
+ if (!entry || isReservation(entry)) return null
409
+ return entry
331
410
  },
332
411
  /** @returns {string[]} pubKeys currently tracked. */
333
412
  listTracked() {
@@ -23,9 +23,34 @@
23
23
  * explicit "out of scope" list (UDP relay, inbound listen-relay).
24
24
  *
25
25
  * No browser-only imports at module level.
26
+ *
27
+ * `@johnhenry/browsermesh-netway` (an optional peerDependency) is lazily
28
+ * resolved via `createLazyRequire(import.meta.url)`
29
+ * (`./internal/lazy-node-require.mjs`, using
30
+ * `process.getBuiltinModule('module')` rather than a static
31
+ * `import ... from 'node:module'`, so no Node-only code runs merely from
32
+ * importing this file -- see issue #183). `Backend` is used as a
33
+ * base class (`class MeshRelayBackend extends Backend`); a class's
34
+ * `extends` clause is evaluated at class-DECLARATION time, and a
35
+ * `class ... extends ... {}` statement written at module top level always
36
+ * runs at module-LOAD time, no matter how the `Backend` reference feeding
37
+ * it is obtained -- there is no way to defer that with a plain lazy
38
+ * import, sync or async (see `cloud-storage-backend.mjs`'s identical
39
+ * constraint). The fix here instead moves the class declaration itself out
40
+ * of module-top-level scope, into a function that resolves `Backend` via
41
+ * `require()` and builds+memoizes the class on first call, so it still
42
+ * only runs once, lazily, the first time this file is actually used, not
43
+ * merely imported.
44
+ *
45
+ * **BREAKING CHANGE**: `MeshRelayBackend` is no longer exported as a
46
+ * class. Replace `new MeshRelayBackend(opts)` with
47
+ * `createMeshRelayBackend(opts)` (same `opts` shape, still returns a real
48
+ * `MeshRelayBackend` instance with the exact same instance API) -- see the
49
+ * CHANGELOG entry documenting this fix across the package for the full
50
+ * rationale and the sibling `cloud-storage-backend.mjs` fix.
26
51
  */
27
52
 
28
- import { Backend, StreamSocket, ConnectionRefusedError } from '@johnhenry/browsermesh-netway'
53
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
29
54
 
30
55
  /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
31
56
  const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
@@ -62,13 +87,27 @@ function fromBase64(str) {
62
87
  // MeshRelayBackend
63
88
  // ---------------------------------------------------------------------------
64
89
 
90
+ let _MeshRelayBackendClass = null
91
+
65
92
  /**
66
- * A `Backend` that relays TCP-like `connect()`s through one specific mesh
67
- * peer's `MeshRelayHost`, over `PeerNode.sendTo()`/`onIncomingData()`.
68
- *
69
- * @extends Backend
93
+ * Lazily builds (and memoizes) the `MeshRelayBackend` class, deferring
94
+ * resolution of `@johnhenry/browsermesh-netway`'s `Backend` past
95
+ * module-load time -- see module doc comment. Only ever runs once per
96
+ * process; every later call returns the same class reference.
97
+ * @returns {typeof MeshRelayBackend}
70
98
  */
71
- export class MeshRelayBackend extends Backend {
99
+ function resolveMeshRelayBackendClass() {
100
+ if (_MeshRelayBackendClass) return _MeshRelayBackendClass
101
+ const require = createLazyRequire(import.meta.url)
102
+ const { Backend, StreamSocket, ConnectionRefusedError } = require('@johnhenry/browsermesh-netway')
103
+
104
+ /**
105
+ * A `Backend` that relays TCP-like `connect()`s through one specific mesh
106
+ * peer's `MeshRelayHost`, over `PeerNode.sendTo()`/`onIncomingData()`.
107
+ *
108
+ * @extends Backend
109
+ */
110
+ class MeshRelayBackend extends Backend {
72
111
  /** @type {import('./peer-node.mjs').PeerNode} */
73
112
  #node
74
113
 
@@ -284,6 +323,24 @@ export class MeshRelayBackend extends Backend {
284
323
  pending.reject(new Error('MeshRelayBackend closed'))
285
324
  }
286
325
  }
326
+ }
327
+
328
+ _MeshRelayBackendClass = MeshRelayBackend
329
+ return MeshRelayBackend
330
+ }
331
+
332
+ /**
333
+ * Construct a `MeshRelayBackend` -- the class itself is no longer exported
334
+ * directly (see module doc comment's "BREAKING CHANGE" note).
335
+ *
336
+ * @param {object} opts - Same shape as `MeshRelayBackend`'s constructor:
337
+ * `{node, relayPeerPubKey, envelopeType?, connectTimeoutMs?, onLog?}`.
338
+ * @returns {import('@johnhenry/browsermesh-netway').Backend} A real
339
+ * `MeshRelayBackend` instance (the full instance API is unchanged).
340
+ */
341
+ export function createMeshRelayBackend(opts) {
342
+ const MeshRelayBackend = resolveMeshRelayBackendClass()
343
+ return new MeshRelayBackend(opts)
287
344
  }
288
345
 
289
346
  export { DEFAULT_ENVELOPE_TYPE }
@@ -204,16 +204,24 @@
204
204
  * received a task notification from a remote submitter.
205
205
  *
206
206
  * No browser-only imports at module level.
207
+ *
208
+ * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
209
+ * lazily resolved via `createLazyRequire(import.meta.url)`
210
+ * (`./internal/lazy-node-require.mjs`, using
211
+ * `process.getBuiltinModule('module')` rather than a static
212
+ * `import ... from 'node:module'`, so no Node-only code runs merely from
213
+ * importing this file -- see issue #183), not a dynamic `import()`.
214
+ * `SwimMembership`/`SwarmCoordinator` are both constructed synchronously
215
+ * inside this service's `attach()`, whose synchronous-return contract is a
216
+ * hard, repo-wide convention (`mesh-service.mjs`'s `attachService()`,
217
+ * relied on -- without `await` -- throughout `mesh-bootstrap.mjs`); an
218
+ * async `import()` would have broken that (see the CHANGELOG entry
219
+ * documenting this fix across the package). `require()` resolves lazily
220
+ * (only when `attach()` actually runs) while staying fully synchronous, so
221
+ * `attach()`'s contract doesn't change.
207
222
  */
208
223
 
209
- import {
210
- SwarmCoordinator,
211
- SwimMembership,
212
- SWARM_JOIN,
213
- SWARM_LEAVE,
214
- SWARM_HEARTBEAT,
215
- SWARM_TASK_ASSIGN,
216
- } from '@johnhenry/browsermesh-discovery'
224
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
217
225
 
218
226
  const DEFAULT_SWIM_ENVELOPE_TYPE = 'swarm-swim'
219
227
  const DEFAULT_HEARTBEAT_ENVELOPE_TYPE = 'swarm-heartbeat'
@@ -279,6 +287,17 @@ export function createSwarmService(opts = {}) {
279
287
  attach(peerNode, ctx) {
280
288
  const localPodId = peerNode.podId
281
289
 
290
+ // Lazy, synchronous (see module doc comment).
291
+ const require = createLazyRequire(import.meta.url)
292
+ const {
293
+ SwarmCoordinator,
294
+ SwimMembership,
295
+ SWARM_JOIN,
296
+ SWARM_LEAVE,
297
+ SWARM_HEARTBEAT,
298
+ SWARM_TASK_ASSIGN,
299
+ } = require('@johnhenry/browsermesh-discovery')
300
+
282
301
  // -----------------------------------------------------------------
283
302
  // SwimMembership -- see module doc comment's "SWIM BRIDGE" section.
284
303
  // -----------------------------------------------------------------
@@ -204,10 +204,31 @@
204
204
  * reason}` -- an accepted session transitioned to `CLOSED`, from either
205
205
  * side (this peer's own `close()` or a received `ws-close`).
206
206
  *
207
- * No browser-only imports at module level.
207
+ * No browser-only imports at module level, and -- as of the fix for
208
+ * issue #183 -- no Node-only imports at module level either.
209
+ *
210
+ * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
211
+ * lazily resolved via `createLazyRequire(import.meta.url)`
212
+ * (`./internal/lazy-node-require.mjs`), which gets Node's `require()`
213
+ * from `process.getBuiltinModule('module')` rather than a static
214
+ * `import ... from 'node:module'` -- see that file's doc comment for why
215
+ * the static-vs-lazy distinction matters for browser safety. This is the
216
+ * file that motivated trying `require()` at all: `parseMeshRequest()` is
217
+ * used inside `BrowserMeshWebSocket`'s *constructor*, which can never be
218
+ * `async` -- `import()` was a dead end here (an async factory replacing
219
+ * direct `new BrowserMeshWebSocket(...)` construction would have been a
220
+ * real, unwanted breaking change to this class's whole reason for
221
+ * existing: matching real `new WebSocket(url)` construction ergonomics as
222
+ * closely as possible, per this file's own "API SHAPE DECISION" precedent
223
+ * in `mesh-fetch.mjs`). `require()` resolves synchronously, so it works
224
+ * directly inside the constructor with zero API changes: the module is
225
+ * only actually loaded the first time a `BrowserMeshWebSocket` is
226
+ * constructed (or `createMeshWebSocketService()`'s `api.connect()` is
227
+ * called), not at this module's own load time -- and, unlike before,
228
+ * `process.getBuiltinModule` is not even referenced until then either.
208
229
  */
209
230
 
210
- import { parseMeshRequest } from '@johnhenry/browsermesh-discovery'
231
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
211
232
 
212
233
  /** Default `envelope.type` used to route mesh-websocket payloads on the shared `onIncomingData()` bus. */
213
234
  const DEFAULT_ENVELOPE_TYPE = 'mesh-websocket'
@@ -355,6 +376,10 @@ export class BrowserMeshWebSocket {
355
376
  if (!peerNode || typeof peerNode.sendTo !== 'function' || typeof peerNode.onIncomingData !== 'function') {
356
377
  throw new Error('BrowserMeshWebSocket: opts.peerNode is required and must provide sendTo()/onIncomingData()')
357
378
  }
379
+ // Lazy, synchronous (see module doc comment) -- cached by require()'s
380
+ // own module cache after the first construction.
381
+ const require = createLazyRequire(import.meta.url)
382
+ const { parseMeshRequest } = require('@johnhenry/browsermesh-discovery')
358
383
  const parsed = parseMeshRequest(url)
359
384
  if (!parsed) {
360
385
  throw new Error(`BrowserMeshWebSocket: invalid mesh URL '${url}' (expected mesh://podId/path or https://podId.mesh.local/path)`)
@@ -33,9 +33,26 @@
33
33
  * option's shape exactly, no adapter needed.
34
34
  *
35
35
  * @module serverless-fetch
36
+ *
37
+ * `@johnhenry/browsermesh-discovery` (an optional peerDependency) is
38
+ * lazily resolved via `createLazyRequire(import.meta.url)`
39
+ * (`./internal/lazy-node-require.mjs`, itself using
40
+ * `process.getBuiltinModule('module')` rather than a static
41
+ * `import ... from 'node:module'`, so no Node-only code runs merely from
42
+ * importing this file -- see issue #183), not a dynamic `import()`.
43
+ * `createServerlessFetchRouter()` is synchronous, has a directly-tested
44
+ * synchronous validation-throw contract (`test/serverless-fetch.test.mjs`'s
45
+ * `assert.throws(...)`), and returns a real `MeshFetchRouter` instance
46
+ * directly to ~10 synchronous call sites in its own test file -- an async
47
+ * `import()` would have broken all of that (see the CHANGELOG entry
48
+ * documenting this fix across the package). `require()` resolves lazily
49
+ * (only when `createServerlessFetchRouter()` is actually called, after its
50
+ * own validation throw) while staying fully synchronous, so none of that
51
+ * changes.
36
52
  */
37
53
 
38
- import { MeshFetchRouter } from '@johnhenry/browsermesh-discovery'
54
+ import { createLazyRequire } from './internal/lazy-node-require.mjs'
55
+
39
56
  import { decodeWireResponse } from './serverless-wire.mjs'
40
57
 
41
58
  /**
@@ -59,6 +76,10 @@ export function createServerlessFetchRouter(meshRpcApi, { resolveSite } = {}) {
59
76
  throw new Error('createServerlessFetchRouter: meshRpcApi (a mesh-rpc.mjs service api with .request()) is required')
60
77
  }
61
78
 
79
+ // Lazy, synchronous (see module doc comment).
80
+ const require = createLazyRequire(import.meta.url)
81
+ const { MeshFetchRouter } = require('@johnhenry/browsermesh-discovery')
82
+
62
83
  return new MeshFetchRouter({
63
84
  onRpc: async ({ podId: siteOrPodId, method, path, headers, body }) => {
64
85
  const resolved = typeof resolveSite === 'function' ? resolveSite(siteOrPodId) : null
@@ -30,9 +30,11 @@
30
30
  * regardless of which side initiated it.
31
31
  *
32
32
  * ## Multiple connections per peer (issue #116)
33
- * `auth.connectionId` (default `DEFAULT_CONNECTION_ID`, re-exported from
34
- * `@johnhenry/browsermesh-transport`) selects which of possibly-several
35
- * independent `RTCPeerConnection`s to `endpoint` this call negotiates --
33
+ * `auth.connectionId` (default `DEFAULT_CONNECTION_ID`, duplicated locally
34
+ * in this file rather than imported from `@johnhenry/browsermesh-transport`
35
+ * -- see that constant's own definition below for why) selects which of
36
+ * possibly-several independent `RTCPeerConnection`s to `endpoint` this call
37
+ * negotiates --
36
38
  * `PeerNode.connectToPeer(pubKey, endpoints, auth)` already threads `auth`
37
39
  * straight through to `negotiator.negotiate(endpoints, auth)`, so callers
38
40
  * can request a second, fully independent connection to a peer already
@@ -48,7 +50,21 @@
48
50
  * No browser-only imports at module level.
49
51
  */
50
52
 
51
- import { WebRTCTransportAdapter, DEFAULT_CONNECTION_ID } from '@johnhenry/browsermesh-transport'
53
+ // @johnhenry/browsermesh-transport (an optional peerDependency) is imported
54
+ // lazily, at each of the two `WebRTCTransportAdapter` call sites below, not
55
+ // eagerly here -- so this module doesn't force it on every consumer of
56
+ // this package's top-level `.` entrypoint. See the CHANGELOG entry
57
+ // documenting this fix.
58
+ //
59
+ // DEFAULT_CONNECTION_ID is duplicated locally (its real value, confirmed by
60
+ // reading browsermesh-transport/src/webrtc.mjs directly: `export const
61
+ // DEFAULT_CONNECTION_ID = 'default'`) rather than lazily imported --
62
+ // unlike WebRTCTransportAdapter, it's used as a *default parameter value*
63
+ // in several places below, which is evaluated at call time from whatever
64
+ // is in scope; a lazily-imported `let` binding could still be `undefined`
65
+ // the first time one of those calls happens before the import resolves. A
66
+ // plain literal has no such timing hazard.
67
+ const DEFAULT_CONNECTION_ID = 'default'
52
68
 
53
69
  /** Default time to wait for an SDP answer before giving up. */
54
70
  const DEFAULT_ANSWER_TIMEOUT_MS = 15_000
@@ -158,6 +174,7 @@ export function createWebRTCTransportFactory({
158
174
  // side gets from connectToPeer() -- see PeerNode.adoptIncomingSession().
159
175
  if (typeof onIncomingConnection === 'function') {
160
176
  await waitForOpen(conn, defaultOpenTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS)
177
+ const { WebRTCTransportAdapter } = await import('@johnhenry/browsermesh-transport')
161
178
  const adapter = new WebRTCTransportAdapter(conn)
162
179
  await adapter.connect()
163
180
  onIncomingConnection(fromPodId, adapter, connectionId)
@@ -222,6 +239,7 @@ export function createWebRTCTransportFactory({
222
239
  throw new Error(`WebRTC DataChannel with ${remotePodId} did not open in time`)
223
240
  }
224
241
 
242
+ const { WebRTCTransportAdapter } = await import('@johnhenry/browsermesh-transport')
225
243
  const adapter = new WebRTCTransportAdapter(conn)
226
244
  await adapter.connect()
227
245
  return adapter