@niscorp/moss 0.1.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 (96) hide show
  1. package/DESIGN.md +592 -0
  2. package/DOCS.md +943 -0
  3. package/LICENSE +202 -0
  4. package/README.md +155 -0
  5. package/dist/chunk-2AHJ6VDR.js +3314 -0
  6. package/dist/chunk-2AHJ6VDR.js.map +1 -0
  7. package/dist/chunk-EMRDIZLY.js +99 -0
  8. package/dist/chunk-EMRDIZLY.js.map +1 -0
  9. package/dist/chunk-HF6IGQ74.js +3342 -0
  10. package/dist/chunk-HF6IGQ74.js.map +1 -0
  11. package/dist/chunk-J72N3EMJ.js +238 -0
  12. package/dist/chunk-J72N3EMJ.js.map +1 -0
  13. package/dist/chunk-SK4PDGEE.js +55 -0
  14. package/dist/chunk-SK4PDGEE.js.map +1 -0
  15. package/dist/chunk-ZOEUEMDX.js +251 -0
  16. package/dist/chunk-ZOEUEMDX.js.map +1 -0
  17. package/dist/client/node.cjs +42 -0
  18. package/dist/client/node.cjs.map +1 -0
  19. package/dist/client/node.d.cts +9 -0
  20. package/dist/client/node.d.ts +9 -0
  21. package/dist/client/node.js +40 -0
  22. package/dist/client/node.js.map +1 -0
  23. package/dist/client.cjs +275 -0
  24. package/dist/client.cjs.map +1 -0
  25. package/dist/client.d.cts +52 -0
  26. package/dist/client.d.ts +52 -0
  27. package/dist/client.js +4 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/document-BEn2zXah.d.cts +993 -0
  30. package/dist/document-BEn2zXah.d.ts +993 -0
  31. package/dist/index.cjs +3716 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +104 -0
  34. package/dist/index.d.ts +104 -0
  35. package/dist/index.js +96 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/node.cjs +3309 -0
  38. package/dist/node.cjs.map +1 -0
  39. package/dist/node.d.cts +28 -0
  40. package/dist/node.d.ts +28 -0
  41. package/dist/node.js +64 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/slots-Do9ScG7v.d.cts +37 -0
  44. package/dist/slots-Do9ScG7v.d.ts +37 -0
  45. package/dist/terminal/dom/index.cjs +34 -0
  46. package/dist/terminal/dom/index.cjs.map +1 -0
  47. package/dist/terminal/dom/index.d.cts +11 -0
  48. package/dist/terminal/dom/index.d.ts +11 -0
  49. package/dist/terminal/dom/index.js +32 -0
  50. package/dist/terminal/dom/index.js.map +1 -0
  51. package/dist/terminal/dom/server.cjs +16 -0
  52. package/dist/terminal/dom/server.cjs.map +1 -0
  53. package/dist/terminal/dom/server.d.cts +14 -0
  54. package/dist/terminal/dom/server.d.ts +14 -0
  55. package/dist/terminal/dom/server.js +14 -0
  56. package/dist/terminal/dom/server.js.map +1 -0
  57. package/dist/terminal/index.cjs +346 -0
  58. package/dist/terminal/index.cjs.map +1 -0
  59. package/dist/terminal/index.d.cts +32 -0
  60. package/dist/terminal/index.d.ts +32 -0
  61. package/dist/terminal/index.js +100 -0
  62. package/dist/terminal/index.js.map +1 -0
  63. package/dist/terminal/ink/index.d.ts +33 -0
  64. package/dist/terminal/ink/index.js +189 -0
  65. package/dist/terminal/ink/index.js.map +1 -0
  66. package/dist/terminal/react/index.cjs +87 -0
  67. package/dist/terminal/react/index.cjs.map +1 -0
  68. package/dist/terminal/react/index.d.cts +15 -0
  69. package/dist/terminal/react/index.d.ts +15 -0
  70. package/dist/terminal/react/index.js +35 -0
  71. package/dist/terminal/react/index.js.map +1 -0
  72. package/dist/terminal/react/server.cjs +79 -0
  73. package/dist/terminal/react/server.cjs.map +1 -0
  74. package/dist/terminal/react/server.d.cts +16 -0
  75. package/dist/terminal/react/server.d.ts +16 -0
  76. package/dist/terminal/react/server.js +28 -0
  77. package/dist/terminal/react/server.js.map +1 -0
  78. package/dist/terminal/tty/index.cjs +201 -0
  79. package/dist/terminal/tty/index.cjs.map +1 -0
  80. package/dist/terminal/tty/index.d.cts +18 -0
  81. package/dist/terminal/tty/index.d.ts +18 -0
  82. package/dist/terminal/tty/index.js +199 -0
  83. package/dist/terminal/tty/index.js.map +1 -0
  84. package/dist/terminal/vue/index.cjs +104 -0
  85. package/dist/terminal/vue/index.cjs.map +1 -0
  86. package/dist/terminal/vue/index.d.cts +23 -0
  87. package/dist/terminal/vue/index.d.ts +23 -0
  88. package/dist/terminal/vue/index.js +3 -0
  89. package/dist/terminal/vue/index.js.map +1 -0
  90. package/dist/terminal/vue/server.cjs +88 -0
  91. package/dist/terminal/vue/server.cjs.map +1 -0
  92. package/dist/terminal/vue/server.d.cts +18 -0
  93. package/dist/terminal/vue/server.d.ts +18 -0
  94. package/dist/terminal/vue/server.js +21 -0
  95. package/dist/terminal/vue/server.js.map +1 -0
  96. package/package.json +213 -0
@@ -0,0 +1,238 @@
1
+ import { applyDelta, frameHash, PROTOCOL_MIN, PROTOCOL, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, CLOSE_INVALID_TOKEN } from './chunk-ZOEUEMDX.js';
2
+
3
+ // src/client/index.ts
4
+ var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
5
+ var readDocumentSnapshot = (doc = document) => {
6
+ try {
7
+ const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;
8
+ if (text === void 0 || text === null || text === "") return void 0;
9
+ const parsed = JSON.parse(text);
10
+ if (parsed === null || typeof parsed !== "object") return void 0;
11
+ const { frame, trees, seed, principal, path, live } = parsed;
12
+ if (!Array.isArray(frame) || trees === null || typeof trees !== "object" || typeof principal !== "boolean") return void 0;
13
+ return {
14
+ frame,
15
+ trees,
16
+ principal,
17
+ ...typeof seed === "string" ? { seed } : {},
18
+ ...typeof path === "string" ? { path } : {},
19
+ ...typeof live === "boolean" ? { live } : {}
20
+ };
21
+ } catch {
22
+ return void 0;
23
+ }
24
+ };
25
+ var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
26
+ var browserEnv = (config = {}) => {
27
+ const tokenKey = config.tokenKey ?? "nisc.token";
28
+ const mirror = (token) => {
29
+ if (config.cookie !== true) return;
30
+ try {
31
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
32
+ document.cookie = token === null ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}` : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;
33
+ } catch {
34
+ }
35
+ };
36
+ return {
37
+ tokens: {
38
+ load: () => {
39
+ try {
40
+ const token = window.localStorage.getItem(tokenKey);
41
+ mirror(token);
42
+ return token;
43
+ } catch {
44
+ return null;
45
+ }
46
+ },
47
+ save: (token) => {
48
+ try {
49
+ window.localStorage.setItem(tokenKey, token);
50
+ } catch {
51
+ }
52
+ mirror(token);
53
+ },
54
+ clear: () => {
55
+ try {
56
+ window.localStorage.removeItem(tokenKey);
57
+ } catch {
58
+ }
59
+ mirror(null);
60
+ }
61
+ },
62
+ socket: (url) => new WebSocket(url),
63
+ defaultUrl: () => {
64
+ const scheme = window.location.protocol === "https:" ? "wss" : "ws";
65
+ return `${scheme}://${window.location.host}/socket`;
66
+ }
67
+ };
68
+ };
69
+ var createWire = (config = {}) => {
70
+ const env = config.env ?? browserEnv();
71
+ let token = env.tokens.load();
72
+ const initial = config.initial !== void 0 && config.initial.principal === (token !== null) ? config.initial : void 0;
73
+ let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
74
+ let seed = initial?.seed;
75
+ const path = config.path ?? config.initial?.path;
76
+ let status = "connecting";
77
+ let incompatible = false;
78
+ let socket = null;
79
+ let retry;
80
+ let attempts = 0;
81
+ let disposed = false;
82
+ const listeners = /* @__PURE__ */ new Set();
83
+ const publishSnapshot = (next) => {
84
+ snapshot = next;
85
+ for (const listener of listeners) listener();
86
+ };
87
+ const setStatus = (next) => {
88
+ if (status === next) return;
89
+ status = next;
90
+ for (const listener of listeners) listener();
91
+ };
92
+ const url = () => config.url ?? env.defaultUrl();
93
+ const send = (message) => {
94
+ if (socket === null || status !== "open") return;
95
+ socket.send(JSON.stringify(message));
96
+ };
97
+ const bases = /* @__PURE__ */ new Map();
98
+ const connect = () => {
99
+ if (disposed) return;
100
+ setStatus("connecting");
101
+ bases.clear();
102
+ const params = [];
103
+ if (token !== null) params.push(`token=${encodeURIComponent(token)}`);
104
+ params.push(`protocol=${PROTOCOL}`);
105
+ if (config.delta === true) params.push("delta=1");
106
+ if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
107
+ seed = void 0;
108
+ if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
109
+ const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join("&")}` : ""}`);
110
+ socket = ws;
111
+ ws.onopen = () => {
112
+ attempts = 0;
113
+ setStatus("open");
114
+ };
115
+ ws.onmessage = (e) => {
116
+ const text = String(e.data);
117
+ const data = JSON.parse(text);
118
+ if (data.type === "render" && data.canvas !== void 0 && data.tree !== void 0) {
119
+ if (config.delta === true) bases.set(data.canvas, text);
120
+ publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });
121
+ } else if (data.type === "render-delta" && data.canvas !== void 0 && data.ops !== void 0 && data.hash !== void 0) {
122
+ const base = bases.get(data.canvas);
123
+ let rebuilt = null;
124
+ if (base !== void 0) {
125
+ try {
126
+ const candidate = applyDelta(base, data.ops);
127
+ rebuilt = frameHash(candidate) === data.hash ? candidate : null;
128
+ } catch {
129
+ rebuilt = null;
130
+ }
131
+ }
132
+ if (rebuilt === null) {
133
+ console.warn(`[moss/wire] canvas "${data.canvas}": delta did not rebuild the server's frame \u2014 resyncing.`);
134
+ bases.delete(data.canvas);
135
+ send({ type: "resync" });
136
+ return;
137
+ }
138
+ const frame = JSON.parse(rebuilt);
139
+ bases.set(data.canvas, rebuilt);
140
+ publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });
141
+ } else if (data.type === "frame" && data.tree !== void 0) {
142
+ publishSnapshot({ ...snapshot, frame: data.tree });
143
+ } else if (data.type === "session" && typeof data.token === "string") {
144
+ become(data.token);
145
+ } else if (data.type === "error") {
146
+ console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
147
+ } else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
148
+ 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.`);
149
+ incompatible = true;
150
+ ws.close();
151
+ } else if (data.type !== "hello" && data.type !== "catalog") {
152
+ console.warn(`[moss/wire] unhandled server message: ${data.type}`);
153
+ }
154
+ };
155
+ ws.onclose = (e) => {
156
+ if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {
157
+ incompatible = true;
158
+ setStatus("incompatible");
159
+ return;
160
+ }
161
+ setStatus("closed");
162
+ if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
163
+ become(null);
164
+ return;
165
+ }
166
+ if (!disposed) scheduleReconnect();
167
+ };
168
+ };
169
+ const RECONNECT_CAP_MS = 3e4;
170
+ const scheduleReconnect = () => {
171
+ const ceiling = Math.min(RECONNECT_CAP_MS, 1e3 * 2 ** attempts);
172
+ attempts += 1;
173
+ const delay = ceiling / 2 + Math.random() * (ceiling / 2);
174
+ retry = setTimeout(connect, delay);
175
+ };
176
+ const become = (next) => {
177
+ if (next === null) env.tokens.clear();
178
+ else env.tokens.save(next);
179
+ token = next;
180
+ clearTimeout(retry);
181
+ attempts = 0;
182
+ publishSnapshot(EMPTY);
183
+ const old = socket;
184
+ socket = null;
185
+ if (old !== null) {
186
+ old.onclose = null;
187
+ old.close();
188
+ }
189
+ connect();
190
+ };
191
+ if (initial?.live === false) status = "static";
192
+ else connect();
193
+ return {
194
+ subscribe: (listener) => {
195
+ listeners.add(listener);
196
+ return () => listeners.delete(listener);
197
+ },
198
+ snapshot: () => snapshot,
199
+ status: () => status,
200
+ dispatch: (canvasId, event) => send({ type: "event", canvas: canvasId, event }),
201
+ publish: (channel, payload) => send(payload === void 0 ? { type: "publish", channel } : { type: "publish", channel, payload }),
202
+ // Only on an open socket, and deliberately not queued: a back pressed while
203
+ // the connection is down is a gesture about a screen the person is no
204
+ // longer being served, and replaying it on reconnect would move them
205
+ // somewhere they asked to go some seconds and one outage ago.
206
+ back: () => {
207
+ if (socket === null || status !== "open") return;
208
+ send({ type: "back" });
209
+ },
210
+ // Same posture as `back`: only on an open socket, never queued. A jump
211
+ // replayed on reconnect would move somebody to where they wanted to be
212
+ // one outage ago.
213
+ popTo: (canvas, instance) => {
214
+ if (socket === null || status !== "open") return;
215
+ send({ type: "popTo", canvas, instance });
216
+ },
217
+ reset: () => {
218
+ if (disposed) return;
219
+ if (socket !== null && status === "open") {
220
+ send({ type: "reset" });
221
+ return;
222
+ }
223
+ clearTimeout(retry);
224
+ attempts = 0;
225
+ connect();
226
+ },
227
+ dispose: () => {
228
+ disposed = true;
229
+ status = "closed";
230
+ clearTimeout(retry);
231
+ socket?.close();
232
+ }
233
+ };
234
+ };
235
+
236
+ export { SNAPSHOT_ELEMENT_ID, browserEnv, createWire, readDocumentSnapshot };
237
+ //# sourceMappingURL=chunk-J72N3EMJ.js.map
238
+ //# sourceMappingURL=chunk-J72N3EMJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/index.ts"],"names":[],"mappings":";;;AAoFO,IAAM,mBAAA,GAAsB;AAK5B,IAAM,oBAAA,GAAuB,CAAC,GAAA,GAAwC,QAAA,KAA2C;AACtH,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,GAAA,CAAI,cAAA,CAAe,mBAAmB,CAAA,EAAG,WAAA;AACtD,IAAA,IAAI,SAAS,KAAA,CAAA,IAAa,IAAA,KAAS,IAAA,IAAQ,IAAA,KAAS,IAAI,OAAO,KAAA,CAAA;AAC/D,IAAA,MAAM,MAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAA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Y,EAAE,IAAA,EAAM,SAAA,EAAW,SAAQ,GAAI,EAAE,MAAM,SAAA,EAAW,OAAA,EAAS,SAAS,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhI,MAAM,MAAM;AACV,MAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,MAAA,KAAW,MAAA,EAAQ;AAC1C,MAAA,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA;AAAA,IACvB,CAAA;AAAA;AAAA;AAAA;AAAA,IAIA,KAAA,EAAO,CAAC,MAAA,EAAgB,QAAA,KAAqB;AAC3C,MAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,MAAA,KAAW,MAAA,EAAQ;AAC1C,MAAA,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAS,MAAA,EAAQ,UAAU,CAAA;AAAA,IAC1C,CAAA;AAAA,IACA,OAAO,MAAM;AACX,MAAA,IAAI,QAAA,EAAU;AAId,MAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,MAAA,KAAW,MAAA,EAAQ;AACxC,QAAA,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAS,CAAA;AACtB,QAAA;AAAA,MACF;AAIA,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,QAAA,GAAW,CAAA;AACX,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,GAAS,QAAA;AACT,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,EAAQ,KAAA,EAAM;AAAA,IAChB;AAAA,GACF;AACF","file":"chunk-J72N3EMJ.js","sourcesContent":["import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\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};\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 — `new WebSocket(url)` in every host\n socket: (url: 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: token in localStorage, url derived from location, the\n// page's WebSocket. The try/catches keep a storage-less context (private\n// mode, sandboxed iframe) alive — the session just lives for this page only.\n//\n// `cookie: true` keeps a COPY of the token in a cookie of the same name, written\n// and cleared with the stored one. A page request carries cookies and nothing\n// else, so this is what lets a server render the document for whoever is asking.\n// The cookie is only ever read to render a page: every other surface still wants\n// the token itself (the socket's URL, a Bearer header), so it adds no way in.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n const mirror = (token: string | null): void => {\n if (config.cookie !== true) return;\n try {\n const secure = window.location.protocol === 'https:' ? '; Secure' : '';\n document.cookie =\n token === null\n ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}`\n : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;\n } catch {\n /* no document, or cookies refused — the page is simply rendered for nobody */\n }\n };\n return {\n tokens: {\n load: () => {\n try {\n const token = window.localStorage.getItem(tokenKey);\n // Level the copy with the stored one — a token put there by something\n // other than this wire (a sign-in handoff page) reaches the cookie on\n // the first load after it, and a token that is gone takes its copy along.\n mirror(token);\n return token;\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 mirror(token);\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n mirror(null);\n },\n },\n socket: (url) => new WebSocket(url),\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 and holding a token, or neither. Anything else is somebody else's\n // screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null) ? 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 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 const params: string[] = [];\n if (token !== null) params.push(`token=${encodeURIComponent(token)}`);\n params.push(`protocol=${PROTOCOL}`);\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()}${params.length > 0 ? `?${params.join('&')}` : ''}`);\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 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 === 'error') {\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' && data.type !== 'catalog') {\n // hello/catalog are 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 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.\n const become = (next: string | null): void => {\n if (next === null) env.tokens.clear();\n else 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"]}
@@ -0,0 +1,55 @@
1
+ import { createContext, useContext, createElement, Fragment } from 'react';
2
+ import { RenderTree, NovaRenderProvider } from '@niscorp/nova/adapters/react';
3
+
4
+ // src/terminal/react/slots.ts
5
+ var TerminalApiContext = createContext(void 0);
6
+ var registerWireSlots = (registry, options = {}) => {
7
+ const { slotWrapper, fallback, textWrapper, errorMarker, canvasProvider, instanceProvider } = options;
8
+ const CanvasSlot = ({ canvasId }) => {
9
+ const api = useContext(TerminalApiContext);
10
+ if (api === void 0 || canvasId === void 0 || canvasId === "") return null;
11
+ const tree = api.canvasTree(canvasId);
12
+ if (tree.length === 0) return null;
13
+ const body = createElement(RenderTree, { nodes: tree });
14
+ return createElement(
15
+ NovaRenderProvider,
16
+ {
17
+ registry,
18
+ dispatch: (event) => api.dispatch(canvasId, event),
19
+ publish: (channel, payload) => api.publish(channel, payload),
20
+ fallback,
21
+ textWrapper,
22
+ errorMarker
23
+ },
24
+ canvasProvider === void 0 ? body : createElement(canvasProvider, { canvasId }, body)
25
+ );
26
+ };
27
+ registry.register("CanvasSlot", CanvasSlot, { description: "A canvas, live from the server." });
28
+ const ActionSlot = ({
29
+ instanceId,
30
+ canvasId,
31
+ definitionId,
32
+ children
33
+ }) => {
34
+ const api = useContext(TerminalApiContext);
35
+ const wrapped = slotWrapper === void 0 ? createElement(Fragment, { key: instanceId }, children) : createElement(slotWrapper, { key: instanceId, instanceId, canvasId, definitionId }, children);
36
+ if (api === void 0 || instanceId === void 0 || canvasId === void 0) return wrapped;
37
+ return createElement(
38
+ NovaRenderProvider,
39
+ {
40
+ registry,
41
+ dispatch: (event) => api.dispatch(canvasId, event.origin === void 0 ? { ...event, origin: instanceId } : event),
42
+ publish: (channel, payload) => api.publish(channel, payload),
43
+ fallback,
44
+ textWrapper,
45
+ errorMarker
46
+ },
47
+ instanceProvider === void 0 ? wrapped : createElement(instanceProvider, { canvasId, instanceId }, wrapped)
48
+ );
49
+ };
50
+ registry.register("ActionSlot", ActionSlot, { description: "An action instance boundary from the server; the app slotWrapper wraps it." });
51
+ };
52
+
53
+ export { TerminalApiContext, registerWireSlots };
54
+ //# sourceMappingURL=chunk-SK4PDGEE.js.map
55
+ //# sourceMappingURL=chunk-SK4PDGEE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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AAA,IACA,YAAA;AAAA,IACA;AAAA,GACF,KAAgC;AAC9B,IAAA,MAAM,GAAA,GAAM,WAAW,kBAAkB,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,gBAAgB,MAAA,GAAY,aAAA,CAAc,UAAU,EAAE,GAAA,EAAK,YAAW,EAAG,QAAQ,IAAI,aAAA,CAAc,WAAA,EAAa,EAAE,GAAA,EAAK,UAAA,EAAY,YAAY,QAAA,EAAU,YAAA,IAAgB,QAAQ,CAAA;AAMjM,IAAA,IAAI,QAAQ,MAAA,IAAa,UAAA,KAAe,MAAA,IAAa,QAAA,KAAa,QAAW,OAAO,OAAA;AACpF,IAAA,OAAO,aAAA;AAAA,MACL,kBAAA;AAAA,MACA;AAAA,QACE,QAAA;AAAA,QACA,QAAA,EAAU,CAAC,KAAA,KAAqB,GAAA,CAAI,SAAS,QAAA,EAAU,KAAA,CAAM,MAAA,KAAW,MAAA,GAAY,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,UAAA,KAAe,KAAK,CAAA;AAAA,QAC5H,SAAS,CAAC,OAAA,EAAiB,YAAsB,GAAA,CAAI,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,QAC7E,QAAA;AAAA,QACA,WAAA;AAAA,QACA;AAAA,OACF;AAAA,MACA,gBAAA,KAAqB,SAAY,OAAA,GAAU,aAAA,CAAc,kBAAkB,EAAE,QAAA,EAAU,UAAA,EAAW,EAAG,OAAO;AAAA,KAC9G;AAAA,EACF,CAAA;AACA,EAAA,QAAA,CAAS,SAAS,YAAA,EAAc,UAAA,EAAY,EAAE,WAAA,EAAa,8EAA8E,CAAA;AAC3I","file":"chunk-SK4PDGEE.js","sourcesContent":["import { createContext, createElement, Fragment, useContext, type ComponentType, type FC, type ReactNode } from 'react';\nimport { NovaRenderProvider, RenderTree } from '@niscorp/nova/adapters/react';\nimport type { NovaComponent } from '@niscorp/nova/adapters/react';\nimport type { ComponentRegistry, NovaEvent } from '@niscorp/nova';\nimport type { TerminalApi } from '../index';\n\n// ═══════════════════════════════════════════════════════════\n// The wire-backed structural slots, shared by every react-shaped render\n// target (terminal/react in the browser, terminal/ink in a TTY) — same seam,\n// different renderer. Split from the react target so the ink bundle never\n// drags react-dom.\n// ═══════════════════════════════════════════════════════════\n\nexport const TerminalApiContext = createContext<TerminalApi | undefined>(undefined);\n\n// An app-supplied component wrapping each action instance at the ActionSlot\n// boundary — the terminal twin of nova's client-shell SlotWrapper (same seam,\n// same job: animation, gating, logging, chips). Served trees carry IDENTITY\n// only (ids, not the definition — wire weight), so the props diverge from the\n// client-shell wrapper in exactly that one way: `definitionId`, not `action`.\nexport type TerminalSlotWrapperProps = {\n canvasId?: string;\n instanceId?: string;\n definitionId?: string;\n children?: ReactNode;\n};\nexport type TerminalSlotWrapper = FC<TerminalSlotWrapperProps>;\n\n// The host-specific leaf renderers a react-shaped target may thread through\n// to nova's provider (ink needs all three; the browser needs none).\nexport type WireSlotOptions = {\n slotWrapper?: TerminalSlotWrapper;\n fallback?: NovaComponent;\n textWrapper?: ComponentType<{ children?: ReactNode }>;\n errorMarker?: ComponentType<{ code: string; message: string }>;\n // wraps each canvas's rendered tree with a host context (ink provides the\n // per-canvas marker resolver here); the browser omits it\n canvasProvider?: ComponentType<{ canvasId: string; children?: ReactNode }>;\n // the same, per action instance — inside a list canvas several instances\n // share refs, so ink resolves markers per instance here\n instanceProvider?: ComponentType<{ canvasId: string; instanceId: string; children?: ReactNode }>;\n};\n\n// Register the wire-backed structural slots on a registry:\n//\n// - CanvasSlot: a served CanvasSlot marker in the frame resolves to that\n// canvas's live tree, dispatching events tagged with the canvas (the\n// server stamps origin). It overrides nova's shell-backed CanvasSlot,\n// which the terminal has no shell for.\n// - ActionSlot: the per-instance boundary a served tree carries (identity in\n// props, rendered content as children). With no wrapper it's transparent;\n// with one, the wrapper decides everything. Keyed by instanceId so an\n// instance swap REMOUNTS: no stale view state crossing instances.\nexport const registerWireSlots = (registry: ComponentRegistry<NovaComponent>, options: WireSlotOptions = {}): void => {\n const { slotWrapper, fallback, textWrapper, errorMarker, canvasProvider, instanceProvider } = options;\n\n const CanvasSlot: NovaComponent<{ canvasId?: string }> = ({ canvasId }: { canvasId?: string }) => {\n const api = useContext(TerminalApiContext);\n if (api === undefined || canvasId === undefined || canvasId === '') return null;\n const tree = api.canvasTree(canvasId);\n if (tree.length === 0) return null;\n const body = createElement(RenderTree, { nodes: tree });\n return createElement(\n NovaRenderProvider,\n {\n registry,\n dispatch: (event: NovaEvent) => api.dispatch(canvasId, event),\n publish: (channel: string, payload?: unknown) => api.publish(channel, payload),\n fallback,\n textWrapper,\n errorMarker,\n },\n canvasProvider === undefined ? body : createElement(canvasProvider, { canvasId }, body),\n );\n };\n registry.register('CanvasSlot', CanvasSlot, { description: 'A canvas, live from the server.' });\n\n const ActionSlot: NovaComponent<{ instanceId?: string; canvasId?: string; definitionId?: string }> = ({\n instanceId,\n canvasId,\n definitionId,\n children,\n }: TerminalSlotWrapperProps) => {\n const api = useContext(TerminalApiContext);\n const wrapped = slotWrapper === undefined ? createElement(Fragment, { key: instanceId }, children) : createElement(slotWrapper, { key: instanceId, instanceId, canvasId, definitionId }, children);\n // Origin is decided HERE, where instance identity lives: a list canvas\n // renders several live cards at once, and a click inside THIS boundary\n // must reach THIS instance's triggers — the server's active-instance\n // fallback only holds for card-deck canvases. Events that already carry\n // an origin keep it.\n if (api === undefined || instanceId === undefined || canvasId === undefined) return wrapped;\n return createElement(\n NovaRenderProvider,\n {\n registry,\n dispatch: (event: NovaEvent) => api.dispatch(canvasId, event.origin === undefined ? { ...event, origin: instanceId } : event),\n publish: (channel: string, payload?: unknown) => api.publish(channel, payload),\n fallback,\n textWrapper,\n errorMarker,\n },\n instanceProvider === undefined ? wrapped : createElement(instanceProvider, { canvasId, instanceId }, wrapped),\n );\n };\n registry.register('ActionSlot', ActionSlot, { description: 'An action instance boundary from the server; the app slotWrapper wraps it.' });\n};\n"]}
@@ -0,0 +1,251 @@
1
+ import { DefinitionValidationError } from '@niscorp/nova';
2
+
3
+ // src/telemetry.ts
4
+ var emitterOf = (telemetry) => telemetry === void 0 ? void 0 : (span) => {
5
+ try {
6
+ telemetry.emit(span);
7
+ } catch (err) {
8
+ console.error("[moss:telemetry]", err);
9
+ }
10
+ };
11
+ var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
12
+ var spanClock = () => {
13
+ const startUnixNano = Date.now() * 1e6;
14
+ const t0 = elapsedClock();
15
+ return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };
16
+ };
17
+ var PROTOCOL = 1;
18
+ var PROTOCOL_MIN = 1;
19
+ var CLOSE_INVALID_TOKEN = 4401;
20
+ var CLOSE_SIGNED_OUT = 4403;
21
+ var CLOSE_SHELL_FAILED = 4500;
22
+ var CLOSE_PROTOCOL_MISMATCH = 4426;
23
+ var DEFAULT_REVALIDATE_MS = 60 * 1e3;
24
+ var parse = (text) => {
25
+ try {
26
+ const value = JSON.parse(text);
27
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
28
+ } catch {
29
+ return null;
30
+ }
31
+ };
32
+ var createSocket = (ctx) => {
33
+ const emit = emitterOf(ctx.telemetry);
34
+ const live = /* @__PURE__ */ new Map();
35
+ const expire = (connection) => {
36
+ connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
37
+ connection.close(CLOSE_INVALID_TOKEN, "session expired");
38
+ live.delete(connection);
39
+ };
40
+ const revalidate = async () => {
41
+ for (const [connection, credential] of [...live]) {
42
+ if (credential === null) continue;
43
+ let resolved;
44
+ try {
45
+ resolved = await ctx.session(credential.token);
46
+ } catch {
47
+ continue;
48
+ }
49
+ if (resolved === credential.principal) continue;
50
+ if (!live.has(connection)) continue;
51
+ expire(connection);
52
+ }
53
+ };
54
+ const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;
55
+ let sweeper;
56
+ if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {
57
+ sweeper = setInterval(() => void revalidate(), revalidateMs);
58
+ sweeper.unref?.();
59
+ }
60
+ const accept = async (url, connection) => {
61
+ const send = (message) => connection.send(JSON.stringify(message));
62
+ try {
63
+ await open(url, connection, send);
64
+ } catch (error) {
65
+ console.error("[moss/socket] refused a session:", error);
66
+ live.delete(connection);
67
+ const failures = error instanceof DefinitionValidationError ? (error.context?.failures ?? []).map((f) => f.id) : [];
68
+ const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(", ")}` : String(error);
69
+ try {
70
+ send({ type: "error", code: "session_failed", message: `This session could not be opened \u2014 ${detail}. The refusal is this terminal's alone; the server is up.` });
71
+ connection.close(CLOSE_SHELL_FAILED, "session failed");
72
+ } catch {
73
+ }
74
+ }
75
+ };
76
+ const open = async (url, connection, send) => {
77
+ const upClock = emit === void 0 ? void 0 : spanClock();
78
+ const params = new URL(url, "http://nisc.local").searchParams;
79
+ const spoken = Number(params.get("protocol") ?? "1");
80
+ if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {
81
+ const behind = spoken > PROTOCOL ? "server" : "client";
82
+ send({
83
+ type: "error",
84
+ code: `${behind}_too_old`,
85
+ message: `This terminal speaks protocol ${params.get("protocol") ?? "1"}; this server speaks ${PROTOCOL_MIN}\u2013${PROTOCOL}. ${behind === "client" ? "Reload the terminal to get the current build." : "The server has not been updated yet."}`
86
+ });
87
+ connection.close(CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
88
+ return;
89
+ }
90
+ const token = params.get("token");
91
+ let principal = null;
92
+ if (token !== null && token !== "") {
93
+ principal = await ctx.session(token);
94
+ if (principal === null) {
95
+ if (emit !== void 0 && upClock !== void 0) {
96
+ emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
97
+ }
98
+ send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
99
+ connection.close(CLOSE_INVALID_TOKEN, "invalid token");
100
+ return;
101
+ }
102
+ }
103
+ live.set(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
104
+ connection.onClose(() => live.delete(connection));
105
+ if (emit !== void 0 && upClock !== void 0) {
106
+ const hadPrincipal = principal !== null;
107
+ connection.onClose(() => emit({ name: "socket.close", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "ok", attributes: { hasPrincipal: hadPrincipal } }));
108
+ }
109
+ const { ids, hash } = await ctx.catalog(principal);
110
+ send({ type: "hello", protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });
111
+ const wantsDelta = params.get("delta") === "1";
112
+ const named = params.get("seed");
113
+ const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : void 0;
114
+ const path = params.get("path");
115
+ const route = path === null ? void 0 : ctx.page?.(path);
116
+ const host = route?.host ?? ctx.shells;
117
+ const session = await host?.session(token, principal, { ...seed === void 0 ? {} : { seed }, ...route === void 0 ? {} : { inputs: route.inputs } });
118
+ if (session !== void 0) {
119
+ session.attach(connection, { delta: wantsDelta });
120
+ connection.onClose(() => session.detach(connection));
121
+ }
122
+ if (emit !== void 0 && upClock !== void 0) {
123
+ emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "ok", attributes: { hasPrincipal: principal !== null } });
124
+ }
125
+ connection.onMessage((text) => {
126
+ const message = parse(text);
127
+ if (message !== null && message["type"] === "reset") {
128
+ if (session === void 0) {
129
+ send({ type: "error", code: "no_shell", message: "This app serves no shell." });
130
+ return;
131
+ }
132
+ session.reset();
133
+ return;
134
+ }
135
+ if (message !== null && message["type"] === "resync") {
136
+ if (session === void 0) {
137
+ send({ type: "error", code: "no_shell", message: "This app serves no shell." });
138
+ return;
139
+ }
140
+ session.resync(connection);
141
+ return;
142
+ }
143
+ if (message !== null && message["type"] === "back") {
144
+ if (session === void 0) {
145
+ send({ type: "error", code: "no_shell", message: "This app serves no shell." });
146
+ return;
147
+ }
148
+ session.back();
149
+ return;
150
+ }
151
+ if (message !== null && message["type"] === "popTo" && typeof message["canvas"] === "string" && typeof message["instance"] === "string") {
152
+ if (session === void 0) {
153
+ send({ type: "error", code: "no_shell", message: "This app serves no shell." });
154
+ return;
155
+ }
156
+ session.popTo(message["canvas"], message["instance"]);
157
+ return;
158
+ }
159
+ if (message !== null && message["type"] === "publish" && typeof message["channel"] === "string") {
160
+ if (session === void 0) {
161
+ send({ type: "error", code: "no_shell", message: "This app serves no shell." });
162
+ return;
163
+ }
164
+ session.publish(message["channel"], message["payload"]);
165
+ return;
166
+ }
167
+ if (message === null || message["type"] !== "event" || typeof message["canvas"] !== "string") {
168
+ send({ type: "error", code: "invalid_message", message: 'Messages are JSON { type: "event", canvas, event }.' });
169
+ return;
170
+ }
171
+ if (session === void 0) {
172
+ send({ type: "error", code: "no_shell", message: "This app serves no shell.", canvas: message["canvas"] });
173
+ return;
174
+ }
175
+ const event = message["event"];
176
+ if (event === null || typeof event !== "object" || Array.isArray(event)) {
177
+ send({ type: "error", code: "invalid_message", message: "The event field must be a NovaEvent object.", canvas: message["canvas"] });
178
+ return;
179
+ }
180
+ session.dispatch(message["canvas"], event);
181
+ });
182
+ };
183
+ return Object.assign(accept, {
184
+ stop: () => {
185
+ if (sweeper !== void 0) clearInterval(sweeper);
186
+ sweeper = void 0;
187
+ }
188
+ });
189
+ };
190
+
191
+ // src/delta.ts
192
+ var BLOCK = 16;
193
+ var encodeDelta = (base, target) => {
194
+ if (base.length < BLOCK) return [[1, target]];
195
+ const index = /* @__PURE__ */ new Map();
196
+ for (let i = 0; i + BLOCK <= base.length; i += 1) {
197
+ const key = base.slice(i, i + BLOCK);
198
+ if (!index.has(key)) index.set(key, i);
199
+ }
200
+ const ops = [];
201
+ let literal = "";
202
+ let at = 0;
203
+ while (at < target.length) {
204
+ const key = target.slice(at, at + BLOCK);
205
+ const found = key.length === BLOCK ? index.get(key) : void 0;
206
+ if (found === void 0) {
207
+ literal += target[at];
208
+ at += 1;
209
+ continue;
210
+ }
211
+ let length = BLOCK;
212
+ while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {
213
+ length += 1;
214
+ }
215
+ if (literal !== "") {
216
+ ops.push([1, literal]);
217
+ literal = "";
218
+ }
219
+ ops.push([0, found, length]);
220
+ at += length;
221
+ }
222
+ if (literal !== "") ops.push([1, literal]);
223
+ return ops;
224
+ };
225
+ var applyDelta = (base, ops) => {
226
+ let out = "";
227
+ for (const op of ops) {
228
+ if (op[0] === 1) {
229
+ out += op[1];
230
+ continue;
231
+ }
232
+ const [, offset, length] = op;
233
+ if (offset < 0 || length < 0 || offset + length > base.length) {
234
+ throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);
235
+ }
236
+ out += base.slice(offset, offset + length);
237
+ }
238
+ return out;
239
+ };
240
+ var frameHash = (text) => {
241
+ let hash = 2166136261;
242
+ for (let i = 0; i < text.length; i += 1) {
243
+ hash ^= text.charCodeAt(i);
244
+ hash = Math.imul(hash, 16777619);
245
+ }
246
+ return hash >>> 0;
247
+ };
248
+
249
+ export { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SHELL_FAILED, CLOSE_SIGNED_OUT, DEFAULT_REVALIDATE_MS, PROTOCOL, PROTOCOL_MIN, applyDelta, createSocket, emitterOf, encodeDelta, frameHash, spanClock };
250
+ //# sourceMappingURL=chunk-ZOEUEMDX.js.map
251
+ //# sourceMappingURL=chunk-ZOEUEMDX.js.map