@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,121 @@
1
+ /**
2
+ * Forms without JS: the server half of the kit `<Form>`.
3
+ */
4
+ /**
5
+ * Reserved fields the kit `<Form>` adds to a no-JS form post. They steer
6
+ * the redirect and never reach the mutation's input (`_`-prefixed fields
7
+ * are dropped before decoding).
8
+ *
9
+ * - `_return`: the page the form is on (path + search). The redirect back
10
+ * after a failure (and after success without `_next`). Needed because
11
+ * pages send `Referrer-Policy: no-referrer`, so the browser sends no
12
+ * `Referer` to redirect back to.
13
+ * - `_next`: where to go after an `Ok` result (e.g. the sign-in page's
14
+ * `?next=`). Optional.
15
+ *
16
+ * Both must be same-origin paths (`/...`); anything else is ignored.
17
+ */
18
+ export declare const FORM_FIELD: {
19
+ readonly RETURN_TO: '_return';
20
+ readonly NEXT: '_next';
21
+ };
22
+ export type FormField = (typeof FORM_FIELD)[keyof typeof FORM_FIELD];
23
+ /**
24
+ * A same-origin path (`/x?y#z`) from untrusted input, or `undefined`.
25
+ * Refuses absolute URLs, protocol-relative `//host`, backslash tricks and
26
+ * anything that resolves to another origin, so `?next=` and form fields
27
+ * can't become open redirects.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * safeLocalPath("/account?tab=1", "https://app.example"); // "/account?tab=1"
32
+ * safeLocalPath("//evil.example", "https://app.example"); // undefined
33
+ * ```
34
+ */
35
+ export declare function safeLocalPath(raw: unknown, origin: string): string | undefined;
36
+ /** Whether `request` is a browser form post (urlencoded or multipart, no scripted body tag). */
37
+ export declare function isFormPost(request: Request): boolean;
38
+ /** What a form post's mutation produced, as replayed on the page after the redirect. */
39
+ export type FormFlashOutcome =
40
+ /** The mutation returned (a kit `Result`: `Ok`, or `Err` with e.g. `ValidationFailed.field_errors`). */
41
+ {
42
+ readonly _tag: 'Returned';
43
+ readonly result: unknown;
44
+ }
45
+ /** The mutation threw (a defect; sanitized, no details). */
46
+ | {
47
+ readonly _tag: 'Thrown';
48
+ }
49
+ /** The outcome was too big for the 4 KB cookie; only "it happened" survives. */
50
+ | {
51
+ readonly _tag: 'Truncated';
52
+ };
53
+ /**
54
+ * The one-shot outcome of a no-JS form post, read from Solid's encrypted
55
+ * flash cookie on the page render right after the redirect, and put on
56
+ * `getRequestEvent().locals.formFlash` (by the Worker and the dev
57
+ * middleware). The kit `<Form>` whose action is `action` shows it: the
58
+ * submitted values back in the inputs and the field errors next to them.
59
+ */
60
+ export interface FormFlash {
61
+ /** The server function's form action (`fn.url`, `/_server/<id>`): which `<Form>` it belongs to. */
62
+ readonly action: string;
63
+ /** The submitted fields (reserved `_` fields and files left out); last value wins per name. */
64
+ readonly values: Readonly<Record<string, string>>;
65
+ readonly outcome: FormFlashOutcome;
66
+ }
67
+ /**
68
+ * A form body as Solid hands it to the server function: `URLSearchParams`
69
+ * for `application/x-www-form-urlencoded`, `FormData` for multipart.
70
+ * `undefined` for anything else.
71
+ */
72
+ export declare function formBodyOf(value: unknown): FormData | URLSearchParams | undefined;
73
+ /**
74
+ * Reads (and validates) the request's flash cookie. Returns the
75
+ * {@link FormFlash} and whether a flash cookie was present at all (the
76
+ * caller then clears it with `clearFlashCookie()` on the response, even
77
+ * when it did not decode: tampered, expired key, other build).
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * const flash = await readFormFlash(request);
82
+ * locals.formFlash = flash.flash; // undefined when none
83
+ * if (flash.present) response.headers.append("Set-Cookie", clearFlashCookie());
84
+ * ```
85
+ */
86
+ export declare function readFormFlash(request: Request): Promise<{
87
+ readonly present: boolean;
88
+ readonly flash: FormFlash | undefined;
89
+ }>;
90
+ /** Clears the flash cookie on a (mutable) page response after its render read the flash. */
91
+ export declare function clearFormFlash(response: Response): Response;
92
+ /**
93
+ * Installs {@link formActionHandler} as Solid's `handleNoJS`. Call once from
94
+ * the app's server-functions setup module (`serverFunctions.serverSetup`).
95
+ */
96
+ export declare function installFormActions(): void;
97
+ /**
98
+ * The kit's no-JS form protocol, installed as Solid's `handleNoJS`
99
+ * (`configureServerFunctionsServer({ handleNoJS: formActionHandler })` in
100
+ * the app's server-functions setup module). Solid calls it for every call
101
+ * at a server function's bare address (`fn.url`), which is what a
102
+ * `<form method="post" action={fn.url}>` posts to.
103
+ *
104
+ * Form posts (urlencoded / multipart):
105
+ * - The function ran with the form body as its one argument
106
+ * (`URLSearchParams` for urlencoded, `FormData` for multipart) (the app's
107
+ * `decodeInput` turns it into the input object; `_` fields dropped).
108
+ * - Answer: `303 See Other`, `Cache-Control: no-store`, plus Solid's
109
+ * encrypted one-shot flash cookie (60 s) carrying the submitted fields and
110
+ * the outcome (see {@link readFormFlash}). Cookies the function set (via
111
+ * `respond(value, { headers: { "Set-Cookie": ... } })`, e.g. sign-in) are
112
+ * kept.
113
+ * - Where: an `Ok` result goes to `_next` if given, else `_return`; an
114
+ * `Err` result or a throw goes to `_return`; with neither, `/`. A
115
+ * `Response` the function returned or threw (`redirect(...)`) wins when it
116
+ * carries a same-origin `Location`.
117
+ *
118
+ * Anything else at the bare address (raw HTTP, non-form bodies) gets the
119
+ * outcome as JSON (`500` when it threw), no redirect.
120
+ */
121
+ export declare function formActionHandler(result: unknown, request: Request, args: unknown[], thrown?: boolean): Promise<Response>;
@@ -0,0 +1,211 @@
1
+ import { clearFlashCookie, getRequestEvent, hasFlashCookie, respond, } from '@solidjs/web';
2
+ import { configureServerFunctionsServer, decodeFlashCookie, encodeFlashCookie, } from '@solidjs/web/server-functions/server';
3
+ import {} from '../logic/result.js';
4
+ /**
5
+ * Forms without JS: the server half of the kit `<Form>`.
6
+ */
7
+ // ---------------------------------------------------------------------------
8
+ // Forms without JS: the server half of the kit's `<Form>`.
9
+ // ---------------------------------------------------------------------------
10
+ /**
11
+ * Reserved fields the kit `<Form>` adds to a no-JS form post. They steer
12
+ * the redirect and never reach the mutation's input (`_`-prefixed fields
13
+ * are dropped before decoding).
14
+ *
15
+ * - `_return`: the page the form is on (path + search). The redirect back
16
+ * after a failure (and after success without `_next`). Needed because
17
+ * pages send `Referrer-Policy: no-referrer`, so the browser sends no
18
+ * `Referer` to redirect back to.
19
+ * - `_next`: where to go after an `Ok` result (e.g. the sign-in page's
20
+ * `?next=`). Optional.
21
+ *
22
+ * Both must be same-origin paths (`/...`); anything else is ignored.
23
+ */
24
+ export const FORM_FIELD = {
25
+ RETURN_TO: '_return',
26
+ NEXT: '_next',
27
+ };
28
+ /**
29
+ * A same-origin path (`/x?y#z`) from untrusted input, or `undefined`.
30
+ * Refuses absolute URLs, protocol-relative `//host`, backslash tricks and
31
+ * anything that resolves to another origin, so `?next=` and form fields
32
+ * can't become open redirects.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * safeLocalPath("/account?tab=1", "https://app.example"); // "/account?tab=1"
37
+ * safeLocalPath("//evil.example", "https://app.example"); // undefined
38
+ * ```
39
+ */
40
+ export function safeLocalPath(raw, origin) {
41
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 2048)
42
+ return undefined;
43
+ if (!raw.startsWith('/') || raw.startsWith('//') || raw.includes('\\'))
44
+ return undefined;
45
+ try {
46
+ const url = new URL(raw, origin);
47
+ if (url.origin !== origin)
48
+ return undefined;
49
+ return `${url.pathname}${url.search}${url.hash}`;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ /** A `Location` (absolute or relative) as a same-origin path, or `undefined` if it leaves the origin. */
56
+ function sameOriginPath(location, origin) {
57
+ if (!location)
58
+ return undefined;
59
+ try {
60
+ const target = new URL(location, origin);
61
+ if (target.origin !== origin)
62
+ return undefined;
63
+ return safeLocalPath(`${target.pathname}${target.search}${target.hash}`, origin);
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ /** Whether `request` is a browser form post (urlencoded or multipart, no scripted body tag). */
70
+ export function isFormPost(request) {
71
+ if (request.method !== 'POST')
72
+ return false;
73
+ const type = request.headers.get('content-type') ?? '';
74
+ return (type.startsWith('application/x-www-form-urlencoded') ||
75
+ type.startsWith('multipart/form-data'));
76
+ }
77
+ /**
78
+ * A form body as Solid hands it to the server function: `URLSearchParams`
79
+ * for `application/x-www-form-urlencoded`, `FormData` for multipart.
80
+ * `undefined` for anything else.
81
+ */
82
+ export function formBodyOf(value) {
83
+ if (typeof URLSearchParams !== 'undefined' &&
84
+ value instanceof URLSearchParams)
85
+ return value;
86
+ if (typeof FormData !== 'undefined' && value instanceof FormData)
87
+ return value;
88
+ return undefined;
89
+ }
90
+ /** A flash's input (the form body, decoded back by Solid) as field values. */
91
+ function flashValues(input) {
92
+ const values = {};
93
+ const body = formBodyOf(Array.isArray(input) ? input[0] : undefined);
94
+ if (!body)
95
+ return values;
96
+ for (const [name, value] of body.entries()) {
97
+ if (typeof value !== 'string' || name.startsWith('_'))
98
+ continue;
99
+ values[name] = value;
100
+ }
101
+ return values;
102
+ }
103
+ /**
104
+ * Reads (and validates) the request's flash cookie. Returns the
105
+ * {@link FormFlash} and whether a flash cookie was present at all (the
106
+ * caller then clears it with `clearFlashCookie()` on the response, even
107
+ * when it did not decode: tampered, expired key, other build).
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * const flash = await readFormFlash(request);
112
+ * locals.formFlash = flash.flash; // undefined when none
113
+ * if (flash.present) response.headers.append("Set-Cookie", clearFlashCookie());
114
+ * ```
115
+ */
116
+ export async function readFormFlash(request) {
117
+ const cookie = request.headers.get('cookie');
118
+ if (!hasFlashCookie(cookie))
119
+ return { present: false, flash: undefined };
120
+ const submission = await decodeFlashCookie(cookie);
121
+ if (!submission)
122
+ return { present: true, flash: undefined };
123
+ const outcome = submission.truncated
124
+ ? { _tag: 'Truncated' }
125
+ : 'error' in submission && submission.error !== undefined
126
+ ? { _tag: 'Thrown' }
127
+ : { _tag: 'Returned', result: submission.result };
128
+ return {
129
+ present: true,
130
+ flash: {
131
+ action: submission.url,
132
+ values: flashValues(submission.input),
133
+ outcome,
134
+ },
135
+ };
136
+ }
137
+ /** Clears the flash cookie on a (mutable) page response after its render read the flash. */
138
+ export function clearFormFlash(response) {
139
+ response.headers.append('Set-Cookie', clearFlashCookie());
140
+ return response;
141
+ }
142
+ /**
143
+ * Installs {@link formActionHandler} as Solid's `handleNoJS`. Call once from
144
+ * the app's server-functions setup module (`serverFunctions.serverSetup`).
145
+ */
146
+ export function installFormActions() {
147
+ configureServerFunctionsServer({ handleNoJS: formActionHandler });
148
+ }
149
+ const REDIRECT_STATUSES = new Set([
150
+ 301, 302, 303, 307, 308,
151
+ ]);
152
+ /**
153
+ * The kit's no-JS form protocol, installed as Solid's `handleNoJS`
154
+ * (`configureServerFunctionsServer({ handleNoJS: formActionHandler })` in
155
+ * the app's server-functions setup module). Solid calls it for every call
156
+ * at a server function's bare address (`fn.url`), which is what a
157
+ * `<form method="post" action={fn.url}>` posts to.
158
+ *
159
+ * Form posts (urlencoded / multipart):
160
+ * - The function ran with the form body as its one argument
161
+ * (`URLSearchParams` for urlencoded, `FormData` for multipart) (the app's
162
+ * `decodeInput` turns it into the input object; `_` fields dropped).
163
+ * - Answer: `303 See Other`, `Cache-Control: no-store`, plus Solid's
164
+ * encrypted one-shot flash cookie (60 s) carrying the submitted fields and
165
+ * the outcome (see {@link readFormFlash}). Cookies the function set (via
166
+ * `respond(value, { headers: { "Set-Cookie": ... } })`, e.g. sign-in) are
167
+ * kept.
168
+ * - Where: an `Ok` result goes to `_next` if given, else `_return`; an
169
+ * `Err` result or a throw goes to `_return`; with neither, `/`. A
170
+ * `Response` the function returned or threw (`redirect(...)`) wins when it
171
+ * carries a same-origin `Location`.
172
+ *
173
+ * Anything else at the bare address (raw HTTP, non-form bodies) gets the
174
+ * outcome as JSON (`500` when it threw), no redirect.
175
+ */
176
+ export async function formActionHandler(result, request, args, thrown) {
177
+ if (!isFormPost(request)) {
178
+ return Response.json(thrown ? { _tag: 'Unexpected' } : (result ?? null), {
179
+ status: thrown ? 500 : 200,
180
+ headers: { 'Cache-Control': 'no-store' },
181
+ });
182
+ }
183
+ const url = new URL(request.url);
184
+ const form = formBodyOf(args[0]);
185
+ const back = safeLocalPath(form?.get(FORM_FIELD.RETURN_TO), url.origin) ?? '/';
186
+ const headers = new Headers({ 'Cache-Control': 'no-store' });
187
+ if (result instanceof Response) {
188
+ for (const cookie of result.headers.getSetCookie())
189
+ headers.append('Set-Cookie', cookie);
190
+ const location = sameOriginPath(result.headers.get('Location'), url.origin);
191
+ headers.set('Location', location ?? back);
192
+ const status = location && REDIRECT_STATUSES.has(result.status)
193
+ ? result.status
194
+ : 303;
195
+ return new Response(null, { status, headers });
196
+ }
197
+ const succeeded = !thrown &&
198
+ typeof result === 'object' &&
199
+ result !== null &&
200
+ result._tag === 'Ok';
201
+ const next = succeeded
202
+ ? safeLocalPath(form?.get(FORM_FIELD.NEXT), url.origin)
203
+ : undefined;
204
+ headers.set('Location', next ?? back);
205
+ if (result !== undefined) {
206
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
207
+ if (flash !== null)
208
+ headers.append('Set-Cookie', flash);
209
+ }
210
+ return new Response(null, { status: 303, headers });
211
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/server`: server-only helpers (Effect) for an app's
3
+ * server functions, programs and services: running programs, decoding
4
+ * inputs, forms without JS, read caching, sessions, cookies, rate limits
5
+ * and typed bindings.
6
+ *
7
+ * Declares a read server function as GET-able, so its calls are plain
8
+ * cacheable GETs (`/_server?...`), with a POST fallback for oversized
9
+ * argument URLs. Mutations stay plain (POST). Re-exported from Solid's
10
+ * conditional `@solidjs/web/server-functions` entry, so app code keeps to
11
+ * the kit. Needs a function-level `"use server"` inside the wrapped
12
+ * function.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * export const loadPlan = GET(async (raw: string) => {
17
+ * 'use server'
18
+ * return runRead(READ_CACHE.loadPlan, getPlanProgram(raw))
19
+ * })
20
+ * ```
21
+ */
22
+ export { GET } from '@solidjs/web/server-functions';
23
+ export * from './bindings.ts';
24
+ export * from './edge-cache.ts';
25
+ export * from './errors.ts';
26
+ export * from './form-actions.ts';
27
+ export * from './inputs.ts';
28
+ export * from './rate-limit.ts';
29
+ export * from './read-cache.ts';
30
+ export * from './request-info.ts';
31
+ export * from './request.ts';
32
+ export * from './response-cookies.ts';
33
+ export * from './run-effect.ts';
34
+ export * from './run.ts';
35
+ export * from './session.ts';
36
+ export type { D1Binding, D1Statement, DurableObjectNamespaceBinding, EnvOf, R2Binding, RateLimitBinding, } from '../logic/resources.ts';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/server`: server-only helpers (Effect) for an app's
3
+ * server functions, programs and services: running programs, decoding
4
+ * inputs, forms without JS, read caching, sessions, cookies, rate limits
5
+ * and typed bindings.
6
+ *
7
+ * Declares a read server function as GET-able, so its calls are plain
8
+ * cacheable GETs (`/_server?...`), with a POST fallback for oversized
9
+ * argument URLs. Mutations stay plain (POST). Re-exported from Solid's
10
+ * conditional `@solidjs/web/server-functions` entry, so app code keeps to
11
+ * the kit. Needs a function-level `"use server"` inside the wrapped
12
+ * function.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * export const loadPlan = GET(async (raw: string) => {
17
+ * 'use server'
18
+ * return runRead(READ_CACHE.loadPlan, getPlanProgram(raw))
19
+ * })
20
+ * ```
21
+ */
22
+ export { GET } from '@solidjs/web/server-functions';
23
+ export * from './bindings.js';
24
+ export * from './edge-cache.js';
25
+ export * from './errors.js';
26
+ export * from './form-actions.js';
27
+ export * from './inputs.js';
28
+ export * from './rate-limit.js';
29
+ export * from './read-cache.js';
30
+ export * from './request-info.js';
31
+ export * from './request.js';
32
+ export * from './response-cookies.js';
33
+ export * from './run-effect.js';
34
+ export * from './run.js';
35
+ export * from './session.js';
@@ -0,0 +1,45 @@
1
+ import { Effect, Schema, SchemaIssue } from 'effect';
2
+ import { ValidationFailed } from './errors.ts';
3
+ /**
4
+ * Decoding a server function's raw argument. Every `"use server"` export is
5
+ * a public HTTP endpoint, so it decodes its input with Effect Schema first;
6
+ * a failure becomes `ValidationFailed`.
7
+ */
8
+ /**
9
+ * Functions that take no argument still decode it: `undefined` from a
10
+ * scripted call, or a no-JS form post's fields (only reserved `_` fields,
11
+ * so an empty object).
12
+ */
13
+ export declare const NoInput: Schema.UndefinedOr<Schema.Struct<{}>>;
14
+ /** A short slug id (1 to 64 characters): keeps a hostile caller's payload small. */
15
+ export declare const IdInput: Schema.String;
16
+ /**
17
+ * Form fields the kit's `<Form>` adds for the no-JS protocol (see
18
+ * `form-actions.ts`). They steer the redirect and are never part of a
19
+ * mutation's input.
20
+ */
21
+ export declare const RESERVED_FORM_FIELD_PREFIX = "_";
22
+ /**
23
+ * A no-JS form post's body (`URLSearchParams` or `FormData`) as the plain object the input schema
24
+ * decodes: one key per field name (a repeated name becomes an array of its
25
+ * values), files dropped, reserved `_`-prefixed fields left out. Anything
26
+ * that is not `FormData` passes through unchanged (scripted calls send the
27
+ * input object itself).
28
+ */
29
+ export declare function formInput(raw: unknown): unknown;
30
+ /** A schema issue as `ValidationFailed.field_errors` (path joined with `.`; `""` for the root). */
31
+ export declare function fieldErrorsOf(issue: SchemaIssue.Issue): ValidationFailed['field_errors'];
32
+ /**
33
+ * Decodes a server function's raw argument with `schema`, failing with
34
+ * `ValidationFailed` (named after `what`, every problem listed by field)
35
+ * instead of a `SchemaError`. A no-JS form post's `FormData` is turned into
36
+ * a plain object first (`formInput`), so one schema serves both the
37
+ * scripted call and the form.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const tick = yield* decodeInput(LoadLiveFeedInput, "live feed tick")(raw);
42
+ * // a bad form post: ValidationFailed { field_errors: [{ field: "display_name", message: "Use 2 to 32 characters." }] }
43
+ * ```
44
+ */
45
+ export declare const decodeInput: <S extends Schema.Decoder<unknown>>(schema: S, what: string) => (raw: unknown) => Effect.Effect<S['Type'], ValidationFailed>;
@@ -0,0 +1,77 @@
1
+ import { Effect, Schema, SchemaIssue } from 'effect';
2
+ import { ValidationFailed } from './errors.js';
3
+ import { formBodyOf } from './form-actions.js';
4
+ /**
5
+ * Decoding a server function's raw argument. Every `"use server"` export is
6
+ * a public HTTP endpoint, so it decodes its input with Effect Schema first;
7
+ * a failure becomes `ValidationFailed`.
8
+ */
9
+ /**
10
+ * Functions that take no argument still decode it: `undefined` from a
11
+ * scripted call, or a no-JS form post's fields (only reserved `_` fields,
12
+ * so an empty object).
13
+ */
14
+ export const NoInput = Schema.UndefinedOr(Schema.Struct({}));
15
+ /** A short slug id (1 to 64 characters): keeps a hostile caller's payload small. */
16
+ export const IdInput = Schema.String.check(Schema.isBetweenLength(1, 64));
17
+ /**
18
+ * Form fields the kit's `<Form>` adds for the no-JS protocol (see
19
+ * `form-actions.ts`). They steer the redirect and are never part of a
20
+ * mutation's input.
21
+ */
22
+ export const RESERVED_FORM_FIELD_PREFIX = '_';
23
+ /**
24
+ * A no-JS form post's body (`URLSearchParams` or `FormData`) as the plain object the input schema
25
+ * decodes: one key per field name (a repeated name becomes an array of its
26
+ * values), files dropped, reserved `_`-prefixed fields left out. Anything
27
+ * that is not `FormData` passes through unchanged (scripted calls send the
28
+ * input object itself).
29
+ */
30
+ export function formInput(raw) {
31
+ const body = formBodyOf(raw);
32
+ if (!body)
33
+ return raw;
34
+ const fields = {};
35
+ for (const [name, value] of body.entries()) {
36
+ if (typeof value !== 'string' ||
37
+ name.startsWith(RESERVED_FORM_FIELD_PREFIX))
38
+ continue;
39
+ const seen = fields[name];
40
+ if (seen === undefined)
41
+ fields[name] = value;
42
+ else
43
+ fields[name] = Array.isArray(seen)
44
+ ? [...seen, value]
45
+ : [seen, value];
46
+ }
47
+ return fields;
48
+ }
49
+ const standardIssues = SchemaIssue.makeFormatterStandardSchemaV1();
50
+ /** A schema issue as `ValidationFailed.field_errors` (path joined with `.`; `""` for the root). */
51
+ export function fieldErrorsOf(issue) {
52
+ return standardIssues(issue).issues.map((entry) => ({
53
+ field: (entry.path ?? [])
54
+ .map((segment) => String(typeof segment === 'object' ? segment.key : segment))
55
+ .join('.'),
56
+ message: entry.message,
57
+ }));
58
+ }
59
+ /**
60
+ * Decodes a server function's raw argument with `schema`, failing with
61
+ * `ValidationFailed` (named after `what`, every problem listed by field)
62
+ * instead of a `SchemaError`. A no-JS form post's `FormData` is turned into
63
+ * a plain object first (`formInput`), so one schema serves both the
64
+ * scripted call and the form.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const tick = yield* decodeInput(LoadLiveFeedInput, "live feed tick")(raw);
69
+ * // a bad form post: ValidationFailed { field_errors: [{ field: "display_name", message: "Use 2 to 32 characters." }] }
70
+ * ```
71
+ */
72
+ export const decodeInput = (schema, what) => (raw) => Schema.decodeUnknownEffect(schema)(formInput(raw), {
73
+ errors: 'all',
74
+ }).pipe(Effect.mapError((error) => new ValidationFailed({
75
+ message: `Invalid ${what}: ${error.message}`,
76
+ field_errors: fieldErrorsOf(error.issue),
77
+ })));
@@ -0,0 +1,29 @@
1
+ import { Effect } from 'effect';
2
+ import { Bindings } from './bindings.ts';
3
+ import { RateLimited } from './errors.ts';
4
+ import { RequestInfo } from './request-info.ts';
5
+ /** What `rateLimit` needs: which binding, how to key a client, and what to tell it. */
6
+ export interface RateLimitSpec {
7
+ /** The binding's name in the resource declaration's `rateLimits`. */
8
+ readonly binding: string;
9
+ /** The key for a client (`client_ip` is `local` without `CF-Connecting-IP`). */
10
+ readonly key: (client_ip: string) => string;
11
+ /** The binding's period, told to the client as `retry_after_sec`. */
12
+ readonly period: number;
13
+ readonly message: string;
14
+ }
15
+ /**
16
+ * Counts this call against the limit and fails with `RateLimited` when the
17
+ * client is over it. A missing binding is a defect (`Unexpected`).
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * yield* rateLimit({
22
+ * binding: 'SIGN_IN_LIMIT',
23
+ * key: (ip) => `sign-in:${ip}`,
24
+ * period: 60,
25
+ * message: 'Too many sign-ins from this network.',
26
+ * })
27
+ * ```
28
+ */
29
+ export declare const rateLimit: (spec: RateLimitSpec) => Effect.Effect<undefined, RateLimited, Bindings | RequestInfo>;
@@ -0,0 +1,32 @@
1
+ import { Effect } from 'effect';
2
+ import { Bindings } from './bindings.js';
3
+ import { RateLimited } from './errors.js';
4
+ import { RequestInfo } from './request-info.js';
5
+ /**
6
+ * Counts this call against the limit and fails with `RateLimited` when the
7
+ * client is over it. A missing binding is a defect (`Unexpected`).
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * yield* rateLimit({
12
+ * binding: 'SIGN_IN_LIMIT',
13
+ * key: (ip) => `sign-in:${ip}`,
14
+ * period: 60,
15
+ * message: 'Too many sign-ins from this network.',
16
+ * })
17
+ * ```
18
+ */
19
+ export const rateLimit = (spec) => Effect.gen(function* () {
20
+ const env = yield* Bindings;
21
+ const info = yield* RequestInfo;
22
+ // `Bindings` checks the binding's kind when it is read.
23
+ const binding = env[spec.binding];
24
+ const key = spec.key(info.client_ip ?? 'local');
25
+ const { success } = yield* Effect.promise(() => binding.limit({ key }));
26
+ if (success)
27
+ return;
28
+ return yield* new RateLimited({
29
+ message: spec.message,
30
+ retry_after_sec: spec.period,
31
+ });
32
+ });
@@ -0,0 +1,74 @@
1
+ import { type Result, type Tagged } from '../logic/result.ts';
2
+ /**
3
+ * Read caching: the cache policy a GET read declares, and the headers it
4
+ * becomes.
5
+ */
6
+ /**
7
+ * How a GET read's answer may be cached. Declared per read on the server
8
+ * (next to the program), applied by the app's `runRead`.
9
+ *
10
+ * - `Shared`: public, non-personal data. Edge-cached by Workers Cache for
11
+ * `maxAgeSec`, then served stale for up to `staleWhileRevalidateSec` while
12
+ * one request refreshes it. Tagged (`Cache-Tag`) so the mutations that
13
+ * change it purge it (`ctx.cache.purge({ tags })`). Browsers revalidate
14
+ * every time (`Cache-Control: no-cache`): the edge TTL rides on
15
+ * `CDN-Cache-Control`, which browsers ignore, so a purge reaches every
16
+ * copy and a writer never re-reads its own stale answer from its browser.
17
+ * - `Private`: depends on who is asking (the session) or must always be
18
+ * fresh. `Cache-Control: private, no-store`.
19
+ */
20
+ export type ReadCachePolicy<A> = {
21
+ readonly _tag: 'Shared';
22
+ readonly maxAgeSec: number;
23
+ readonly staleWhileRevalidateSec: number;
24
+ /** Purge tags for an `Ok` value (letters, digits, `:`, `-`, `_`, `.`, `/` only). */
25
+ readonly tags: (value: A) => readonly string[];
26
+ } | {
27
+ readonly _tag: 'Private';
28
+ };
29
+ /** Header values for a cache policy (pure; `runRead` applies them). */
30
+ export declare const CACHE_CONTROL: {
31
+ /** Personal or session-dependent: nobody but this browser, and not even stored there. */
32
+ readonly PRIVATE: 'private, no-store';
33
+ /** Errors and anything else that must not be stored anywhere. */
34
+ readonly NO_STORE: 'no-store';
35
+ /** Browsers keep shared reads but revalidate (at the edge) every time. */
36
+ readonly BROWSER_REVALIDATE: 'no-cache';
37
+ };
38
+ /**
39
+ * The response headers for one GET read's outcome.
40
+ *
41
+ * Rules, in order:
42
+ * 1. the read touched the session (`sessionRead`): `private, no-store`,
43
+ * whatever the policy says (a session read is never shared-cached);
44
+ * 2. `Private` policy: `private, no-store`;
45
+ * 3. an `Err` outcome: `no-store` (errors aren't cached);
46
+ * 4. `Shared` + `Ok`: `Cache-Control: no-cache`, `CDN-Cache-Control:
47
+ * public, max-age=N, stale-while-revalidate=M`, `Cache-Tag: a,b`.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * readCacheHeaders(policy, ok(plan), { sessionRead: false });
52
+ * // { "Cache-Control": "no-cache", "CDN-Cache-Control": "public, max-age=10, stale-while-revalidate=60", "Cache-Tag": "plan,plan:voltar-main" }
53
+ * ```
54
+ */
55
+ export declare function readCacheHeaders<A>(policy: ReadCachePolicy<A>, result: Result<A, Tagged>, read: {
56
+ readonly sessionRead: boolean;
57
+ }): Record<string, string>;
58
+ /**
59
+ * A `Shared` policy: edge-cached `maxAgeSec`, served stale up to
60
+ * `staleWhileRevalidateSec` while it refreshes, purged by `tags`.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * export const READ_CACHE = {
65
+ * loadCharacter: sharedRead<Character>(60, 300, (c) => [`character:${c.id}`]),
66
+ * loadPlan: PRIVATE_READ,
67
+ * } as const
68
+ * ```
69
+ */
70
+ export declare function sharedRead<A>(maxAgeSec: number, staleWhileRevalidateSec: number, tags: (value: A) => readonly string[]): ReadCachePolicy<A>;
71
+ /** The `Private` policy: never shared-cached. */
72
+ export declare const PRIVATE_READ: {
73
+ readonly _tag: 'Private';
74
+ };