@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,13 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/build`: the `ui-kit` command's steps as functions
3
+ * (prerender, SEO files, local preview, CPU measurement, the import-graph
4
+ * check, feature listing). Bun only.
5
+ */
6
+ export { loadResources, loadRoutes, loadSeoTables } from './app-modules.ts';
7
+ export { checkApp, migrationNameProblems } from './check.ts';
8
+ export { main } from './cli.ts';
9
+ export { featureFiles } from './feature.ts';
10
+ export { measureCpu } from './measure-cpu.ts';
11
+ export { prerender } from './prerender.ts';
12
+ export { preview } from './preview.ts';
13
+ export { SEO_FILES, seoFiles } from './seo-files.ts';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@alecsibilia/ui-kit/build`: the `ui-kit` command's steps as functions
3
+ * (prerender, SEO files, local preview, CPU measurement, the import-graph
4
+ * check, feature listing). Bun only.
5
+ */
6
+ export { loadResources, loadRoutes, loadSeoTables } from './app-modules.js';
7
+ export { checkApp, migrationNameProblems } from './check.js';
8
+ export { main } from './cli.js';
9
+ export { featureFiles } from './feature.js';
10
+ export { measureCpu } from './measure-cpu.js';
11
+ export { prerender } from './prerender.js';
12
+ export { preview } from './preview.js';
13
+ export { SEO_FILES, seoFiles } from './seo-files.js';
@@ -0,0 +1,2 @@
1
+ /** `ui-kit measure-cpu [path] [count]` or `ui-kit measure-cpu --cold [runs] [path]`. */
2
+ export declare function measureCpu(appDir: string, args: readonly string[]): Promise<void>;
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Measures the Worker's CPU per request on local workerd, from V8 CPU
3
+ * profiles taken over `wrangler dev`'s inspector.
4
+ *
5
+ * workerd's sampler only ticks while the isolate runs, so the samples
6
+ * that aren't `(idle)` / `(program)`, times the sampling interval, are
7
+ * the request's JS + GC CPU time. (Summing the profile's time deltas
8
+ * instead charges async waits, the demo's `Effect.sleep`s and D1 calls,
9
+ * to the last frame, overstating CPU by ~100x; `ps` on the workerd
10
+ * processes also counts workerd's HTTP and local D1 work.)
11
+ *
12
+ * Two modes (build first):
13
+ *
14
+ * - Warm: `ui-kit measure-cpu [path] [count]` (defaults `/` and 20)
15
+ * against a running `ui-kit preview` (`ORIGIN`, default
16
+ * `http://127.0.0.1:5401`; `INSPECTOR`, default `http://127.0.0.1:5402`).
17
+ * Prints the first request and the median / p90 / max of the rest.
18
+ * - Cold: `ui-kit measure-cpu --cold [runs] [path]` (defaults 5 and `/`)
19
+ * starts its own `wrangler dev` (port 5403, inspector 5404; override with
20
+ * `COLD_PORT` / `COLD_INSPECTOR_PORT`) `runs` times, profiles the first
21
+ * request after each start, then a second one for contrast, and stops it.
22
+ *
23
+ * Local workerd is not the edge: read the numbers as an estimate, not as
24
+ * the billed figure.
25
+ */
26
+ import { spawn } from 'node:child_process';
27
+ import { relative } from 'node:path';
28
+ import { loadResources } from './app-modules.js';
29
+ import { wranglerBin, writeLocalConfig, LOCAL_STATE_DIR, } from '../vite/local-config.js';
30
+ const INTERVAL_US = 100;
31
+ /** JS + GC milliseconds in one profile. */
32
+ function cpuMs(profile) {
33
+ const names = new Map(profile.nodes.map((n) => [n.id, n.callFrame.functionName]));
34
+ const busy = profile.samples.filter((id) => {
35
+ const name = names.get(id);
36
+ return name !== '(idle)' && name !== '(program)';
37
+ }).length;
38
+ return (busy * INTERVAL_US) / 1000;
39
+ }
40
+ async function connectInspector(inspector) {
41
+ const [target] = (await (await fetch(`${inspector}/json`)).json());
42
+ if (!target)
43
+ throw new Error(`no inspector target at ${inspector}`);
44
+ const socket = new WebSocket(target.webSocketDebuggerUrl);
45
+ await new Promise((ok, fail) => {
46
+ socket.addEventListener('open', ok, { once: true });
47
+ socket.addEventListener('error', fail, { once: true });
48
+ });
49
+ let nextId = 1;
50
+ const waiting = new Map();
51
+ socket.addEventListener('message', (event) => {
52
+ const message = JSON.parse(String(event.data));
53
+ if (message.id !== undefined)
54
+ waiting.get(message.id)?.(message.result);
55
+ });
56
+ const session = {
57
+ send(method, params = {}) {
58
+ const id = nextId++;
59
+ socket.send(JSON.stringify({ id, method, params }));
60
+ return new Promise((ok) => waiting.set(id, ok));
61
+ },
62
+ close: () => socket.close(),
63
+ };
64
+ await session.send('Profiler.enable');
65
+ await session.send('Profiler.setSamplingInterval', {
66
+ interval: INTERVAL_US,
67
+ });
68
+ return session;
69
+ }
70
+ /** CPU ms of each of `count` sequential requests to `origin + path`, whole stream read. */
71
+ async function profileRequests(session, origin, path, count) {
72
+ const results = [];
73
+ for (let i = 0; i < count; i += 1) {
74
+ await session.send('Profiler.start');
75
+ const response = await fetch(`${origin}${path}`, {
76
+ headers: { accept: 'text/html' },
77
+ });
78
+ await response.text(); // the whole stream: every boundary rendered
79
+ const { profile } = await session.send('Profiler.stop');
80
+ results.push(cpuMs(profile));
81
+ }
82
+ return results;
83
+ }
84
+ function percentile(sorted, p) {
85
+ return (sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] ?? 0);
86
+ }
87
+ const ms = (value) => `${(value ?? 0).toFixed(1)} ms`;
88
+ async function warm(path, count) {
89
+ const inspector = process.env.INSPECTOR ?? 'http://127.0.0.1:5402';
90
+ const origin = process.env.ORIGIN ?? 'http://127.0.0.1:5401';
91
+ const session = await connectInspector(inspector).catch((error) => {
92
+ throw new Error(`${String(error)}: run \`ui-kit preview\` first`);
93
+ });
94
+ const results = await profileRequests(session, origin, path, count);
95
+ session.close();
96
+ const sorted = results.slice(1).toSorted((a, b) => a - b);
97
+ console.log(`${path}: first request ${ms(results[0])} CPU`);
98
+ console.log(`${path}: next ${sorted.length}: median ${ms(percentile(sorted, 0.5))}, p90 ${ms(percentile(sorted, 0.9))}, max ${ms(sorted.at(-1))}`);
99
+ }
100
+ /** Polls until `url` answers (any status), or fails after `timeoutMs`. */
101
+ async function waitFor(url, timeoutMs) {
102
+ const deadline = Date.now() + timeoutMs;
103
+ while (Date.now() < deadline) {
104
+ try {
105
+ await fetch(url);
106
+ return;
107
+ }
108
+ catch {
109
+ await Bun.sleep(200);
110
+ }
111
+ }
112
+ throw new Error(`${url} did not come up in ${timeoutMs} ms`);
113
+ }
114
+ /** Stops wrangler and its workerd (their own process group). */
115
+ async function stop(child) {
116
+ if (child.pid === undefined || child.exitCode !== null)
117
+ return;
118
+ const exited = new Promise((ok) => child.once('exit', ok));
119
+ try {
120
+ process.kill(-child.pid, 'SIGTERM');
121
+ }
122
+ catch {
123
+ child.kill('SIGTERM');
124
+ }
125
+ await Promise.race([exited, Bun.sleep(5000)]);
126
+ if (child.exitCode === null) {
127
+ try {
128
+ process.kill(-child.pid, 'SIGKILL');
129
+ }
130
+ catch {
131
+ // Already gone.
132
+ }
133
+ }
134
+ }
135
+ async function cold(appDir, runs, path) {
136
+ const local = writeLocalConfig({
137
+ appDir,
138
+ resources: await loadResources(appDir),
139
+ });
140
+ const port = Number(process.env.COLD_PORT ?? 5403);
141
+ const inspectorPort = Number(process.env.COLD_INSPECTOR_PORT ?? 5404);
142
+ const origin = `http://127.0.0.1:${port}`;
143
+ const inspector = `http://127.0.0.1:${inspectorPort}`;
144
+ const firsts = [];
145
+ const seconds = [];
146
+ for (let run = 1; run <= runs; run += 1) {
147
+ const child = spawn(wranglerBin(appDir), [
148
+ 'dev',
149
+ '-c',
150
+ relative(appDir, local.wranglerPath),
151
+ '--persist-to',
152
+ LOCAL_STATE_DIR,
153
+ '--ip',
154
+ '127.0.0.1',
155
+ '--port',
156
+ String(port),
157
+ '--inspector-port',
158
+ String(inspectorPort),
159
+ ], {
160
+ cwd: appDir,
161
+ detached: true,
162
+ stdio: 'ignore',
163
+ env: {
164
+ ...process.env,
165
+ CI: '1',
166
+ WRANGLER_SEND_METRICS: 'false',
167
+ },
168
+ });
169
+ try {
170
+ // The inspector answers once workerd has loaded the Worker; no
171
+ // request reaches the Worker before the profiled one.
172
+ await waitFor(`${inspector}/json`, 30_000);
173
+ const session = await connectInspector(inspector);
174
+ const [first, second] = await profileRequests(session, origin, path, 2);
175
+ session.close();
176
+ firsts.push(first ?? 0);
177
+ seconds.push(second ?? 0);
178
+ console.log(`run ${run}/${runs}: first request ${ms(first)}, second ${ms(second)}`);
179
+ }
180
+ finally {
181
+ await stop(child);
182
+ }
183
+ }
184
+ const sorted = firsts.toSorted((a, b) => a - b);
185
+ const secondSorted = seconds.toSorted((a, b) => a - b);
186
+ console.log(`${path} cold, ${runs} restarts: first request median ${ms(percentile(sorted, 0.5))}, min ${ms(sorted[0])}, max ${ms(sorted.at(-1))}; second request median ${ms(percentile(secondSorted, 0.5))}`);
187
+ }
188
+ /** `ui-kit measure-cpu [path] [count]` or `ui-kit measure-cpu --cold [runs] [path]`. */
189
+ export async function measureCpu(appDir, args) {
190
+ if (args[0] === '--cold') {
191
+ await cold(appDir, Number(args[1] ?? 5), args[2] ?? '/');
192
+ }
193
+ else {
194
+ await warm(args[0] ?? '/', Number(args[1] ?? 20));
195
+ }
196
+ }
@@ -0,0 +1,5 @@
1
+ import { type CspHosts } from '../worker/security.ts';
2
+ export declare function prerender({ appDir, cspHosts, }: {
3
+ appDir: string;
4
+ cspHosts?: CspHosts;
5
+ }): Promise<void>;
@@ -0,0 +1,109 @@
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 { access, readFile, rm, writeFile } from 'node:fs/promises';
10
+ import { resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { loadRoutes } from './app-modules.js';
13
+ import { prerenderedPathsOf } from '../logic/route-table.js';
14
+ import { BASE_HEADERS, contentSecurityPolicy, IMMUTABLE_ASSET_HEADERS, prerenderedFile, SEO_FILE_HEADERS, scriptHashes, } from '../worker/security.js';
15
+ async function readManifest(clientDir) {
16
+ return JSON.parse(await readFile(resolve(clientDir, '.vite/manifest.json'), 'utf8'));
17
+ }
18
+ /**
19
+ * A manifest key that survives a rebuild: source modules keep their key;
20
+ * shared chunks (`_components-<hash>.js`) lose the hash, which differs
21
+ * between the two builds whenever the chunk's contents do.
22
+ */
23
+ function stableKey(key) {
24
+ return key.startsWith('_') ? key.replace(/-[\w-]{8}(\.\w+)$/, '$1') : key;
25
+ }
26
+ /** Prerender-build asset path → deployed asset path, by source module (or shared chunk name). */
27
+ function assetMap(from, to) {
28
+ const map = new Map();
29
+ const targets = new Map(Object.entries(to).map(([key, entry]) => [stableKey(key), entry]));
30
+ for (const [key, entry] of Object.entries(from)) {
31
+ const target = targets.get(stableKey(key));
32
+ if (!target || typeof entry !== 'object')
33
+ continue;
34
+ if (entry.file && target.file)
35
+ map.set(entry.file, target.file);
36
+ (entry.css ?? []).forEach((css, i) => {
37
+ const targetCss = target.css?.[i];
38
+ if (targetCss)
39
+ map.set(css, targetCss);
40
+ });
41
+ }
42
+ return map;
43
+ }
44
+ /** Every `/assets/…` URL the page names must exist in the deployed build. */
45
+ async function checkAssets(CLIENT_DIR, path, html) {
46
+ for (const [, asset] of html.matchAll(/(\/assets\/[\w.-]+\.(?:js|css))/g)) {
47
+ try {
48
+ await access(resolve(CLIENT_DIR, `.${asset}`));
49
+ }
50
+ catch {
51
+ throw new Error(`prerender ${path}: ${asset} is not in dist/client`);
52
+ }
53
+ }
54
+ }
55
+ function isWorkerModule(value) {
56
+ const fetch = value?.default
57
+ ?.fetch;
58
+ return typeof fetch === 'function';
59
+ }
60
+ export async function prerender({ appDir, cspHosts, }) {
61
+ const CLIENT_DIR = resolve(appDir, 'dist/client');
62
+ const PRERENDER_DIR = resolve(appDir, 'dist/prerender');
63
+ const SERVER_ENTRY = resolve(PRERENDER_DIR, 'server/server.js');
64
+ const routes = await loadRoutes(appDir);
65
+ const loaded = await import(__rewriteRelativeImportExtension(pathToFileURL(SERVER_ENTRY).href, true));
66
+ if (!isWorkerModule(loaded)) {
67
+ throw new Error(`${SERVER_ENTRY} has no default { fetch } export`);
68
+ }
69
+ const worker = loaded.default;
70
+ const pending = [];
71
+ const ctx = {
72
+ waitUntil: (promise) => pending.push(promise),
73
+ };
74
+ const renames = assetMap(await readManifest(resolve(PRERENDER_DIR, 'client')), await readManifest(CLIENT_DIR));
75
+ const headerBlock = (path, headers) => [path, ...Object.entries(headers).map(([k, v]) => ` ${k}: ${v}`)].join('\n');
76
+ const headerBlocks = [
77
+ headerBlock('/*', BASE_HEADERS),
78
+ // Vite's hashed output only: a new build gets new names.
79
+ headerBlock('/assets/*', IMMUTABLE_ASSET_HEADERS),
80
+ // Written by `ui-kit seo-files` (the next build step).
81
+ headerBlock('/sitemap.xml', SEO_FILE_HEADERS),
82
+ headerBlock('/robots.txt', SEO_FILE_HEADERS),
83
+ ];
84
+ for (const path of prerenderedPathsOf(routes)) {
85
+ const response = await worker.fetch(new Request(`https://prerender.invalid${path}`, {
86
+ headers: { accept: 'text/html' },
87
+ }), {}, ctx);
88
+ if (response.status !== 200) {
89
+ throw new Error(`prerender ${path}: status ${response.status}`);
90
+ }
91
+ let html = await response.text();
92
+ for (const [from, to] of renames)
93
+ html = html.replaceAll(`/${from}`, `/${to}`);
94
+ await checkAssets(CLIENT_DIR, path, html);
95
+ const csp = contentSecurityPolicy({
96
+ _tag: 'Hashes',
97
+ scriptHashes: await scriptHashes(html),
98
+ }, cspHosts);
99
+ const file = resolve(CLIENT_DIR, prerenderedFile(path));
100
+ await writeFile(file, html, 'utf8');
101
+ headerBlocks.push(`${path}\n Content-Security-Policy: ${csp}`);
102
+ console.log(`prerendered ${path} -> ${file}`);
103
+ }
104
+ await Promise.all(pending);
105
+ await writeFile(resolve(CLIENT_DIR, '_headers'), headerBlocks.join('\n') + '\n', 'utf8');
106
+ // The manifest is build metadata, not a public asset.
107
+ await rm(resolve(CLIENT_DIR, '.vite'), { recursive: true, force: true });
108
+ console.log(`wrote ${resolve(CLIENT_DIR, '_headers')}`);
109
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `ui-kit preview [--port N] [--inspector-port M]`: the built app on local
3
+ * workerd (`wrangler dev`) with every declared binding (D1, R2, Durable
4
+ * Objects, rate limits), from the config the kit writes from the resource
5
+ * declaration. Applies pending D1 migrations first. Build first.
6
+ */
7
+ export declare function preview(appDir: string, args: readonly string[]): Promise<number>;
@@ -0,0 +1,41 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { relative } from 'node:path';
3
+ import { loadResources } from './app-modules.js';
4
+ import { LOCAL_STATE_DIR, migrateLocalD1, wranglerBin, writeLocalConfig, } from '../vite/local-config.js';
5
+ /**
6
+ * `ui-kit preview [--port N] [--inspector-port M]`: the built app on local
7
+ * workerd (`wrangler dev`) with every declared binding (D1, R2, Durable
8
+ * Objects, rate limits), from the config the kit writes from the resource
9
+ * declaration. Applies pending D1 migrations first. Build first.
10
+ */
11
+ export async function preview(appDir, args) {
12
+ const option = (name, fallback) => {
13
+ const at = args.indexOf(name);
14
+ return at === -1 ? fallback : (args[at + 1] ?? fallback);
15
+ };
16
+ const port = option('--port', '5401');
17
+ const inspector = option('--inspector-port', String(Number(port) + 1));
18
+ const local = writeLocalConfig({
19
+ appDir,
20
+ resources: await loadResources(appDir),
21
+ });
22
+ await migrateLocalD1(local);
23
+ const child = spawn(wranglerBin(appDir), [
24
+ 'dev',
25
+ '-c',
26
+ relative(appDir, local.wranglerPath),
27
+ '--persist-to',
28
+ LOCAL_STATE_DIR,
29
+ '--ip',
30
+ '127.0.0.1',
31
+ '--port',
32
+ port,
33
+ '--inspector-port',
34
+ inspector,
35
+ ], {
36
+ cwd: appDir,
37
+ stdio: 'inherit',
38
+ env: { ...process.env, WRANGLER_SEND_METRICS: 'false' },
39
+ });
40
+ return new Promise((done) => child.on('exit', (code) => done(code ?? 1)));
41
+ }
@@ -0,0 +1,27 @@
1
+ import type { SiteHead } from '../logic/head.ts';
2
+ import type { RouteTable } from '../logic/route-table.ts';
3
+ import { type SitemapProviders } from '../logic/seo.ts';
4
+ /**
5
+ * `sitemap.xml` and `robots.txt` from the route table (`ui-kit seo-files`
6
+ * writes them into the build; the dev server answers them the same way):
7
+ *
8
+ * - `sitemap.xml`: every public, indexable route (no `auth: "required"`,
9
+ * no `robots: "noindex"` head), static paths plus param routes through
10
+ * the app's `sitemap-sources.ts`; absolute URLs on the site origin.
11
+ * - `robots.txt`: allows all but `/_server/` and the auth-only pages, and
12
+ * names the sitemap.
13
+ */
14
+ export declare function seoFiles<T extends RouteTable>({ routes, siteHead, sitemapSources, }: {
15
+ routes: T;
16
+ siteHead: SiteHead;
17
+ sitemapSources: SitemapProviders<T>;
18
+ }): Promise<{
19
+ readonly sitemap: string;
20
+ readonly robots: string;
21
+ readonly skipped: readonly string[];
22
+ }>;
23
+ /** The files `seoFiles` writes and the dev server answers, with their content types. */
24
+ export declare const SEO_FILES: Readonly<Record<string, {
25
+ readonly key: 'sitemap' | 'robots';
26
+ readonly type: string;
27
+ }>>;
@@ -0,0 +1,24 @@
1
+ import { robotsTxt, sitemapPlan, sitemapXml, } from '../logic/seo.js';
2
+ /**
3
+ * `sitemap.xml` and `robots.txt` from the route table (`ui-kit seo-files`
4
+ * writes them into the build; the dev server answers them the same way):
5
+ *
6
+ * - `sitemap.xml`: every public, indexable route (no `auth: "required"`,
7
+ * no `robots: "noindex"` head), static paths plus param routes through
8
+ * the app's `sitemap-sources.ts`; absolute URLs on the site origin.
9
+ * - `robots.txt`: allows all but `/_server/` and the auth-only pages, and
10
+ * names the sitemap.
11
+ */
12
+ export async function seoFiles({ routes, siteHead, sitemapSources, }) {
13
+ const plan = await sitemapPlan(routes, siteHead, sitemapSources);
14
+ return {
15
+ sitemap: sitemapXml(plan.urls),
16
+ robots: robotsTxt(routes, siteHead),
17
+ skipped: plan.skipped,
18
+ };
19
+ }
20
+ /** The files `seoFiles` writes and the dev server answers, with their content types. */
21
+ export const SEO_FILES = {
22
+ '/sitemap.xml': { key: 'sitemap', type: 'application/xml; charset=utf-8' },
23
+ '/robots.txt': { key: 'robots', type: 'text/plain; charset=utf-8' },
24
+ };
@@ -0,0 +1,45 @@
1
+ import type { AnyIslandTable } from './index.ts';
2
+ /**
3
+ * The document side of a client navigation (`nav-client.ts`): which inline
4
+ * scripts the fetched page's CSP allows, the managed head tags it replaces,
5
+ * its stylesheets and island modules, scrolling, focus and the screen
6
+ * reader announcement. DOM only; no Solid.
7
+ */
8
+ /** Head tags that belong to a page (replaced on every swap). */
9
+ export declare const MANAGED_HEAD: string;
10
+ export declare const isExecutable: (script: HTMLScriptElement) => boolean;
11
+ /** The nonce this document's scripts run with (`""` on a page served without CSP, e.g. `vite dev`). */
12
+ export declare function documentNonce(): string;
13
+ /** The island client entry a document loads (a new deploy changes it). */
14
+ export declare function entryOf(doc: Document): string | null;
15
+ export declare function sha256Base64(text: string): Promise<string>;
16
+ /**
17
+ * The fetched page's inline scripts its response's CSP allows. `undefined`
18
+ * when the navigation must be a full load instead (this document enforces a
19
+ * nonce CSP but the response has none, or the response's script CSP has no
20
+ * nonce: a hash-CSP page). A document and response both without CSP (`vite
21
+ * dev`) allow every inline script, as a direct load would.
22
+ */
23
+ export declare function scriptsAllowedBy(csp: string | null, next: Document, documentHasNonce: boolean): Promise<Set<HTMLScriptElement> | undefined>;
24
+ /** What the island client entry hands over (kit-internal). */
25
+ export interface ViewTransitionLike {
26
+ readonly updateCallbackDone: Promise<void>;
27
+ readonly finished: Promise<void>;
28
+ }
29
+ export declare function viewTransitionsWanted(): boolean;
30
+ export declare const round: (ms: number) => number;
31
+ /** Resolves when `p` settles or after `ms`, whichever is first. */
32
+ export declare function settled(p: Promise<unknown>, ms: number): Promise<void>;
33
+ /** Adds the next page's stylesheets this document lacks and waits for them. */
34
+ export declare function loadStyles(next: Document): Promise<unknown>;
35
+ /** Loads the next page's hydrated island modules (the pass then renders without waiting on the network). */
36
+ export declare function preloadIslands(next: Document, table: AnyIslandTable): Promise<unknown>;
37
+ /** Replaces the page-owned head tags and adds the next page's modulepreloads. */
38
+ export declare function swapHead(next: Document): void;
39
+ /** Re-runs the next page's allowed inline scripts (Solid's bootstrap is a no-op the second time; serialization fills `_$HY.r`). */
40
+ export declare function runScripts(next: Document, allowed: ReadonlySet<HTMLScriptElement>, nonce: string): void;
41
+ export declare function scrollAfterSwap(url: URL, restore: number | undefined): void;
42
+ /** A polite live region that moves with every swap (a region created with its text is often not read). */
43
+ export declare function createAnnouncer(): HTMLElement;
44
+ /** Focus the new page's first heading (or `main`) without scrolling, and announce its title. */
45
+ export declare function focusAndAnnounce(announcer: HTMLElement): void;