chat / client / test / harness / ts.mjs
  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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
 * Loads the REAL TypeScript implementation into the vector generators.
 *
 * dev/docs/CLJS.md's method: "splice the real modules into a harness rather
 * than transcribing their logic into a generator" — it removes the whole class
 * of "my fixture encodes my misreading". Here the real modules are `src/**.ts`,
 * so esbuild bundles them once (single module graph ⇒ one copy of every shared
 * module, one class identity) with every npm package left external, and the
 * Vite-only globals replaced by the values the production build injects.
 *
 * Hard-private members (`#name`) are aliased onto a public `__t` bag by the
 * same mechanical class-field injection rooms-kit uses (test/helpers/expose.mjs):
 * not one line of logic is retyped.
 *
 * Only usable while the TypeScript is still in the tree, and only before
 * package.json is swapped to the CLJS shape (the CLJS install drops esbuild).
 */
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));
export const CLIENT = join(HERE, "..", "..");
const STAGE = join(CLIENT, "node_modules", ".sueta-ts");

/** Everything the generators need, re-exported from one entry. */
const ENTRY = `
export * from "../../src/config";
export * from "../../src/lib/crypto";
export * as access from "../../src/lib/access";
export * as encryption from "../../src/lib/encryption";
export * as turn from "../../src/lib/turn";
export * as descriptor from "../../src/lib/descriptor";
export * as net from "../../src/lib/net";
export * as media from "../../src/lib/media";
export * as orbitIdentity from "../../src/lib/orbit-identity";
export * as log from "../../src/lib/log";
export * as mailbox from "../../src/lib/mailbox";
export * as selftest from "../../src/lib/selftest";
export * as history from "../../src/app/history";
export * as trust from "../../src/app/trust";
export * as rooms from "../../src/app/rooms";
export * as migrate from "../../src/app/migrate";
export * as migrateStorage from "../../src/app/migrate-storage";
export * as chat from "../../src/app/chat";
export * as call from "../../src/app/call";
export * as i18n from "../../src/i18n/index";
export { en } from "../../src/i18n/en";
export { ro } from "../../src/i18n/ro";
export { hu } from "../../src/i18n/hu";
`;

// NOT in the entry: `main.ts` (it imports the Vite-only `virtual:pwa-register`)
// and `app/ui.ts` (pure DOM, no serialisable surface worth pinning).
//
// `lib/net.ts` and `helia` both pull @libp2p/webrtc, whose Node build loads the
// libdatachannel native addon. `npm install` fetches it via prebuild-install;
// if it is missing, run
//   (cd node_modules/@ipshipyard/node-datachannel && npx prebuild-install -r napi)
// Without it neither this harness nor the OrbitDB-address test can run at all.

/** className -> hard-private members the generators must reach. */
const EXPOSE = {
  ChatStore: [
    "idFields",
    "applyReactOp",
    "foldReaction",
    "applyLegacy",
    "toMessage",
    "addMessage",
    "verifyPeerIdentity",
    "onRoomSync",
  ],
  CallManager: ["statePayload"],
  // the same member lists rooms-kit's machines.test.mjs drives, so its
  // log/net/relay transcripts replay unchanged against chat's copies
  RoomLog: ["emit", "onUpdate", "sweepUnseen", "authorOf", "canJoinLocally", "identityLocal"],
  Net: [
    "dialPeer", "recFor", "onConnChange", "refreshState", "maybeReady", "sweep", "endChannels",
    "dropPeer", "hangUpStr", "beacon", "verified", "onTopicMessage", "onPresence", "beaconTo",
    "onMsgFrame", "frame", "relayPeerId", "ensureRelay", "scheduleRedial", "setRelayUp", "pubsub",
  ],
  MailboxSync: ["buildPayload", "processMessage", "enqueueIdentityOnce", "push", "dropHead", "markSent"],
};

const SPEC_INJECT = (src) => {
  let out = src;
  for (const [cls, members] of Object.entries(EXPOSE)) {
    // esbuild emits `var Name = class [_Name] {` for an exported class
    const re = new RegExp(`(var\\s+${cls}\\s*=\\s*class\\b[^{]*\\{)`);
    if (!re.test(out)) throw new Error(`expose: class ${cls} not found in the bundle`);
    const bag = members.map((m) => `${m}: (...a) => this.#${m}(...a)`).join(", ");
    out = out.replace(re, `$1\n  __t = { ${bag} };\n`);
  }
  return out;
};

/** The version the production build defines; fixtures must not depend on it. */
const APP_VERSION = JSON.parse(readFileSync(join(CLIENT, "version.json"), "utf8")).version;

let cached = null;

export async function loadTs() {
  if (cached) return cached;
  mkdirSync(STAGE, { recursive: true });
  const entryFile = join(STAGE, "entry.ts");
  writeFileSync(entryFile, ENTRY);
  const bundleFile = join(STAGE, "bundle.mjs");
  execFileSync(
    join(CLIENT, "node_modules", ".bin", "esbuild"),
    [
      entryFile,
      "--bundle",
      "--format=esm",
      "--target=es2022",
      "--platform=neutral",
      "--packages=external",
      "--define:import.meta.env={}",
      `--define:__APP_VERSION__=${APP_VERSION}`,
      `--outfile=${bundleFile}`,
      "--log-level=warning",
    ],
    { cwd: CLIENT, stdio: ["ignore", "inherit", "inherit"] },
  );
  writeFileSync(bundleFile, SPEC_INJECT(readFileSync(bundleFile, "utf8")));
  cached = await import(pathToFileURL(bundleFile).href);
  return cached;
}

export const priv = (o, n) => o.__t[n];

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/chat.git