@niscorp/moss 0.4.0 → 0.6.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 +492 -0
  2. package/DESIGN.md +265 -49
  3. package/DOCS.md +1527 -344
  4. package/README.md +37 -20
  5. package/dist/app-CUnDcXQu.d.ts +143 -0
  6. package/dist/app-CdANzi2q.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-6QPTMKRE.cjs +53 -0
  12. package/dist/chunk-6QPTMKRE.cjs.map +1 -0
  13. package/dist/chunk-D3YZIAYV.cjs +137 -0
  14. package/dist/chunk-D3YZIAYV.cjs.map +1 -0
  15. package/dist/chunk-IUJ2TRNB.cjs +57 -0
  16. package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
  17. package/dist/chunk-IW3A2YIC.js +49 -0
  18. package/dist/chunk-IW3A2YIC.js.map +1 -0
  19. package/dist/chunk-NRZ3Z2FF.js +61 -0
  20. package/dist/chunk-NRZ3Z2FF.js.map +1 -0
  21. package/dist/chunk-NSK7QSSG.js +26 -0
  22. package/dist/chunk-NSK7QSSG.js.map +1 -0
  23. package/dist/chunk-PWUO4RET.js +374 -0
  24. package/dist/chunk-PWUO4RET.js.map +1 -0
  25. package/dist/chunk-R2YPQHQH.cjs +383 -0
  26. package/dist/chunk-R2YPQHQH.cjs.map +1 -0
  27. package/dist/chunk-R66WUKGC.cjs +2716 -0
  28. package/dist/chunk-R66WUKGC.cjs.map +1 -0
  29. package/dist/chunk-T5BRTFKP.js +53 -0
  30. package/dist/chunk-T5BRTFKP.js.map +1 -0
  31. package/dist/chunk-TGKDS2T7.cjs +330 -0
  32. package/dist/chunk-TGKDS2T7.cjs.map +1 -0
  33. package/dist/chunk-TLNRFAQ6.js +326 -0
  34. package/dist/chunk-TLNRFAQ6.js.map +1 -0
  35. package/dist/chunk-V5YMJL7Z.js +2704 -0
  36. package/dist/chunk-V5YMJL7Z.js.map +1 -0
  37. package/dist/chunk-VBWNHF4H.cjs +30 -0
  38. package/dist/chunk-VBWNHF4H.cjs.map +1 -0
  39. package/dist/chunk-VKQPOZDJ.cjs +72 -0
  40. package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
  41. package/dist/{chunk-U3UR5AOQ.js → chunk-WKBH3UMB.js} +43 -16
  42. package/dist/chunk-WKBH3UMB.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-D7nroBww.d.cts +169 -0
  53. package/dist/document-DeTPGBil.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-B411sK9M.d.cts +130 -0
  57. package/dist/index-B411sK9M.d.ts +130 -0
  58. package/dist/index.cjs +45 -3916
  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 -3455
  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 +52 -9
  161. package/dist/chunk-4T6KAXBP.js +0 -256
  162. package/dist/chunk-4T6KAXBP.js.map +0 -1
  163. package/dist/chunk-EMRDIZLY.js +0 -99
  164. package/dist/chunk-EMRDIZLY.js.map +0 -1
  165. package/dist/chunk-HOZID4EM.js +0 -366
  166. package/dist/chunk-HOZID4EM.js.map +0 -1
  167. package/dist/chunk-R3QMJ3JF.js +0 -3404
  168. package/dist/chunk-R3QMJ3JF.js.map +0 -1
  169. package/dist/chunk-SK4PDGEE.js +0 -55
  170. package/dist/chunk-SK4PDGEE.js.map +0 -1
  171. package/dist/chunk-U3UR5AOQ.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
package/README.md CHANGED
@@ -4,15 +4,16 @@ The nisc application server. A principal logs in, a charter resolves, and what a
4
4
 
5
5
  Moss does not host code and guard it. It serves *existence*: a resolved catalog **is** the application. The warehouse kiosk granted two actions is not a locked-down app; it is a two-action app. There is nothing else to render, invoke, or attack.
6
6
 
7
- > On npm, and still early. The data/policy plane, the socket, per-principal server shells, ring-2 served layout variants, the in-process function seam, server-drawn documents and pages, and the canvas terminal (the wire plus swappable render targets) are built and tested — except the ink render target, which has no tests yet. The fn *host* (`/fns`), the artifact library, the projection model, and scale-out are specified and pending. See [DESIGN.md](DESIGN.md) for the thesis and the unbuilt ladder.
7
+ > On npm, and still early. The data/policy plane, the socket, per-principal server shells, ring-2 served layout variants, the in-process function seam, server-drawn documents and pages, and the canvas terminal (the wire plus five swappable render targets) are built and tested. The fn *host* (`/fns`), the artifact library, the projection model, and scale-out are specified and pending. See [DESIGN.md](DESIGN.md) for the thesis, how the code is laid out, and the unbuilt ladder.
8
8
 
9
9
  ## Install
10
10
 
11
11
  ```bash
12
- pnpm add @niscorp/moss @niscorp/charter @niscorp/nova @niscorp/prism @niscorp/strata @niscorp/tide @niscorp/vex zod
12
+ pnpm add @niscorp/moss @niscorp/charter @niscorp/nova @niscorp/prism @niscorp/strata @niscorp/vex zod
13
13
  # the nisc packages moss composes and zod are required peers — the app owns
14
14
  # the one copy of each. hono, the Node listener and ws come with moss as
15
15
  # regular dependencies. The optional peers, each needed by one subpath only:
16
+ pnpm add @niscorp/tide # ./tide (an app that runs tide)
16
17
  pnpm add react react-dom # ./terminal/react (and its /server)
17
18
  pnpm add vue # ./terminal/vue (and its /server)
18
19
  pnpm add ink react # ./terminal/ink
@@ -23,7 +24,7 @@ Node ≥ 22.12.
23
24
 
24
25
  ## The shape
25
26
 
26
- An app hands moss its **artifacts** (`defineApp`) and an **environment** (`NiscRuntime` — a database and how a session token is verified, optionally a cache). Everything mechanical is derived: the data layer from the schema, per-principal policy and catalogs from the charter, the server shells from the manifest. The server refuses to boot on an incoherent charter.
27
+ An app hands moss its **artifacts** (`defineApp`) and an **environment** (`NiscRuntime` — a database and how a session token is verified, optionally a cache). Everything mechanical is derived: the data layer from the schema, per-principal policy and catalogs from the charter, the server shells from the manifest. The manifest is read by a schema and frozen when it is handed over, and the server refuses to boot on one that does not parse, or on an incoherent charter.
27
28
 
28
29
  ```typescript
29
30
  import { defineApp } from '@niscorp/moss';
@@ -73,7 +74,7 @@ server.get('*', async (c) => {
73
74
  const page = await renderDocument({
74
75
  server,
75
76
  template: indexHtml,
76
- request: { path: c.req.path, cookie: c.req.header('cookie') },
77
+ request: { path: c.req.path, cookie: c.req.header('cookie'), host: c.req.header('host') },
77
78
  draw: (snapshot) => renderSnapshot({ snapshot, registry, slotWrapper }),
78
79
  });
79
80
  return c.html(page.html, 200, page.headers);
@@ -86,9 +87,12 @@ const drawn = readDocumentSnapshot();
86
87
  createWire({ env: browserEnv(), ...(drawn ? { initial: drawn } : {}) });
87
88
  ```
88
89
 
89
- Who may keep the page follows from who asked: drawn for nobody it is the same
90
- for everybody; drawn for somebody it is `private, no-store`. A page that cannot
91
- be drawn goes out undrawn.
90
+ Who is asking is read off the browser's session cookie. Its name ends with the
91
+ port a page is on, so the request's `Host` is how a page on a port finds it;
92
+ `mountSite` (`@niscorp/moss/node`) and the dev plugin are this route, written
93
+ once. Who may keep the page follows from who asked: drawn for nobody it is the
94
+ same for everybody; drawn for somebody it is `private, no-store`. A page that
95
+ cannot be drawn goes out undrawn.
92
96
 
93
97
  The page's `<head>` is a node in a layout too — nova's `nova:head`, holding
94
98
  the elements a head holds, bound to the action's data. It is read off the
@@ -120,6 +124,12 @@ already signed in — the token file is the terminal's localStorage. The
120
124
  server never learns which target rendered the frame; policy, layouts, and
121
125
  data are decided per principal, never per client.
122
126
 
127
+ Every target is told the connection's status the same way, because a screen
128
+ left up by a dead socket looks exactly like a live one. The REPL and the TUI
129
+ print it. The three browser targets say it on their root element
130
+ (`data-wire-status="closed"`) and draw nothing: what a lost connection looks
131
+ like is the app's stylesheet's.
132
+
123
133
  ```
124
134
  ── main ────────────────────────────────
125
135
  Sign in to Relay
@@ -132,19 +142,23 @@ Magic link sent to alex@relay.app. The email is faked — the link is right here
132
142
  ```
133
143
 
134
144
  Under the hood: `./client` is the wire (a plain-TS protocol client: token
135
- slot, reconnect, session lifecycle — host-shaped pieces injected as a
136
- `WireEnv`, browser by default, `./client/node` for a plain process);
137
- `./terminal` is the conductor and the hot-swap switcher; targets close over
138
- their own surface (a DOM root, a stdio pair), so the contract is
145
+ slot, one socket at a time, reconnect, session lifecycle — host-shaped pieces
146
+ injected as a `WireEnv`, browser by default, `./client/node` for a plain
147
+ process); `./terminal` is the conductor and the hot-swap switcher; targets
148
+ close over their own surface (a DOM root, a stdio pair), so the contract is
139
149
  surface-blind. Framework-shaped code lives only in the target subpaths,
140
150
  never in moss core.
141
151
 
142
152
  ## Subpaths
143
153
 
144
- - **`@niscorp/moss`** — the server: `defineApp`, `createServer`, the resolution and shell-host internals, the socket protocol types.
154
+ - **`@niscorp/moss`** — the server: `defineApp`, `createServer`, the drawn document (`renderDocument`, `exportDocuments`), moss's stored session credential (`mintSession`), `migrateTables`, and the types an app names (`NiscApp`, `NiscRuntime`, `MossServer`, `FunctionSession`). [DOCS.md](DOCS.md) documents every name each entry exports; the list itself is `packages/moss/api.txt` in the repository, which a build holds the entries to.
145
155
  - **`@niscorp/moss/node`** — the Node listener: `serve` + `attachSocket` (raw `ws`), and `mountSite(server, { dist, draw })` — the built terminal served by the same process, every page drawn. Bun swaps this file, never the app.
146
- - **`@niscorp/moss/vite`** — `mossDev({ app })`: the app server inside vite's dev process — loaded through vite (an edit re-boots it), the socket attached once, pages drawn, moss's paths answered, a dev-only `/dev/as/<who>`. `nisc dev` adds it for an app behind moss; `vite` is an optional peer.
147
- - **`@niscorp/moss/client`** — the wire: `createWire()`, the app end of the socket. Plain TypeScript, zero React, zero globals — the host comes in as a `WireEnv` (default: `browserEnv()`, localStorage + location).
156
+ - **`@niscorp/moss/integrations`** — a feature, not part of the core: `createIntegrations(config)` makes the object an app puts in its manifest's `features` to take in separate services that add screens (registration, approval, the proxy, webhooks), and carries the calls the app makes on it afterwards. A bundle is nisc's own five fields and `extension`, the app's own vocabulary: the app supplies the schema that reads it (`extension: { schema, check?, prepare?, contract? }`) and reads it back with `integrations.listIntegrations()`.
157
+ - **`@niscorp/moss/tide`** — a feature too: `createTideFacts({ tide, identity, chain })` mints each committed write into [tide](../tide/README.md) as a fact, for the identity the write's own scope names. It is what moss keeps of hosting tide: the Postgres store (`@niscorp/tide/postgres`) and the driver (`createTideDriver`) are tide's own, and `@niscorp/tide` is an optional peer.
158
+ - **`@niscorp/moss/protocol`** — for code that speaks the wire itself, a client written by hand or a transport other than `./node`: `PROTOCOL`, `offerToken`, the two close codes a terminal recovers from, and the types `ServerMessage` and `Connection`. An app served by `nisc` or `serve` needs none of it.
159
+ - **`@niscorp/moss/unverified`** — `unverifiedShell(session)`, the whole nova shell of a session. On the shell a session hands out, the nine members that change what a shell is made of (`registerAction`, `setLayout`, `addCanvas` and their kin) throw, because what they add is not verified by moss.
160
+ - **`@niscorp/moss/vite`** — `mossDev({ app })`: the app server inside vite's dev process — loaded through vite (an edit re-boots it), the socket answered by the app that is booted, pages drawn, moss's paths answered, a dev-only `/dev/as/<who>`. `nisc dev` adds it for an app behind moss; `vite` is an optional peer.
161
+ - **`@niscorp/moss/client`** — the wire: `createWire()`, the app end of the socket. Plain TypeScript, zero React, zero globals — the host comes in as a `WireEnv` (default: `browserEnv()`: the page's location, and the session kept by the browser in a cookie the page cannot read, or in localStorage where the page is not served by its app).
148
162
  - **`@niscorp/moss/client/node`** — the Node host env: `nodeEnv({ url, tokenFile? })` runs the same wire on a plain Node (or Bun) process — token in a file, the runtime's WHATWG WebSocket.
149
163
  - **`@niscorp/moss/terminal`** — the terminal: `createTerminal` (one target, one wire) and `mountTerminal` (hot-swaps render targets on a hotkey over one wire; the session survives the swap). Framework-blind, surface-blind.
150
164
  - **`@niscorp/moss/terminal/react`** — the React render target: `reactTarget({ root, registry, slotWrapper? })` binds the app's component registry to the wire via nova's React adapter.
@@ -162,12 +176,15 @@ never in moss core.
162
176
 
163
177
  ## Tables and documents, versioned
164
178
 
165
- moss creates no table on its own: its tables (`MOSS_SEQUENCE`, plus
166
- `SESSIONS_SEQUENCE` when the runtime's `session` is `'sessions'`) and the vex
167
- cache's go through one [strata](../strata/README.md) ledger run at boot — once,
168
- recorded, refused if the ledger was edited or written by newer code. The tide
169
- store's tables (`TIDE_SEQUENCE`) go through the same ledger when
170
- `createTideStore(pool)` is called. `migrations: 'verify'` on the
179
+ moss creates no table on its own: its tables (`MOSS_SEQUENCE`, plus the
180
+ sessions table's sequence when the runtime's `session` is `'sessions'`), the
181
+ vex cache's and the ones the app's features keep go through one
182
+ [strata](../strata/README.md) ledger run at boot — once,
183
+ recorded, refused if the ledger was edited or written by newer code. Tide's
184
+ tables are tide's (`TIDE_SEQUENCE`, from `@niscorp/tide/postgres`): they go
185
+ through the same ledger when `createTideStore(pool)` is called, or in moss's
186
+ own run when the app hands the sequence over in `runtime.tables`.
187
+ `migrations: 'verify'` on the
171
188
  runtime refuses to boot with anything pending. Stored integration actions carry
172
189
  a grammar stamp and are upgraded at boot, at intake and on read — through
173
190
  nova's and Prism's grammars plus the app's own (`NiscApp.grammars`); a bundle or
@@ -0,0 +1,143 @@
1
+ import { Sequence } from '@niscorp/strata';
2
+ import { GenerateDsl, MapToShape, QueryResponse, ScopeBehaviors, SeedEntry, SeedMutation } from '@niscorp/vex';
3
+ import { Charter } from '@niscorp/charter';
4
+ import { Shell, FetchFn, LayoutNode, ActionDefinition, CanvasConfig, ActionFragment, FunctionHandler } from '@niscorp/nova';
5
+ import { Phrasebook, PhraseKeys } from '@niscorp/nova/i18n';
6
+ import { F as Feature } from './index-B411sK9M.js';
7
+ import { I as IdentityRecord } from './document-DeTPGBil.js';
8
+
9
+ type LayoutVariant = {
10
+ action: string;
11
+ layout: LayoutNode;
12
+ };
13
+ type NiscApp = {
14
+ charter: Charter;
15
+ assignments?: Record<string, readonly string[]>;
16
+ wearable?: readonly (readonly string[])[];
17
+ actions: Record<string, ActionDefinition>;
18
+ layouts?: Record<string, LayoutVariant>;
19
+ behaviors?: ScopeBehaviors;
20
+ scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;
21
+ identity?: {
22
+ as?: string;
23
+ resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;
24
+ };
25
+ phrases?: (session: {
26
+ principal: string | null;
27
+ identity: Record<string, unknown>;
28
+ wire: FetchFn;
29
+ }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;
30
+ phraseKeys?: PhraseKeys;
31
+ features?: readonly Feature[];
32
+ entries?: readonly (SeedEntry | SeedMutation)[];
33
+ resources?: Record<string, readonly string[] | {
34
+ entities: readonly string[];
35
+ }>;
36
+ shell?: ShellManifest;
37
+ pages?: Record<string, PageManifest>;
38
+ grammars?: readonly Sequence[];
39
+ functions?: (session: FunctionSession) => Record<string, FunctionHandler>;
40
+ onSession?: (session: FunctionSession) => void;
41
+ runs?: RunSink;
42
+ reactions?: readonly {
43
+ table: string;
44
+ op?: 'insert' | 'update' | 'delete';
45
+ run: (event: {
46
+ fingerprint: string;
47
+ table: string;
48
+ op: 'insert' | 'update' | 'delete';
49
+ count: number;
50
+ scope: Record<string, unknown>;
51
+ }, tools: {
52
+ deliver: (principal: string, channel: string, payload?: unknown) => boolean;
53
+ }) => void;
54
+ }[];
55
+ };
56
+ type RunTurn = {
57
+ role: 'system' | 'user' | 'assistant' | 'tool';
58
+ content: string;
59
+ calls?: ReadonlyArray<{
60
+ name: string;
61
+ args: string;
62
+ }>;
63
+ name?: string;
64
+ };
65
+ type RunRecord = {
66
+ at: number;
67
+ principal: string | null;
68
+ shellId: string;
69
+ agentId: string;
70
+ agentPath: readonly string[];
71
+ label: string;
72
+ provider: string;
73
+ model: string;
74
+ inputTokens: number;
75
+ outputTokens: number;
76
+ totalTokens: number;
77
+ reported: boolean;
78
+ steps: number;
79
+ elapsedMs: number;
80
+ turns?: readonly RunTurn[];
81
+ response?: string;
82
+ outcome: 'ok' | 'failed';
83
+ };
84
+ type RunSink = (record: RunRecord, session: FunctionSession) => void;
85
+ type FunctionSession = {
86
+ shell: Shell;
87
+ principal: string | null;
88
+ roles: readonly string[];
89
+ identity: Record<string, unknown>;
90
+ actions: readonly string[];
91
+ wire: FetchFn;
92
+ grant: (token: string) => void;
93
+ revoke: () => Promise<void>;
94
+ answerIntent: (writers: {
95
+ generateDsl: GenerateDsl;
96
+ mapToShape: MapToShape;
97
+ }, asked: {
98
+ intent: string;
99
+ shape: unknown;
100
+ context?: Record<string, unknown>;
101
+ }) => Promise<QueryResponse>;
102
+ recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;
103
+ };
104
+ type CanvasSeed = string | {
105
+ action: string;
106
+ input?: Record<string, unknown>;
107
+ with?: string[];
108
+ };
109
+ type ShellCanvas = Omit<CanvasConfig, 'initial'> & {
110
+ initial?: CanvasSeed | CanvasSeed[];
111
+ };
112
+ type ShellManifest = {
113
+ canvases: ShellCanvas[];
114
+ layout?: LayoutNode;
115
+ layoutStore?: Record<string, LayoutNode>;
116
+ fragments?: Record<string, ActionFragment>;
117
+ seeds?: (session: {
118
+ principal: string | null;
119
+ actions: readonly string[];
120
+ roles: readonly string[];
121
+ wire: FetchFn;
122
+ }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;
123
+ components?: Record<string, {
124
+ meta?: {
125
+ description?: string;
126
+ propsSchema?: unknown;
127
+ };
128
+ }>;
129
+ inputs?: (session: {
130
+ principal: string | null;
131
+ actions: readonly string[];
132
+ roles: readonly string[];
133
+ identity: Record<string, unknown>;
134
+ wire: FetchFn;
135
+ }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;
136
+ };
137
+ type PageManifest = ShellManifest & {
138
+ path: string;
139
+ params?: string;
140
+ };
141
+ declare const defineApp: (app: NiscApp) => NiscApp;
142
+
143
+ export { type FunctionSession as F, type LayoutVariant as L, type NiscApp as N, type PageManifest as P, type RunRecord as R, type ShellManifest as S, type RunSink as a, type RunTurn as b, defineApp as d };
@@ -0,0 +1,143 @@
1
+ import { Sequence } from '@niscorp/strata';
2
+ import { GenerateDsl, MapToShape, QueryResponse, ScopeBehaviors, SeedEntry, SeedMutation } from '@niscorp/vex';
3
+ import { Charter } from '@niscorp/charter';
4
+ import { Shell, FetchFn, LayoutNode, ActionDefinition, CanvasConfig, ActionFragment, FunctionHandler } from '@niscorp/nova';
5
+ import { Phrasebook, PhraseKeys } from '@niscorp/nova/i18n';
6
+ import { F as Feature } from './index-B411sK9M.cjs';
7
+ import { I as IdentityRecord } from './document-D7nroBww.cjs';
8
+
9
+ type LayoutVariant = {
10
+ action: string;
11
+ layout: LayoutNode;
12
+ };
13
+ type NiscApp = {
14
+ charter: Charter;
15
+ assignments?: Record<string, readonly string[]>;
16
+ wearable?: readonly (readonly string[])[];
17
+ actions: Record<string, ActionDefinition>;
18
+ layouts?: Record<string, LayoutVariant>;
19
+ behaviors?: ScopeBehaviors;
20
+ scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;
21
+ identity?: {
22
+ as?: string;
23
+ resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;
24
+ };
25
+ phrases?: (session: {
26
+ principal: string | null;
27
+ identity: Record<string, unknown>;
28
+ wire: FetchFn;
29
+ }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;
30
+ phraseKeys?: PhraseKeys;
31
+ features?: readonly Feature[];
32
+ entries?: readonly (SeedEntry | SeedMutation)[];
33
+ resources?: Record<string, readonly string[] | {
34
+ entities: readonly string[];
35
+ }>;
36
+ shell?: ShellManifest;
37
+ pages?: Record<string, PageManifest>;
38
+ grammars?: readonly Sequence[];
39
+ functions?: (session: FunctionSession) => Record<string, FunctionHandler>;
40
+ onSession?: (session: FunctionSession) => void;
41
+ runs?: RunSink;
42
+ reactions?: readonly {
43
+ table: string;
44
+ op?: 'insert' | 'update' | 'delete';
45
+ run: (event: {
46
+ fingerprint: string;
47
+ table: string;
48
+ op: 'insert' | 'update' | 'delete';
49
+ count: number;
50
+ scope: Record<string, unknown>;
51
+ }, tools: {
52
+ deliver: (principal: string, channel: string, payload?: unknown) => boolean;
53
+ }) => void;
54
+ }[];
55
+ };
56
+ type RunTurn = {
57
+ role: 'system' | 'user' | 'assistant' | 'tool';
58
+ content: string;
59
+ calls?: ReadonlyArray<{
60
+ name: string;
61
+ args: string;
62
+ }>;
63
+ name?: string;
64
+ };
65
+ type RunRecord = {
66
+ at: number;
67
+ principal: string | null;
68
+ shellId: string;
69
+ agentId: string;
70
+ agentPath: readonly string[];
71
+ label: string;
72
+ provider: string;
73
+ model: string;
74
+ inputTokens: number;
75
+ outputTokens: number;
76
+ totalTokens: number;
77
+ reported: boolean;
78
+ steps: number;
79
+ elapsedMs: number;
80
+ turns?: readonly RunTurn[];
81
+ response?: string;
82
+ outcome: 'ok' | 'failed';
83
+ };
84
+ type RunSink = (record: RunRecord, session: FunctionSession) => void;
85
+ type FunctionSession = {
86
+ shell: Shell;
87
+ principal: string | null;
88
+ roles: readonly string[];
89
+ identity: Record<string, unknown>;
90
+ actions: readonly string[];
91
+ wire: FetchFn;
92
+ grant: (token: string) => void;
93
+ revoke: () => Promise<void>;
94
+ answerIntent: (writers: {
95
+ generateDsl: GenerateDsl;
96
+ mapToShape: MapToShape;
97
+ }, asked: {
98
+ intent: string;
99
+ shape: unknown;
100
+ context?: Record<string, unknown>;
101
+ }) => Promise<QueryResponse>;
102
+ recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;
103
+ };
104
+ type CanvasSeed = string | {
105
+ action: string;
106
+ input?: Record<string, unknown>;
107
+ with?: string[];
108
+ };
109
+ type ShellCanvas = Omit<CanvasConfig, 'initial'> & {
110
+ initial?: CanvasSeed | CanvasSeed[];
111
+ };
112
+ type ShellManifest = {
113
+ canvases: ShellCanvas[];
114
+ layout?: LayoutNode;
115
+ layoutStore?: Record<string, LayoutNode>;
116
+ fragments?: Record<string, ActionFragment>;
117
+ seeds?: (session: {
118
+ principal: string | null;
119
+ actions: readonly string[];
120
+ roles: readonly string[];
121
+ wire: FetchFn;
122
+ }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;
123
+ components?: Record<string, {
124
+ meta?: {
125
+ description?: string;
126
+ propsSchema?: unknown;
127
+ };
128
+ }>;
129
+ inputs?: (session: {
130
+ principal: string | null;
131
+ actions: readonly string[];
132
+ roles: readonly string[];
133
+ identity: Record<string, unknown>;
134
+ wire: FetchFn;
135
+ }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;
136
+ };
137
+ type PageManifest = ShellManifest & {
138
+ path: string;
139
+ params?: string;
140
+ };
141
+ declare const defineApp: (app: NiscApp) => NiscApp;
142
+
143
+ export { type FunctionSession as F, type LayoutVariant as L, type NiscApp as N, type PageManifest as P, type RunRecord as R, type ShellManifest as S, type RunSink as a, type RunTurn as b, defineApp as d };
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ // src/protocol/connection.ts
6
+ var PROTOCOL = 2;
7
+ var PROTOCOL_MIN = 2;
8
+ var SUBPROTOCOL = "nisc";
9
+ var TOKEN_OFFER = "nisc.token.";
10
+ var SEALED_OFFER = "nisc.sealed.";
11
+ var offerToken = (token, sealed = null) => {
12
+ const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
13
+ if (token === null) return offer;
14
+ const bytes = String.fromCharCode(...new TextEncoder().encode(token));
15
+ return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
16
+ };
17
+ var offeredToken = (offered = []) => {
18
+ const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));
19
+ if (offer === void 0) return null;
20
+ try {
21
+ const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, "+").replace(/_/g, "/"));
22
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ };
27
+ var offeredSealed = (offered = []) => offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;
28
+ var CLOSE_INVALID_TOKEN = 4401;
29
+ var CLOSE_SIGNED_OUT = 4403;
30
+ var CLOSE_SHELL_FAILED = 4500;
31
+ var CLOSE_AT_CAPACITY = 4503;
32
+ var CLOSE_PROTOCOL_MISMATCH = 4426;
33
+ var DEFAULT_TOKEN_KEY = "nisc.token";
34
+ var sessionNameOf = (key2, port) => `${key2}${port === "" ? "" : `.${port}`}`;
35
+ var heldCookieName = (key2 = DEFAULT_TOKEN_KEY, port = "") => encodeURIComponent(`${sessionNameOf(key2, port)}.held`);
36
+
37
+ // src/protocol/delta.ts
38
+ var BLOCK = 16;
39
+ var encodeDelta = (base, target) => {
40
+ if (base.length < BLOCK) return [[1, target]];
41
+ const index = /* @__PURE__ */ new Map();
42
+ for (let i = 0; i + BLOCK <= base.length; i += 1) {
43
+ const key2 = base.slice(i, i + BLOCK);
44
+ if (!index.has(key2)) index.set(key2, i);
45
+ }
46
+ const ops = [];
47
+ let literal = "";
48
+ let at = 0;
49
+ while (at < target.length) {
50
+ const key2 = target.slice(at, at + BLOCK);
51
+ const found = key2.length === BLOCK ? index.get(key2) : void 0;
52
+ if (found === void 0) {
53
+ literal += target[at];
54
+ at += 1;
55
+ continue;
56
+ }
57
+ let length = BLOCK;
58
+ while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {
59
+ length += 1;
60
+ }
61
+ if (literal !== "") {
62
+ ops.push([1, literal]);
63
+ literal = "";
64
+ }
65
+ ops.push([0, found, length]);
66
+ at += length;
67
+ }
68
+ if (literal !== "") ops.push([1, literal]);
69
+ return ops;
70
+ };
71
+ var applyDelta = (base, ops) => {
72
+ let out = "";
73
+ for (const op of ops) {
74
+ if (op[0] === 1) {
75
+ out += op[1];
76
+ continue;
77
+ }
78
+ const [, offset, length] = op;
79
+ if (offset < 0 || length < 0 || offset + length > base.length) {
80
+ throw new Error(`moss/delta: copy ${offset}+${length} is outside a base of ${base.length}`);
81
+ }
82
+ out += base.slice(offset, offset + length);
83
+ }
84
+ return out;
85
+ };
86
+ var frameHash = (text) => {
87
+ let hash = 2166136261;
88
+ for (let i = 0; i < text.length; i += 1) {
89
+ hash ^= text.charCodeAt(i);
90
+ hash = Math.imul(hash, 16777619);
91
+ }
92
+ return hash >>> 0;
93
+ };
94
+ var key = zod.z.string().optional();
95
+ var children = zod.z.lazy(() => zod.z.array(RenderNodeSchema));
96
+ var renderNodeShapes = zod.z.discriminatedUnion("type", [
97
+ zod.z.strictObject({
98
+ type: zod.z.literal("component"),
99
+ name: zod.z.string(),
100
+ props: zod.z.record(zod.z.string(), zod.z.unknown()),
101
+ children,
102
+ ref: zod.z.string().optional(),
103
+ key,
104
+ model: zod.z.strictObject({ path: zod.z.string(), ref: zod.z.string() }).optional()
105
+ }),
106
+ zod.z.strictObject({ type: zod.z.literal("text"), value: zod.z.string(), key }),
107
+ zod.z.strictObject({ type: zod.z.literal("fragment"), children, key }),
108
+ zod.z.strictObject({ type: zod.z.literal("error"), code: zod.z.string(), message: zod.z.string(), nodeRef: zod.z.string().optional(), key })
109
+ ]);
110
+ var RenderNodeSchema = renderNodeShapes;
111
+ var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
112
+ var DocumentSnapshotSchema = zod.z.strictObject({
113
+ frame: zod.z.array(RenderNodeSchema),
114
+ trees: zod.z.record(zod.z.string(), zod.z.array(RenderNodeSchema)),
115
+ seed: zod.z.string().optional(),
116
+ // Whether it was drawn for somebody signed in, not who.
117
+ principal: zod.z.boolean(),
118
+ path: zod.z.string().optional(),
119
+ // False when nothing on the screen can still happen. Absent reads as live.
120
+ live: zod.z.boolean().optional()
121
+ });
122
+ var DeltaOpSchema = zod.z.union([zod.z.tuple([zod.z.literal(0), zod.z.number(), zod.z.number()]), zod.z.tuple([zod.z.literal(1), zod.z.string()])]);
123
+ var catalogActions = zod.z.array(zod.z.string()).readonly();
124
+ var ServerMessageByTypeSchema = zod.z.discriminatedUnion("type", [
125
+ zod.z.strictObject({
126
+ type: zod.z.literal("hello"),
127
+ // A server that names none speaks 1.
128
+ protocol: zod.z.number().default(1),
129
+ principal: zod.z.string().nullable(),
130
+ catalog: zod.z.strictObject({ actions: catalogActions, hash: zod.z.string() })
131
+ }),
132
+ zod.z.strictObject({ type: zod.z.literal("catalog"), actions: catalogActions, hash: zod.z.string() }),
133
+ zod.z.strictObject({ type: zod.z.literal("frame"), tree: zod.z.array(RenderNodeSchema) }),
134
+ zod.z.strictObject({ type: zod.z.literal("render"), canvas: zod.z.string(), tree: zod.z.array(RenderNodeSchema) }),
135
+ zod.z.strictObject({ type: zod.z.literal("render-delta"), canvas: zod.z.string(), ops: zod.z.array(DeltaOpSchema), hash: zod.z.number() }),
136
+ zod.z.strictObject({ type: zod.z.literal("error"), code: zod.z.string(), message: zod.z.string(), canvas: zod.z.string().optional() })
137
+ ]);
138
+ var ServerMessageSchema = zod.z.union([
139
+ ServerMessageByTypeSchema,
140
+ zod.z.strictObject({ type: zod.z.literal("session"), token: zod.z.string() }),
141
+ zod.z.strictObject({ type: zod.z.literal("session"), sealed: zod.z.string() })
142
+ ]);
143
+ var ClientMessageSchema = zod.z.discriminatedUnion("type", [
144
+ zod.z.strictObject({ type: zod.z.literal("event"), canvas: zod.z.string(), event: zod.z.record(zod.z.string(), zod.z.unknown()) }),
145
+ zod.z.strictObject({ type: zod.z.literal("publish"), channel: zod.z.string(), payload: zod.z.unknown().optional() }),
146
+ zod.z.strictObject({ type: zod.z.literal("resync") }),
147
+ zod.z.strictObject({ type: zod.z.literal("back") }),
148
+ zod.z.strictObject({ type: zod.z.literal("popTo"), canvas: zod.z.string(), instance: zod.z.string() }),
149
+ zod.z.strictObject({ type: zod.z.literal("reset") })
150
+ ]);
151
+
152
+ exports.CLOSE_AT_CAPACITY = CLOSE_AT_CAPACITY;
153
+ exports.CLOSE_INVALID_TOKEN = CLOSE_INVALID_TOKEN;
154
+ exports.CLOSE_PROTOCOL_MISMATCH = CLOSE_PROTOCOL_MISMATCH;
155
+ exports.CLOSE_SHELL_FAILED = CLOSE_SHELL_FAILED;
156
+ exports.CLOSE_SIGNED_OUT = CLOSE_SIGNED_OUT;
157
+ exports.ClientMessageSchema = ClientMessageSchema;
158
+ exports.DEFAULT_TOKEN_KEY = DEFAULT_TOKEN_KEY;
159
+ exports.DocumentSnapshotSchema = DocumentSnapshotSchema;
160
+ exports.PROTOCOL = PROTOCOL;
161
+ exports.PROTOCOL_MIN = PROTOCOL_MIN;
162
+ exports.SNAPSHOT_ELEMENT_ID = SNAPSHOT_ELEMENT_ID;
163
+ exports.SUBPROTOCOL = SUBPROTOCOL;
164
+ exports.ServerMessageSchema = ServerMessageSchema;
165
+ exports.applyDelta = applyDelta;
166
+ exports.encodeDelta = encodeDelta;
167
+ exports.frameHash = frameHash;
168
+ exports.heldCookieName = heldCookieName;
169
+ exports.offerToken = offerToken;
170
+ exports.offeredSealed = offeredSealed;
171
+ exports.offeredToken = offeredToken;
172
+ exports.sessionNameOf = sessionNameOf;
173
+ //# sourceMappingURL=chunk-3RIWTXGI.cjs.map
174
+ //# sourceMappingURL=chunk-3RIWTXGI.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol/connection.ts","../src/protocol/delta.ts","../src/protocol/messages.ts"],"names":["key","z"],"mappings":";;;;;AACO,IAAM,QAAA,GAAW;AACjB,IAAM,YAAA,GAAe;AAKrB,IAAM,WAAA,GAAc;AAC3B,IAAM,WAAA,GAAc,aAAA;AACpB,IAAM,YAAA,GAAe,cAAA;AAEd,IAAM,UAAA,GAAa,CAAC,KAAA,EAAsB,MAAA,GAAwB,IAAA,KAAmB;AAC1F,EAAA,MAAM,KAAA,GAAQ,MAAA,KAAW,IAAA,GAAO,CAAC,WAAW,CAAA,GAAI,CAAC,WAAA,EAAa,CAAA,EAAG,YAAY,CAAA,EAAG,MAAM,CAAA,CAAE,CAAA;AACxF,EAAA,IAAI,KAAA,KAAU,MAAM,OAAO,KAAA;AAC3B,EAAA,MAAM,KAAA,GAAQ,OAAO,YAAA,CAAa,GAAG,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAC,CAAA;AACpE,EAAA,OAAO,CAAC,GAAG,KAAA,EAAO,CAAA,EAAG,WAAW,CAAA,EAAG,IAAA,CAAK,KAAK,CAAA,CAAE,OAAA,CAAQ,OAAO,GAAG,CAAA,CAAE,QAAQ,KAAA,EAAO,GAAG,EAAE,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAC,CAAA,CAAE,CAAA;AAC7G;AAEO,IAAM,YAAA,GAAe,CAAC,OAAA,GAA6B,EAAC,KAAqB;AAC9E,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A;AAAA,EAC1CA,MAAE,YAAA,CAAa,EAAE,IAAA,EAAMA,KAAA,CAAE,QAAQ,OAAO,CAAA,EAAG,MAAA,EAAQA,KAAA,CAAE,QAAO,EAAG,QAAA,EAAUA,KAAA,CAAE,MAAA,IAAU,CAAA;AAAA,EACrFA,KAAA,CAAE,aAAa,EAAE,IAAA,EAAMA,MAAE,OAAA,CAAQ,OAAO,GAAG;AAC7C,CAAC","file":"chunk-3RIWTXGI.cjs","sourcesContent":["// PROTOCOL moves when a message changes shape; PROTOCOL_MIN when the server stops speaking an old one.\nexport const PROTOCOL = 2;\nexport const PROTOCOL_MIN = 2;\n\n// A terminal says who it is in the subprotocols it offers, the one header a browser lets it set\n// on an upgrade, and never in the address, which every proxy on the way logs. The token is\n// base64url because a subprotocol is an HTTP token and a session token need not be.\nexport const SUBPROTOCOL = 'nisc';\nconst TOKEN_OFFER = 'nisc.token.';\nconst SEALED_OFFER = 'nisc.sealed.';\n\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\nexport const offeredSealed = (offered: readonly string[] = []): string | null => offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;\n\nexport const CLOSE_INVALID_TOKEN = 4401;\nexport const CLOSE_SIGNED_OUT = 4403;\nexport const CLOSE_SHELL_FAILED = 4500;\nexport const CLOSE_AT_CAPACITY = 4503;\nexport const CLOSE_PROTOCOL_MISMATCH = 4426;\n\nexport const DEFAULT_TOKEN_KEY = 'nisc.token';\n\n// The name ends with the port because a browser keeps cookies by host and not by port: two apps\n// on localhost would otherwise sign each other out.\nexport const sessionNameOf = (key: string, port: string): string => `${key}${port === '' ? '' : `.${port}`}`;\n\nexport const heldCookieName = (key = DEFAULT_TOKEN_KEY, port = ''): string => encodeURIComponent(`${sessionNameOf(key, port)}.held`);\n","import type { DeltaOp } from './messages';\n\n// The shortest run worth a copy, in characters.\nconst BLOCK = 16;\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 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\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\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 { z } from 'zod';\nimport type { RenderNode } from '@niscorp/nova';\n\nconst key = z.string().optional();\nconst children = z.lazy(() => z.array(RenderNodeSchema));\n\nexport const renderNodeShapes = z.discriminatedUnion('type', [\n z.strictObject({\n type: z.literal('component'),\n name: z.string(),\n props: z.record(z.string(), z.unknown()),\n children,\n ref: z.string().optional(),\n key,\n model: z.strictObject({ path: z.string(), ref: z.string() }).optional(),\n }),\n z.strictObject({ type: z.literal('text'), value: z.string(), key }),\n z.strictObject({ type: z.literal('fragment'), children, key }),\n z.strictObject({ type: z.literal('error'), code: z.string(), message: z.string(), nodeRef: z.string().optional(), key }),\n]);\n\n// Nova publishes the node as a type and no schema. The annotation refuses a schema wider than\n// that type, and a test refuses the two differing at all.\nexport const RenderNodeSchema: z.ZodType<RenderNode> = renderNodeShapes;\n\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\nexport const DocumentSnapshotSchema = z.strictObject({\n frame: z.array(RenderNodeSchema),\n trees: z.record(z.string(), z.array(RenderNodeSchema)),\n seed: z.string().optional(),\n // Whether it was drawn for somebody signed in, not who.\n principal: z.boolean(),\n path: z.string().optional(),\n // False when nothing on the screen can still happen. Absent reads as live.\n live: z.boolean().optional(),\n});\nexport type DocumentSnapshot = z.infer<typeof DocumentSnapshotSchema>;\n\n// [0, offset, length] copies a run of the base frame; [1, text] is text the base does not hold.\nexport const DeltaOpSchema = z.union([z.tuple([z.literal(0), z.number(), z.number()]), z.tuple([z.literal(1), z.string()])]);\nexport type DeltaOp = z.infer<typeof DeltaOpSchema>;\n\nconst catalogActions = z.array(z.string()).readonly();\n\nconst ServerMessageByTypeSchema = z.discriminatedUnion('type', [\n z.strictObject({\n type: z.literal('hello'),\n // A server that names none speaks 1.\n protocol: z.number().default(1),\n principal: z.string().nullable(),\n catalog: z.strictObject({ actions: catalogActions, hash: z.string() }),\n }),\n z.strictObject({ type: z.literal('catalog'), actions: catalogActions, hash: z.string() }),\n z.strictObject({ type: z.literal('frame'), tree: z.array(RenderNodeSchema) }),\n z.strictObject({ type: z.literal('render'), canvas: z.string(), tree: z.array(RenderNodeSchema) }),\n z.strictObject({ type: z.literal('render-delta'), canvas: z.string(), ops: z.array(DeltaOpSchema), hash: z.number() }),\n z.strictObject({ type: z.literal('error'), code: z.string(), message: z.string(), canvas: z.string().optional() }),\n]);\n\n// `session` is two shapes under one type, which a union discriminated on the type cannot hold:\n// they sit beside it.\nexport const ServerMessageSchema = z.union([\n ServerMessageByTypeSchema,\n z.strictObject({ type: z.literal('session'), token: z.string() }),\n z.strictObject({ type: z.literal('session'), sealed: z.string() }),\n]);\nexport type ServerMessage = z.infer<typeof ServerMessageSchema>;\n\nexport const ClientMessageSchema = z.discriminatedUnion('type', [\n z.strictObject({ type: z.literal('event'), canvas: z.string(), event: z.record(z.string(), z.unknown()) }),\n z.strictObject({ type: z.literal('publish'), channel: z.string(), payload: z.unknown().optional() }),\n z.strictObject({ type: z.literal('resync') }),\n z.strictObject({ type: z.literal('back') }),\n z.strictObject({ type: z.literal('popTo'), canvas: z.string(), instance: z.string() }),\n z.strictObject({ type: z.literal('reset') }),\n]);\nexport type ClientMessage = z.infer<typeof ClientMessageSchema>;\n"]}