@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,31 @@
1
+ /**
2
+ * Alchemy for live rooms: the Worker bindings a live rooms declaration
3
+ * needs, made from that one declaration (`declareLiveRooms`,
4
+ * `@alecsibilia/ui-kit/live`). An app spreads them into its Worker's `env` in
5
+ * `alchemy.run.ts`; Alchemy creates the SQLite-backed Durable Object
6
+ * namespace (and writes its class migration) and the rate limit.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const worker = yield* Cloudflare.Worker("App", {
11
+ * main: "./dist/server/server.js",
12
+ * env: { DB: db, ...liveRoomsBindings(LIVE_ROOMS) },
13
+ * });
14
+ * ```
15
+ */
16
+ import * as Cloudflare from '@alchemy.run/cloudflare';
17
+ /** The `env` entries for a declaration: the room namespace, and the connect limit when declared. */
18
+ export function liveRoomsBindings(decl) {
19
+ const { binding, className } = decl.durableObject;
20
+ const rooms = { [binding]: Cloudflare.DurableObject(className) };
21
+ if (!decl.connectLimit)
22
+ return rooms;
23
+ const limit = decl.connectLimit;
24
+ return {
25
+ ...rooms,
26
+ [limit.binding]: Cloudflare.RateLimit(limit.binding, {
27
+ namespaceId: limit.namespaceId,
28
+ simple: { limit: limit.limit, period: limit.period },
29
+ }),
30
+ };
31
+ }
@@ -0,0 +1,28 @@
1
+ import type { ResourcesDecl } from '../logic/resources.ts';
2
+ /**
3
+ * D1 migrations as Alchemy and wrangler apply them: one folder per
4
+ * database. The sessions database gets the kit's own migrations first
5
+ * (`0000-ui-kit-<file>`, the `sessions` table), then the app's, so one
6
+ * folder holds both and D1's migration table tracks them together.
7
+ */
8
+ /** The kit's migrations folder (the package's `migrations/`). */
9
+ export declare const KIT_MIGRATIONS: string;
10
+ /** The prefix kit migrations get in an assembled folder (sorts before the app's `0001-...`). */
11
+ export declare const KIT_MIGRATION_PREFIX = "0000-ui-kit-";
12
+ /** Where the kit writes generated files for an app (gitignored). */
13
+ export declare const GENERATED_DIR = ".ui-kit";
14
+ /** The files an assembled folder holds for one database, in apply order: `[name, source path]`. */
15
+ export declare function migrationPlan({ appDir, resources, binding, }: {
16
+ appDir: string;
17
+ resources: ResourcesDecl;
18
+ binding: string;
19
+ }): [string, string][];
20
+ /**
21
+ * Writes each D1 database's assembled migrations folder under
22
+ * `<appDir>/.ui-kit/migrations/<binding>/` and returns the folders by
23
+ * binding (absolute paths).
24
+ */
25
+ export declare function assembleMigrations({ appDir, resources, }: {
26
+ appDir: string;
27
+ resources: ResourcesDecl;
28
+ }): Readonly<Record<string, string>>;
@@ -0,0 +1,56 @@
1
+ import { copyFileSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ /**
4
+ * D1 migrations as Alchemy and wrangler apply them: one folder per
5
+ * database. The sessions database gets the kit's own migrations first
6
+ * (`0000-ui-kit-<file>`, the `sessions` table), then the app's, so one
7
+ * folder holds both and D1's migration table tracks them together.
8
+ */
9
+ /** The kit's migrations folder (the package's `migrations/`). */
10
+ export const KIT_MIGRATIONS = resolve(import.meta.dirname, '../../migrations');
11
+ /** The prefix kit migrations get in an assembled folder (sorts before the app's `0001-...`). */
12
+ export const KIT_MIGRATION_PREFIX = '0000-ui-kit-';
13
+ /** Where the kit writes generated files for an app (gitignored). */
14
+ export const GENERATED_DIR = '.ui-kit';
15
+ /** The files an assembled folder holds for one database, in apply order: `[name, source path]`. */
16
+ export function migrationPlan({ appDir, resources, binding, }) {
17
+ const kit = resources.sessions?.database === binding
18
+ ? readdirSync(KIT_MIGRATIONS)
19
+ .filter((file) => file.endsWith('.sql'))
20
+ .sort()
21
+ .map((file) => [
22
+ `${KIT_MIGRATION_PREFIX}${file}`,
23
+ join(KIT_MIGRATIONS, file),
24
+ ])
25
+ : [];
26
+ const dir = resources.d1?.[binding]?.migrations;
27
+ const app = dir === undefined
28
+ ? []
29
+ : readdirSync(resolve(appDir, dir))
30
+ .filter((file) => file.endsWith('.sql'))
31
+ .sort()
32
+ .map((file) => [file, resolve(appDir, dir, file)]);
33
+ return [...kit, ...app];
34
+ }
35
+ /**
36
+ * Writes each D1 database's assembled migrations folder under
37
+ * `<appDir>/.ui-kit/migrations/<binding>/` and returns the folders by
38
+ * binding (absolute paths).
39
+ */
40
+ export function assembleMigrations({ appDir, resources, }) {
41
+ const out = {};
42
+ for (const binding of Object.keys(resources.d1 ?? {})) {
43
+ const dir = resolve(appDir, GENERATED_DIR, 'migrations', binding);
44
+ rmSync(dir, { recursive: true, force: true });
45
+ mkdirSync(dir, { recursive: true });
46
+ for (const [name, source] of migrationPlan({
47
+ appDir,
48
+ resources,
49
+ binding,
50
+ })) {
51
+ copyFileSync(source, join(dir, name));
52
+ }
53
+ out[binding] = dir;
54
+ }
55
+ return out;
56
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stage naming for an app's Alchemy stack: `prod` (bare names) and PR
3
+ * previews `pr-<n>` (every resource name gets `-<stage>`). Pure, so tests
4
+ * and the local tooling share it with `uiKitApp`.
5
+ */
6
+ /** The production stage. Every other stage is a PR preview (`pr-<n>`). */
7
+ export declare const PRODUCTION_STAGE = "prod";
8
+ /** A resource name for a stage: bare on production, `<base>-<stage>` elsewhere. */
9
+ export declare function stageName(base: string, stage: string): string;
10
+ /** The Cloudflare resource names a declaration gets on a stage, by binding. */
11
+ export declare function stageResourceNames({ name, d1, r2, stage, }: {
12
+ name: string;
13
+ d1: readonly string[];
14
+ r2: readonly string[];
15
+ stage: string;
16
+ }): {
17
+ readonly worker: string;
18
+ readonly d1: Readonly<Record<string, string>>;
19
+ readonly r2: Readonly<Record<string, string>>;
20
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stage naming for an app's Alchemy stack: `prod` (bare names) and PR
3
+ * previews `pr-<n>` (every resource name gets `-<stage>`). Pure, so tests
4
+ * and the local tooling share it with `uiKitApp`.
5
+ */
6
+ /** The production stage. Every other stage is a PR preview (`pr-<n>`). */
7
+ export const PRODUCTION_STAGE = 'prod';
8
+ /** A resource name for a stage: bare on production, `<base>-<stage>` elsewhere. */
9
+ export function stageName(base, stage) {
10
+ return stage === PRODUCTION_STAGE ? base : `${base}-${stage}`;
11
+ }
12
+ /** The Cloudflare resource names a declaration gets on a stage, by binding. */
13
+ export function stageResourceNames({ name, d1, r2, stage, }) {
14
+ const suffixed = (binding, index) => stageName(index === 0 ? name : `${name}-${binding.toLowerCase()}`, stage);
15
+ return {
16
+ worker: stageName(name, stage),
17
+ d1: Object.fromEntries(d1.map((b, i) => [b, suffixed(b, i)])),
18
+ r2: Object.fromEntries(r2.map((b) => [b, stageName(`${name}-${b.toLowerCase()}`, stage)])),
19
+ };
20
+ }
@@ -0,0 +1,76 @@
1
+ import { type ResourcesDecl } from '../logic/resources.ts';
2
+ /**
3
+ * The local workerd config (`wrangler.json` for `wrangler dev`, `vite dev`'s
4
+ * platform proxy and the dev Durable Object Worker), made from the same
5
+ * resource declaration Alchemy deploys. Never used to deploy. Pure data:
6
+ * the Vite plugin and `ui-kit preview` write it to `.ui-kit/`.
7
+ */
8
+ /** A wrangler config (the fields the kit writes). */
9
+ export interface WranglerConfig {
10
+ readonly name: string;
11
+ readonly main: string;
12
+ readonly compatibility_date: string;
13
+ readonly compatibility_flags: readonly string[];
14
+ readonly assets?: {
15
+ readonly directory: string;
16
+ };
17
+ readonly cache?: {
18
+ readonly enabled: boolean;
19
+ };
20
+ readonly d1_databases?: readonly {
21
+ readonly binding: string;
22
+ readonly database_name: string;
23
+ readonly database_id: string;
24
+ readonly migrations_dir: string;
25
+ }[];
26
+ readonly r2_buckets?: readonly {
27
+ readonly binding: string;
28
+ readonly bucket_name: string;
29
+ }[];
30
+ readonly ratelimits?: readonly {
31
+ readonly name: string;
32
+ readonly namespace_id: string;
33
+ readonly simple: {
34
+ readonly limit: number;
35
+ readonly period: number;
36
+ };
37
+ }[];
38
+ readonly durable_objects?: {
39
+ readonly bindings: readonly {
40
+ readonly name: string;
41
+ readonly class_name: string;
42
+ }[];
43
+ };
44
+ readonly migrations?: readonly {
45
+ readonly tag: string;
46
+ readonly new_sqlite_classes: readonly string[];
47
+ }[];
48
+ readonly triggers?: {
49
+ readonly crons: readonly string[];
50
+ };
51
+ }
52
+ /** Every Durable Object binding a declaration gives: `[binding, class, migration tag]`. */
53
+ export declare function durableObjectsOf(resources: ResourcesDecl): [string, string, string][];
54
+ /** Every rate limit a declaration gives (its own and the live rooms' connect limit). */
55
+ export declare function rateLimitsOf(resources: ResourcesDecl): [string, {
56
+ namespaceId: string;
57
+ limit: number;
58
+ period: 10 | 60;
59
+ }][];
60
+ /** Every cron the Worker runs: the app's own, plus the sessions cleanup. */
61
+ export declare function cronsOf(resources: ResourcesDecl): string[];
62
+ /**
63
+ * The local wrangler config for a declaration.
64
+ *
65
+ * @param main - the Worker module, relative to where the config is written
66
+ * @param assets - the static assets folder, relative likewise (none for a side Worker)
67
+ * @param migrations - each D1 binding's migrations folder, relative likewise
68
+ */
69
+ export declare function wranglerConfig({ resources, name, main, assets, migrations, crons, }: {
70
+ resources: ResourcesDecl;
71
+ name: string;
72
+ main: string;
73
+ assets?: string;
74
+ migrations: Readonly<Record<string, string>>;
75
+ crons?: boolean;
76
+ }): WranglerConfig;
@@ -0,0 +1,82 @@
1
+ import { DEFAULT_SESSIONS_CRON, } from '../logic/resources.js';
2
+ /** Every Durable Object binding a declaration gives: `[binding, class, migration tag]`. */
3
+ export function durableObjectsOf(resources) {
4
+ const out = Object.entries(resources.durableObjects ?? {}).map(([binding, decl]) => [binding, decl.className, decl.migrationTag]);
5
+ const rooms = resources.liveRooms?.durableObject;
6
+ if (rooms)
7
+ out.push([rooms.binding, rooms.className, rooms.migrationTag]);
8
+ return out;
9
+ }
10
+ /** Every rate limit a declaration gives (its own and the live rooms' connect limit). */
11
+ export function rateLimitsOf(resources) {
12
+ const out = Object.entries(resources.rateLimits ?? {}).map(([name, decl]) => [
13
+ name,
14
+ decl,
15
+ ]);
16
+ const connect = resources.liveRooms?.connectLimit;
17
+ if (connect)
18
+ out.push([connect.binding, connect]);
19
+ return out;
20
+ }
21
+ /** Every cron the Worker runs: the app's own, plus the sessions cleanup. */
22
+ export function cronsOf(resources) {
23
+ const crons = [...(resources.crons ?? [])];
24
+ if (resources.sessions) {
25
+ const cron = resources.sessions.cron ?? DEFAULT_SESSIONS_CRON;
26
+ if (!crons.includes(cron))
27
+ crons.push(cron);
28
+ }
29
+ return crons;
30
+ }
31
+ /** A fixed local database id per binding (local D1 only needs it to be stable). */
32
+ function localDatabaseId(index) {
33
+ return `00000000-0000-0000-0000-${String(index).padStart(12, '0')}`;
34
+ }
35
+ /**
36
+ * The local wrangler config for a declaration.
37
+ *
38
+ * @param main - the Worker module, relative to where the config is written
39
+ * @param assets - the static assets folder, relative likewise (none for a side Worker)
40
+ * @param migrations - each D1 binding's migrations folder, relative likewise
41
+ */
42
+ export function wranglerConfig({ resources, name, main, assets, migrations, crons = true, }) {
43
+ const objects = durableObjectsOf(resources);
44
+ const limits = rateLimitsOf(resources);
45
+ const cronList = crons ? cronsOf(resources) : [];
46
+ return {
47
+ name,
48
+ main,
49
+ compatibility_date: resources.compatibility.date,
50
+ compatibility_flags: [...resources.compatibility.flags],
51
+ ...(assets === undefined ? {} : { assets: { directory: assets } }),
52
+ ...(resources.readCache ? { cache: { enabled: true } } : {}),
53
+ d1_databases: Object.keys(resources.d1 ?? {}).map((binding, i) => ({
54
+ binding,
55
+ database_name: `${resources.name}-${binding.toLowerCase()}-local`,
56
+ database_id: localDatabaseId(i),
57
+ migrations_dir: migrations[binding] ?? 'migrations',
58
+ })),
59
+ r2_buckets: Object.keys(resources.r2 ?? {}).map((binding) => ({
60
+ binding,
61
+ bucket_name: `${resources.name}-${binding.toLowerCase()}-local`,
62
+ })),
63
+ ratelimits: limits.map(([limitName, decl]) => ({
64
+ name: limitName,
65
+ namespace_id: decl.namespaceId,
66
+ simple: { limit: decl.limit, period: decl.period },
67
+ })),
68
+ durable_objects: {
69
+ bindings: objects.map(([binding, className]) => ({
70
+ name: binding,
71
+ class_name: className,
72
+ })),
73
+ },
74
+ migrations: [...objects]
75
+ .sort((a, b) => a[2].localeCompare(b[2]))
76
+ .map(([, className, tag]) => ({
77
+ tag,
78
+ new_sqlite_classes: [className],
79
+ })),
80
+ ...(cronList.length > 0 ? { triggers: { crons: cronList } } : {}),
81
+ };
82
+ }
@@ -0,0 +1,11 @@
1
+ import type { SiteHead } from '../logic/head.ts';
2
+ import type { ResourcesDecl } from '../logic/resources.ts';
3
+ import type { RouteTable } from '../logic/route-table.ts';
4
+ import type { SitemapProviders } from '../logic/seo.ts';
5
+ export declare function loadRoutes(appDir: string): Promise<RouteTable>;
6
+ export declare function loadResources(appDir: string): Promise<ResourcesDecl>;
7
+ export declare function loadSeoTables(appDir: string): Promise<{
8
+ readonly routes: RouteTable;
9
+ readonly siteHead: SiteHead;
10
+ readonly sitemapSources: SitemapProviders<RouteTable>;
11
+ }>;
@@ -0,0 +1,40 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { resolve } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ /**
12
+ * The app's tables, loaded by the `ui-kit` command (under Bun) from their
13
+ * fixed places in a layer-first app: `src/routes.ts` (`routes`),
14
+ * `src/site.ts` (`siteHead`), `src/sitemap-sources.ts` (`sitemapSources`)
15
+ * and `src/resources.ts` (`resources`). Pure data modules: loading them
16
+ * runs no page, island or server code (pages are thunks).
17
+ */
18
+ async function load(appDir, path) {
19
+ return import(__rewriteRelativeImportExtension(pathToFileURL(resolve(appDir, path)).href, true));
20
+ }
21
+ function exportOf(mod, name, path) {
22
+ if (typeof mod !== 'object' || mod === null || !(name in mod)) {
23
+ throw new Error(`${path} has no \`${name}\` export`);
24
+ }
25
+ // The app's table module: its shape is the kit's type (checked by tsc in the app).
26
+ return Reflect.get(mod, name);
27
+ }
28
+ export async function loadRoutes(appDir) {
29
+ return exportOf(await load(appDir, 'src/routes.ts'), 'routes', 'src/routes.ts');
30
+ }
31
+ export async function loadResources(appDir) {
32
+ return exportOf(await load(appDir, 'src/resources.ts'), 'resources', 'src/resources.ts');
33
+ }
34
+ export async function loadSeoTables(appDir) {
35
+ return {
36
+ routes: await loadRoutes(appDir),
37
+ siteHead: exportOf(await load(appDir, 'src/site.ts'), 'siteHead', 'src/site.ts'),
38
+ sitemapSources: exportOf(await load(appDir, 'src/sitemap-sources.ts'), 'sitemapSources', 'src/sitemap-sources.ts'),
39
+ };
40
+ }
@@ -0,0 +1,4 @@
1
+ /** `snake_case` problems in a migration's `CREATE TABLE` / `ADD COLUMN` names. */
2
+ export declare function migrationNameProblems(sql: string): string[];
3
+ /** Every problem in the app at `appDir` (empty when it passes). */
4
+ export declare function checkApp(appDir: string): string[];
@@ -0,0 +1,170 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ /**
4
+ * `ui-kit check`: the import-graph checks lint can't do one file at a
5
+ * time, over a layer-first app's `src/`, plus its migrations' names.
6
+ *
7
+ * 1. No Effect is reachable from a browser folder: from every file in
8
+ * `lib/`, `models/`, `commands/`, `page-models/`, `queries/`,
9
+ * `mutations/`, `views/`, `islands/`, `pages/` and the root tables,
10
+ * following value imports (type-only imports are erased; `import()` is
11
+ * a lazy chunk, checked on its own; `server/functions/` are RPC stubs in
12
+ * the browser), nothing reaches `effect` or a server-only kit subpath.
13
+ * 2. A model reaches nothing impure: from `models/`, no Solid, no Effect,
14
+ * no `.tsx`, and only the kit's `/logic` and `/live`.
15
+ * 3. Migrations use `snake_case` table and column names.
16
+ *
17
+ * The built-bundle check (an app's `client-bundle` e2e test) stays as the
18
+ * final guard.
19
+ */
20
+ const BROWSER_FOLDERS = [
21
+ 'lib',
22
+ 'models',
23
+ 'commands',
24
+ 'page-models',
25
+ 'queries',
26
+ 'mutations',
27
+ 'views',
28
+ 'islands',
29
+ 'pages',
30
+ ];
31
+ const ROOT_BROWSER_FILES = [
32
+ 'routes.ts',
33
+ 'islands.ts',
34
+ 'live-rooms.ts',
35
+ 'site.ts',
36
+ 'app.tsx',
37
+ 'document.tsx',
38
+ 'entry-client.tsx',
39
+ ];
40
+ const SERVER_ONLY = /^(effect(\/.*)?|@alecsibilia\/ui-kit\/(server|worker|render|live\/server|alchemy|vite|build|test)(\/.*)?)$/;
41
+ const IMPURE_FOR_MODELS = /^(effect(\/.*)?|solid-js(\/.*)?|@solidjs\/.*|@alecsibilia\/ui-kit\/(?!logic$|live$).*)$/;
42
+ const SNAKE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
43
+ const isTest = (file) => /\.(test|e2e\.test|probe|check)\.tsx?$/.test(file);
44
+ function sourceFiles(dir) {
45
+ if (!existsSync(dir))
46
+ return [];
47
+ return readdirSync(dir).flatMap((name) => {
48
+ const full = join(dir, name);
49
+ if (statSync(full).isDirectory())
50
+ return sourceFiles(full);
51
+ return /\.(ts|tsx)$/.test(name) &&
52
+ !name.endsWith('.d.ts') &&
53
+ !isTest(name)
54
+ ? [full]
55
+ : [];
56
+ });
57
+ }
58
+ /** A relative specifier resolved to a file (`.ts`, `.tsx`, `/index.ts`), or `undefined`. */
59
+ function resolveFile(from, spec) {
60
+ const base = resolve(dirname(from), spec);
61
+ for (const candidate of [
62
+ base,
63
+ `${base}.ts`,
64
+ `${base}.tsx`,
65
+ join(base, 'index.ts'),
66
+ ]) {
67
+ if (existsSync(candidate) && statSync(candidate).isFile())
68
+ return candidate;
69
+ }
70
+ return undefined;
71
+ }
72
+ /** The value imports of every file (static ones; `import()` is left out). */
73
+ function importGraph(files) {
74
+ const ts = new Bun.Transpiler({ loader: 'ts' });
75
+ const tsx = new Bun.Transpiler({ loader: 'tsx' });
76
+ const graph = new Map();
77
+ for (const file of files) {
78
+ const transpiler = file.endsWith('.tsx') ? tsx : ts;
79
+ const imports = transpiler
80
+ .scanImports(readFileSync(file, 'utf8'))
81
+ .filter((entry) => entry.kind !== 'dynamic-import');
82
+ graph.set(file, imports.map((entry) => ({
83
+ spec: entry.path,
84
+ file: entry.path.startsWith('.')
85
+ ? resolveFile(file, entry.path)
86
+ : undefined,
87
+ })));
88
+ }
89
+ return graph;
90
+ }
91
+ /** The first path from `start` to a package matching `banned`, or `undefined`. */
92
+ function reach(graph, start, banned, stop, bannedFile = () => false) {
93
+ const seen = new Set([start]);
94
+ const queue = [[start, [start]]];
95
+ while (queue.length > 0) {
96
+ const [file, path] = queue.shift() ?? ['', []];
97
+ for (const edge of graph.get(file) ?? []) {
98
+ if (edge.file === undefined) {
99
+ if (banned.test(edge.spec))
100
+ return [...path, edge.spec];
101
+ continue;
102
+ }
103
+ if (bannedFile(edge.file))
104
+ return [...path, edge.file];
105
+ if (seen.has(edge.file) || stop(edge.file))
106
+ continue;
107
+ seen.add(edge.file);
108
+ queue.push([edge.file, [...path, edge.file]]);
109
+ }
110
+ }
111
+ return undefined;
112
+ }
113
+ /** `snake_case` problems in a migration's `CREATE TABLE` / `ADD COLUMN` names. */
114
+ export function migrationNameProblems(sql) {
115
+ const problems = [];
116
+ const body = sql.replace(/--.*$/gm, '');
117
+ for (const match of body.matchAll(/CREATE TABLE(?: IF NOT EXISTS)?\s+(\w+)\s*\(([\s\S]*?)\);/gi)) {
118
+ const table = match[1] ?? '';
119
+ if (!SNAKE.test(table))
120
+ problems.push(`table "${table}"`);
121
+ for (const line of (match[2] ?? '').split(',')) {
122
+ const column = /^\s*(\w+)/.exec(line)?.[1];
123
+ if (column === undefined ||
124
+ /^(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)$/i.test(column))
125
+ continue;
126
+ if (!SNAKE.test(column))
127
+ problems.push(`column "${table}.${column}"`);
128
+ }
129
+ }
130
+ for (const match of body.matchAll(/ALTER TABLE\s+(\w+)\s+ADD COLUMN\s+(\w+)/gi)) {
131
+ if (!SNAKE.test(match[2] ?? ''))
132
+ problems.push(`column "${match[1]}.${match[2]}"`);
133
+ }
134
+ return problems;
135
+ }
136
+ /** Every problem in the app at `appDir` (empty when it passes). */
137
+ export function checkApp(appDir) {
138
+ const src = resolve(appDir, 'src');
139
+ const files = sourceFiles(src);
140
+ const graph = importGraph(files);
141
+ const rel = (file) => relative(appDir, file);
142
+ // A file as a path relative to the app, a package as its specifier.
143
+ const show = (step) => (step.startsWith('/') ? rel(step) : step);
144
+ const problems = [];
145
+ const isFunctions = (file) => rel(file).startsWith('src/server/functions/');
146
+ const browserRoots = files.filter((file) => {
147
+ const path = relative(src, file);
148
+ const folder = path.split('/')[0] ?? '';
149
+ return (BROWSER_FOLDERS.includes(folder) ||
150
+ ROOT_BROWSER_FILES.includes(path));
151
+ });
152
+ for (const root of browserRoots) {
153
+ const path = reach(graph, root, SERVER_ONLY, isFunctions);
154
+ if (path)
155
+ problems.push(`browser code reaches server-only ${show(path.at(-1) ?? '')}: ${path.map(show).join(' -> ')}`);
156
+ }
157
+ for (const model of files.filter((f) => relative(src, f).startsWith('models/'))) {
158
+ const path = reach(graph, model, IMPURE_FOR_MODELS, () => false, (file) => file.endsWith('.tsx'));
159
+ if (path)
160
+ problems.push(`model reaches impure ${show(path.at(-1) ?? '')}: ${path.map(show).join(' -> ')}`);
161
+ }
162
+ const migrations = resolve(appDir, 'migrations');
163
+ if (existsSync(migrations)) {
164
+ for (const file of readdirSync(migrations).filter((f) => f.endsWith('.sql'))) {
165
+ for (const problem of migrationNameProblems(readFileSync(join(migrations, file), 'utf8')))
166
+ problems.push(`migrations/${file}: ${problem} is not snake_case`);
167
+ }
168
+ }
169
+ return problems;
170
+ }
@@ -0,0 +1 @@
1
+ export declare function main(args: readonly string[]): Promise<number>;
@@ -0,0 +1,79 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { resolve } from 'node:path';
3
+ import { loadSeoTables } from './app-modules.js';
4
+ import { checkApp } from './check.js';
5
+ import { featureFiles } from './feature.js';
6
+ import { measureCpu } from './measure-cpu.js';
7
+ import { prerender } from './prerender.js';
8
+ import { preview } from './preview.js';
9
+ import { seoFiles } from './seo-files.js';
10
+ import { PRERENDER_BUILD_ENV } from '../vite/worker-build.js';
11
+ /**
12
+ * The `ui-kit` command (run by Bun, in the app's folder):
13
+ *
14
+ * - `ui-kit prerender`: the prerender build, then each `render:
15
+ * "prerender"` page into `dist/client`, and `_headers`;
16
+ * - `ui-kit seo-files`: `dist/client/sitemap.xml` and `robots.txt`;
17
+ * - `ui-kit preview [--port N]`: the built app on local workerd;
18
+ * - `ui-kit measure-cpu [path] [count] | --cold [runs] [path]`: CPU per
19
+ * request on local workerd;
20
+ * - `ui-kit check`: the import-graph and migration checks;
21
+ * - `ui-kit feature <name>`: a feature's files across the layers.
22
+ */
23
+ const USAGE = 'usage: ui-kit prerender | seo-files | preview [--port N] | measure-cpu [args] | check | feature <name>';
24
+ export async function main(args) {
25
+ const appDir = process.cwd();
26
+ const [command, ...rest] = args;
27
+ switch (command) {
28
+ case 'prerender': {
29
+ const vite = resolve(appDir, 'node_modules/.bin/vite');
30
+ const built = spawnSync(vite, ['build'], {
31
+ cwd: appDir,
32
+ stdio: 'inherit',
33
+ env: { ...process.env, [PRERENDER_BUILD_ENV]: 'prerender' },
34
+ });
35
+ if (built.status !== 0)
36
+ return built.status ?? 1;
37
+ await prerender({ appDir });
38
+ return 0;
39
+ }
40
+ case 'seo-files': {
41
+ const files = await seoFiles(await loadSeoTables(appDir));
42
+ const client = resolve(appDir, 'dist/client');
43
+ await Bun.write(resolve(client, 'sitemap.xml'), files.sitemap);
44
+ await Bun.write(resolve(client, 'robots.txt'), files.robots);
45
+ if (files.skipped.length > 0) {
46
+ console.warn(`sitemap: no provider for ${files.skipped.join(', ')} (left out)`);
47
+ }
48
+ console.log('wrote dist/client/sitemap.xml and robots.txt');
49
+ return 0;
50
+ }
51
+ case 'preview':
52
+ return preview(appDir, rest);
53
+ case 'measure-cpu':
54
+ await measureCpu(appDir, rest);
55
+ return 0;
56
+ case 'check': {
57
+ const problems = checkApp(appDir);
58
+ for (const problem of problems)
59
+ console.error(problem);
60
+ console.log(problems.length === 0
61
+ ? 'ui-kit check: no problems'
62
+ : `ui-kit check: ${problems.length} problem(s)`);
63
+ return problems.length === 0 ? 0 : 1;
64
+ }
65
+ case 'feature': {
66
+ const name = rest[0];
67
+ if (name === undefined) {
68
+ console.error('usage: ui-kit feature <name>');
69
+ return 1;
70
+ }
71
+ for (const file of featureFiles(appDir, name))
72
+ console.log(file);
73
+ return 0;
74
+ }
75
+ default:
76
+ console.error(USAGE);
77
+ return 1;
78
+ }
79
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `ui-kit feature <name>`: a feature's files across a layer-first app's
3
+ * layers. Base names are feature names (`planner.model.ts`,
4
+ * `planner-island.tsx`, `planner-trace.model.ts`), so the feature is every
5
+ * file under `src/` whose name starts with `<name>.` or `<name>-`, listed
6
+ * by layer folder.
7
+ */
8
+ export declare function featureFiles(appDir: string, name: string): string[];
@@ -0,0 +1,24 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ /**
4
+ * `ui-kit feature <name>`: a feature's files across a layer-first app's
5
+ * layers. Base names are feature names (`planner.model.ts`,
6
+ * `planner-island.tsx`, `planner-trace.model.ts`), so the feature is every
7
+ * file under `src/` whose name starts with `<name>.` or `<name>-`, listed
8
+ * by layer folder.
9
+ */
10
+ export function featureFiles(appDir, name) {
11
+ const src = resolve(appDir, 'src');
12
+ const walk = (dir) => existsSync(dir)
13
+ ? readdirSync(dir).flatMap((entry) => {
14
+ const full = join(dir, entry);
15
+ if (statSync(full).isDirectory())
16
+ return walk(full);
17
+ return entry.startsWith(`${name}.`) ||
18
+ entry.startsWith(`${name}-`)
19
+ ? [relative(appDir, full)]
20
+ : [];
21
+ })
22
+ : [];
23
+ return walk(src).sort();
24
+ }