@narumitw/pi-chat 0.1.1 → 0.1.3
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 +141 -148
- package/dist/chunks/chat-view-QEAZMMXC.ts +222 -0
- package/dist/chunks/chat-view-QEAZMMXC.ts.map +7 -0
- package/dist/chunks/chunk-2N4YIKBV.ts +274 -0
- package/dist/chunks/chunk-2N4YIKBV.ts.map +7 -0
- package/dist/chunks/chunk-4O25EPNQ.ts +489 -0
- package/dist/chunks/chunk-4O25EPNQ.ts.map +7 -0
- package/dist/chunks/chunk-6YVQGIUO.ts +286 -0
- package/dist/chunks/chunk-6YVQGIUO.ts.map +7 -0
- package/dist/chunks/chunk-IVUX27XD.ts +72 -0
- package/dist/chunks/chunk-IVUX27XD.ts.map +7 -0
- package/dist/chunks/chunk-RCEMXXHH.ts +10 -0
- package/dist/chunks/chunk-RCEMXXHH.ts.map +7 -0
- package/dist/chunks/directory-network-OV6FYWIK.ts +340 -0
- package/dist/chunks/directory-network-OV6FYWIK.ts.map +7 -0
- package/dist/chunks/menu-6KBWK6KS.ts +487 -0
- package/dist/chunks/menu-6KBWK6KS.ts.map +7 -0
- package/dist/chunks/network-U5O6BOQN.ts +171 -0
- package/dist/chunks/network-U5O6BOQN.ts.map +7 -0
- package/dist/chunks/widget-ER6SODIX.ts +62 -0
- package/dist/chunks/widget-ER6SODIX.ts.map +7 -0
- package/dist/index.ts +1222 -0
- package/dist/index.ts.map +7 -0
- package/package.json +12 -8
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
MAX_DIRECT_NEIGHBORS
|
|
5
|
+
} from "./chunk-RCEMXXHH.js";
|
|
6
|
+
import {
|
|
7
|
+
FrameDecoder,
|
|
8
|
+
encodeFrame
|
|
9
|
+
} from "./chunk-4O25EPNQ.js";
|
|
10
|
+
|
|
11
|
+
// src/network.ts
|
|
12
|
+
import Hyperswarm from "hyperswarm";
|
|
13
|
+
function directNeighborLimit(requested) {
|
|
14
|
+
if (!Number.isSafeInteger(requested) || (requested ?? 0) <= 0) return MAX_DIRECT_NEIGHBORS;
|
|
15
|
+
return Math.min(requested ?? MAX_DIRECT_NEIGHBORS, MAX_DIRECT_NEIGHBORS);
|
|
16
|
+
}
|
|
17
|
+
var HyperswarmTransport = class {
|
|
18
|
+
options;
|
|
19
|
+
swarm;
|
|
20
|
+
discovery;
|
|
21
|
+
listener;
|
|
22
|
+
connections = /* @__PURE__ */ new Map();
|
|
23
|
+
refreshTimers = /* @__PURE__ */ new Set();
|
|
24
|
+
stopPromise;
|
|
25
|
+
constructor(options) {
|
|
26
|
+
this.options = options;
|
|
27
|
+
}
|
|
28
|
+
get connectionCount() {
|
|
29
|
+
return this.connections.size;
|
|
30
|
+
}
|
|
31
|
+
get connectedPeerKeys() {
|
|
32
|
+
return [...this.connections.values()].map(({ peer }) => peer.publicKey.toString("hex")).sort();
|
|
33
|
+
}
|
|
34
|
+
async start(listener, signal) {
|
|
35
|
+
if (this.swarm) throw new Error("Hyperswarm transport has already started.");
|
|
36
|
+
const startupSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3);
|
|
37
|
+
startupSignal.throwIfAborted();
|
|
38
|
+
this.listener = listener;
|
|
39
|
+
const maxPeers = directNeighborLimit(this.options.maxPeers);
|
|
40
|
+
const swarm = new Hyperswarm({
|
|
41
|
+
keyPair: {
|
|
42
|
+
publicKey: this.options.identity.publicKey,
|
|
43
|
+
secretKey: this.options.identity.secretKey
|
|
44
|
+
},
|
|
45
|
+
maxPeers,
|
|
46
|
+
...this.options.dht ? { dht: this.options.dht } : {},
|
|
47
|
+
...this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}
|
|
48
|
+
});
|
|
49
|
+
this.swarm = swarm;
|
|
50
|
+
swarm.on("connection", (socket, info) => this.accept(socket, info));
|
|
51
|
+
swarm.on("error", (error) => this.listener?.onError(safeNetworkError(error)));
|
|
52
|
+
try {
|
|
53
|
+
const discovery = swarm.join(this.options.room.topic, {
|
|
54
|
+
server: true,
|
|
55
|
+
client: true,
|
|
56
|
+
limit: maxPeers
|
|
57
|
+
});
|
|
58
|
+
this.discovery = discovery;
|
|
59
|
+
await raceAbort(discovery.flushed(), startupSignal);
|
|
60
|
+
startupSignal.throwIfAborted();
|
|
61
|
+
this.scheduleEarlyRefreshes(discovery);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
await this.stop();
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
stop() {
|
|
68
|
+
if (this.stopPromise) return this.stopPromise;
|
|
69
|
+
this.stopPromise = this.stopOwned();
|
|
70
|
+
return this.stopPromise;
|
|
71
|
+
}
|
|
72
|
+
scheduleEarlyRefreshes(discovery) {
|
|
73
|
+
const delays = [250, 750, 1500, 3e3, 6e3, 12e3];
|
|
74
|
+
const schedule = (index) => {
|
|
75
|
+
const delayMs = delays[index];
|
|
76
|
+
if (delayMs === void 0 || this.discovery !== discovery) return;
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
this.refreshTimers.delete(timer);
|
|
79
|
+
if (this.discovery !== discovery) return;
|
|
80
|
+
void discovery.refresh().catch(() => void 0).finally(() => {
|
|
81
|
+
if (this.discovery === discovery) schedule(index + 1);
|
|
82
|
+
});
|
|
83
|
+
}, delayMs);
|
|
84
|
+
this.refreshTimers.add(timer);
|
|
85
|
+
};
|
|
86
|
+
schedule(0);
|
|
87
|
+
}
|
|
88
|
+
accept(socket, info) {
|
|
89
|
+
if (!this.swarm || !this.listener || this.connections.size >= MAX_DIRECT_NEIGHBORS) {
|
|
90
|
+
socket.destroy();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const decoder = new FrameDecoder();
|
|
94
|
+
let closed = false;
|
|
95
|
+
const peer = {
|
|
96
|
+
publicKey: Buffer.from(info.publicKey),
|
|
97
|
+
send(message) {
|
|
98
|
+
if (closed || socket.destroyed) throw new Error("Peer connection is closed.");
|
|
99
|
+
const accepted = socket.write(encodeFrame(message));
|
|
100
|
+
if (!accepted && socket.destroyed) throw new Error("Peer connection rejected the message.");
|
|
101
|
+
},
|
|
102
|
+
close() {
|
|
103
|
+
if (closed) return;
|
|
104
|
+
closed = true;
|
|
105
|
+
socket.destroy();
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
this.connections.set(socket, { socket, peer });
|
|
109
|
+
this.listener.onPeer(peer);
|
|
110
|
+
socket.on("data", (chunk) => {
|
|
111
|
+
if (closed || !this.listener) return;
|
|
112
|
+
try {
|
|
113
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
114
|
+
for (const message of decoder.push(bytes)) this.listener.onMessage(peer, message);
|
|
115
|
+
} catch {
|
|
116
|
+
closed = true;
|
|
117
|
+
socket.destroy();
|
|
118
|
+
this.listener?.onError(new Error("Pi Chat rejected invalid peer protocol data."));
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
const disconnected = () => {
|
|
122
|
+
if (!this.connections.delete(socket)) return;
|
|
123
|
+
closed = true;
|
|
124
|
+
this.listener?.onDisconnect(peer);
|
|
125
|
+
};
|
|
126
|
+
socket.once("close", disconnected);
|
|
127
|
+
socket.once("error", (error) => {
|
|
128
|
+
this.listener?.onError(safeNetworkError(error));
|
|
129
|
+
disconnected();
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async stopOwned() {
|
|
133
|
+
for (const timer of this.refreshTimers) clearTimeout(timer);
|
|
134
|
+
this.refreshTimers.clear();
|
|
135
|
+
const discovery = this.discovery;
|
|
136
|
+
this.discovery = void 0;
|
|
137
|
+
if (discovery) await discovery.destroy().catch(() => void 0);
|
|
138
|
+
for (const { socket } of this.connections.values()) socket.destroy();
|
|
139
|
+
this.connections.clear();
|
|
140
|
+
const swarm = this.swarm;
|
|
141
|
+
this.swarm = void 0;
|
|
142
|
+
this.listener = void 0;
|
|
143
|
+
if (swarm) await swarm.destroy().catch(() => void 0);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
async function raceAbort(operation, signal) {
|
|
147
|
+
if (!signal) return operation;
|
|
148
|
+
signal.throwIfAborted();
|
|
149
|
+
let remove = () => {
|
|
150
|
+
};
|
|
151
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
152
|
+
const onAbort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
153
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
154
|
+
remove = () => signal.removeEventListener("abort", onAbort);
|
|
155
|
+
});
|
|
156
|
+
try {
|
|
157
|
+
return await Promise.race([operation, aborted]);
|
|
158
|
+
} finally {
|
|
159
|
+
remove();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function safeNetworkError(error) {
|
|
163
|
+
const code = error instanceof Error && "code" in error ? String(Reflect.get(error, "code")) : "error";
|
|
164
|
+
return new Error(`Pi Chat network ${code}.`);
|
|
165
|
+
}
|
|
166
|
+
export {
|
|
167
|
+
HyperswarmTransport,
|
|
168
|
+
MAX_DIRECT_NEIGHBORS,
|
|
169
|
+
directNeighborLimit
|
|
170
|
+
};
|
|
171
|
+
//# sourceMappingURL=network-U5O6BOQN.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/network.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Duplex } from \"node:stream\";\nimport Hyperswarm, { type PeerDiscovery, type PeerInfo } from \"hyperswarm\";\nimport type { ChatTransport, ChatTransportListener, TransportPeer } from \"./chat-session.js\";\nimport { type HyperswarmTransportOptions, MAX_DIRECT_NEIGHBORS } from \"./network-contract.js\";\nimport { encodeFrame, FrameDecoder, type ProtocolMessage } from \"./protocol.js\";\n\nexport type { HyperswarmTransportOptions } from \"./network-contract.js\";\n\ninterface ActiveConnection {\n\tsocket: Duplex;\n\tpeer: TransportPeer;\n}\n\nexport { MAX_DIRECT_NEIGHBORS } from \"./network-contract.js\";\n\nexport function directNeighborLimit(requested?: number): number {\n\tif (!Number.isSafeInteger(requested) || (requested ?? 0) <= 0) return MAX_DIRECT_NEIGHBORS;\n\treturn Math.min(requested ?? MAX_DIRECT_NEIGHBORS, MAX_DIRECT_NEIGHBORS);\n}\n\nexport class HyperswarmTransport implements ChatTransport {\n\tprivate readonly options: HyperswarmTransportOptions;\n\tprivate swarm: Hyperswarm | undefined;\n\tprivate discovery: PeerDiscovery | undefined;\n\tprivate listener: ChatTransportListener | undefined;\n\tprivate readonly connections = new Map<Duplex, ActiveConnection>();\n\tprivate readonly refreshTimers = new Set<NodeJS.Timeout>();\n\tprivate stopPromise: Promise<void> | undefined;\n\n\tconstructor(options: HyperswarmTransportOptions) {\n\t\tthis.options = options;\n\t}\n\n\tget connectionCount(): number {\n\t\treturn this.connections.size;\n\t}\n\n\tget connectedPeerKeys(): string[] {\n\t\treturn [...this.connections.values()].map(({ peer }) => peer.publicKey.toString(\"hex\")).sort();\n\t}\n\n\tasync start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void> {\n\t\tif (this.swarm) throw new Error(\"Hyperswarm transport has already started.\");\n\t\tconst startupSignal = signal\n\t\t\t? AbortSignal.any([signal, AbortSignal.timeout(15_000)])\n\t\t\t: AbortSignal.timeout(15_000);\n\t\tstartupSignal.throwIfAborted();\n\t\tthis.listener = listener;\n\t\tconst maxPeers = directNeighborLimit(this.options.maxPeers);\n\t\tconst swarm = new Hyperswarm({\n\t\t\tkeyPair: {\n\t\t\t\tpublicKey: this.options.identity.publicKey,\n\t\t\t\tsecretKey: this.options.identity.secretKey,\n\t\t\t},\n\t\t\tmaxPeers,\n\t\t\t...(this.options.dht ? { dht: this.options.dht } : {}),\n\t\t\t...(this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}),\n\t\t});\n\t\tthis.swarm = swarm;\n\t\tswarm.on(\"connection\", (socket, info) => this.accept(socket, info));\n\t\tswarm.on(\"error\", (error) => this.listener?.onError(safeNetworkError(error)));\n\t\ttry {\n\t\t\tconst discovery = swarm.join(this.options.room.topic, {\n\t\t\t\tserver: true,\n\t\t\t\tclient: true,\n\t\t\t\tlimit: maxPeers,\n\t\t\t});\n\t\t\tthis.discovery = discovery;\n\t\t\tawait raceAbort(discovery.flushed(), startupSignal);\n\t\t\tstartupSignal.throwIfAborted();\n\t\t\tthis.scheduleEarlyRefreshes(discovery);\n\t\t} catch (error) {\n\t\t\tawait this.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tstop(): Promise<void> {\n\t\tif (this.stopPromise) return this.stopPromise;\n\t\tthis.stopPromise = this.stopOwned();\n\t\treturn this.stopPromise;\n\t}\n\n\tprivate scheduleEarlyRefreshes(discovery: PeerDiscovery): void {\n\t\tconst delays = [250, 750, 1_500, 3_000, 6_000, 12_000];\n\t\tconst schedule = (index: number): void => {\n\t\t\tconst delayMs = delays[index];\n\t\t\tif (delayMs === undefined || this.discovery !== discovery) return;\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.refreshTimers.delete(timer);\n\t\t\t\tif (this.discovery !== discovery) return;\n\t\t\t\tvoid discovery\n\t\t\t\t\t.refresh()\n\t\t\t\t\t.catch(() => undefined)\n\t\t\t\t\t.finally(() => {\n\t\t\t\t\t\tif (this.discovery === discovery) schedule(index + 1);\n\t\t\t\t\t});\n\t\t\t}, delayMs);\n\t\t\tthis.refreshTimers.add(timer);\n\t\t};\n\t\tschedule(0);\n\t}\n\n\tprivate accept(socket: Duplex, info: PeerInfo): void {\n\t\tif (!this.swarm || !this.listener || this.connections.size >= MAX_DIRECT_NEIGHBORS) {\n\t\t\tsocket.destroy();\n\t\t\treturn;\n\t\t}\n\t\tconst decoder = new FrameDecoder();\n\t\tlet closed = false;\n\t\tconst peer: TransportPeer = {\n\t\t\tpublicKey: Buffer.from(info.publicKey),\n\t\t\tsend(message: ProtocolMessage) {\n\t\t\t\tif (closed || socket.destroyed) throw new Error(\"Peer connection is closed.\");\n\t\t\t\tconst accepted = socket.write(encodeFrame(message));\n\t\t\t\tif (!accepted && socket.destroyed) throw new Error(\"Peer connection rejected the message.\");\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tsocket.destroy();\n\t\t\t},\n\t\t};\n\t\tthis.connections.set(socket, { socket, peer });\n\t\tthis.listener.onPeer(peer);\n\t\tsocket.on(\"data\", (chunk: unknown) => {\n\t\t\tif (closed || !this.listener) return;\n\t\t\ttry {\n\t\t\t\tconst bytes =\n\t\t\t\t\ttypeof chunk === \"string\"\n\t\t\t\t\t\t? Buffer.from(chunk)\n\t\t\t\t\t\t: Buffer.isBuffer(chunk)\n\t\t\t\t\t\t\t? chunk\n\t\t\t\t\t\t\t: Buffer.from(chunk as Uint8Array);\n\t\t\t\tfor (const message of decoder.push(bytes)) this.listener.onMessage(peer, message);\n\t\t\t} catch {\n\t\t\t\tclosed = true;\n\t\t\t\tsocket.destroy();\n\t\t\t\tthis.listener?.onError(new Error(\"Pi Chat rejected invalid peer protocol data.\"));\n\t\t\t}\n\t\t});\n\t\tconst disconnected = () => {\n\t\t\tif (!this.connections.delete(socket)) return;\n\t\t\tclosed = true;\n\t\t\tthis.listener?.onDisconnect(peer);\n\t\t};\n\t\tsocket.once(\"close\", disconnected);\n\t\tsocket.once(\"error\", (error) => {\n\t\t\tthis.listener?.onError(safeNetworkError(error));\n\t\t\tdisconnected();\n\t\t});\n\t}\n\n\tprivate async stopOwned(): Promise<void> {\n\t\tfor (const timer of this.refreshTimers) clearTimeout(timer);\n\t\tthis.refreshTimers.clear();\n\t\tconst discovery = this.discovery;\n\t\tthis.discovery = undefined;\n\t\tif (discovery) await discovery.destroy().catch(() => undefined);\n\t\tfor (const { socket } of this.connections.values()) socket.destroy();\n\t\tthis.connections.clear();\n\t\tconst swarm = this.swarm;\n\t\tthis.swarm = undefined;\n\t\tthis.listener = undefined;\n\t\tif (swarm) await swarm.destroy().catch(() => undefined);\n\t}\n}\n\nasync function raceAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {\n\tif (!signal) return operation;\n\tsignal.throwIfAborted();\n\tlet remove = () => {};\n\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? new DOMException(\"Aborted\", \"AbortError\"));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tremove = () => signal.removeEventListener(\"abort\", onAbort);\n\t});\n\ttry {\n\t\treturn await Promise.race([operation, aborted]);\n\t} finally {\n\t\tremove();\n\t}\n}\n\nfunction safeNetworkError(error: unknown): Error {\n\tconst code =\n\t\terror instanceof Error && \"code\" in error ? String(Reflect.get(error, \"code\")) : \"error\";\n\treturn new Error(`Pi Chat network ${code}.`);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;AACA,OAAO,gBAAuD;AAcvD,SAAS,oBAAoB,WAA4B;AAC/D,MAAI,CAAC,OAAO,cAAc,SAAS,MAAM,aAAa,MAAM,EAAG,QAAO;AACtE,SAAO,KAAK,IAAI,aAAa,sBAAsB,oBAAoB;AACxE;AAEO,IAAM,sBAAN,MAAmD;AAAA,EACxC;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EACS,cAAc,oBAAI,IAA8B;AAAA,EAChD,gBAAgB,oBAAI,IAAoB;AAAA,EACjD;AAAA,EAER,YAAY,SAAqC;AAChD,SAAK,UAAU;AAAA,EAChB;AAAA,EAEA,IAAI,kBAA0B;AAC7B,WAAO,KAAK,YAAY;AAAA,EACzB;AAAA,EAEA,IAAI,oBAA8B;AACjC,WAAO,CAAC,GAAG,KAAK,YAAY,OAAO,CAAC,EAAE,IAAI,CAAC,EAAE,KAAK,MAAM,KAAK,UAAU,SAAS,KAAK,CAAC,EAAE,KAAK;AAAA,EAC9F;AAA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,WAAW,YAAY,CAAC;AACvF,WAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACxD,aAAS,MAAM,OAAO,oBAAoB,SAAS,OAAO;AAAA,EAC3D,CAAC;AACD,MAAI;AACH,WAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,CAAC;AAAA,EAC/C,UAAE;AACD,WAAO;AAAA,EACR;AACD;AAEA,SAAS,iBAAiB,OAAuB;AAChD,QAAM,OACL,iBAAiB,SAAS,UAAU,QAAQ,OAAO,QAAQ,IAAI,OAAO,MAAM,CAAC,IAAI;AAClF,SAAO,IAAI,MAAM,mBAAmB,IAAI,GAAG;AAC5C;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
sanitizeChatText,
|
|
5
|
+
sanitizeSingleLine
|
|
6
|
+
} from "./chunk-IVUX27XD.js";
|
|
7
|
+
|
|
8
|
+
// src/widget.ts
|
|
9
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
10
|
+
function renderChatWidget(snapshot, mode, width, theme, terminalRows = 24) {
|
|
11
|
+
if (mode === "off" || snapshot.state === "disconnected") return [];
|
|
12
|
+
const safeWidth = Math.max(1, width);
|
|
13
|
+
if (mode === "dock") return renderRoomDock(snapshot, safeWidth, terminalRows, theme);
|
|
14
|
+
const participants = snapshot.participants.length;
|
|
15
|
+
const presence = `${participants} active \xB7 ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
|
|
16
|
+
const unread = snapshot.unread > 0 ? `${snapshot.unread} unread \xB7 ` : "";
|
|
17
|
+
const attention = snapshot.state === "degraded" ? " \xB7 reconnecting" : "";
|
|
18
|
+
const header = truncateToWidth(
|
|
19
|
+
theme.fg(
|
|
20
|
+
snapshot.state === "degraded" ? "warning" : "accent",
|
|
21
|
+
`chat \xB7 ${unread}${presence}${attention}`
|
|
22
|
+
),
|
|
23
|
+
safeWidth
|
|
24
|
+
);
|
|
25
|
+
const roomHint = truncateToWidth(
|
|
26
|
+
theme.fg("dim", `${sanitizeSingleLine(snapshot.room.label)} \xB7 /chat to open`),
|
|
27
|
+
safeWidth
|
|
28
|
+
);
|
|
29
|
+
if (mode !== "latest") return [header, roomHint];
|
|
30
|
+
const latest = snapshot.transcript.at(-1);
|
|
31
|
+
if (!latest) return [header, roomHint];
|
|
32
|
+
return [header, roomHint, renderMessagePreview(latest, safeWidth, theme, false)];
|
|
33
|
+
}
|
|
34
|
+
function renderRoomDock(snapshot, width, terminalRows, theme) {
|
|
35
|
+
const participantText = `${snapshot.participants.length} active \xB7 ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
|
|
36
|
+
const stateText = snapshot.state === "connecting" ? "joining\u2026" : snapshot.state === "degraded" ? `reconnecting \xB7 ${participantText}` : snapshot.directNeighbors === 0 ? "waiting for neighbors" : participantText;
|
|
37
|
+
const unread = snapshot.unread > 0 ? ` \xB7 ${snapshot.unread} unread` : "";
|
|
38
|
+
const roomTitle = `ROOM ${sanitizeSingleLine(snapshot.room.label)}`;
|
|
39
|
+
const status = `${stateText}${unread}`;
|
|
40
|
+
const color = snapshot.state === "degraded" ? "warning" : "accent";
|
|
41
|
+
const combinedHeader = `${roomTitle} \xB7 ${status}`;
|
|
42
|
+
const header = visibleWidth(combinedHeader) <= width ? [theme.fg(color, combinedHeader)] : [
|
|
43
|
+
truncateToWidth(theme.fg(color, roomTitle), width),
|
|
44
|
+
truncateToWidth(theme.fg(color, status), width)
|
|
45
|
+
];
|
|
46
|
+
const previewCount = terminalRows < 10 ? 0 : terminalRows < 18 ? 1 : terminalRows < 26 ? 2 : 3;
|
|
47
|
+
const previews = (previewCount === 0 ? [] : snapshot.transcript.slice(-previewCount)).map(
|
|
48
|
+
(entry) => renderMessagePreview(entry, width, theme, true)
|
|
49
|
+
);
|
|
50
|
+
const target = snapshot.composerOpen ? `Input \u2192 CHAT ${sanitizeSingleLine(snapshot.room.label)} \xB7 Esc returns to Pi/LLM` : "Input \u2192 Pi/LLM \xB7 /chat then Enter to reply";
|
|
51
|
+
return [...header, ...previews, truncateToWidth(theme.fg("dim", target), width)];
|
|
52
|
+
}
|
|
53
|
+
function renderMessagePreview(entry, width, theme, includeIdentity = false) {
|
|
54
|
+
const preview = sanitizeChatText(entry.text).replace(/\n+/gu, " ");
|
|
55
|
+
const label = sanitizeSingleLine(entry.label);
|
|
56
|
+
const author = includeIdentity ? label || "peer" : label.split("~", 1)[0] || "peer";
|
|
57
|
+
return truncateToWidth(theme.fg("muted", `${author}: ${preview}`), width);
|
|
58
|
+
}
|
|
59
|
+
export {
|
|
60
|
+
renderChatWidget
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=widget-ER6SODIX.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/widget.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Theme } from \"@earendil-works/pi-coding-agent\";\nimport { truncateToWidth, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { ChatSnapshot, TranscriptEntry } from \"./chat-session.js\";\nimport type { WidgetMode } from \"./settings.js\";\nimport { sanitizeChatText, sanitizeSingleLine } from \"./text.js\";\n\nexport function renderChatWidget(\n\tsnapshot: ChatSnapshot,\n\tmode: WidgetMode,\n\twidth: number,\n\ttheme: Theme,\n\tterminalRows = 24,\n): string[] {\n\tif (mode === \"off\" || snapshot.state === \"disconnected\") return [];\n\tconst safeWidth = Math.max(1, width);\n\tif (mode === \"dock\") return renderRoomDock(snapshot, safeWidth, terminalRows, theme);\n\n\tconst participants = snapshot.participants.length;\n\tconst presence = `${participants} active \u00B7 ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? \"\" : \"s\"}`;\n\tconst unread = snapshot.unread > 0 ? `${snapshot.unread} unread \u00B7 ` : \"\";\n\tconst attention = snapshot.state === \"degraded\" ? \" \u00B7 reconnecting\" : \"\";\n\tconst header = truncateToWidth(\n\t\ttheme.fg(\n\t\t\tsnapshot.state === \"degraded\" ? \"warning\" : \"accent\",\n\t\t\t`chat \u00B7 ${unread}${presence}${attention}`,\n\t\t),\n\t\tsafeWidth,\n\t);\n\tconst roomHint = truncateToWidth(\n\t\ttheme.fg(\"dim\", `${sanitizeSingleLine(snapshot.room.label)} \u00B7 /chat to open`),\n\t\tsafeWidth,\n\t);\n\tif (mode !== \"latest\") return [header, roomHint];\n\tconst latest = snapshot.transcript.at(-1);\n\tif (!latest) return [header, roomHint];\n\treturn [header, roomHint, renderMessagePreview(latest, safeWidth, theme, false)];\n}\n\nfunction renderRoomDock(\n\tsnapshot: ChatSnapshot,\n\twidth: number,\n\tterminalRows: number,\n\ttheme: Theme,\n): string[] {\n\tconst participantText = `${snapshot.participants.length} active \u00B7 ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? \"\" : \"s\"}`;\n\tconst stateText =\n\t\tsnapshot.state === \"connecting\"\n\t\t\t? \"joining\u2026\"\n\t\t\t: snapshot.state === \"degraded\"\n\t\t\t\t? `reconnecting \u00B7 ${participantText}`\n\t\t\t\t: snapshot.directNeighbors === 0\n\t\t\t\t\t? \"waiting for neighbors\"\n\t\t\t\t\t: participantText;\n\tconst unread = snapshot.unread > 0 ? ` \u00B7 ${snapshot.unread} unread` : \"\";\n\tconst roomTitle = `ROOM ${sanitizeSingleLine(snapshot.room.label)}`;\n\tconst status = `${stateText}${unread}`;\n\tconst color = snapshot.state === \"degraded\" ? \"warning\" : \"accent\";\n\tconst combinedHeader = `${roomTitle} \u00B7 ${status}`;\n\tconst header =\n\t\tvisibleWidth(combinedHeader) <= width\n\t\t\t? [theme.fg(color, combinedHeader)]\n\t\t\t: [\n\t\t\t\t\ttruncateToWidth(theme.fg(color, roomTitle), width),\n\t\t\t\t\ttruncateToWidth(theme.fg(color, status), width),\n\t\t\t\t];\n\tconst previewCount = terminalRows < 10 ? 0 : terminalRows < 18 ? 1 : terminalRows < 26 ? 2 : 3;\n\tconst previews = (previewCount === 0 ? [] : snapshot.transcript.slice(-previewCount)).map(\n\t\t(entry) => renderMessagePreview(entry, width, theme, true),\n\t);\n\tconst target = snapshot.composerOpen\n\t\t? `Input \u2192 CHAT ${sanitizeSingleLine(snapshot.room.label)} \u00B7 Esc returns to Pi/LLM`\n\t\t: \"Input \u2192 Pi/LLM \u00B7 /chat then Enter to reply\";\n\treturn [...header, ...previews, truncateToWidth(theme.fg(\"dim\", target), width)];\n}\n\nfunction renderMessagePreview(\n\tentry: TranscriptEntry,\n\twidth: number,\n\ttheme: Theme,\n\tincludeIdentity = false,\n): string {\n\tconst preview = sanitizeChatText(entry.text).replace(/\\n+/gu, \" \");\n\tconst label = sanitizeSingleLine(entry.label);\n\tconst author = includeIdentity ? label || \"peer\" : label.split(\"~\", 1)[0] || \"peer\";\n\treturn truncateToWidth(theme.fg(\"muted\", `${author}: ${preview}`), width);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AACA,SAAS,iBAAiB,oBAAoB;AAKvC,SAAS,iBACf,UACA,MACA,OACA,OACA,eAAe,IACJ;AACX,MAAI,SAAS,SAAS,SAAS,UAAU,eAAgB,QAAO,CAAC;AACjE,QAAM,YAAY,KAAK,IAAI,GAAG,KAAK;AACnC,MAAI,SAAS,OAAQ,QAAO,eAAe,UAAU,WAAW,cAAc,KAAK;AAEnF,QAAM,eAAe,SAAS,aAAa;AAC3C,QAAM,WAAW,GAAG,YAAY,gBAAa,SAAS,eAAe,mBAAmB,SAAS,oBAAoB,IAAI,KAAK,GAAG;AACjI,QAAM,SAAS,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,kBAAe;AACtE,QAAM,YAAY,SAAS,UAAU,aAAa,uBAAoB;AACtE,QAAM,SAAS;AAAA,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