@niscorp/moss 0.3.3 → 0.5.0

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.
Files changed (175) hide show
  1. package/CHANGELOG.md +534 -0
  2. package/DESIGN.md +265 -49
  3. package/DOCS.md +1524 -341
  4. package/README.md +37 -20
  5. package/dist/app-BoVB0_0j.d.ts +143 -0
  6. package/dist/app-Cc8VnOz8.d.cts +143 -0
  7. package/dist/chunk-3RIWTXGI.cjs +174 -0
  8. package/dist/chunk-3RIWTXGI.cjs.map +1 -0
  9. package/dist/chunk-4ZGAFZGS.js +152 -0
  10. package/dist/chunk-4ZGAFZGS.js.map +1 -0
  11. package/dist/chunk-5U2ZZUI5.cjs +137 -0
  12. package/dist/chunk-5U2ZZUI5.cjs.map +1 -0
  13. package/dist/chunk-6QPTMKRE.cjs +53 -0
  14. package/dist/chunk-6QPTMKRE.cjs.map +1 -0
  15. package/dist/chunk-BQRPR2F7.js +2704 -0
  16. package/dist/chunk-BQRPR2F7.js.map +1 -0
  17. package/dist/chunk-BZK37HR3.cjs +2716 -0
  18. package/dist/chunk-BZK37HR3.cjs.map +1 -0
  19. package/dist/chunk-FTFME3HS.cjs +383 -0
  20. package/dist/chunk-FTFME3HS.cjs.map +1 -0
  21. package/dist/{chunk-NE2EXMTO.js → chunk-FTZ6NFKZ.js} +43 -16
  22. package/dist/chunk-FTZ6NFKZ.js.map +1 -0
  23. package/dist/chunk-IUJ2TRNB.cjs +57 -0
  24. package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
  25. package/dist/chunk-IW3A2YIC.js +49 -0
  26. package/dist/chunk-IW3A2YIC.js.map +1 -0
  27. package/dist/chunk-JYBHJDT7.cjs +30 -0
  28. package/dist/chunk-JYBHJDT7.cjs.map +1 -0
  29. package/dist/chunk-NRZ3Z2FF.js +61 -0
  30. package/dist/chunk-NRZ3Z2FF.js.map +1 -0
  31. package/dist/chunk-PCPQMC7A.js +26 -0
  32. package/dist/chunk-PCPQMC7A.js.map +1 -0
  33. package/dist/chunk-T5BRTFKP.js +53 -0
  34. package/dist/chunk-T5BRTFKP.js.map +1 -0
  35. package/dist/chunk-TGKDS2T7.cjs +330 -0
  36. package/dist/chunk-TGKDS2T7.cjs.map +1 -0
  37. package/dist/chunk-TLNRFAQ6.js +326 -0
  38. package/dist/chunk-TLNRFAQ6.js.map +1 -0
  39. package/dist/chunk-VKQPOZDJ.cjs +72 -0
  40. package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
  41. package/dist/chunk-ZWB6QDGF.js +374 -0
  42. package/dist/chunk-ZWB6QDGF.js.map +1 -0
  43. package/dist/client/node.cjs.map +1 -1
  44. package/dist/client/node.d.cts +3 -1
  45. package/dist/client/node.d.ts +3 -1
  46. package/dist/client/node.js.map +1 -1
  47. package/dist/client.cjs +14 -302
  48. package/dist/client.cjs.map +1 -1
  49. package/dist/client.d.cts +9 -33
  50. package/dist/client.d.ts +9 -33
  51. package/dist/client.js +2 -2
  52. package/dist/document-CU3muGbz.d.cts +169 -0
  53. package/dist/document-UFbAd-Ka.d.ts +169 -0
  54. package/dist/env-CY8EGWnD.d.cts +24 -0
  55. package/dist/env-DEPqqHEb.d.ts +24 -0
  56. package/dist/index-BuDuOSyx.d.cts +130 -0
  57. package/dist/index-BuDuOSyx.d.ts +130 -0
  58. package/dist/index.cjs +45 -3918
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +46 -100
  61. package/dist/index.d.ts +46 -100
  62. package/dist/index.js +4 -94
  63. package/dist/index.js.map +1 -1
  64. package/dist/integrations.cjs +975 -0
  65. package/dist/integrations.cjs.map +1 -0
  66. package/dist/integrations.d.cts +63 -0
  67. package/dist/integrations.d.ts +63 -0
  68. package/dist/integrations.js +972 -0
  69. package/dist/integrations.js.map +1 -0
  70. package/dist/messages-CSwCJgH3.d.cts +51 -0
  71. package/dist/messages-CSwCJgH3.d.ts +51 -0
  72. package/dist/node.cjs +17 -3457
  73. package/dist/node.cjs.map +1 -1
  74. package/dist/node.d.cts +13 -10
  75. package/dist/node.d.ts +13 -10
  76. package/dist/node.js +5 -3
  77. package/dist/protocol.cjs +24 -0
  78. package/dist/protocol.cjs.map +1 -0
  79. package/dist/protocol.d.cts +11 -0
  80. package/dist/protocol.d.ts +11 -0
  81. package/dist/protocol.js +3 -0
  82. package/dist/protocol.js.map +1 -0
  83. package/dist/slots-96gNc9uH.d.cts +12 -0
  84. package/dist/slots-BX5N0Juv.d.ts +14 -0
  85. package/dist/slots-CU-AbnJg.d.cts +14 -0
  86. package/dist/slots-sLXDrlbG.d.ts +12 -0
  87. package/dist/socket-D90h1xSV.d.cts +24 -0
  88. package/dist/socket-D90h1xSV.d.ts +24 -0
  89. package/dist/targets-DInbLzff.d.cts +9 -0
  90. package/dist/targets-DInbLzff.d.ts +9 -0
  91. package/dist/terminal/dom/index.cjs +8 -3
  92. package/dist/terminal/dom/index.cjs.map +1 -1
  93. package/dist/terminal/dom/index.d.cts +3 -0
  94. package/dist/terminal/dom/index.d.ts +3 -0
  95. package/dist/terminal/dom/index.js +8 -3
  96. package/dist/terminal/dom/index.js.map +1 -1
  97. package/dist/terminal/dom/server.cjs +2 -7
  98. package/dist/terminal/dom/server.cjs.map +1 -1
  99. package/dist/terminal/dom/server.d.cts +3 -5
  100. package/dist/terminal/dom/server.d.ts +3 -5
  101. package/dist/terminal/dom/server.js +2 -7
  102. package/dist/terminal/dom/server.js.map +1 -1
  103. package/dist/terminal/index.cjs +22 -300
  104. package/dist/terminal/index.cjs.map +1 -1
  105. package/dist/terminal/index.d.cts +7 -2
  106. package/dist/terminal/index.d.ts +7 -2
  107. package/dist/terminal/index.js +21 -22
  108. package/dist/terminal/index.js.map +1 -1
  109. package/dist/terminal/ink/index.d.ts +3 -2
  110. package/dist/terminal/ink/index.js +149 -106
  111. package/dist/terminal/ink/index.js.map +1 -1
  112. package/dist/terminal/react/index.cjs +21 -71
  113. package/dist/terminal/react/index.cjs.map +1 -1
  114. package/dist/terminal/react/index.d.cts +5 -2
  115. package/dist/terminal/react/index.d.ts +5 -2
  116. package/dist/terminal/react/index.js +17 -20
  117. package/dist/terminal/react/index.js.map +1 -1
  118. package/dist/terminal/react/server.cjs +4 -68
  119. package/dist/terminal/react/server.cjs.map +1 -1
  120. package/dist/terminal/react/server.d.cts +9 -6
  121. package/dist/terminal/react/server.d.ts +9 -6
  122. package/dist/terminal/react/server.js +3 -18
  123. package/dist/terminal/react/server.js.map +1 -1
  124. package/dist/terminal/tty/index.cjs +147 -130
  125. package/dist/terminal/tty/index.cjs.map +1 -1
  126. package/dist/terminal/tty/index.d.cts +4 -2
  127. package/dist/terminal/tty/index.d.ts +4 -2
  128. package/dist/terminal/tty/index.js +147 -130
  129. package/dist/terminal/tty/index.js.map +1 -1
  130. package/dist/terminal/vue/index.cjs +20 -72
  131. package/dist/terminal/vue/index.cjs.map +1 -1
  132. package/dist/terminal/vue/index.d.cts +8 -12
  133. package/dist/terminal/vue/index.d.ts +8 -12
  134. package/dist/terminal/vue/index.js +45 -1
  135. package/dist/terminal/vue/index.js.map +1 -1
  136. package/dist/terminal/vue/server.cjs +4 -76
  137. package/dist/terminal/vue/server.cjs.map +1 -1
  138. package/dist/terminal/vue/server.d.cts +7 -6
  139. package/dist/terminal/vue/server.d.ts +7 -6
  140. package/dist/terminal/vue/server.js +3 -10
  141. package/dist/terminal/vue/server.js.map +1 -1
  142. package/dist/tide.cjs +41 -0
  143. package/dist/tide.cjs.map +1 -0
  144. package/dist/tide.d.cts +25 -0
  145. package/dist/tide.d.ts +25 -0
  146. package/dist/tide.js +39 -0
  147. package/dist/tide.js.map +1 -0
  148. package/dist/unverified.cjs +12 -0
  149. package/dist/unverified.cjs.map +1 -0
  150. package/dist/unverified.d.cts +7 -0
  151. package/dist/unverified.d.ts +7 -0
  152. package/dist/unverified.js +10 -0
  153. package/dist/unverified.js.map +1 -0
  154. package/dist/vite.cjs +96 -232
  155. package/dist/vite.cjs.map +1 -1
  156. package/dist/vite.d.cts +6 -8
  157. package/dist/vite.d.ts +6 -8
  158. package/dist/vite.js +97 -71
  159. package/dist/vite.js.map +1 -1
  160. package/package.json +56 -13
  161. package/dist/chunk-4T6KAXBP.js +0 -256
  162. package/dist/chunk-4T6KAXBP.js.map +0 -1
  163. package/dist/chunk-AUZMT3GL.js +0 -3406
  164. package/dist/chunk-AUZMT3GL.js.map +0 -1
  165. package/dist/chunk-EMRDIZLY.js +0 -99
  166. package/dist/chunk-EMRDIZLY.js.map +0 -1
  167. package/dist/chunk-HOZID4EM.js +0 -366
  168. package/dist/chunk-HOZID4EM.js.map +0 -1
  169. package/dist/chunk-NE2EXMTO.js.map +0 -1
  170. package/dist/chunk-SK4PDGEE.js +0 -55
  171. package/dist/chunk-SK4PDGEE.js.map +0 -1
  172. package/dist/document-DhWxieUc.d.cts +0 -1024
  173. package/dist/document-DhWxieUc.d.ts +0 -1024
  174. package/dist/slots-Do9ScG7v.d.cts +0 -37
  175. package/dist/slots-Do9ScG7v.d.ts +0 -37
@@ -1,310 +1,18 @@
1
1
  'use strict';
2
2
 
3
- require('@niscorp/nova');
3
+ var chunkTGKDS2T7_cjs = require('../chunk-TGKDS2T7.cjs');
4
+ require('../chunk-3RIWTXGI.cjs');
4
5
  var document$1 = require('@niscorp/nova/document');
5
6
 
6
- // src/socket.ts
7
-
8
- // src/session-cookie.ts
9
- var DEFAULT_TOKEN_KEY = "nisc.token";
10
- var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
11
- var heldCookieName = (key = DEFAULT_TOKEN_KEY, port = "") => encodeURIComponent(`${nameOf(key, port)}.held`);
12
-
13
- // src/socket.ts
14
- var PROTOCOL = 2;
15
- var PROTOCOL_MIN = 2;
16
- var SUBPROTOCOL = "nisc";
17
- var TOKEN_OFFER = "nisc.token.";
18
- var SEALED_OFFER = "nisc.sealed.";
19
- var offerToken = (token, sealed = null) => {
20
- const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
21
- if (token === null) return offer;
22
- const bytes = String.fromCharCode(...new TextEncoder().encode(token));
23
- return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
24
- };
25
- var CLOSE_INVALID_TOKEN = 4401;
26
- var CLOSE_SIGNED_OUT = 4403;
27
- var CLOSE_PROTOCOL_MISMATCH = 4426;
28
-
29
- // src/delta.ts
30
- var applyDelta = (base, ops) => {
31
- let out = "";
32
- for (const op of ops) {
33
- if (op[0] === 1) {
34
- out += op[1];
35
- continue;
36
- }
37
- const [, offset, length] = op;
38
- if (offset < 0 || length < 0 || offset + length > base.length) {
39
- throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);
40
- }
41
- out += base.slice(offset, offset + length);
42
- }
43
- return out;
44
- };
45
- var frameHash = (text) => {
46
- let hash = 2166136261;
47
- for (let i = 0; i < text.length; i += 1) {
48
- hash ^= text.charCodeAt(i);
49
- hash = Math.imul(hash, 16777619);
50
- }
51
- return hash >>> 0;
52
- };
53
-
54
- // src/client/index.ts
55
- var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
56
- var browserEnv = (config = {}) => {
57
- const tokenKey = config.tokenKey ?? "nisc.token";
58
- return {
59
- tokens: {
60
- load: () => {
61
- try {
62
- return window.localStorage.getItem(tokenKey);
63
- } catch {
64
- return null;
65
- }
66
- },
67
- save: (token) => {
68
- try {
69
- window.localStorage.setItem(tokenKey, token);
70
- } catch {
71
- }
72
- },
73
- clear: () => {
74
- try {
75
- window.localStorage.removeItem(tokenKey);
76
- } catch {
77
- }
78
- try {
79
- document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
80
- } catch {
81
- }
82
- },
83
- held: () => {
84
- try {
85
- return document.cookie.split("; ").includes(`${heldCookieName(tokenKey, window.location.port)}=1`);
86
- } catch {
87
- return false;
88
- }
89
- },
90
- ...config.tokenKey !== void 0 ? { key: tokenKey } : {}
91
- },
92
- socket: ({ url, offered }) => new WebSocket(url, offered),
93
- defaultUrl: () => {
94
- const scheme = window.location.protocol === "https:" ? "wss" : "ws";
95
- return `${scheme}://${window.location.host}/socket`;
96
- }
97
- };
98
- };
99
- var createWire = (config = {}) => {
100
- const env = config.env ?? browserEnv();
101
- let token = env.tokens.load();
102
- const initial = config.initial !== void 0 && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : void 0;
103
- let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
104
- let seed = initial?.seed;
105
- const path = config.path ?? config.initial?.path;
106
- let status = "connecting";
107
- let incompatible = false;
108
- let leaving = false;
109
- let sealed = null;
110
- let unsealed = false;
111
- let socket = null;
112
- let retry;
113
- let attempts = 0;
114
- let disposed = false;
115
- const listeners = /* @__PURE__ */ new Set();
116
- const publishSnapshot = (next) => {
117
- snapshot = next;
118
- for (const listener of listeners) listener();
119
- };
120
- const setStatus = (next) => {
121
- if (status === next) return;
122
- status = next;
123
- for (const listener of listeners) listener();
124
- };
125
- const url = () => config.url ?? env.defaultUrl();
126
- const send = (message) => {
127
- if (socket === null || status !== "open") return;
128
- socket.send(JSON.stringify(message));
129
- };
130
- const bases = /* @__PURE__ */ new Map();
131
- const connect = () => {
132
- if (disposed) return;
133
- setStatus("connecting");
134
- bases.clear();
135
- const params = [`protocol=${PROTOCOL}`];
136
- if (env.tokens.key !== void 0) params.push(`key=${encodeURIComponent(env.tokens.key)}`);
137
- if (leaving) params.push("leave=1");
138
- if (env.tokens.held !== void 0 && !unsealed) params.push("sealed=1");
139
- if (config.delta === true) params.push("delta=1");
140
- if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
141
- seed = void 0;
142
- if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
143
- const ws = env.socket({ url: `${url()}?${params.join("&")}`, offered: offerToken(token, sealed) });
144
- socket = ws;
145
- ws.onopen = () => {
146
- attempts = 0;
147
- setStatus("open");
148
- };
149
- ws.onmessage = (e) => {
150
- const text = String(e.data);
151
- const data = JSON.parse(text);
152
- if (data.type === "render" && data.canvas !== void 0 && data.tree !== void 0) {
153
- if (config.delta === true) bases.set(data.canvas, text);
154
- publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });
155
- } else if (data.type === "render-delta" && data.canvas !== void 0 && data.ops !== void 0 && data.hash !== void 0) {
156
- const base = bases.get(data.canvas);
157
- let rebuilt = null;
158
- if (base !== void 0) {
159
- try {
160
- const candidate = applyDelta(base, data.ops);
161
- rebuilt = frameHash(candidate) === data.hash ? candidate : null;
162
- } catch {
163
- rebuilt = null;
164
- }
165
- }
166
- if (rebuilt === null) {
167
- console.warn(`[moss/wire] canvas "${data.canvas}": delta did not rebuild the server's frame \u2014 resyncing.`);
168
- bases.delete(data.canvas);
169
- send({ type: "resync" });
170
- return;
171
- }
172
- const frame = JSON.parse(rebuilt);
173
- bases.set(data.canvas, rebuilt);
174
- publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });
175
- } else if (data.type === "frame" && data.tree !== void 0) {
176
- publishSnapshot({ ...snapshot, frame: data.tree });
177
- } else if (data.type === "session" && typeof data.token === "string") {
178
- become(data.token);
179
- } else if (data.type === "session" && typeof data.sealed === "string") {
180
- become(null, data.sealed);
181
- } else if (data.type === "error") {
182
- if (data.code === "seal_not_kept") unsealed = true;
183
- console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
184
- } else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
185
- console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}\u2013${PROTOCOL}. The server has not been updated yet.`);
186
- incompatible = true;
187
- ws.close();
188
- } else if (data.type === "hello") {
189
- leaving = false;
190
- sealed = null;
191
- if (token !== null && env.tokens.held !== void 0) {
192
- if (env.tokens.held()) {
193
- env.tokens.clear();
194
- token = null;
195
- } else env.tokens.save(token);
196
- }
197
- } else if (data.type !== "catalog") {
198
- console.warn(`[moss/wire] unhandled server message: ${data.type}`);
199
- }
200
- };
201
- ws.onclose = (e) => {
202
- if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {
203
- incompatible = true;
204
- setStatus("incompatible");
205
- return;
206
- }
207
- setStatus("closed");
208
- if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
209
- leaving = e.code === CLOSE_SIGNED_OUT;
210
- become(null);
211
- return;
212
- }
213
- if (!disposed) scheduleReconnect();
214
- };
215
- };
216
- const RECONNECT_CAP_MS = 3e4;
217
- const scheduleReconnect = () => {
218
- const ceiling = Math.min(RECONNECT_CAP_MS, 1e3 * 2 ** attempts);
219
- attempts += 1;
220
- const delay = ceiling / 2 + Math.random() * (ceiling / 2);
221
- retry = setTimeout(connect, delay);
222
- };
223
- const become = (next, handedSealed = null) => {
224
- sealed = handedSealed;
225
- if (handedSealed !== null) ; else if (next === null) env.tokens.clear();
226
- else if (env.tokens.held === void 0) env.tokens.save(next);
227
- token = next;
228
- clearTimeout(retry);
229
- attempts = 0;
230
- publishSnapshot(EMPTY);
231
- const old = socket;
232
- socket = null;
233
- if (old !== null) {
234
- old.onclose = null;
235
- old.close();
236
- }
237
- connect();
238
- };
239
- if (initial?.live === false) status = "static";
240
- else connect();
241
- return {
242
- subscribe: (listener) => {
243
- listeners.add(listener);
244
- return () => listeners.delete(listener);
245
- },
246
- snapshot: () => snapshot,
247
- status: () => status,
248
- dispatch: (canvasId, event) => send({ type: "event", canvas: canvasId, event }),
249
- publish: (channel, payload) => send(payload === void 0 ? { type: "publish", channel } : { type: "publish", channel, payload }),
250
- // Only on an open socket, and deliberately not queued: a back pressed while
251
- // the connection is down is a gesture about a screen the person is no
252
- // longer being served, and replaying it on reconnect would move them
253
- // somewhere they asked to go some seconds and one outage ago.
254
- back: () => {
255
- if (socket === null || status !== "open") return;
256
- send({ type: "back" });
257
- },
258
- // Same posture as `back`: only on an open socket, never queued. A jump
259
- // replayed on reconnect would move somebody to where they wanted to be
260
- // one outage ago.
261
- popTo: (canvas, instance) => {
262
- if (socket === null || status !== "open") return;
263
- send({ type: "popTo", canvas, instance });
264
- },
265
- reset: () => {
266
- if (disposed) return;
267
- if (socket !== null && status === "open") {
268
- send({ type: "reset" });
269
- return;
270
- }
271
- clearTimeout(retry);
272
- attempts = 0;
273
- connect();
274
- },
275
- dispose: () => {
276
- disposed = true;
277
- status = "closed";
278
- clearTimeout(retry);
279
- socket?.close();
280
- }
281
- };
282
- };
283
-
284
- // src/terminal/hotkey.ts
285
- var onHotkey = (spec, handler) => {
286
- const parts = spec.toLowerCase().split("+");
287
- const key = parts[parts.length - 1] ?? "";
288
- const mods = new Set(parts.slice(0, -1));
289
- const listener = (event) => {
290
- if (event.key.toLowerCase() === key && event.ctrlKey === mods.has("ctrl") && event.shiftKey === mods.has("shift") && event.altKey === mods.has("alt") && event.metaKey === (mods.has("meta") || mods.has("cmd"))) {
291
- event.preventDefault();
292
- handler();
293
- }
294
- };
295
- window.addEventListener("keydown", listener);
296
- return () => window.removeEventListener("keydown", listener);
297
- };
298
-
299
7
  // src/terminal/history.ts
300
- var SENTINEL = { nisc: "terminal-back" };
8
+ var BACK_ENTRY_STATE = { nisc: "terminal-back" };
301
9
  var trapBack = (handler) => {
302
10
  if (typeof window === "undefined") return () => void 0;
303
11
  const history = window.history;
304
12
  if (history === void 0 || typeof history.pushState !== "function") return () => void 0;
305
13
  const spare = () => {
306
14
  try {
307
- history.pushState(SENTINEL, "");
15
+ history.pushState(BACK_ENTRY_STATE, "");
308
16
  } catch {
309
17
  }
310
18
  };
@@ -318,6 +26,21 @@ var trapBack = (handler) => {
318
26
  window.removeEventListener("popstate", onPopState);
319
27
  };
320
28
  };
29
+
30
+ // src/terminal/index.ts
31
+ var onHotkey = (spec, handler) => {
32
+ const parts = spec.toLowerCase().split("+");
33
+ const key = parts[parts.length - 1] ?? "";
34
+ const mods = new Set(parts.slice(0, -1));
35
+ const listener = (event) => {
36
+ if (event.key.toLowerCase() === key && event.ctrlKey === mods.has("ctrl") && event.shiftKey === mods.has("shift") && event.altKey === mods.has("alt") && event.metaKey === (mods.has("meta") || mods.has("cmd"))) {
37
+ event.preventDefault();
38
+ handler();
39
+ }
40
+ };
41
+ window.addEventListener("keydown", listener);
42
+ return () => window.removeEventListener("keydown", listener);
43
+ };
321
44
  var followHead = (api, subscribe) => {
322
45
  if (typeof document === "undefined") return () => void 0;
323
46
  const keep = document$1.createHeadKeeper(document);
@@ -325,15 +48,14 @@ var followHead = (api, subscribe) => {
325
48
  read();
326
49
  return subscribe(read);
327
50
  };
328
-
329
- // src/terminal/index.ts
330
51
  var createTerminal = (config) => {
331
52
  const { target, wire } = config;
332
53
  const api = {
333
54
  frame: () => wire.snapshot().frame,
334
55
  canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],
335
56
  dispatch: (id, event) => wire.dispatch(id, event),
336
- publish: (channel, payload) => wire.publish(channel, payload)
57
+ publish: (channel, payload) => wire.publish(channel, payload),
58
+ status: () => wire.status()
337
59
  };
338
60
  const mount = target(api);
339
61
  const unsubscribe = wire.subscribe(mount.update);
@@ -350,7 +72,7 @@ var mountTerminal = (config) => {
350
72
  const keys = Object.keys(config.targets);
351
73
  if (keys.length === 0) throw new Error("mountTerminal: at least one target is required");
352
74
  const ownsWire = config.wire === void 0;
353
- const wire = config.wire ?? createWire(config.url !== void 0 ? { url: config.url } : {});
75
+ const wire = config.wire ?? chunkTGKDS2T7_cjs.createWire(config.url !== void 0 ? { url: config.url } : {});
354
76
  const targetAt = (i) => {
355
77
  const key = keys[i];
356
78
  const target = key === void 0 ? void 0 : config.targets[key];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/session-cookie.ts","../../src/socket.ts","../../src/delta.ts","../../src/client/index.ts","../../src/terminal/hotkey.ts","../../src/terminal/history.ts","../../src/terminal/head.ts","../../src/terminal/index.ts"],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B,MAAA,eAAA,IAAkB;AAClB,MAAA,eAAA,IAAkB;AAClB,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════════\n// A BROWSER'S SESSION, KEPT WHERE ITS PAGE CANNOT READ IT.\n//\n// A terminal served by the app it talks to does not hold its session: the\n// browser does, in a cookie no script can read, and sends it by itself with\n// the two requests that need to know who is asking — the page, and the\n// upgrade that opens the socket. The server writes it in its answer to that\n// upgrade (socket.ts), or to a sign-in the app answers over HTTP\n// (`sessionCookies`, below). Any other terminal — a process, a page served\n// from somewhere else — holds its own token and offers it, as before.\n//\n// THE NAME is the terminal's token key (`nisc.token`, or a seat's own), so\n// several people can be signed in on one origin, each in a seat. It ends with\n// the port when the page is on one: a browser keeps cookies by host and not by\n// port, and two apps on localhost would otherwise sign each other out. Over\n// https it is `__Host-` prefixed and `Secure`, which a browser lets nothing\n// but this host set.\n//\n// BESIDE IT, `<name>.held=1`, which script CAN read and which says nothing but\n// that the browser holds a session — how a terminal knows to let go of a token\n// it was holding, and that a page drawn for somebody was drawn for it.\n//\n// NO ROUTE ANSWERS TO THIS COOKIE. It is read for a page request, which every\n// site may link to and none can read the answer of, and on an upgrade from the\n// app's own page — never from another origin's, which a browser would send it\n// with all the same.\n// ═══════════════════════════════════════════════════════════════\n\nexport const DEFAULT_TOKEN_KEY = 'nisc.token';\n\n// The token under one name in a `Cookie` header.\nexport const tokenFromCookie = (header: string | null | undefined, name = DEFAULT_TOKEN_KEY): string | null => {\n if (header === undefined || header === null) return null;\n const wanted = encodeURIComponent(name);\n for (const part of header.split(';')) {\n const at = part.indexOf('=');\n if (at < 0 || part.slice(0, at).trim() !== wanted) continue;\n try {\n const value = decodeURIComponent(part.slice(at + 1).trim());\n return value === '' ? null : value;\n } catch {\n return null;\n }\n }\n return null;\n};\n\n// Is this the app's own page asking? Its origin's host is the host the request\n// was addressed to — or one the deployment lists, behind a proxy that rewrites\n// `Host`. A sibling subdomain, another port, an opaque origin: not it.\nexport const isOwnOrigin = (origin: string | null | undefined, host: string | null | undefined, listed: readonly string[] = []): origin is string => {\n if (origin === undefined || origin === null || !URL.canParse(origin)) return false;\n const asked = new URL(origin);\n return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);\n};\n\nconst nameOf = (key: string, port: string): string => `${key}${port === '' ? '' : `.${port}`}`;\n\n// The flag's name, as a terminal on `port` reads it out of `document.cookie`.\nexport const heldCookieName = (key = DEFAULT_TOKEN_KEY, port = ''): string => encodeURIComponent(`${nameOf(key, port)}.held`);\n\nconst cookiesAt = (where: { port: string; secure: boolean }, key: string, token: string | null, lastsMs?: number | null): string[] => {\n const name = encodeURIComponent(nameOf(key, where.port));\n const life = token === null ? '; Max-Age=0' : typeof lastsMs === 'number' ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1000))}` : '';\n const kept = `Path=/; SameSite=Lax${where.secure ? '; Secure' : ''}${life}`;\n return [`${where.secure ? '__Host-' : ''}${name}=${encodeURIComponent(token ?? '')}; HttpOnly; ${kept}`, `${name}.held=${token === null ? '' : '1'}; ${kept}`];\n};\n\n// The page's origin as its browser sees it: what the request says, else where\n// it was addressed and how a proxy in front says it arrived.\nconst originOf = (request: Request): string => {\n const said = request.headers.get('origin');\n if (said !== null && URL.canParse(said)) return said;\n const here = new URL(request.url);\n const scheme = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim() || here.protocol.slice(0, -1);\n return `${scheme}://${request.headers.get('host') ?? here.host}`;\n};\n\n// THE `Set-Cookie` VALUES that keep `token` in the browser of the page at this\n// origin — or, for `null`, take it back. For a sign-in the app answers over\n// HTTP (a link redeemed, a provider's callback): set these on the response and\n// the page that follows is signed in, having never held the token. `lastsMs`\n// is how long the browser keeps it; left out, until the browser closes.\nexport const sessionCookies = (page: string | Request, token: string | null, options: { key?: string; lastsMs?: number | null } = {}): string[] => {\n const at = new URL(typeof page === 'string' ? page : originOf(page));\n return cookiesAt({ port: at.port, secure: at.protocol === 'https:' }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);\n};\n\n// What the browser holds for this key, out of a request's `Cookie` header.\n// `secure` says which of the two names to read; unknown (a page request does\n// not say how it arrived), the one only this host can have set is read first.\nexport const sessionTokenOf = (\n cookies: string | null | undefined,\n where: { port: string; secure?: boolean },\n key = DEFAULT_TOKEN_KEY,\n): { token: string; clear: string[] } | null => {\n const name = nameOf(key, where.port);\n for (const secure of where.secure === undefined ? [true, false] : [where.secure]) {\n const token = tokenFromCookie(cookies, `${secure ? '__Host-' : ''}${name}`);\n if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };\n }\n return null;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// THE SEAL — how a sign-in made over the socket reaches that cookie.\n//\n// Only an HTTP answer can write a cookie, and a sign-in over the socket is not\n// one: the token has to travel through the page to the next upgrade. It\n// travels SEALED — encrypted with a key the page's browser holds in a second\n// cookie no script can read, set by the answer to its first upgrade. The page\n// can hand it back and cannot open it; neither can anybody it is shown to, on\n// this machine or another. It is good for a minute.\n//\n// The seal rides only the socket's own path: no page request carries it, so a\n// page drawn for nobody is still the same for everybody. It lasts until the\n// browser closes, and is never stored or looked up here — a key, not a name.\n//\n// ITS NAME IS WHAT KEEPS A SCRIPT FROM SUPPLYING IT. A request shows a cookie's\n// name and value and nothing of who set it, so a seal a script planted before\n// the browser's first upgrade would look like one given here — and the script\n// would hold the key. Over https the seal is `__Http-` prefixed: a name a\n// browser lets only an HTTP answer set, never script. A browser that does not\n// know the prefix treats it as any other name, and is where that is still open.\n//\n// WebCrypto, so this is the same on every runtime and nothing here is Node's.\n// ═══════════════════════════════════════════════════════════════\n\nconst SEALED_FOR_MS = 60_000;\nconst sealName = (secure: boolean): string => `${secure ? '__Http-' : ''}nisc.seal`;\nconst toBase64Url = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nconst fromBase64Url = (text: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), (char) => char.charCodeAt(0));\nconst keyOf = async (seal: string): Promise<CryptoKey> => crypto.subtle.importKey('raw', await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seal)), 'AES-GCM', false, ['encrypt', 'decrypt']);\n\nexport const newSeal = (): string => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\n// The seal a browser sent with an upgrade, and the `Set-Cookie` value that\n// gives it one: for the socket's own `path` only, unreadable to script.\nexport const sealOf = (cookies: string | null | undefined, secure: boolean): string | null => tokenFromCookie(cookies, sealName(secure));\nexport const sealCookie = (seal: string, where: { secure: boolean; path: string }): string => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? '; Secure' : ''}`;\n\nexport const sealSession = async (seal: string, token: string, forMs = SEALED_FOR_MS): Promise<string> => {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));\n return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));\n};\n\n// The token in a sealed sign-in — or null: not sealed with this seal, altered, or too old.\nexport const openSealed = async (seal: string, sealed: string): Promise<string | null> => {\n try {\n const bytes = fromBase64Url(sealed);\n const opened = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));\n const { token, until } = JSON.parse(new TextDecoder().decode(opened)) as { token?: unknown; until?: unknown };\n return typeof token === 'string' && typeof until === 'number' && until > Date.now() ? token : null;\n } catch {\n return null;\n }\n};\n","import { DefinitionValidationError } from '@niscorp/nova';\nimport type { RenderNode } from '@niscorp/nova';\nimport type { Catalog } from './principal';\nimport type { DeltaOp } from './delta';\nimport type { ShellHost } from './shells';\nimport { emitterOf, spanClock } from './telemetry';\nimport type { Telemetry } from './telemetry';\nimport { DEFAULT_TOKEN_KEY, isOwnOrigin, newSeal, openSealed, sealCookie, sealOf, sealSession, sessionCookies, sessionTokenOf } from './session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The socket — the authority channel (DESIGN.md § The socket), protocol layer.\n//\n// The socket invents nothing: JSON frames, every canvas-bound message\n// carries its canvas id, reconnect just re-sends current state. This\n// module is transport-blind — it speaks through the four-function\n// `Connection` seam; the RFC 6455 plumbing lives with each runtime's\n// entry (`ws` on Node in ./node, Bun-native later) and is never\n// hand-written.\n//\n// What rides it: connection lifecycle, token auth at upgrade, the CATALOG\n// channel (`hello` on connect — the resolved application + its version\n// token; equal hash, equal application), and the canvas streams (`render`\n// down, `event` up) fed by the server shell host. An app whose manifest\n// declares no shell has no streams, and an event envelope aimed at one is\n// answered honestly with `no_shell` rather than silently dropped.\n//\n// Identity is asked twice: once at upgrade, and then on a timer for as long\n// as the connection lives (see DEFAULT_REVALIDATE_MS). The second is what\n// lets a `session` verifier's expiry mean anything here — the HTTP surfaces\n// re-ask on every request, and a socket that asked once would be the hole\n// every long-lived credential leaks through.\n// ═══════════════════════════════════════════════════════════════\n\n// The transport seam — what a runtime's websocket must provide. Four\n// functions, and what the request that opened the connection offered;\n// everything above them is identical on every runtime.\nexport type Connection = {\n send: (text: string) => void;\n close: (code?: number, reason?: string) => void;\n onMessage: (fn: (text: string) => void) => void;\n onClose: (fn: () => void) => void;\n // The upgrade request, as far as it says who is asking: the subprotocols it\n // offered (`Sec-WebSocket-Protocol`, split), and — for a browser's session\n // (session-cookie.ts) — where the page is, where the request was addressed,\n // and the cookies it carried. A transport that leaves this out serves every\n // terminal as nobody.\n //\n // `answer`: a transport that has NOT answered the request yet says so by\n // giving this, and is told — once who is asking is decided, before the\n // connection is used at all — the `Set-Cookie` values its answer is to\n // carry: the one moment a cookie can be written. It answers when the\n // connection is first used.\n // Without it nothing is written, and a browser's terminal goes on holding\n // its own token.\n upgrade?: {\n offered: readonly string[];\n origin?: string | null;\n host?: string | null;\n cookie?: string | null;\n answer?: (cookies: readonly string[]) => void;\n };\n // Set here, not by a transport: how this connection's terminal is handed a\n // session when its browser holds a seal (session-cookie.ts) — sealed, so the\n // page carries it to the next upgrade and cannot open it. Absent, a session\n // is handed over as its token.\n seal?: (token: string) => Promise<string>;\n};\n\n// ── The envelope ──\nexport type ServerMessage =\n | { type: 'hello'; protocol: number; principal: string | null; catalog: { actions: readonly string[]; hash: string } }\n | { type: 'catalog'; actions: readonly string[]; hash: string }\n // the shell's canvas ARRANGEMENT — a rendered layout whose CanvasSlot\n // markers the terminal resolves against its per-canvas trees\n | { type: 'frame'; tree: RenderNode[] }\n | { type: 'render'; canvas: string; tree: RenderNode[] }\n // The same render, as a DELTA against the last frame this connection was\n // sent for this canvas. Only ever sent to a terminal that asked for deltas\n // (`?delta=1` on the upgrade) and only when a previous frame exists, so a\n // terminal that does not understand this never receives one.\n //\n // `hash` is over the rebuilt message text: a terminal that applies the ops\n // and does not land on it has diverged, and asks for a whole frame instead\n // of rendering something the server never meant.\n | { type: 'render-delta'; canvas: string; ops: DeltaOp[]; hash: number }\n // session GRANT (login succeeded server-side): store the token and\n // reconnect authenticated — the twin of the 4403 SIGNED_OUT revoke\n // A sign-in: the terminal comes back as that principal. As the token, for a\n // terminal that keeps its own; SEALED, for one whose browser keeps the\n // session — it offers it on its next upgrade, where its browser's seal opens it.\n | { type: 'session'; token: string }\n | { type: 'session'; sealed: string }\n | { type: 'error'; code: string; message: string; canvas?: string };\n\nexport type ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n // RESYNC: this terminal's frame for a canvas is not what the server thinks\n // it is — a delta failed its checksum, or arrived with no base to apply it\n // to. Answered with whole frames, which is the state both ends can always\n // agree on. Distinct from `reset`: the SHELL is fine, only this connection's\n // copy of it drifted, so nothing is torn down.\n | { type: 'resync' }\n // BACK: undo this session's last navigation. It names no canvas for the same\n // reason `reset` does not — back is one gesture over the whole shell, and the\n // terminal that sends it has no idea which canvas moved last (it is served\n // trees, not stacks). Protocol-level, so a browser's back button, a TUI's\n // Escape and a REPL word are the same message on one wire, and the app has to\n // author nothing to receive it.\n | { type: 'back' }\n // POP TO: jump straight to an ancestor already on a canvas's stack. Back\n // undoes ONE navigation; a breadcrumb that names a screen three levels down\n // is one intention, not three gestures. Sending three `back`s instead raced\n // the browser's own history repair and dropped presses — the shell can walk\n // its own stack atomically, so it should be asked to.\n | { type: 'popTo'; canvas: string; instance: string }\n // RESET: throw this session's shell away and serve its replacement. The one\n // message that names no canvas, deliberately — it is the recovery for a\n // shell whose canvases are the broken thing, so it must not have to travel\n // through one. Protocol-level, not app-level: no action declares it, no\n // charter grants it, and it reaches a terminal whose every surface is dead.\n | { type: 'reset' };\n\n// The wire protocol this server speaks, and the oldest a terminal may speak to\n// it. A terminal says which it speaks on the upgrade (`?protocol=N` — known\n// before the first frame is sent); one that says nothing speaks 1, which is\n// every terminal built before the question existed. Outside the range the\n// connection is refused with a sentence and CLOSE_PROTOCOL_MISMATCH, never\n// served frames it would misread. Bump PROTOCOL when a message changes shape;\n// raise PROTOCOL_MIN only when the server stops speaking an old one.\n//\n// 2: the token left the address. A terminal at 1 put it in `?token=`, and an\n// address is what every proxy on the way writes into its log. A server that\n// went on reading it there would keep that open for as long as anything used\n// it, so 1 is no longer spoken: a terminal built before is told to reload.\nexport const PROTOCOL = 2;\nexport const PROTOCOL_MIN = 2;\n\n// WHO A TERMINAL IS rides the upgrade request, in the one header every host\n// lets a terminal set, a browser included: the subprotocols it offers. It\n// offers `nisc`, and beside it its token when it holds one — base64url,\n// because a subprotocol is an HTTP token and a session token need not be. The\n// server answers `nisc`, never the other. Decided on the request, so no\n// connection is ever open and waiting to be told who it is.\nexport const SUBPROTOCOL = 'nisc';\nconst TOKEN_OFFER = 'nisc.token.';\nconst SEALED_OFFER = 'nisc.sealed.';\n\n// `sealed`: a sign-in the terminal was handed sealed, offered back as it is.\nexport const offerToken = (token: string | null, sealed: string | null = null): string[] => {\n const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];\n if (token === null) return offer;\n const bytes = String.fromCharCode(...new TextEncoder().encode(token));\n return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')}`];\n};\n\nexport const offeredToken = (offered: readonly string[] = []): string | null => {\n const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));\n if (offer === undefined) return null;\n try {\n const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, '+').replace(/_/g, '/'));\n return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;\n } catch {\n return null;\n }\n};\n\n// Application close code: the token did not resolve to a principal.\nexport const CLOSE_INVALID_TOKEN = 4401;\n// Application close code: the session ended (sign-out, from any of the\n// principal's terminals) — the terminal clears its token instead of\n// reconnecting.\nexport const CLOSE_SIGNED_OUT = 4403;\n// Application close code: the server could not open a session for THIS\n// connection — commonest cause: a definition failing validation reached the\n// live catalog (a dev edit mid-reload). The refusal is this terminal's alone;\n// the process and every other session stay up, and reconnecting later is\n// reasonable — the next build is attempted fresh.\nexport const CLOSE_SHELL_FAILED = 4500;\n// Application close code: terminal and server speak protocols the other cannot\n// (see PROTOCOL). Not a retry: reconnecting speaks the same protocol again. A\n// browser terminal needs a reload to fetch the current build; the preceding\n// `error` says which side is behind (`client_too_old` / `server_too_old`).\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport type SocketContext = {\n session: (token: string) => string | null | Promise<string | null>;\n catalog: (principal: string | null) => Catalog | Promise<Catalog>;\n // The shell host — when the manifest declares a shell, events route into\n // the session's server shell and render frames flow back.\n shells?: ShellHost;\n // WHICH HOST A PATH LEADS TO. A terminal on a page names the path it is on\n // (`?path=`); this answers with that page's host and the input its path\n // carries, or undefined for a path that is the app's. Absent: every\n // connection is the app's, as before pages existed.\n page?: (path: string) => { host: ShellHost; inputs: Record<string, Record<string, unknown>> } | undefined;\n // How often a LIVE connection's credential is re-verified. Default\n // `DEFAULT_REVALIDATE_MS`; `0` or `Infinity` disables it, and a token\n // checked once at upgrade is then trusted for the life of the connection.\n revalidateMs?: number;\n // The deployment's telemetry sink, if any — a `socket.upgrade` span per\n // connection admitted or refused, and a `socket.close` span carrying the\n // whole connection's lifetime. See telemetry.ts.\n telemetry?: Telemetry;\n // Origins that are this app's own page beside the host a request is\n // addressed to (`runtime.origins`) — a proxy that rewrites `Host`.\n origins?: readonly string[];\n // How much longer a token resolves, when the credential knows — how long a\n // browser is told to keep the cookie that carries it. Unknown: until the\n // browser closes.\n sessionLastsMs?: (token: string) => number | null | Promise<number | null>;\n};\n\n// ── Revalidation ──\n// The HTTP surfaces re-ask \"who is this\" on every request; the socket asked\n// once, at upgrade, and never again. That asymmetry is why an app could not\n// give its tokens an expiry that meant anything: the verifier seam is\n// perfectly able to say a token has died (return null), but on a live socket\n// nobody was listening for the answer.\n//\n// It also failed in a shape worth naming. The server shell's own wire rides\n// the HTTP middleware carrying the session's token, so an expired credential\n// used to leave the socket open and cheerful — frames flowing, screen alive —\n// while every endpoint the shell called came back 401. A live interface whose\n// every load silently fails is strictly worse than a lock screen.\n//\n// The recovery for this already existed and is untouched: a `4401` close is a\n// recovery, not a retry, and the terminal drops its token and reconnects\n// anonymous onto the served lock screen. All that was missing was something\n// asking the question. This is that.\nexport const DEFAULT_REVALIDATE_MS = 60 * 1000;\n\n// One accept per new connection: authenticate (the token rides the upgrade\n// URL — browsers cannot set websocket headers; absent = the anonymous\n// principal, invalid = closed with 4401), then say hello with the resolved\n// catalog and settle into the message loop. `stop` ends revalidation, for\n// hosts that outlive their server (dev checks, embedded tools) — the timer is\n// unref'd, so a plain process needn't call it.\nexport type SocketAccept = ((url: string, connection: Connection) => Promise<void>) & { stop: () => void };\n\nconst parse = (text: string): Record<string, unknown> | null => {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport const createSocket = (ctx: SocketContext): SocketAccept => {\n const emit = emitterOf(ctx.telemetry);\n let saidNotOwn = false;\n // Every live connection, with the credential it authenticated under (null =\n // anonymous, which has nothing that can expire). One structure: the future\n // catalog-push fan-out wants the keys, revalidation wants the values.\n const live = new Map<Connection, { token: string; principal: string } | null>();\n\n const expire = (connection: Connection): void => {\n // Diagnostics before authority, as at upgrade — the close code is what\n // the terminal acts on; this is what a person reads in a log.\n connection.send(JSON.stringify({ type: 'error', code: 'invalid_token', message: 'The session token no longer resolves to this principal.' } satisfies ServerMessage));\n connection.close(CLOSE_INVALID_TOKEN, 'session expired');\n live.delete(connection);\n };\n\n const revalidate = async (): Promise<void> => {\n for (const [connection, credential] of [...live]) {\n if (credential === null) continue; // anonymous — nothing to expire\n let resolved: string | null;\n try {\n resolved = await ctx.session(credential.token);\n } catch {\n // The verifier is unreachable — a database blip, a network hiccup.\n // That is not evidence a session ended, and signing everybody out on\n // it would turn a transient fault into an outage. Ask again next pass.\n continue;\n }\n // Unchanged is the overwhelmingly common answer. A token that stops\n // resolving has expired or been revoked; one that resolves to somebody\n // ELSE is not the session that attached, and both are the same close.\n if (resolved === credential.principal) continue;\n if (!live.has(connection)) continue; // it closed while we were awaiting\n expire(connection);\n }\n };\n\n const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;\n let sweeper: ReturnType<typeof setInterval> | undefined;\n if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {\n sweeper = setInterval(() => void revalidate(), revalidateMs);\n // Revalidation must never be the reason a process stays alive.\n (sweeper as unknown as { unref?: () => void }).unref?.();\n }\n\n // REFUSING ONE SESSION MUST NEVER COST THE OTHERS. Every await in the body\n // below can throw — the verifier on a database blip, the shell build on a\n // definition that fails validation — and the runtime transport calls accept\n // without awaiting it, so an escaped rejection is an unhandled one and Node\n // kills the whole process: one bad definition, every session on the box\n // disconnected. So accept NEVER rejects. A failure to open this session is\n // answered to this terminal — a sentence naming the failing definitions\n // when there are any, then a 4500 close — and logged where somebody can\n // read it. The durable map is only written after a successful build, so a\n // refused terminal poisons nothing: the next connect builds fresh.\n const accept = async (url: string, connection: Connection): Promise<void> => {\n const send = (message: ServerMessage): void => connection.send(JSON.stringify(message));\n try {\n await open(url, connection, send);\n } catch (error) {\n console.error('[moss/socket] refused a session:', error);\n live.delete(connection);\n const failures =\n error instanceof DefinitionValidationError\n ? ((error.context as { failures?: { id: string }[] } | undefined)?.failures ?? []).map((f) => f.id)\n : [];\n const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(', ')}` : String(error);\n try {\n send({ type: 'error', code: 'session_failed', message: `This session could not be opened — ${detail}. The refusal is this terminal's alone; the server is up.` });\n connection.close(CLOSE_SHELL_FAILED, 'session failed');\n } catch {\n // The transport is already gone — there is nobody left to tell.\n }\n }\n };\n\n const open = async (url: string, connection: Connection, send: (message: ServerMessage) => void): Promise<void> => {\n // One clock stamped at the handshake serves both the short `socket.upgrade`\n // span and the whole-connection `socket.close` span from the same origin.\n const upClock = emit === undefined ? undefined : spanClock();\n const params = new URL(url, 'http://nisc.local').searchParams;\n const spoken = Number(params.get('protocol') ?? '1');\n if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {\n const behind = spoken > PROTOCOL ? 'server' : 'client';\n send({\n type: 'error',\n code: `${behind}_too_old`,\n message: `This terminal speaks protocol ${params.get('protocol') ?? '1'}; this server speaks ${PROTOCOL_MIN}–${PROTOCOL}. ${behind === 'client' ? 'Reload the terminal to get the current build.' : 'The server has not been updated yet.'}`,\n });\n connection.close(CLOSE_PROTOCOL_MISMATCH, 'protocol mismatch');\n return;\n }\n const upgrade = connection.upgrade;\n // THE APP'S OWN PAGE does not hold its session: its browser does, in a\n // cookie the page cannot read (session-cookie.ts), and sent it with this\n // request. From any other origin the cookie is not looked at — a browser\n // sends it with a stranger's page all the same. `key` is which of the\n // browser's sessions this terminal is (a seat); a name, not a secret.\n const key = /^[\\w.-]{1,64}$/.test(params.get('key') ?? '') ? (params.get('key') as string) : DEFAULT_TOKEN_KEY;\n const page = upgrade !== undefined && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : undefined;\n const secure = page?.protocol === 'https:';\n const held = page === undefined ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);\n // A SIGN-IN OVER THE SOCKET REACHES THAT COOKIE SEALED. A terminal whose\n // browser can keep a session says so (`sealed=1`), and its browser is given\n // a seal — a key in a second cookie no script can read — by the answer to\n // its first upgrade. A sign-in is then handed to the page sealed with it;\n // the page offers it back here, and only this browser's seal opens it.\n const sealing = page !== undefined && params.get('sealed') === '1';\n // A browser terminal that is not on the app's own page works as it always\n // did, holding its own token — which is right for a page served from\n // somewhere else, and is what a proxy that rewrites `Host` looks like too.\n // Said once: nothing else would tell a deployment it is in the second case.\n if (page === undefined && params.get('sealed') === '1' && typeof upgrade?.origin === 'string' && !saidNotOwn) {\n saidNotOwn = true;\n console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? 'nothing'}, so that is not the app’s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);\n }\n const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;\n const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;\n // A sealed sign-in that came back with no seal to open it: this browser\n // does not keep the cookie, and is not handed another sign-in that way.\n const sealLost = sealing && sealedOffer !== null && hadSeal === null;\n const seal = !sealing || sealLost ? null : (hadSeal ?? (upgrade?.answer === undefined ? null : newSeal()));\n const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));\n // A token the terminal offers comes first. `leave`: it was signed out, and\n // says so because what its browser holds may be a token that still\n // resolves — an app's own provider's is not moss's to revoke.\n let token = offered ?? (params.get('leave') === '1' ? null : (held?.token ?? null));\n let principal = token === null ? null : await ctx.session(token);\n if (offered !== null && principal === null) {\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'refused', attributes: { hasPrincipal: false } });\n }\n send({ type: 'error', code: 'invalid_token', message: 'The session token did not resolve to a principal.' });\n connection.close(CLOSE_INVALID_TOKEN, 'invalid token');\n return;\n }\n // What the browser held and no longer resolves is nobody — not a refusal:\n // the page cannot read it to drop it, so a 4401 would be one it could\n // never stop getting.\n if (principal === null) token = null;\n // THE ANSWER makes the browser hold who this turned out to be. A token the\n // page offered — left in storage by an earlier build, or just handed to it\n // at sign-in — is moved into the cookie, and that was the last time the\n // page held it; a session that ended is taken back. An offered token is\n // written even when the browser sent the same one: over plain http on the\n // default port the copy an earlier build kept, readable by script, has\n // this cookie's name.\n const answered = [\n ...(page === undefined || (offered === null && (held?.token ?? null) === token) ? [] : token === null ? (held?.clear ?? []) : sessionCookies(page.origin, token, { key, lastsMs: (await ctx.sessionLastsMs?.(token)) ?? null })),\n ...(seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, 'http://nisc.local').pathname })] : []),\n ];\n if (answered.length > 0) upgrade?.answer?.(answered);\n if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);\n // The terminal is told, and stops asking to be handed sign-ins sealed —\n // the next one reaches it as a token, on this connection already.\n if (sealLost) {\n send({ type: 'error', code: 'seal_not_kept', message: 'This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token.' });\n }\n\n // Remembered WITH its credential — revalidation has to re-ask the same\n // question this connection was admitted on, and the token is not\n // recoverable from anything else here.\n live.set(connection, token !== null && token !== '' && principal !== null ? { token, principal } : null);\n connection.onClose(() => live.delete(connection));\n // The connection's whole life, closed by the same clock — how long\n // terminals stay, and under a principal or anonymous. Registered here so it\n // fires however the connection ends (graceful, expiry, transport drop).\n if (emit !== undefined && upClock !== undefined) {\n const hadPrincipal = principal !== null;\n connection.onClose(() => emit({ name: 'socket.close', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: hadPrincipal } }));\n }\n\n // The catalog channel: the application, resolved for YOU, on every\n // (re)connect — reconnect re-sends current state, no replay machinery.\n const { ids, hash } = await ctx.catalog(principal);\n send({ type: 'hello', protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });\n\n // The canvas streams: attach to the session's shell (durable per\n // principal — the shell outlives this connection) and it re-sends the\n // current trees; every change fans out to every attached connection.\n // Frame deltas are OPT-IN by the terminal, on the upgrade URL beside the\n // token — browsers cannot set websocket headers, and the capability has to\n // be known before the first frame is sent. A terminal that says nothing is\n // served whole frames forever, which is what every terminal built before\n // this existed does.\n const wantsDelta = params.get('delta') === '1';\n\n // An anonymous terminal whose page was rendered server-side names the id\n // seed that page's shell was built under, so this connection's throwaway\n // shell mints the same instance ids and its first frames match the page.\n // Shape-checked, never trusted further: it only ever names ids inside the\n // caller's own shell.\n const named = params.get('seed');\n const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : undefined;\n\n // The path the terminal is on decides which shell it is served: a page's,\n // built for this connection alone, or the app's.\n const path = params.get('path');\n const route = path === null ? undefined : ctx.page?.(path);\n const host = route?.host ?? ctx.shells;\n\n const session = await host?.session(token, principal, { ...(seed === undefined ? {} : { seed }), ...(route === undefined ? {} : { inputs: route.inputs }) });\n if (session !== undefined) {\n session.attach(connection, { delta: wantsDelta });\n connection.onClose(() => session.detach(connection));\n }\n\n // Admitted: the handshake resolved a principal, said hello, and attached a\n // shell. The span measures that, not the connection's life (that is\n // `socket.close`).\n if (emit !== undefined && upClock !== undefined) {\n emit({ name: 'socket.upgrade', startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: 'ok', attributes: { hasPrincipal: principal !== null } });\n }\n\n connection.onMessage((text) => {\n const message = parse(text);\n // Reset first, and answered on its own terms: a wedged session is\n // exactly the one whose other paths cannot be trusted to run.\n if (message !== null && message['type'] === 'reset') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.reset();\n return;\n }\n // Resync before the ordinary paths, for the reason reset is: a terminal\n // asking for this has already decided it cannot trust what it is holding.\n if (message !== null && message['type'] === 'resync') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.resync(connection);\n return;\n }\n if (message !== null && message['type'] === 'back') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.back();\n return;\n }\n if (\n message !== null &&\n message['type'] === 'popTo' &&\n typeof message['canvas'] === 'string' &&\n typeof message['instance'] === 'string'\n ) {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.popTo(message['canvas'], message['instance']);\n return;\n }\n if (message !== null && message['type'] === 'publish' && typeof message['channel'] === 'string') {\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.' });\n return;\n }\n session.publish(message['channel'], message['payload']);\n return;\n }\n if (message === null || message['type'] !== 'event' || typeof message['canvas'] !== 'string') {\n send({ type: 'error', code: 'invalid_message', message: 'Messages are JSON { type: \"event\", canvas, event }.' });\n return;\n }\n if (session === undefined) {\n send({ type: 'error', code: 'no_shell', message: 'This app serves no shell.', canvas: message['canvas'] });\n return;\n }\n const event = message['event'];\n if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n send({ type: 'error', code: 'invalid_message', message: 'The event field must be a NovaEvent object.', canvas: message['canvas'] });\n return;\n }\n session.dispatch(message['canvas'], event as Record<string, unknown>);\n });\n };\n\n return Object.assign(accept, {\n stop: () => {\n if (sweeper !== undefined) clearInterval(sweeper);\n sweeper = undefined;\n },\n });\n};\n","// Frame deltas — send what changed, not the frame.\n//\n// A shell re-sends a whole canvas tree whenever that tree changes. Most changes\n// are small against a large tree (a keystroke filters a list, one badge flips),\n// so the new frame is mostly a rearrangement of bytes the client already holds.\n//\n// This encodes the new frame as COPY runs from the old one plus literal\n// inserts. It is deliberately not a structural diff over the tree: a\n// navigation produces a genuinely different tree, and a path-based diff then\n// costs MORE than the frame it replaces, while a byte matcher still finds the\n// shared vocabulary. It is also not zlib's preset dictionary, which would be\n// two lines here and does not exist in a browser.\n//\n// No dependency, both directions in one file, and small enough to read in\n// full — a delta layer that cannot be audited is a desync you cannot diagnose.\n\n/** A run copied from the base frame: offset, length. */\ntype Copy = [0, number, number];\n/** Bytes that are not in the base at all. */\ntype Insert = [1, string];\nexport type DeltaOp = Copy | Insert;\n\n// Matches shorter than this cost more to describe than to inline. 16 is a\n// compromise: low enough to catch a changed cell inside a row, high enough that\n// the index does not match noise.\nconst BLOCK = 16;\n\n/**\n * Encode `target` as operations against `base`.\n *\n * Greedy and single-pass: at each position look for a block that already exists\n * in the base, extend the match as far as it runs, and emit a copy. Anything\n * unmatched accumulates into a literal. Not optimal — an optimal encoder needs\n * a suffix automaton — but it captures the long shared runs that dominate a\n * render tree, which is where the bytes are.\n */\nexport const encodeDelta = (base: string, target: string): DeltaOp[] => {\n if (base.length < BLOCK) return [[1, target]];\n\n const index = new Map<string, number>();\n for (let i = 0; i + BLOCK <= base.length; i += 1) {\n // First position wins: earlier offsets tend to extend further in a tree\n // whose head is stable chrome.\n const key = base.slice(i, i + BLOCK);\n if (!index.has(key)) index.set(key, i);\n }\n\n const ops: DeltaOp[] = [];\n let literal = '';\n let at = 0;\n\n while (at < target.length) {\n const key = target.slice(at, at + BLOCK);\n const found = key.length === BLOCK ? index.get(key) : undefined;\n if (found === undefined) {\n literal += target[at];\n at += 1;\n continue;\n }\n let length = BLOCK;\n while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {\n length += 1;\n }\n if (literal !== '') {\n ops.push([1, literal]);\n literal = '';\n }\n ops.push([0, found, length]);\n at += length;\n }\n if (literal !== '') ops.push([1, literal]);\n return ops;\n};\n\n/** Rebuild the frame. Throws on a malformed op rather than returning a\n * half-applied string — a silently wrong frame is the failure this whole\n * layer has to not have. */\nexport const applyDelta = (base: string, ops: readonly DeltaOp[]): string => {\n let out = '';\n for (const op of ops) {\n if (op[0] === 1) {\n out += op[1];\n continue;\n }\n const [, offset, length] = op;\n if (offset < 0 || length < 0 || offset + length > base.length) {\n throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);\n }\n out += base.slice(offset, offset + length);\n }\n return out;\n};\n\n/**\n * A cheap, order-sensitive checksum of a frame.\n *\n * Carried on every delta so a client can prove it rebuilt the frame the server\n * meant. A delta protocol without this is one dropped message away from a\n * client that is permanently and silently wrong, with no error anywhere — which\n * is strictly worse than sending whole frames forever.\n */\nexport const frameHash = (text: string): number => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i += 1) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n","import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN, offerToken } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\nimport { heldCookieName } from '../session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n // A host whose BROWSER may keep the session itself, in a cookie the page\n // cannot read (../session-cookie.ts): whether it does, right now. Asked\n // after an upgrade is answered — if it does, the wire lets go of the token\n // it offered and nothing is stored; if not, the token is stored as ever. A\n // host without this (a process) always keeps its own.\n held?: () => boolean;\n // Which of the browser's sessions this terminal is, when not the default one\n // — a seat. Named in the socket's address; it is the cookie's name.\n key?: string;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // Construct a socket for this url, offering these subprotocols —\n // `new WebSocket(url, offered)` in every host. What is offered is who the\n // terminal is (socket.ts): a host that drops it connects as nobody.\n socket: (upgrade: { url: string; offered: string[] }) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: url derived from location, the page's WebSocket, and the\n// session wherever this page can have it kept.\n//\n// SERVED BY THE APP IT TALKS TO, the page does not keep it: the browser does,\n// in a cookie the page cannot read, which the server writes in its answer to\n// the upgrade (../session-cookie.ts). `held` is all the page sees of it. A\n// token this page is handed is offered once and let go of; nothing is stored.\n//\n// ANYWHERE ELSE — another origin, a browser that refuses cookies — the token\n// is in localStorage, as it always was. The try/catches keep a storage-less\n// context (private mode, sandboxed iframe) alive: the session then lives for\n// this page only.\n//\n// `cookie` did one thing — keep a script-readable copy of the token for the\n// server to draw the page from — and is no longer needed: the page is drawn\n// from the browser's own cookie. It is accepted and does nothing.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n return {\n tokens: {\n load: () => {\n try {\n return window.localStorage.getItem(tokenKey);\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n // the copy an earlier build kept beside it, where script could read it\n try {\n document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === 'https:' ? '; Secure' : ''}`;\n } catch {\n /* no document, or cookies refused */\n }\n },\n held: () => {\n try {\n return document.cookie.split('; ').includes(`${heldCookieName(tokenKey, window.location.port)}=1`);\n } catch {\n return false;\n }\n },\n ...(config.tokenKey !== undefined ? { key: tokenKey } : {}),\n },\n socket: ({ url, offered }) => new WebSocket(url, offered),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in (holding a token, or its browser a session), or neither.\n // Anything else is somebody else's screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n // Signed out, and not yet heard by the server: the next upgrade says so,\n // because what the browser holds may be a token that still resolves.\n let leaving = false;\n // A sign-in handed to this terminal SEALED: its browser keeps the session,\n // so the page is given something it can carry to the next upgrade and cannot\n // open. Offered until an upgrade is answered. `unsealed`: this browser turned\n // out not to keep the cookie that opens one, so the terminal stops asking.\n let sealed: string | null = null;\n let unsealed = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n // The address says nothing about who this is — it is what every proxy on\n // the way writes down. The token is offered with the socket, below.\n const params: string[] = [`protocol=${PROTOCOL}`];\n if (env.tokens.key !== undefined) params.push(`key=${encodeURIComponent(env.tokens.key)}`);\n if (leaving) params.push('leave=1');\n if (env.tokens.held !== undefined && !unsealed) params.push('sealed=1');\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket({ url: `${url()}?${params.join('&')}`, offered: offerToken(token, sealed) });\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n sealed?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'session' && typeof data.sealed === 'string') {\n // The same, for a terminal whose browser keeps the session: nothing\n // this page can read — it is carried to the next upgrade as it is.\n become(null, data.sealed);\n } else if (data.type === 'error') {\n if (data.code === 'seal_not_kept') unsealed = true;\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type === 'hello') {\n // The upgrade has been answered, so a browser that keeps the session\n // itself now does: the token this terminal offered is let go of, and\n // the page holds it no longer. One that does not (another origin,\n // cookies refused) leaves it with the terminal, stored as it always was.\n leaving = false;\n sealed = null;\n if (token !== null && env.tokens.held !== undefined) {\n if (env.tokens.held()) {\n env.tokens.clear();\n token = null;\n } else env.tokens.save(token);\n }\n } else if (data.type !== 'catalog') {\n // catalog is known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n leaving = e.code === CLOSE_SIGNED_OUT;\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect. A host whose browser may\n // keep the session stores nothing yet: the token is offered, and what\n // becomes of it is settled when the upgrade is answered (`hello`, above).\n const become = (next: string | null, handedSealed: string | null = null): void => {\n // whatever was being offered sealed is over: taken, or refused\n sealed = handedSealed;\n if (handedSealed !== null) {\n /* nothing this page can read, so nothing to store */\n } else if (next === null) env.tokens.clear();\n else if (env.tokens.held === undefined) env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n","// ═══════════════════════════════════════════════════════════════\n// The live-swap hotkey — isolated here because it is the one imperative,\n// gimmicky corner of the terminal (a render target is not app state, so it\n// can't be a nova action; it's client chrome). Keyed on `event.key`, the\n// CHARACTER the key produces, so a combo matches the key the user actually\n// presses on any layout — `event.code` would bind a physical QWERTY position\n// (the key labelled Y sits elsewhere on QWERTZ/AZERTY). Use letter keys, not\n// punctuation, so Shift never remaps the character.\n// ═══════════════════════════════════════════════════════════════\n\nexport type HotkeyDisposer = () => void;\n\n// Attach `handler` to a keydown matching `spec` (e.g. \"ctrl+shift+y\"); returns\n// a disposer. Matches modifiers exactly, so \"ctrl+shift+y\" never fires on\n// \"ctrl+shift+alt+y\".\nexport const onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n","// ═══════════════════════════════════════════════════════════════\n// The browser's back button, caught.\n//\n// ⟲ IT USED TO UNLOAD THE APPLICATION. A moss terminal never touched the URL,\n// so a tab held exactly one history entry and back meant \"leave the page\" —\n// the socket dropped, the shell went unattended, and somebody who wanted to\n// close a screen got a blank tab instead. Nothing was lost (the shell is\n// durable, keyed by principal, and a reload reattaches to it) but nobody\n// pressing back is thinking about that.\n//\n// What it does instead: keep ONE spare history entry ahead of the page and\n// spend it on every press. Back consumes the spare, this puts another one\n// straight back, and the gesture is handed to the terminal — which sends it up\n// the wire, where the shell that owns the navigation decides what back means.\n//\n// The URL never changes. That is the honest position while location lives on\n// the SERVER: the shell is keyed by principal, not by tab, so an address bar\n// would be a per-tab claim on state two tabs share. When deep links arrive they\n// arrive as a projection of the shell's own location, and this file is where\n// the gesture will already be.\n// ═══════════════════════════════════════════════════════════════\n\nexport type BackTrapDisposer = () => void;\n\n// Marks the entry as ours, so a host that keeps its own history state can tell\n// this one apart. Nothing reads it yet; a debugger looking at `history.state`\n// deserves to find a name rather than an empty object.\nconst SENTINEL = { nisc: 'terminal-back' } as const;\n\n// Catch the host's back gesture and call `handler` instead of letting the page\n// unload. A no-op (and a disposer that does nothing) wherever there is no\n// history to trap — a TTY, a TUI, a plain process — so the conductor can ask\n// for it unconditionally.\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n const history = window.history as History | undefined;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n // The spare. `pushState` with no url keeps the current address, so this adds\n // an entry without changing what the address bar says or asking the server\n // for anything.\n const spare = (): void => {\n try {\n history.pushState(SENTINEL, '');\n } catch {\n // A sandboxed document can refuse this. Back then behaves as it always\n // did rather than throwing on the way out of a keypress.\n }\n };\n\n const onPopState = (): void => {\n // One entry was just spent — replace it, then act. In that order: the\n // handler sends a message up the wire and the answer arrives on another\n // tick, and the history has to be whole before the next press, not after.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays. It cannot be removed without navigating, and one\n // dead entry is a far smaller surprise than a navigation nobody asked for.\n };\n};\n","import { createHeadKeeper, headOf } from '@niscorp/nova/document';\nimport type { TerminalApi } from './index';\n\n// ═══════════════════════════════════════════════════════════════\n// The page's <head>, kept on the screen.\n//\n// A drawn page arrives with its head written (../document). From then on the\n// screen moves over the wire and the page is never fetched again, so the head\n// is read off the trees the wire holds, whenever they change: the elements the\n// screen's head holds go into the page's, and the page's own tags give way to\n// them and come back (nova's head keeper).\n//\n// Terminal chrome, like the back trap beside it: the head is the terminal's\n// relationship to the surface it is painted on, the same for every render\n// target, and the app authors nothing to keep it. Where there is no document\n// (a TTY, a TUI) there is no head, and this does nothing.\n// ═══════════════════════════════════════════════════════════════\n\nexport const followHead = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createHeadKeeper(document);\n const read = (): void => keep(headOf(api)?.elements);\n read();\n return subscribe(read);\n};\n","import type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire } from '../client';\nimport { onHotkey } from './hotkey';\nimport { trapBack } from './history';\nimport { followHead } from './head';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/moss/terminal — the terminal, owned by the protocol that defines\n// it. A terminal is the wire (../client) plus a RENDER TARGET (react, dom,\n// console, …) painting the wire's snapshot and sending events back. This\n// module is framework-blind: the conductor drives one target against the\n// wire; the switcher cycles targets on a hotkey, sharing one wire so the\n// session survives the swap. Targets live in the subpaths (./react, ./dom);\n// the framework-shaped code stays there, never here.\n// ═══════════════════════════════════════════════════════════════\n\n// What a target renders against — nova core's `RenderApi`: the wire's snapshot\n// as pull functions (frame + per-canvas trees) plus the event sinks (dispatch\n// tagged by canvas, publish). Aliased, not redeclared — the dom adapter, the\n// react adapter, and this conductor share ONE contract, so a target written\n// for nova's dom view drops straight onto the wire. A target never touches the\n// wire directly.\nexport type TerminalApi = RenderApi;\n\n// A mounted target: re-render on demand, tear down on swap.\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\n// A render target: paint the api onto the target's own surface, return the\n// mount handle. The surface — a DOM root, a stdio pair — is construction\n// config on the concrete target (`reactTarget({ root, … })`, `domTarget({\n// root })`), never part of this contract: the conductor stays surface-blind\n// and runs anywhere the wire does. A target renders once on mount; the\n// conductor calls `update` on every wire change.\nexport type Target = (api: TerminalApi) => TerminalMount;\n\n// The conductor: one target, one wire. Subscribes the target's `update` to\n// the wire and routes events back. Nothing framework-shaped.\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopHead = followHead(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopHead();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n // render targets by name; the hotkey cycles them in insertion order\n targets: Record<string, Target>;\n // e.g. \"ctrl+shift+t\" — the live render-target swap. Omit for no swapping.\n swapKey?: string;\n // e.g. \"ctrl+shift+r\" — ask the server for a fresh shell. Omit for no key.\n //\n // The one control that must work when nothing else does. It sits on a\n // keystroke for the same reason the swap does — it acts on the terminal's\n // relationship to the server, not on anything the app models — but the\n // reason it exists at all is stronger: a shell lives on the SERVER, keyed by\n // principal, so a broken one survives every gesture a client can make alone.\n // Reloading reattaches to it. Clearing the token and signing back in\n // reattaches to it. Without a key that says \"throw it away\", somebody\n // watching a dead screen has no move left.\n resetKey?: string;\n // Catch the host's BACK gesture — the browser's back button — and send it up\n // the wire instead of letting it unload the page. Default: on, wherever a\n // history exists to catch (see ./history); nothing at all in a TTY or a TUI.\n //\n // Terminal chrome for the same reason the swap and reset keys are: back is\n // the terminal's relationship to the surface it is painted on, and the app\n // authors nothing to receive it. What back MEANS is decided a layer up, by\n // the shell that owns the navigation.\n trapBack?: boolean;\n // which target to mount first (default: the first key)\n initial?: string;\n // inject an existing wire (shared across swaps), or let the terminal make\n // one — `url` seeds a self-made wire (default: /socket on the host).\n wire?: Wire;\n url?: string;\n};\n\n// The switcher: mount a terminal that can hot-swap its render target on a\n// keystroke, over ONE wire (created here unless injected) so the socket,\n// session, and current trees survive the swap. The hotkey is the one legit\n// piece of imperative client chrome — a render target is not app state, so\n// it is not a nova action; it lives here, in the terminal.\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n // All three are returned so a host can bind its own control (a button, a\n // console call) — the keys and the trap are a convenience, not the only way in.\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/terminal/history.ts","../../src/terminal/index.ts"],"names":["createHeadKeeper","headOf","createWire"],"mappings":";;;;;;;AAEA,IAAM,gBAAA,GAAmB,EAAE,IAAA,EAAM,eAAA,EAAgB;AAE1C,IAAM,QAAA,GAAW,CAAC,OAAA,KAA0C;AACjE,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,MAAM,MAAA;AAEhD,EAAA,MAAM,UAA+B,MAAA,CAAO,OAAA;AAC5C,EAAA,IAAI,YAAY,MAAA,IAAa,OAAO,QAAQ,SAAA,KAAc,UAAA,SAAmB,MAAM,MAAA;AAEnF,EAAA,MAAM,QAAQ,MAAY;AACxB,IAAA,IAAI;AACF,MAAA,OAAA,CAAQ,SAAA,CAAU,kBAAkB,EAAE,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,aAAa,MAAY;AAE7B,IAAA,KAAA,EAAM;AACN,IAAA,OAAA,EAAQ;AAAA,EACV,CAAA;AAEA,EAAA,KAAA,EAAM;AACN,EAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAC9C,EAAA,OAAO,MAAM;AACX,IAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AAAA,EAEnD,CAAA;AACF,CAAA;;;ACtBA,IAAM,QAAA,GAAW,CAAC,IAAA,EAAc,OAAA,K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AAA,GAAkB,OAAO,QAAA,KAAa,MAAA,GAAY,SAAY,QAAA,CAAS,MAAA,CAAO,UAAU,KAAK,CAAA;AACnG,EAAA,MAAM,kBAAkB,MAAA,CAAO,QAAA,KAAa,KAAA,GAAQ,MAAA,GAAY,SAAS,IAAI,CAAA;AAE7E,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,cAAA,IAAiB;AACjB,MAAA,eAAA,IAAkB;AAClB,MAAA,eAAA,IAAkB;AAClB,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,IAAI,QAAA,OAAe,OAAA,EAAQ;AAAA,IAC7B;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["export type BackTrapDisposer = () => void;\n\nconst BACK_ENTRY_STATE = { nisc: 'terminal-back' } as const;\n\nexport const trapBack = (handler: () => void): BackTrapDisposer => {\n if (typeof window === 'undefined') return () => undefined;\n // A window stood up outside a browser may have no history, whatever its type says.\n const history: History | undefined = window.history;\n if (history === undefined || typeof history.pushState !== 'function') return () => undefined;\n\n const spare = (): void => {\n try {\n history.pushState(BACK_ENTRY_STATE, '');\n } catch {\n // A sandboxed document can refuse: back then keeps the browser's default.\n }\n };\n\n const onPopState = (): void => {\n // Before the handler: its answer comes on a later tick, and the next press needs the spare.\n spare();\n handler();\n };\n\n spare();\n window.addEventListener('popstate', onPopState);\n return () => {\n window.removeEventListener('popstate', onPopState);\n // The spare entry stays: it cannot be removed without navigating.\n };\n};\n","import { createHeadKeeper, headOf } from '@niscorp/nova/document';\nimport type { RenderApi } from '@niscorp/nova';\nimport { createWire } from '../client';\nimport type { Wire, WireStatus } from '../client';\nimport { trapBack } from './history';\n\ntype HotkeyDisposer = () => void;\n\nconst onHotkey = (spec: string, handler: () => void): HotkeyDisposer => {\n const parts = spec.toLowerCase().split('+');\n const key = parts[parts.length - 1] ?? '';\n const mods = new Set(parts.slice(0, -1));\n // event.key, not event.code: the character the key produces, wherever the layout puts it.\n const listener = (event: KeyboardEvent): void => {\n if (\n event.key.toLowerCase() === key &&\n event.ctrlKey === mods.has('ctrl') &&\n event.shiftKey === mods.has('shift') &&\n event.altKey === mods.has('alt') &&\n event.metaKey === (mods.has('meta') || mods.has('cmd'))\n ) {\n event.preventDefault();\n handler();\n }\n };\n window.addEventListener('keydown', listener);\n return () => window.removeEventListener('keydown', listener);\n};\n\nconst followHead = (api: TerminalApi, subscribe: (listener: () => void) => () => void): (() => void) => {\n if (typeof document === 'undefined') return () => undefined;\n const keep = createHeadKeeper(document);\n const read = (): void => keep(headOf(api)?.elements);\n read();\n return subscribe(read);\n};\n\nexport type TerminalApi = RenderApi & { status: () => WireStatus };\n\nexport type TerminalMount = { update: () => void; destroy: () => void };\n\nexport type Target = (api: TerminalApi) => TerminalMount;\n\nexport const createTerminal = (config: { target: Target; wire: Wire }): { destroy: () => void } => {\n const { target, wire } = config;\n const api: TerminalApi = {\n frame: () => wire.snapshot().frame,\n canvasTree: (id) => wire.snapshot().trees.get(id) ?? [],\n dispatch: (id, event) => wire.dispatch(id, event),\n publish: (channel, payload) => wire.publish(channel, payload),\n status: () => wire.status(),\n };\n const mount = target(api);\n const unsubscribe = wire.subscribe(mount.update);\n const stopHead = followHead(api, wire.subscribe);\n return {\n destroy: () => {\n unsubscribe();\n stopHead();\n mount.destroy();\n },\n };\n};\n\nexport type MountTerminalConfig = {\n targets: Record<string, Target>;\n swapKey?: string;\n resetKey?: string;\n trapBack?: boolean;\n initial?: string;\n wire?: Wire;\n url?: string;\n};\n\nexport const mountTerminal = (config: MountTerminalConfig): { swap: () => void; reset: () => void; back: () => void; destroy: () => void } => {\n const keys = Object.keys(config.targets);\n if (keys.length === 0) throw new Error('mountTerminal: at least one target is required');\n\n const ownsWire = config.wire === undefined;\n const wire = config.wire ?? createWire(config.url !== undefined ? { url: config.url } : {});\n\n const targetAt = (i: number): Target => {\n const key = keys[i];\n const target = key === undefined ? undefined : config.targets[key];\n if (target === undefined) throw new Error(`mountTerminal: no target at index ${i}`);\n return target;\n };\n\n const start = config.initial === undefined ? 0 : keys.indexOf(config.initial);\n let index = start < 0 ? 0 : start;\n let active = createTerminal({ target: targetAt(index), wire });\n\n const swap = (): void => {\n active.destroy();\n index = (index + 1) % keys.length;\n active = createTerminal({ target: targetAt(index), wire });\n };\n\n const reset = (): void => wire.reset();\n const back = (): void => wire.back();\n\n const disposeSwapKey = config.swapKey === undefined ? undefined : onHotkey(config.swapKey, swap);\n const disposeResetKey = config.resetKey === undefined ? undefined : onHotkey(config.resetKey, reset);\n const disposeBackTrap = config.trapBack === false ? undefined : trapBack(back);\n\n return {\n swap,\n reset,\n back,\n destroy: () => {\n disposeSwapKey?.();\n disposeResetKey?.();\n disposeBackTrap?.();\n active.destroy();\n if (ownsWire) wire.dispose();\n },\n };\n};\n"]}