p2p-db / browser / vendor-entry.mjs
320 words
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// The browser's copy of the ESM-only p2p stack, as one chunk.
//
// ird.p2p.db imports helia, @orbitdb/core and the libp2p packages at runtime
// through the global `ird_dyn_import` helper (Node resolves the bare
// specifiers from node_modules). A browser cannot resolve bare specifiers, so
// a page bundles this entry with esbuild into one classic script exposing
// `irdVendor`, loads it BEFORE the compiled ClojureScript, and points the
// helper at it (README, "Browser peers"):
//
//   esbuild browser/vendor-entry.mjs --bundle --format=iife --global-name=irdVendor \
//           --platform=browser --outfile=vendor.js
//   <script src="vendor.js"></script>
//   <script>globalThis.ird_dyn_import = n => Promise.resolve(irdVendor.load(n))</script>
//   <script src="app.js"></script>
//
// Loading it first matters: evaluating the chunk installs Node's Buffer (the
// `buffer` package) as a global, and the byte helpers of ird-p2p-cljs use
// Buffer as soon as their namespaces load. (An ESM build — --format=esm, then
// `import './vendor.mjs'` statically before the app — works the same way.)
//
// What is NOT here, on purpose: @libp2p/tcp and @libp2p/mdns (no such thing
// in a browser), bootstrap, kad-dht, any public gateway or delegated router.
import { Buffer } from 'buffer'
import * as helia from 'helia'
import * as orbitdb from '@orbitdb/core'
import * as websockets from '@libp2p/websockets'
import * as circuitRelay from '@libp2p/circuit-relay-v2'
import * as noise from '@chainsafe/libp2p-noise'
import * as yamux from '@chainsafe/libp2p-yamux'
import * as identify from '@libp2p/identify'
import * as gossipsub from '@libp2p/gossipsub'
import * as multiaddr from '@multiformats/multiaddr'
import * as blockstoreLevel from 'blockstore-level'
import * as datastoreLevel from 'datastore-level'

globalThis.Buffer ??= Buffer

export const modules = {
  'helia': helia,
  '@orbitdb/core': orbitdb,
  '@libp2p/websockets': websockets,
  '@libp2p/circuit-relay-v2': circuitRelay,
  '@chainsafe/libp2p-noise': noise,
  '@chainsafe/libp2p-yamux': yamux,
  '@libp2p/identify': identify,
  '@libp2p/gossipsub': gossipsub,
  '@multiformats/multiaddr': multiaddr,
  'blockstore-level': blockstoreLevel,
  'datastore-level': datastoreLevel
}

// the module namespace for a bare specifier, as import() would return it
export function load (name) {
  const m = modules[name]
  if (m == null) throw new Error(`ird_dyn_import: "${name}" is not in the browser vendor chunk`)
  return m
}

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/p2p-db.git