@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,71 @@
1
+ import type { RoomHub } from './room-hub.ts';
2
+ import type { Subscription } from '../logic/subscriptions.ts';
3
+ /**
4
+ * Runs a model's subscriptions in the browser: `update(list)` diffs the new
5
+ * list against the running one by `key` (start new, stop missing, keep the
6
+ * rest with their newest message mappers); `stop()` ends everything. No
7
+ * Solid: `createModel` calls it after hydration settles and after every
8
+ * Message. Unit-tested with fake sockets / timers.
9
+ */
10
+ /** The slice of `WebSocket` the runner uses (injectable for tests). */
11
+ export interface SocketLike {
12
+ onopen: ((event: unknown) => void) | null;
13
+ onmessage: ((event: {
14
+ readonly data: unknown;
15
+ }) => void) | null;
16
+ onclose: ((event: unknown) => void) | null;
17
+ onerror: ((event: unknown) => void) | null;
18
+ close(): void;
19
+ }
20
+ export interface SubscriptionRunnerDeps {
21
+ readonly openSocket: (url: string) => SocketLike;
22
+ readonly setInterval: (fn: () => void, ms: number) => unknown;
23
+ readonly clearInterval: (handle: unknown) => void;
24
+ readonly setTimeout: (fn: () => void, ms: number) => unknown;
25
+ readonly clearTimeout: (handle: unknown) => void;
26
+ readonly now: () => number;
27
+ /** `[0, 1)`; reconnect jitter. Defaults to `Math.random`. */
28
+ readonly random?: () => number;
29
+ /**
30
+ * The page's room hub (`KitScope.rooms`), for `presence` / `roomSaved`.
31
+ * Room subscriptions without one log an error and do nothing.
32
+ */
33
+ readonly rooms?: () => RoomHub;
34
+ }
35
+ export interface SubscriptionRunner<Msg> {
36
+ readonly update: (subscriptions: readonly Subscription<Msg>[]) => void;
37
+ readonly stop: () => void;
38
+ /** Running keys (tests / debugging). */
39
+ readonly keys: () => readonly string[];
40
+ }
41
+ export declare const RECONNECT_MIN_MS = 1000;
42
+ export declare const RECONNECT_MAX_MS = 30000;
43
+ /**
44
+ * A socket must stay open this long before the backoff resets. A server
45
+ * that accepts and closes at once (overloaded, rejecting) keeps backing off
46
+ * to the cap instead of being retried every second forever.
47
+ */
48
+ export declare const STABLE_OPEN_MS = 10000;
49
+ /**
50
+ * "Equal jitter": half the step fixed, half random, so many tabs dropped by
51
+ * one deploy don't reconnect in lockstep, and no retry is ever immediate.
52
+ */
53
+ export declare function jitteredDelay(step: number, random: number): number;
54
+ /** Resolves a same-origin path to a `ws(s)://` URL. */
55
+ export declare function socketUrl(url: string): string;
56
+ /** Browser deps with the page's room hub (kit-internal; `createModel` uses it). */
57
+ export declare function browserRunnerDeps(rooms?: () => RoomHub): SubscriptionRunnerDeps;
58
+ /**
59
+ * Creates a runner that delivers subscription Messages through `send`.
60
+ *
61
+ * @param send - The model's `send`.
62
+ * @param deps - Socket and timer functions (browser globals by default).
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const runner = createSubscriptionRunner(send);
67
+ * runner.update([every(1000, () => ({ _tag: "Tick" }))]);
68
+ * runner.update([]); // stops the timer
69
+ * ```
70
+ */
71
+ export declare function createSubscriptionRunner<Msg>(send: (msg: Msg) => void, deps?: SubscriptionRunnerDeps): SubscriptionRunner<Msg>;
@@ -0,0 +1,240 @@
1
+ import { IS_DEV } from '../logic/dev.js';
2
+ export const RECONNECT_MIN_MS = 1000;
3
+ export const RECONNECT_MAX_MS = 30_000;
4
+ /**
5
+ * A socket must stay open this long before the backoff resets. A server
6
+ * that accepts and closes at once (overloaded, rejecting) keeps backing off
7
+ * to the cap instead of being retried every second forever.
8
+ */
9
+ export const STABLE_OPEN_MS = 10_000;
10
+ /**
11
+ * "Equal jitter": half the step fixed, half random, so many tabs dropped by
12
+ * one deploy don't reconnect in lockstep, and no retry is ever immediate.
13
+ */
14
+ export function jitteredDelay(step, random) {
15
+ return Math.round(step / 2 + (step / 2) * random);
16
+ }
17
+ /** Resolves a same-origin path to a `ws(s)://` URL. */
18
+ export function socketUrl(url) {
19
+ if (/^wss?:\/\//.test(url))
20
+ return url;
21
+ if (typeof location === 'undefined')
22
+ return url;
23
+ const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:';
24
+ return `${scheme}//${location.host}${url.startsWith('/') ? url : `/${url}`}`;
25
+ }
26
+ function browserDeps(rooms) {
27
+ return {
28
+ rooms,
29
+ openSocket: (url) => new WebSocket(socketUrl(url)),
30
+ setInterval: (fn, ms) => globalThis.setInterval(fn, ms),
31
+ clearInterval: (h) => globalThis.clearInterval(h),
32
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
33
+ clearTimeout: (h) => globalThis.clearTimeout(h),
34
+ now: () => Date.now(),
35
+ random: () => Math.random(),
36
+ };
37
+ }
38
+ function parseFrame(data) {
39
+ if (typeof data !== 'string')
40
+ return data;
41
+ try {
42
+ return JSON.parse(data);
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ /** Browser deps with the page's room hub (kit-internal; `createModel` uses it). */
49
+ export function browserRunnerDeps(rooms) {
50
+ return browserDeps(rooms);
51
+ }
52
+ /**
53
+ * Creates a runner that delivers subscription Messages through `send`.
54
+ *
55
+ * @param send - The model's `send`.
56
+ * @param deps - Socket and timer functions (browser globals by default).
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const runner = createSubscriptionRunner(send);
61
+ * runner.update([every(1000, () => ({ _tag: "Tick" }))]);
62
+ * runner.update([]); // stops the timer
63
+ * ```
64
+ */
65
+ export function createSubscriptionRunner(send, deps = browserDeps()) {
66
+ const running = new Map();
67
+ /** Rides the page's shared room socket; releasing the handle may close it. */
68
+ const startRoom = (entry, sub) => {
69
+ const hub = deps.rooms?.();
70
+ if (!hub) {
71
+ console.error(`[subscriptions] ${sub.key}: no room hub (create the model inside <AppScope> / an island).`);
72
+ return () => { };
73
+ }
74
+ const handle = hub.acquire(sub.path);
75
+ let stopped = false;
76
+ const deliver = (event) => {
77
+ if (stopped)
78
+ return;
79
+ const msg = entry.current.receive(event);
80
+ if (msg !== undefined)
81
+ send(msg);
82
+ };
83
+ handle.onStatus((status) => deliver({ _tag: 'Status', status }));
84
+ // A late subscriber hears the current list at once (the room only re-sends it on join / leave).
85
+ const known = handle.presence();
86
+ if (known)
87
+ deliver({ _tag: 'Frame', frame: known, welcome: handle.welcome() });
88
+ handle.onFrame((frame) => deliver({ _tag: 'Frame', frame, welcome: handle.welcome() }));
89
+ return () => {
90
+ stopped = true;
91
+ handle.release();
92
+ };
93
+ };
94
+ const startEvery = (entry, sub) => {
95
+ const handle = deps.setInterval(() => {
96
+ const latest = entry.current;
97
+ send(latest.toMessage(deps.now()));
98
+ }, sub.ms);
99
+ return () => deps.clearInterval(handle);
100
+ };
101
+ const startChannel = (entry, sub) => {
102
+ let stopped = false;
103
+ let socket;
104
+ let retryHandle;
105
+ let stableHandle;
106
+ let step = RECONNECT_MIN_MS;
107
+ const random = deps.random ?? Math.random;
108
+ const latest = () => entry.current;
109
+ const status = (s) => {
110
+ const toMsg = latest().onStatus;
111
+ if (toMsg && !stopped)
112
+ send(toMsg(s));
113
+ };
114
+ const clearStable = () => {
115
+ if (stableHandle !== undefined)
116
+ deps.clearTimeout(stableHandle);
117
+ stableHandle = undefined;
118
+ };
119
+ const connect = () => {
120
+ retryHandle = undefined;
121
+ if (stopped)
122
+ return;
123
+ status('Connecting');
124
+ let ws;
125
+ try {
126
+ ws = deps.openSocket(sub.url);
127
+ }
128
+ catch (error) {
129
+ console.error(`[subscriptions] channel ${sub.url} failed to open:`, error);
130
+ scheduleReconnect();
131
+ return;
132
+ }
133
+ socket = ws;
134
+ ws.onopen = () => {
135
+ if (socket !== ws || stopped)
136
+ return;
137
+ clearStable();
138
+ stableHandle = deps.setTimeout(() => {
139
+ stableHandle = undefined;
140
+ if (socket === ws)
141
+ step = RECONNECT_MIN_MS;
142
+ }, STABLE_OPEN_MS);
143
+ status('Open');
144
+ };
145
+ ws.onmessage = (event) => {
146
+ if (stopped)
147
+ return;
148
+ const current = latest();
149
+ const frame = current.frames === 'text'
150
+ ? event.data
151
+ : parseFrame(event.data);
152
+ const msg = current.receive(frame);
153
+ if (msg !== undefined)
154
+ send(msg);
155
+ };
156
+ ws.onerror = () => { };
157
+ ws.onclose = () => {
158
+ if (socket !== ws || stopped)
159
+ return;
160
+ socket = undefined;
161
+ clearStable();
162
+ status('Closed');
163
+ scheduleReconnect();
164
+ };
165
+ };
166
+ const scheduleReconnect = () => {
167
+ if (stopped)
168
+ return;
169
+ retryHandle = deps.setTimeout(connect, jitteredDelay(step, random()));
170
+ step = Math.min(step * 2, RECONNECT_MAX_MS);
171
+ };
172
+ connect();
173
+ return () => {
174
+ stopped = true;
175
+ clearStable();
176
+ if (retryHandle !== undefined)
177
+ deps.clearTimeout(retryHandle);
178
+ const ws = socket;
179
+ socket = undefined;
180
+ ws?.close();
181
+ };
182
+ };
183
+ /**
184
+ * Registers the entry BEFORE starting it: starting may send a Message
185
+ * synchronously (a channel's `Connecting` status), which re-diffs the
186
+ * list; the re-entrant diff must already see this key as running.
187
+ */
188
+ const start = (key, sub) => {
189
+ const entry = { current: sub, stop: () => { } };
190
+ running.set(key, entry);
191
+ entry.stop =
192
+ sub._tag === 'Every'
193
+ ? startEvery(entry, sub)
194
+ : sub._tag === 'Room'
195
+ ? startRoom(entry, sub)
196
+ : startChannel(entry, sub);
197
+ };
198
+ return {
199
+ update: (subscriptions) => {
200
+ const next = new Map();
201
+ const repeats = new Map();
202
+ for (const sub of subscriptions) {
203
+ if (sub.keySource === 'explicit') {
204
+ if (next.has(sub.key)) {
205
+ const problem = `[subscriptions] duplicate explicit key "${sub.key}": give each subscription its own key.`;
206
+ if (IS_DEV)
207
+ throw new Error(problem);
208
+ console.error(`${problem} Only the first runs.`);
209
+ continue;
210
+ }
211
+ next.set(sub.key, sub);
212
+ continue;
213
+ }
214
+ // Derived keys: repeats all run, numbered by position among that key.
215
+ const seen = (repeats.get(sub.key) ?? 0) + 1;
216
+ repeats.set(sub.key, seen);
217
+ next.set(seen === 1 ? sub.key : `${sub.key}#${seen}`, sub);
218
+ }
219
+ for (const [key, entry] of [...running]) {
220
+ if (!next.has(key)) {
221
+ running.delete(key);
222
+ entry.stop();
223
+ }
224
+ }
225
+ for (const [key, sub] of next) {
226
+ const entry = running.get(key);
227
+ if (entry)
228
+ entry.current = sub;
229
+ else
230
+ start(key, sub);
231
+ }
232
+ },
233
+ stop: () => {
234
+ for (const entry of running.values())
235
+ entry.stop();
236
+ running.clear();
237
+ },
238
+ keys: () => [...running.keys()],
239
+ };
240
+ }
@@ -0,0 +1,41 @@
1
+ import { Context, Effect, Layer } from 'effect';
2
+ import { type EnvOf, type ResourcesDecl } from '../logic/resources.ts';
3
+ declare const Bindings_base: Context.ServiceClass<Bindings, "@alecsibilia/ui-kit/server/Bindings", Readonly<Record<string, unknown>>>;
4
+ /**
5
+ * The request's Worker bindings as an Effect service. Service Layers are
6
+ * built once at module level and read `Bindings` when a method runs, so a
7
+ * server-function call provides only this (from `locals.env`), and tests
8
+ * provide fakes (`fakeBindings`, `@alecsibilia/ui-kit/test`).
9
+ *
10
+ * The value is the lazy env from `bindingsOf(resources).lazy(env)`: each
11
+ * binding is checked when it is used, not before, so a call that never
12
+ * touches D1 runs where there are no bindings (the build-time prerender).
13
+ */
14
+ export declare class Bindings extends Bindings_base {
15
+ static layer(env: Readonly<Record<string, unknown>>): Layer.Layer<Bindings>;
16
+ }
17
+ /** What `bindingsOf` gives an app: its binding names and typed access to them. */
18
+ export interface AppBindings<R extends ResourcesDecl> {
19
+ /** Every binding the declaration gives (the dev server checks its platform has them all). */
20
+ readonly names: readonly string[];
21
+ /** `env` with each binding checked when read: a missing one throws, naming it. */
22
+ readonly lazy: (env: unknown) => EnvOf<R>;
23
+ /** `env` checked whole, or a throw naming the first missing binding. */
24
+ readonly parse: (env: unknown) => EnvOf<R>;
25
+ /** This call's bindings, typed (`const { DB } = yield* appEnv`). */
26
+ readonly env: Effect.Effect<EnvOf<R>, never, Bindings>;
27
+ }
28
+ /**
29
+ * Typed bindings for a resource declaration (`src/resources.ts`): the same
30
+ * names Alchemy deploys and local workerd runs, so they can't drift. A
31
+ * missing binding is a deploy or dev-setup bug: it throws (a defect,
32
+ * `Unexpected` on the wire), never a typed failure.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * export const { env: appEnv } = bindingsOf(resources)
37
+ * const { DB } = yield* appEnv
38
+ * ```
39
+ */
40
+ export declare function bindingsOf<const R extends ResourcesDecl>(resources: R): AppBindings<R>;
41
+ export {};
@@ -0,0 +1,74 @@
1
+ import { Context, Effect, Layer } from 'effect';
2
+ import { bindingSpecsOf, } from '../logic/resources.js';
3
+ /**
4
+ * The request's Worker bindings as an Effect service. Service Layers are
5
+ * built once at module level and read `Bindings` when a method runs, so a
6
+ * server-function call provides only this (from `locals.env`), and tests
7
+ * provide fakes (`fakeBindings`, `@alecsibilia/ui-kit/test`).
8
+ *
9
+ * The value is the lazy env from `bindingsOf(resources).lazy(env)`: each
10
+ * binding is checked when it is used, not before, so a call that never
11
+ * touches D1 runs where there are no bindings (the build-time prerender).
12
+ */
13
+ export class Bindings extends Context.Service()('@alecsibilia/ui-kit/server/Bindings') {
14
+ static layer(env) {
15
+ return Layer.succeed(Bindings, env);
16
+ }
17
+ }
18
+ function hasMethod(value, name) {
19
+ return (typeof value === 'object' &&
20
+ value !== null &&
21
+ typeof Reflect.get(value, name) === 'function');
22
+ }
23
+ /**
24
+ * Typed bindings for a resource declaration (`src/resources.ts`): the same
25
+ * names Alchemy deploys and local workerd runs, so they can't drift. A
26
+ * missing binding is a deploy or dev-setup bug: it throws (a defect,
27
+ * `Unexpected` on the wire), never a typed failure.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * export const { env: appEnv } = bindingsOf(resources)
32
+ * const { DB } = yield* appEnv
33
+ * ```
34
+ */
35
+ export function bindingsOf(resources) {
36
+ const specs = bindingSpecsOf(resources);
37
+ const names = Object.keys(specs);
38
+ const bindingOf = (env, name) => {
39
+ if (typeof env !== 'object' || env === null) {
40
+ throw new Error('Worker env missing: no bindings on the request event');
41
+ }
42
+ const value = Reflect.get(env, name);
43
+ const spec = specs[name];
44
+ if (spec && !hasMethod(value, spec.method)) {
45
+ throw new Error(`Worker env missing the ${spec.kind} binding \`${name}\``);
46
+ }
47
+ return value;
48
+ };
49
+ const lazy = (env) => {
50
+ const out = {};
51
+ for (const name of names) {
52
+ Object.defineProperty(out, name, {
53
+ enumerable: true,
54
+ get: () => bindingOf(env, name),
55
+ });
56
+ }
57
+ // The getters above check each binding against its declared kind.
58
+ return out;
59
+ };
60
+ const parse = (env) => {
61
+ for (const name of names)
62
+ bindingOf(env, name);
63
+ return env;
64
+ };
65
+ return {
66
+ names,
67
+ lazy,
68
+ parse,
69
+ env: Effect.gen(function* () {
70
+ // `Bindings` holds `lazy(env)` for this declaration (`createRunner`).
71
+ return (yield* Bindings);
72
+ }),
73
+ };
74
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/server` as a browser bundle sees it (the `browser`
3
+ * export condition): only `GET`. An app's `"use server"` modules ship to
4
+ * the browser as RPC stubs (Solid's compiler replaces each body), and the
5
+ * one value they still import there is the `GET` wrapper. Anything else a
6
+ * browser module imports from `/server` is a missing export: the client
7
+ * build fails, which is the side guard.
8
+ */
9
+ export { GET } from '@solidjs/web/server-functions';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/server` as a browser bundle sees it (the `browser`
3
+ * export condition): only `GET`. An app's `"use server"` modules ship to
4
+ * the browser as RPC stubs (Solid's compiler replaces each body), and the
5
+ * one value they still import there is the `GET` wrapper. Anything else a
6
+ * browser module imports from `/server` is a missing export: the client
7
+ * build fails, which is the side guard.
8
+ */
9
+ export { GET } from '@solidjs/web/server-functions';
@@ -0,0 +1,28 @@
1
+ import { Context, Effect, Layer } from 'effect';
2
+ /** The slice of the Workers `ctx.cache` (Workers Cache purge API) the app uses. */
3
+ export interface WorkerCachePurge {
4
+ purge(options: {
5
+ readonly tags?: string[];
6
+ }): Promise<{
7
+ readonly success: boolean;
8
+ readonly errors: readonly unknown[];
9
+ }>;
10
+ }
11
+ interface EdgeCacheShape {
12
+ /**
13
+ * Purges every edge-cached answer carrying any of `tags`, and waits for
14
+ * Cloudflare to accept it. Never fails the mutation: the write already
15
+ * happened, so a failed purge is logged and the read's short TTL bounds
16
+ * the staleness. A no-op where Workers Cache isn't on (`vite dev`, local
17
+ * workerd without `ctx.cache`).
18
+ */
19
+ readonly purge: (tags: readonly string[]) => Effect.Effect<void>;
20
+ }
21
+ declare const EdgeCache_base: Context.ServiceClass<EdgeCache, "@alecsibilia/ui-kit/server/EdgeCache", EdgeCacheShape>;
22
+ /** Workers Cache purge for this request, provided per call from `locals.ctx` (like `Bindings`). */
23
+ export declare class EdgeCache extends EdgeCache_base {
24
+ static layer(ctx: unknown): Layer.Layer<EdgeCache>;
25
+ /** The service value for one call. */
26
+ static forCall(ctx: unknown): EdgeCacheShape;
27
+ }
28
+ export {};
@@ -0,0 +1,35 @@
1
+ import { Context, Effect, Layer } from 'effect';
2
+ function cacheOf(ctx) {
3
+ const cache = ctx
4
+ ?.cache;
5
+ return typeof cache?.purge === 'function'
6
+ ? cache
7
+ : undefined;
8
+ }
9
+ /** Workers Cache purge for this request, provided per call from `locals.ctx` (like `Bindings`). */
10
+ export class EdgeCache extends Context.Service()('@alecsibilia/ui-kit/server/EdgeCache') {
11
+ static layer(ctx) {
12
+ return Layer.succeed(EdgeCache, EdgeCache.forCall(ctx));
13
+ }
14
+ /** The service value for one call. */
15
+ static forCall(ctx) {
16
+ const cache = cacheOf(ctx);
17
+ return {
18
+ purge: (tags) => cache === undefined || tags.length === 0
19
+ ? Effect.void
20
+ : Effect.promise(async () => {
21
+ try {
22
+ const result = await cache.purge({
23
+ tags: [...tags],
24
+ });
25
+ if (!result.success) {
26
+ console.warn(`[edge-cache] purge ${tags.join(',')} failed`, result.errors);
27
+ }
28
+ }
29
+ catch (error) {
30
+ console.warn(`[edge-cache] purge ${tags.join(',')} threw`, error);
31
+ }
32
+ }),
33
+ };
34
+ }
35
+ }
@@ -0,0 +1,45 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * The kit's tagged errors: what kit plumbing fails with, and what server
4
+ * functions return for the common cases. They cross the wire as plain
5
+ * tagged JSON (`runEffectResult`); the browser types them with the plain
6
+ * shapes in `@alecsibilia/ui-kit/logic` (`ValidationFailedError`, ...).
7
+ * Keys are `snake_case` (wire keys).
8
+ */
9
+ /** One field's problem: `field` is the input key (`""` for the input as a whole). */
10
+ export declare const FieldErrorSchema: Schema.Struct<{
11
+ readonly field: Schema.String;
12
+ readonly message: Schema.String;
13
+ }>;
14
+ declare const ValidationFailed_base: Schema.Class<ValidationFailed, Schema.TaggedStruct<"ValidationFailed", {
15
+ readonly message: Schema.String;
16
+ readonly field_errors: Schema.$Array<Schema.Struct<{
17
+ readonly field: Schema.String;
18
+ readonly message: Schema.String;
19
+ }>>;
20
+ }>, import("effect/Cause").YieldableError>;
21
+ /**
22
+ * A server function's input did not decode (`decodeInput`). `field_errors`
23
+ * lists each problem by field (a `<Form>` shows them next to its inputs);
24
+ * `message` is the whole thing in one line.
25
+ */
26
+ export declare class ValidationFailed extends ValidationFailed_base {
27
+ }
28
+ declare const Unauthorized_base: Schema.Class<Unauthorized, Schema.TaggedStruct<"Unauthorized", {
29
+ readonly message: Schema.String;
30
+ }>, import("effect/Cause").YieldableError>;
31
+ /**
32
+ * The request has no valid session (none, expired, or signed out): what
33
+ * `sessions.require` fails with. Protected pages never render without one
34
+ * (the Worker redirects to sign-in first).
35
+ */
36
+ export declare class Unauthorized extends Unauthorized_base {
37
+ }
38
+ declare const RateLimited_base: Schema.Class<RateLimited, Schema.TaggedStruct<"RateLimited", {
39
+ readonly message: Schema.String;
40
+ readonly retry_after_sec: Schema.Number;
41
+ }>, import("effect/Cause").YieldableError>;
42
+ /** Over a Workers Rate Limiting binding's limit (`rateLimit`); try again after `retry_after_sec`. */
43
+ export declare class RateLimited extends RateLimited_base {
44
+ }
45
+ export {};
@@ -0,0 +1,36 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * The kit's tagged errors: what kit plumbing fails with, and what server
4
+ * functions return for the common cases. They cross the wire as plain
5
+ * tagged JSON (`runEffectResult`); the browser types them with the plain
6
+ * shapes in `@alecsibilia/ui-kit/logic` (`ValidationFailedError`, ...).
7
+ * Keys are `snake_case` (wire keys).
8
+ */
9
+ /** One field's problem: `field` is the input key (`""` for the input as a whole). */
10
+ export const FieldErrorSchema = Schema.Struct({
11
+ field: Schema.String,
12
+ message: Schema.String,
13
+ });
14
+ /**
15
+ * A server function's input did not decode (`decodeInput`). `field_errors`
16
+ * lists each problem by field (a `<Form>` shows them next to its inputs);
17
+ * `message` is the whole thing in one line.
18
+ */
19
+ export class ValidationFailed extends Schema.TaggedError()('ValidationFailed', {
20
+ message: Schema.String,
21
+ field_errors: Schema.Array(FieldErrorSchema),
22
+ }) {
23
+ }
24
+ /**
25
+ * The request has no valid session (none, expired, or signed out): what
26
+ * `sessions.require` fails with. Protected pages never render without one
27
+ * (the Worker redirects to sign-in first).
28
+ */
29
+ export class Unauthorized extends Schema.TaggedError()('Unauthorized', { message: Schema.String }) {
30
+ }
31
+ /** Over a Workers Rate Limiting binding's limit (`rateLimit`); try again after `retry_after_sec`. */
32
+ export class RateLimited extends Schema.TaggedError()('RateLimited', {
33
+ message: Schema.String,
34
+ retry_after_sec: Schema.Number,
35
+ }) {
36
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Server-function runtime setup, side-effect imported by the Solid plugin's
3
+ * server-function handler before any dispatch, on every surface (`vite dev`
4
+ * and the Worker build): the kit's Vite plugin sets it as
5
+ * `serverFunctions.serverSetup`.
6
+ *
7
+ * Installs the kit's no-JS form protocol (`formActionHandler`): a form post
8
+ * to a server function's bare address (`fn.url`) decodes the `FormData`,
9
+ * runs the function and answers `303` back to the page (or `_next` after
10
+ * `Ok`) with Solid's encrypted one-shot flash cookie, which the next page
11
+ * render replays (`locals.formFlash`). Config, not per-request state: set
12
+ * once at module load.
13
+ */
14
+ import { installFormActions } from './form-actions.js';
15
+ installFormActions();