@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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 (283) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +201 -0
  3. package/README.md +233 -2
  4. package/bin/ui-kit.js +12 -0
  5. package/dist/alchemy/app.d.ts +34 -0
  6. package/dist/alchemy/app.js +88 -0
  7. package/dist/alchemy/index.d.ts +11 -0
  8. package/dist/alchemy/index.js +11 -0
  9. package/dist/alchemy/live-rooms.d.ts +21 -0
  10. package/dist/alchemy/live-rooms.js +31 -0
  11. package/dist/alchemy/migrations.d.ts +28 -0
  12. package/dist/alchemy/migrations.js +56 -0
  13. package/dist/alchemy/stage.d.ts +20 -0
  14. package/dist/alchemy/stage.js +20 -0
  15. package/dist/alchemy/wrangler-config.d.ts +76 -0
  16. package/dist/alchemy/wrangler-config.js +82 -0
  17. package/dist/build/app-modules.d.ts +11 -0
  18. package/dist/build/app-modules.js +40 -0
  19. package/dist/build/check.d.ts +4 -0
  20. package/dist/build/check.js +170 -0
  21. package/dist/build/cli.d.ts +1 -0
  22. package/dist/build/cli.js +79 -0
  23. package/dist/build/feature.d.ts +8 -0
  24. package/dist/build/feature.js +24 -0
  25. package/dist/build/index.d.ts +13 -0
  26. package/dist/build/index.js +13 -0
  27. package/dist/build/measure-cpu.d.ts +2 -0
  28. package/dist/build/measure-cpu.js +196 -0
  29. package/dist/build/prerender.d.ts +5 -0
  30. package/dist/build/prerender.js +109 -0
  31. package/dist/build/preview.d.ts +7 -0
  32. package/dist/build/preview.js +41 -0
  33. package/dist/build/seo-files.d.ts +27 -0
  34. package/dist/build/seo-files.js +24 -0
  35. package/dist/client/head-swap.d.ts +45 -0
  36. package/dist/client/head-swap.js +183 -0
  37. package/dist/client/hydration-pass.d.ts +56 -0
  38. package/dist/client/hydration-pass.js +186 -0
  39. package/dist/client/hydration-reset.d.ts +82 -0
  40. package/dist/client/hydration-reset.js +154 -0
  41. package/dist/client/index.d.ts +37 -0
  42. package/dist/client/index.js +65 -0
  43. package/dist/client/nav-client.d.ts +35 -0
  44. package/dist/client/nav-client.js +371 -0
  45. package/dist/live/collab/doc-provider.d.ts +74 -0
  46. package/dist/live/collab/doc-provider.js +412 -0
  47. package/dist/live/collab/index.d.ts +51 -0
  48. package/dist/live/collab/index.jsx +142 -0
  49. package/dist/live/collab-status.d.ts +25 -0
  50. package/dist/live/collab-status.js +17 -0
  51. package/dist/live/cursors/cursor-engine.d.ts +57 -0
  52. package/dist/live/cursors/cursor-engine.js +243 -0
  53. package/dist/live/cursors/index.d.ts +46 -0
  54. package/dist/live/cursors/index.jsx +110 -0
  55. package/dist/live/declaration.d.ts +113 -0
  56. package/dist/live/declaration.js +94 -0
  57. package/dist/live/index.d.ts +8 -0
  58. package/dist/live/index.js +8 -0
  59. package/dist/live/protocol.d.ts +224 -0
  60. package/dist/live/protocol.js +272 -0
  61. package/dist/live/server/doc-store.d.ts +68 -0
  62. package/dist/live/server/doc-store.js +187 -0
  63. package/dist/live/server/index.d.ts +60 -0
  64. package/dist/live/server/index.js +77 -0
  65. package/dist/live/server/room-presence.d.ts +24 -0
  66. package/dist/live/server/room-presence.js +123 -0
  67. package/dist/live/server/room-sockets.d.ts +65 -0
  68. package/dist/live/server/room-sockets.js +97 -0
  69. package/dist/live/server/room.d.ts +20 -0
  70. package/dist/live/server/room.js +348 -0
  71. package/dist/live/server/route.d.ts +56 -0
  72. package/dist/live/server/route.js +159 -0
  73. package/dist/live/server/types.d.ts +163 -0
  74. package/dist/live/server/types.js +2 -0
  75. package/dist/logic/agent-actions.d.ts +133 -0
  76. package/dist/logic/agent-actions.js +150 -0
  77. package/dist/logic/command-types.d.ts +53 -0
  78. package/dist/logic/command-types.js +0 -0
  79. package/dist/logic/dev.d.ts +9 -0
  80. package/dist/logic/dev.js +10 -0
  81. package/dist/logic/draft-rebase.d.ts +59 -0
  82. package/dist/logic/draft-rebase.js +71 -0
  83. package/dist/logic/form-state.d.ts +105 -0
  84. package/dist/logic/form-state.js +93 -0
  85. package/dist/logic/head.d.ts +145 -0
  86. package/dist/logic/head.js +140 -0
  87. package/dist/logic/index.d.ts +27 -0
  88. package/dist/logic/index.js +25 -0
  89. package/dist/logic/island-def.d.ts +89 -0
  90. package/dist/logic/island-def.js +59 -0
  91. package/dist/logic/kit-commands.d.ts +104 -0
  92. package/dist/logic/kit-commands.js +72 -0
  93. package/dist/logic/kit-errors.d.ts +25 -0
  94. package/dist/logic/kit-errors.js +6 -0
  95. package/dist/logic/listen.d.ts +99 -0
  96. package/dist/logic/listen.js +92 -0
  97. package/dist/logic/mutation-def.d.ts +65 -0
  98. package/dist/logic/mutation-def.js +43 -0
  99. package/dist/logic/navigation-data.d.ts +50 -0
  100. package/dist/logic/navigation-data.js +55 -0
  101. package/dist/logic/navigation-policy.d.ts +74 -0
  102. package/dist/logic/navigation-policy.js +127 -0
  103. package/dist/logic/page-model-def.d.ts +108 -0
  104. package/dist/logic/page-model-def.js +31 -0
  105. package/dist/logic/path.d.ts +31 -0
  106. package/dist/logic/path.js +48 -0
  107. package/dist/logic/query-def.d.ts +56 -0
  108. package/dist/logic/query-def.js +37 -0
  109. package/dist/logic/query-key.d.ts +24 -0
  110. package/dist/logic/query-key.js +35 -0
  111. package/dist/logic/query-types.d.ts +28 -0
  112. package/dist/logic/query-types.js +2 -0
  113. package/dist/logic/resources.d.ts +163 -0
  114. package/dist/logic/resources.js +62 -0
  115. package/dist/logic/result.d.ts +30 -0
  116. package/dist/logic/result.js +23 -0
  117. package/dist/logic/route-model.d.ts +139 -0
  118. package/dist/logic/route-model.js +207 -0
  119. package/dist/logic/route-params.d.ts +80 -0
  120. package/dist/logic/route-params.js +114 -0
  121. package/dist/logic/route-table.d.ts +308 -0
  122. package/dist/logic/route-table.js +206 -0
  123. package/dist/logic/seo.d.ts +61 -0
  124. package/dist/logic/seo.js +101 -0
  125. package/dist/logic/site.d.ts +12 -0
  126. package/dist/logic/site.js +0 -0
  127. package/dist/logic/subscriptions.d.ts +177 -0
  128. package/dist/logic/subscriptions.js +152 -0
  129. package/dist/render/index.d.ts +32 -0
  130. package/dist/render/index.js +52 -0
  131. package/dist/runtime/island-wake.d.ts +38 -0
  132. package/dist/runtime/island-wake.js +147 -0
  133. package/dist/runtime/query-scope.d.ts +224 -0
  134. package/dist/runtime/query-scope.js +222 -0
  135. package/dist/runtime/room-hub.d.ts +107 -0
  136. package/dist/runtime/room-hub.js +307 -0
  137. package/dist/runtime/subscription-runner.d.ts +71 -0
  138. package/dist/runtime/subscription-runner.js +240 -0
  139. package/dist/server/bindings.d.ts +41 -0
  140. package/dist/server/bindings.js +74 -0
  141. package/dist/server/browser.d.ts +9 -0
  142. package/dist/server/browser.js +9 -0
  143. package/dist/server/edge-cache.d.ts +28 -0
  144. package/dist/server/edge-cache.js +35 -0
  145. package/dist/server/errors.d.ts +45 -0
  146. package/dist/server/errors.js +36 -0
  147. package/dist/server/form-actions-setup.d.ts +1 -0
  148. package/dist/server/form-actions-setup.js +15 -0
  149. package/dist/server/form-actions.d.ts +121 -0
  150. package/dist/server/form-actions.js +211 -0
  151. package/dist/server/index.d.ts +36 -0
  152. package/dist/server/index.js +35 -0
  153. package/dist/server/inputs.d.ts +45 -0
  154. package/dist/server/inputs.js +77 -0
  155. package/dist/server/rate-limit.d.ts +29 -0
  156. package/dist/server/rate-limit.js +32 -0
  157. package/dist/server/read-cache.d.ts +74 -0
  158. package/dist/server/read-cache.js +58 -0
  159. package/dist/server/request-info.d.ts +17 -0
  160. package/dist/server/request-info.js +11 -0
  161. package/dist/server/request.d.ts +52 -0
  162. package/dist/server/request.js +73 -0
  163. package/dist/server/response-cookies.d.ts +23 -0
  164. package/dist/server/response-cookies.js +24 -0
  165. package/dist/server/run-effect.d.ts +42 -0
  166. package/dist/server/run-effect.js +92 -0
  167. package/dist/server/run.d.ts +63 -0
  168. package/dist/server/run.js +66 -0
  169. package/dist/server/session.d.ts +125 -0
  170. package/dist/server/session.js +247 -0
  171. package/dist/test/fake-bindings.d.ts +32 -0
  172. package/dist/test/fake-bindings.js +108 -0
  173. package/dist/test/fake-room.d.ts +66 -0
  174. package/dist/test/fake-room.js +216 -0
  175. package/dist/test/index.d.ts +19 -0
  176. package/dist/test/index.js +44 -0
  177. package/dist/test/probe.d.ts +11 -0
  178. package/dist/test/probe.js +11 -0
  179. package/dist/test/solid-jsx.d.ts +23 -0
  180. package/dist/test/solid-jsx.js +28 -0
  181. package/dist/test/solid-preload.d.ts +1 -0
  182. package/dist/test/solid-preload.js +29 -0
  183. package/dist/ui/code-editor/index.d.ts +21 -0
  184. package/dist/ui/code-editor/index.jsx +286 -0
  185. package/dist/ui/collab-text/index.d.ts +29 -0
  186. package/dist/ui/collab-text/index.jsx +96 -0
  187. package/dist/ui/components/controls.d.ts +69 -0
  188. package/dist/ui/components/controls.jsx +81 -0
  189. package/dist/ui/components/feedback.d.ts +26 -0
  190. package/dist/ui/components/feedback.jsx +80 -0
  191. package/dist/ui/components/layout.d.ts +74 -0
  192. package/dist/ui/components/layout.jsx +146 -0
  193. package/dist/ui/components/lists.d.ts +69 -0
  194. package/dist/ui/components/lists.jsx +133 -0
  195. package/dist/ui/components/navigation.d.ts +73 -0
  196. package/dist/ui/components/navigation.jsx +112 -0
  197. package/dist/ui/components/text.d.ts +34 -0
  198. package/dist/ui/components/text.jsx +163 -0
  199. package/dist/ui/index.d.ts +7 -0
  200. package/dist/ui/index.js +7 -0
  201. package/dist/ui/jsx-runtime.d.ts +19 -0
  202. package/dist/ui/jsx-runtime.js +0 -0
  203. package/dist/ui/list-keys.d.ts +31 -0
  204. package/dist/ui/list-keys.js +45 -0
  205. package/dist/ui/styles/base.css +38 -0
  206. package/dist/ui/styles/components.css +608 -0
  207. package/dist/ui/styles/tokens.css +27 -0
  208. package/dist/ui/styles/transitions.css +23 -0
  209. package/dist/ui/styles/workbench.css +428 -0
  210. package/dist/ui/styles.css +9 -0
  211. package/dist/view/agent-actions-view.d.ts +30 -0
  212. package/dist/view/agent-actions-view.js +27 -0
  213. package/dist/view/agent-surface.d.ts +42 -0
  214. package/dist/view/agent-surface.js +123 -0
  215. package/dist/view/app-scope.d.ts +51 -0
  216. package/dist/view/app-scope.js +75 -0
  217. package/dist/view/boundary.d.ts +18 -0
  218. package/dist/view/boundary.jsx +26 -0
  219. package/dist/view/command-runner.d.ts +16 -0
  220. package/dist/view/command-runner.js +245 -0
  221. package/dist/view/form.d.ts +82 -0
  222. package/dist/view/form.jsx +109 -0
  223. package/dist/view/head-view.d.ts +31 -0
  224. package/dist/view/head-view.js +46 -0
  225. package/dist/view/index.d.ts +41 -0
  226. package/dist/view/index.js +40 -0
  227. package/dist/view/island-root.d.ts +30 -0
  228. package/dist/view/island-root.js +36 -0
  229. package/dist/view/island.d.ts +102 -0
  230. package/dist/view/island.jsx +154 -0
  231. package/dist/view/match.d.ts +41 -0
  232. package/dist/view/match.js +111 -0
  233. package/dist/view/model.d.ts +92 -0
  234. package/dist/view/model.js +162 -0
  235. package/dist/view/navigation-head.d.ts +29 -0
  236. package/dist/view/navigation-head.jsx +38 -0
  237. package/dist/view/page-model.d.ts +46 -0
  238. package/dist/view/page-model.js +146 -0
  239. package/dist/view/query-effects.d.ts +87 -0
  240. package/dist/view/query-effects.js +147 -0
  241. package/dist/view/query-ok.d.ts +45 -0
  242. package/dist/view/query-ok.js +96 -0
  243. package/dist/view/query.d.ts +115 -0
  244. package/dist/view/query.jsx +179 -0
  245. package/dist/view/result-view.d.ts +14 -0
  246. package/dist/view/result-view.jsx +15 -0
  247. package/dist/view/route-pages.d.ts +43 -0
  248. package/dist/view/route-pages.js +59 -0
  249. package/dist/view/router.d.ts +44 -0
  250. package/dist/view/router.js +123 -0
  251. package/dist/vite/dev-middleware.d.ts +12 -0
  252. package/dist/vite/dev-middleware.js +39 -0
  253. package/dist/vite/dev-objects.d.ts +25 -0
  254. package/dist/vite/dev-objects.js +127 -0
  255. package/dist/vite/dev-platform.d.ts +19 -0
  256. package/dist/vite/dev-platform.js +77 -0
  257. package/dist/vite/dev-seo-files.d.ts +11 -0
  258. package/dist/vite/dev-seo-files.js +40 -0
  259. package/dist/vite/index.d.ts +53 -0
  260. package/dist/vite/index.js +148 -0
  261. package/dist/vite/local-config.d.ts +34 -0
  262. package/dist/vite/local-config.js +72 -0
  263. package/dist/vite/worker-build.d.ts +24 -0
  264. package/dist/vite/worker-build.js +84 -0
  265. package/dist/worker/create-worker.d.ts +52 -0
  266. package/dist/worker/create-worker.js +90 -0
  267. package/dist/worker/index.d.ts +12 -0
  268. package/dist/worker/index.js +12 -0
  269. package/dist/worker/page-routes.d.ts +88 -0
  270. package/dist/worker/page-routes.js +100 -0
  271. package/dist/worker/page-status.d.ts +41 -0
  272. package/dist/worker/page-status.js +23 -0
  273. package/dist/worker/request-prelude.d.ts +69 -0
  274. package/dist/worker/request-prelude.js +107 -0
  275. package/dist/worker/security.d.ts +76 -0
  276. package/dist/worker/security.js +137 -0
  277. package/dist/worker/server-app.d.ts +54 -0
  278. package/dist/worker/server-app.js +76 -0
  279. package/guards/browser-only.js +5 -0
  280. package/guards/node-only.js +6 -0
  281. package/guards/server-only.js +5 -0
  282. package/migrations/0001-sessions.sql +22 -0
  283. package/package.json +233 -5
@@ -0,0 +1,222 @@
1
+ import { announceViewerChange, createRoomHub, } from './room-hub.js';
2
+ function outcomeSignature(event) {
3
+ try {
4
+ return `${event.key}|${JSON.stringify(event.outcome)}`;
5
+ }
6
+ catch {
7
+ return `${event.key}|${event.outcome._tag}|[unserializable]`;
8
+ }
9
+ }
10
+ const slotOf = (queryId, inputKey) => `${queryId}\n${inputKey}`;
11
+ /**
12
+ * Creates an isolated outcome channel (see `QueryOutcomeChannel`).
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const channel = createQueryOutcomeChannel();
17
+ * const stop = channel.subscribe((e) => console.log(e.queryId, e.inputKey, e.outcome._tag));
18
+ * channel.publish({ queryId: "planner/character", inputKey: '"x"', key: 'planner/character:"x"#0',
19
+ * outcome: { _tag: "Succeeded", value: 1 } });
20
+ * stop();
21
+ * ```
22
+ */
23
+ export function createQueryOutcomeChannel() {
24
+ const latestBySlot = new Map();
25
+ const listeners = new Set();
26
+ return {
27
+ publish: (event) => {
28
+ const slot = slotOf(event.queryId, event.inputKey);
29
+ const signature = outcomeSignature(event);
30
+ if (latestBySlot.get(slot)?.signature === signature)
31
+ return;
32
+ // Re-insert so replay order is publish order: a listener hearing every
33
+ // input of a query ends on the newest outcome, not the first input's.
34
+ latestBySlot.delete(slot);
35
+ latestBySlot.set(slot, { event, signature });
36
+ for (const listener of [...listeners])
37
+ listener(event);
38
+ },
39
+ subscribe: (listener) => {
40
+ listeners.add(listener);
41
+ for (const { event } of [...latestBySlot.values()])
42
+ listener(event);
43
+ return () => {
44
+ listeners.delete(listener);
45
+ };
46
+ },
47
+ latest: (queryId, inputKey = '') => latestBySlot.get(slotOf(queryId, inputKey))?.event,
48
+ forget: () => {
49
+ latestBySlot.clear();
50
+ },
51
+ };
52
+ }
53
+ /**
54
+ * Creates an isolated invalidation table (see `QueryInvalidations`).
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const inv = createQueryInvalidations();
59
+ * inv.invalidate("planner/plan");
60
+ * inv.generation("planner/plan", '"voltar-main"'); // 1
61
+ * ```
62
+ */
63
+ export function createQueryInvalidations() {
64
+ const allInputs = new Map();
65
+ const oneInput = new Map();
66
+ const listeners = new Set();
67
+ return {
68
+ invalidate: (queryId, inputKey) => {
69
+ if (inputKey === undefined) {
70
+ allInputs.set(queryId, (allInputs.get(queryId) ?? 0) + 1);
71
+ }
72
+ else {
73
+ const slot = slotOf(queryId, inputKey);
74
+ oneInput.set(slot, (oneInput.get(slot) ?? 0) + 1);
75
+ }
76
+ for (const listener of [...listeners])
77
+ listener(queryId, inputKey);
78
+ },
79
+ generation: (queryId, inputKey) => (allInputs.get(queryId) ?? 0) +
80
+ (oneInput.get(slotOf(queryId, inputKey)) ?? 0),
81
+ subscribe: (listener) => {
82
+ listeners.add(listener);
83
+ return () => {
84
+ listeners.delete(listener);
85
+ };
86
+ },
87
+ };
88
+ }
89
+ /**
90
+ * Creates an isolated dedupe cache (see `QueryCache`). Never module-global:
91
+ * `<AppScope>` creates one per SSR request and one per browser page.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * const cache = createQueryCache();
96
+ * const a = cache.acquire("character:\"x\"@", () => fetchCharacter("x"));
97
+ * const b = cache.acquire("character:\"x\"@", () => fetchCharacter("x")); // no second fetch
98
+ * a.value === b.value; // true
99
+ * ```
100
+ */
101
+ export function createQueryCache() {
102
+ const entries = new Map();
103
+ const scheduleCollect = (key, entry) => {
104
+ queueMicrotask(() => {
105
+ if (entry.refs === 0 && entries.get(key) === entry)
106
+ entries.delete(key);
107
+ });
108
+ };
109
+ return {
110
+ acquire: (key, run) => {
111
+ let entry = entries.get(key);
112
+ if (!entry) {
113
+ entry = { value: run(), refs: 0 };
114
+ entries.set(key, entry);
115
+ }
116
+ const held = entry;
117
+ held.refs += 1;
118
+ let released = false;
119
+ return {
120
+ value: held.value,
121
+ release: () => {
122
+ if (released)
123
+ return;
124
+ released = true;
125
+ held.refs -= 1;
126
+ if (held.refs === 0)
127
+ scheduleCollect(key, held);
128
+ },
129
+ };
130
+ },
131
+ evict: (key) => {
132
+ entries.delete(key);
133
+ },
134
+ size: () => entries.size,
135
+ };
136
+ }
137
+ export function createPageLifecycle() {
138
+ let hydrated = false;
139
+ const waiting = [];
140
+ return {
141
+ afterHydration: (start) => {
142
+ if (hydrated)
143
+ queueMicrotask(start);
144
+ else
145
+ waiting.push(start);
146
+ },
147
+ markHydrated: () => {
148
+ if (hydrated)
149
+ return;
150
+ hydrated = true;
151
+ for (const start of waiting.splice(0)) {
152
+ try {
153
+ start();
154
+ }
155
+ catch (error) {
156
+ console.error('[page model] start failed:', error);
157
+ }
158
+ }
159
+ },
160
+ isHydrated: () => hydrated,
161
+ };
162
+ }
163
+ /**
164
+ * Creates a fresh `KitScope`: one per SSR request, and one per browser
165
+ * document (shared by every island root, and kept across client
166
+ * navigations; see `nextPage`).
167
+ */
168
+ export function createKitScope(options = {}) {
169
+ let hub;
170
+ let page = createPageLifecycle();
171
+ let section = options.section;
172
+ const pageModels = new Map();
173
+ const pageModelLives = new Map();
174
+ const outcomes = createQueryOutcomeChannel();
175
+ return {
176
+ queries: createQueryCache(),
177
+ outcomes,
178
+ invalidations: createQueryInvalidations(),
179
+ pageModels,
180
+ pageModelLives,
181
+ pageModelMasks: new WeakMap(),
182
+ get page() {
183
+ return page;
184
+ },
185
+ get section() {
186
+ return section;
187
+ },
188
+ islands: { count: 0 },
189
+ rooms: () => {
190
+ hub ??= createRoomHub();
191
+ return hub;
192
+ },
193
+ holdRooms: () => (hub ? hub.hold() : () => { }),
194
+ nextPage: (nextSection) => {
195
+ section = nextSection;
196
+ for (const [def, life] of [...pageModelLives]) {
197
+ if (life.persist &&
198
+ life.section !== undefined &&
199
+ life.section === nextSection)
200
+ continue;
201
+ pageModelLives.delete(def);
202
+ pageModels.delete(def);
203
+ try {
204
+ life.dispose();
205
+ }
206
+ catch (error) {
207
+ console.error('[page model] dispose failed:', error);
208
+ }
209
+ }
210
+ outcomes.forget();
211
+ page = createPageLifecycle();
212
+ },
213
+ viewerChanged: () => {
214
+ if (typeof window === 'undefined')
215
+ return;
216
+ if (hub)
217
+ hub.viewerChanged();
218
+ else
219
+ announceViewerChange();
220
+ },
221
+ };
222
+ }
@@ -0,0 +1,107 @@
1
+ import { type SocketLike } from './subscription-runner.ts';
2
+ /**
3
+ * A page's live room connections: one WebSocket per room per page, shared
4
+ * and ref-counted by every part that uses the room (`presence(...)` and
5
+ * `roomSaved(...)` subscriptions in any model, `<LiveCursors>`, the collab
6
+ * part). No Solid and no DOM beyond `WebSocket` / `BroadcastChannel`
7
+ * (injectable), so it is unit-tested with fake sockets.
8
+ *
9
+ * Lives on the page's `KitScope` (`scope.rooms()`), created on first use in
10
+ * the browser only; never on the server. Client contract:
11
+ * `docs/guides/ui-kit-live-rooms.md` ("Client").
12
+ *
13
+ * - `acquire(path)` returns a handle. The first handle for a path opens its
14
+ * socket; the last `release()` closes it.
15
+ * - Frames are parsed once (`parseRoomFrame`) and fanned out to every
16
+ * listener. The latest `welcome` and `presence` frames are kept for late
17
+ * listeners (`handle.welcome()`, `handle.presence()`).
18
+ * - Reconnects with the kit's jittered backoff (1 s to 30 s, reset after
19
+ * 10 s open). Close code 4403 (access changed) reconnects at once.
20
+ * - `viewerChanged()` (sign-in, sign-out, rename: a mutation declared with
21
+ * `changesAccess: true`) closes and reopens every room socket at once, so
22
+ * rooms see the new identity, and tells this origin's other tabs to do
23
+ * the same (`BroadcastChannel`).
24
+ */
25
+ import { type RoomServerFrame } from '../live/protocol.ts';
26
+ /** Connection state of a room socket (what `onStatus` reports). */
27
+ export type RoomStatus = 'Connecting' | 'Open' | 'Closed';
28
+ export type WelcomeFrame = Extract<RoomServerFrame, {
29
+ readonly t: 'welcome';
30
+ }>;
31
+ export type PresenceFrame = Extract<RoomServerFrame, {
32
+ readonly t: 'presence';
33
+ }>;
34
+ /** The slice of `WebSocket` the hub uses. */
35
+ export interface RoomSocketLike extends SocketLike {
36
+ readonly readyState: number;
37
+ send(data: string): void;
38
+ }
39
+ /** The slice of `BroadcastChannel` the hub uses (cross-tab viewer changes). */
40
+ export interface ViewerChannelLike {
41
+ onmessage: ((event: {
42
+ readonly data: unknown;
43
+ }) => void) | null;
44
+ postMessage(message: unknown): void;
45
+ close(): void;
46
+ }
47
+ export interface RoomHubDeps {
48
+ readonly openSocket: (path: string) => RoomSocketLike;
49
+ readonly setTimeout: (fn: () => void, ms: number) => unknown;
50
+ readonly clearTimeout: (handle: unknown) => void;
51
+ /** `[0, 1)`; reconnect jitter. */
52
+ readonly random: () => number;
53
+ /** Cross-tab viewer-change channel, or `undefined` where there is none. */
54
+ readonly viewerChannel?: () => ViewerChannelLike | undefined;
55
+ }
56
+ /** One user of one room socket. */
57
+ export interface RoomHandle {
58
+ /** Every parsed server frame. Returns an unsubscribe. */
59
+ readonly onFrame: (fn: (frame: RoomServerFrame) => void) => () => void;
60
+ /** Connection changes; called at once with the current status. Returns an unsubscribe. */
61
+ readonly onStatus: (fn: (status: RoomStatus) => void) => () => void;
62
+ /** Sends if the socket is open, else drops it (room frames are ephemeral). */
63
+ readonly send: (text: string) => boolean;
64
+ /** The latest `welcome` of the current connection. */
65
+ readonly welcome: () => WelcomeFrame | undefined;
66
+ /** The latest `presence` of the current connection. */
67
+ readonly presence: () => PresenceFrame | undefined;
68
+ /** Drops this handle (idempotent); the last one closes the socket. */
69
+ readonly release: () => void;
70
+ }
71
+ export interface RoomHub {
72
+ readonly acquire: (path: string) => RoomHandle;
73
+ /**
74
+ * Parks instead of closing: while held, a room whose last handle is
75
+ * released keeps its socket (and its latest `welcome` / `presence`), so a
76
+ * new `acquire` of the same path picks it up with no reconnect. The
77
+ * returned release ends this hold (idempotent); once no hold is left,
78
+ * parked rooms nobody re-acquired are closed. Used by the kit's client
79
+ * navigation across a page swap.
80
+ */
81
+ readonly hold: () => () => void;
82
+ /** The viewer changed in this tab: reopen every room now and tell the other tabs. */
83
+ readonly viewerChanged: () => void;
84
+ /** Open room paths (tests, debugging). */
85
+ readonly paths: () => readonly string[];
86
+ /** Closes everything (tests; a page never needs it). */
87
+ readonly dispose: () => void;
88
+ }
89
+ /** The `BroadcastChannel` name the kit uses for viewer changes. */
90
+ export declare const VIEWER_CHANNEL = "our-kit:viewer";
91
+ /**
92
+ * Tells this origin's other tabs that the viewer changed, without a hub
93
+ * (a page with no room open still announces a sign-out). Kit-internal.
94
+ */
95
+ export declare function announceViewerChange(channel?: () => ViewerChannelLike | undefined): void;
96
+ /**
97
+ * Creates a page's room hub (see the module comment).
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const hub = createRoomHub();
102
+ * const room = hub.acquire("/live/room/plan/voltar-main");
103
+ * room.onFrame((frame) => frame.t === "presence" && console.log(frame.tabs));
104
+ * room.release(); // the last release closes the socket
105
+ * ```
106
+ */
107
+ export declare function createRoomHub(deps?: RoomHubDeps): RoomHub;
@@ -0,0 +1,307 @@
1
+ import { jitteredDelay, socketUrl, STABLE_OPEN_MS, } from './subscription-runner.js';
2
+ /**
3
+ * A page's live room connections: one WebSocket per room per page, shared
4
+ * and ref-counted by every part that uses the room (`presence(...)` and
5
+ * `roomSaved(...)` subscriptions in any model, `<LiveCursors>`, the collab
6
+ * part). No Solid and no DOM beyond `WebSocket` / `BroadcastChannel`
7
+ * (injectable), so it is unit-tested with fake sockets.
8
+ *
9
+ * Lives on the page's `KitScope` (`scope.rooms()`), created on first use in
10
+ * the browser only; never on the server. Client contract:
11
+ * `docs/guides/ui-kit-live-rooms.md` ("Client").
12
+ *
13
+ * - `acquire(path)` returns a handle. The first handle for a path opens its
14
+ * socket; the last `release()` closes it.
15
+ * - Frames are parsed once (`parseRoomFrame`) and fanned out to every
16
+ * listener. The latest `welcome` and `presence` frames are kept for late
17
+ * listeners (`handle.welcome()`, `handle.presence()`).
18
+ * - Reconnects with the kit's jittered backoff (1 s to 30 s, reset after
19
+ * 10 s open). Close code 4403 (access changed) reconnects at once.
20
+ * - `viewerChanged()` (sign-in, sign-out, rename: a mutation declared with
21
+ * `changesAccess: true`) closes and reopens every room socket at once, so
22
+ * rooms see the new identity, and tells this origin's other tabs to do
23
+ * the same (`BroadcastChannel`).
24
+ */
25
+ import { LIVE_CLOSE, LIVE_TIMING, parseRoomFrame, } from '../live/protocol.js';
26
+ /** The `BroadcastChannel` name the kit uses for viewer changes. */
27
+ export const VIEWER_CHANNEL = 'our-kit:viewer';
28
+ const VIEWER_MESSAGE = 'changed';
29
+ const OPEN = 1;
30
+ function openViewerChannel() {
31
+ if (typeof BroadcastChannel === 'undefined')
32
+ return undefined;
33
+ try {
34
+ return new BroadcastChannel(VIEWER_CHANNEL);
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ function browserDeps() {
41
+ return {
42
+ openSocket: (path) => new WebSocket(socketUrl(path)),
43
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
44
+ clearTimeout: (h) => globalThis.clearTimeout(h),
45
+ random: () => Math.random(),
46
+ viewerChannel: openViewerChannel,
47
+ };
48
+ }
49
+ function closeCodeOf(event) {
50
+ const code = event?.code;
51
+ return typeof code === 'number' ? code : undefined;
52
+ }
53
+ /**
54
+ * Tells this origin's other tabs that the viewer changed, without a hub
55
+ * (a page with no room open still announces a sign-out). Kit-internal.
56
+ */
57
+ export function announceViewerChange(channel = openViewerChannel) {
58
+ const ch = channel();
59
+ if (!ch)
60
+ return;
61
+ try {
62
+ ch.postMessage(VIEWER_MESSAGE);
63
+ }
64
+ finally {
65
+ ch.close();
66
+ }
67
+ }
68
+ /**
69
+ * Creates a page's room hub (see the module comment).
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const hub = createRoomHub();
74
+ * const room = hub.acquire("/live/room/plan/voltar-main");
75
+ * room.onFrame((frame) => frame.t === "presence" && console.log(frame.tabs));
76
+ * room.release(); // the last release closes the socket
77
+ * ```
78
+ */
79
+ export function createRoomHub(deps = browserDeps()) {
80
+ const rooms = new Map();
81
+ let channel;
82
+ let holds = 0;
83
+ /** Closes a room nobody uses (unless a hold parks it). */
84
+ const closeIfUnused = (path, room) => {
85
+ if (room.refs > 0 || holds > 0 || rooms.get(path) !== room)
86
+ return;
87
+ rooms.delete(path);
88
+ room.stop();
89
+ };
90
+ const reopenAll = () => {
91
+ for (const room of rooms.values())
92
+ room.reopen();
93
+ };
94
+ const listenForViewer = () => {
95
+ if (channel || !deps.viewerChannel)
96
+ return;
97
+ channel = deps.viewerChannel();
98
+ if (channel) {
99
+ channel.onmessage = (event) => {
100
+ if (event.data === VIEWER_MESSAGE)
101
+ reopenAll();
102
+ };
103
+ }
104
+ };
105
+ const open = (path, room) => {
106
+ let stopped = false;
107
+ let retry;
108
+ let stable;
109
+ let step = LIVE_TIMING.RECONNECT_MIN_MS;
110
+ const setStatus = (status) => {
111
+ room.status = status;
112
+ for (const fn of [...room.statuses])
113
+ fn(status);
114
+ };
115
+ const clearTimers = () => {
116
+ if (retry !== undefined)
117
+ deps.clearTimeout(retry);
118
+ if (stable !== undefined)
119
+ deps.clearTimeout(stable);
120
+ retry = undefined;
121
+ stable = undefined;
122
+ };
123
+ const dropSocket = () => {
124
+ const ws = room.socket;
125
+ room.socket = undefined;
126
+ room.welcome = undefined;
127
+ room.presence = undefined;
128
+ if (ws) {
129
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
130
+ try {
131
+ ws.close();
132
+ }
133
+ catch {
134
+ // Already closing.
135
+ }
136
+ }
137
+ };
138
+ const schedule = (delay) => {
139
+ if (stopped)
140
+ return;
141
+ retry = deps.setTimeout(connect, delay);
142
+ };
143
+ const backoff = () => {
144
+ schedule(jitteredDelay(step, deps.random()));
145
+ step = Math.min(step * 2, LIVE_TIMING.RECONNECT_MAX_MS);
146
+ };
147
+ function connect() {
148
+ retry = undefined;
149
+ if (stopped)
150
+ return;
151
+ setStatus('Connecting');
152
+ let ws;
153
+ try {
154
+ ws = deps.openSocket(path);
155
+ }
156
+ catch (error) {
157
+ console.error(`[live] room ${path} failed to open:`, error);
158
+ backoff();
159
+ return;
160
+ }
161
+ room.socket = ws;
162
+ ws.onopen = () => {
163
+ if (room.socket !== ws || stopped)
164
+ return;
165
+ stable = deps.setTimeout(() => {
166
+ stable = undefined;
167
+ if (room.socket === ws)
168
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
169
+ }, STABLE_OPEN_MS);
170
+ setStatus('Open');
171
+ };
172
+ ws.onmessage = (event) => {
173
+ if (room.socket !== ws || stopped)
174
+ return;
175
+ const frame = parseRoomFrame(event.data);
176
+ if (!frame)
177
+ return;
178
+ if (frame.t === 'welcome')
179
+ room.welcome = frame;
180
+ else if (frame.t === 'presence')
181
+ room.presence = frame;
182
+ for (const fn of [...room.frames])
183
+ fn(frame);
184
+ };
185
+ ws.onerror = () => { };
186
+ ws.onclose = (event) => {
187
+ if (room.socket !== ws || stopped)
188
+ return;
189
+ room.socket = undefined;
190
+ room.welcome = undefined;
191
+ room.presence = undefined;
192
+ clearTimers();
193
+ setStatus('Closed');
194
+ if (closeCodeOf(event) === LIVE_CLOSE.ACCESS_CHANGED) {
195
+ // Access changed: reconnect now, as whoever the viewer is now.
196
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
197
+ schedule(0);
198
+ return;
199
+ }
200
+ backoff();
201
+ };
202
+ }
203
+ room.reopen = () => {
204
+ if (stopped)
205
+ return;
206
+ clearTimers();
207
+ dropSocket();
208
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
209
+ connect();
210
+ };
211
+ room.stop = () => {
212
+ stopped = true;
213
+ clearTimers();
214
+ dropSocket();
215
+ };
216
+ connect();
217
+ };
218
+ return {
219
+ acquire: (path) => {
220
+ let room = rooms.get(path);
221
+ if (!room) {
222
+ room = {
223
+ refs: 0,
224
+ socket: undefined,
225
+ status: 'Connecting',
226
+ welcome: undefined,
227
+ presence: undefined,
228
+ frames: new Set(),
229
+ statuses: new Set(),
230
+ reopen: () => { },
231
+ stop: () => { },
232
+ };
233
+ rooms.set(path, room);
234
+ listenForViewer();
235
+ open(path, room);
236
+ }
237
+ const current = room;
238
+ current.refs += 1;
239
+ let released = false;
240
+ const mine = [];
241
+ return {
242
+ onFrame: (fn) => {
243
+ current.frames.add(fn);
244
+ const off = () => {
245
+ current.frames.delete(fn);
246
+ };
247
+ mine.push(off);
248
+ return off;
249
+ },
250
+ onStatus: (fn) => {
251
+ current.statuses.add(fn);
252
+ const off = () => {
253
+ current.statuses.delete(fn);
254
+ };
255
+ mine.push(off);
256
+ fn(current.status);
257
+ return off;
258
+ },
259
+ send: (text) => {
260
+ const ws = current.socket;
261
+ if (released || !ws || ws.readyState !== OPEN)
262
+ return false;
263
+ ws.send(text);
264
+ return true;
265
+ },
266
+ welcome: () => current.welcome,
267
+ presence: () => current.presence,
268
+ release: () => {
269
+ if (released)
270
+ return;
271
+ released = true;
272
+ for (const off of mine)
273
+ off();
274
+ current.refs -= 1;
275
+ closeIfUnused(path, current);
276
+ },
277
+ };
278
+ },
279
+ hold: () => {
280
+ holds += 1;
281
+ let released = false;
282
+ return () => {
283
+ if (released)
284
+ return;
285
+ released = true;
286
+ holds -= 1;
287
+ for (const [path, room] of [...rooms])
288
+ closeIfUnused(path, room);
289
+ };
290
+ },
291
+ viewerChanged: () => {
292
+ reopenAll();
293
+ if (channel)
294
+ channel.postMessage(VIEWER_MESSAGE);
295
+ else if (deps.viewerChannel)
296
+ announceViewerChange(deps.viewerChannel);
297
+ },
298
+ paths: () => [...rooms.keys()],
299
+ dispose: () => {
300
+ for (const room of rooms.values())
301
+ room.stop();
302
+ rooms.clear();
303
+ channel?.close();
304
+ channel = undefined;
305
+ },
306
+ };
307
+ }