@kayjs/kay 1.106.0 → 1.107.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 (222) hide show
  1. package/README.md +2 -2
  2. package/dist/eslint.js +428 -176
  3. package/editors/zed/extension.toml +2 -2
  4. package/llms/action-protection.md +1 -1
  5. package/llms/actions-refused-fields.md +22 -0
  6. package/llms/actions.md +2 -22
  7. package/llms/browser-only.md +1 -1
  8. package/llms/compiler-api.md +1 -1
  9. package/llms/components.md +1 -1
  10. package/llms/deprecated-lints.md +2 -3
  11. package/llms/island-and-form-lints.md +1 -0
  12. package/llms/islands.md +10 -1
  13. package/llms/project-new-and-add.md +1 -1
  14. package/llms/project.md +2 -2
  15. package/llms/schemas.md +6 -4
  16. package/llms/upgrading.md +19 -1
  17. package/llms/whats-new.md +14 -1
  18. package/package.json +15 -6
  19. package/src/build/client.ts +20 -24
  20. package/src/build/entry-files.ts +19 -0
  21. package/src/build/lazy-components.ts +130 -0
  22. package/src/build/lazy-manifest.ts +56 -0
  23. package/src/build/lazy-stubs.ts +31 -0
  24. package/src/build/plugin.ts +3 -1
  25. package/src/build/runtime-chunk.ts +1 -1
  26. package/src/build/transform.ts +17 -7
  27. package/src/build/variants.ts +7 -4
  28. package/src/check/action-options.ts +56 -0
  29. package/src/check/schema-json.ts +226 -0
  30. package/src/check/shadow-types.ts +11 -9
  31. package/src/compiler/codegen.ts +7 -17
  32. package/src/compiler/deprecated-lints-1-105.ts +41 -0
  33. package/src/compiler/deprecated-lints-1-106.ts +1 -1
  34. package/src/compiler/deprecated-lints-1-107.ts +14 -0
  35. package/src/compiler/deprecated-lints.ts +7 -55
  36. package/src/compiler/import-edits.ts +15 -0
  37. package/src/compiler/index.ts +8 -3
  38. package/src/compiler/island-declaration.ts +15 -0
  39. package/src/compiler/kay-exports.ts +1 -0
  40. package/src/compiler/lazy-imports.ts +357 -0
  41. package/src/compiler/parser.ts +2 -2
  42. package/src/compiler/route-lints.ts +2 -0
  43. package/src/compiler/schema-lints.ts +13 -0
  44. package/src/compiler/script-server.ts +6 -3
  45. package/src/content/validate.ts +1 -1
  46. package/src/new.ts +6 -2
  47. package/src/runtime/action.ts +47 -4
  48. package/src/runtime/client.ts +10 -0
  49. package/src/runtime/dom-lazy.ts +276 -0
  50. package/src/runtime/field-errors.ts +58 -0
  51. package/src/runtime/field-refusal.ts +179 -0
  52. package/src/runtime/form.ts +3 -2
  53. package/src/runtime/html.ts +6 -1
  54. package/src/runtime/index.ts +2 -0
  55. package/src/runtime/island.server.ts +36 -2
  56. package/src/runtime/schema-record.ts +2 -1
  57. package/src/runtime/schema.client.ts +104 -14
  58. package/src/runtime/schema.ts +9 -2
  59. package/src/runtime/standard-schema.ts +32 -0
  60. package/src/runtime/validate-run.client.ts +179 -0
  61. package/src/runtime/validate.client.ts +11 -0
  62. package/src/runtime/validate.ts +4 -137
  63. package/src/server/actions.ts +48 -43
  64. package/src/server/answer.ts +102 -0
  65. package/src/server/api-input.ts +166 -0
  66. package/src/server/api.ts +12 -44
  67. package/src/server/app-stages.ts +15 -8
  68. package/src/server/app.ts +5 -2
  69. package/src/server/client.ts +2 -0
  70. package/src/server/dev.ts +7 -9
  71. package/src/server/file-limit.ts +7 -1
  72. package/src/server/forms.ts +1 -1
  73. package/src/server/host-allowlist.ts +7 -7
  74. package/src/server/index.ts +2 -0
  75. package/src/server/kay-routes.ts +221 -0
  76. package/src/server/kay-server.ts +228 -0
  77. package/src/server/kept-exports.ts +1 -0
  78. package/src/server/library.ts +0 -2
  79. package/src/server/mcp.ts +1 -1
  80. package/src/server/openapi.ts +12 -3
  81. package/src/server/phases.ts +249 -0
  82. package/src/server/protection.ts +6 -6
  83. package/src/server/proxy-key.ts +8 -8
  84. package/src/server/query.ts +4 -25
  85. package/src/server/receive.ts +43 -0
  86. package/src/server/render-document.ts +13 -3
  87. package/src/server/request-context.ts +137 -0
  88. package/src/server/schema-check.ts +1 -1
  89. package/src/server/socket.ts +19 -47
  90. package/src/server/stream.ts +1 -1
  91. package/src/server/validate.ts +346 -0
  92. package/src/test/mount.ts +6 -2
  93. package/types/build/client.d.ts +3 -2
  94. package/types/build/client.d.ts.map +1 -1
  95. package/types/build/entry-files.d.ts +4 -0
  96. package/types/build/entry-files.d.ts.map +1 -0
  97. package/types/build/lazy-components.d.ts +6 -0
  98. package/types/build/lazy-components.d.ts.map +1 -0
  99. package/types/build/lazy-manifest.d.ts +19 -0
  100. package/types/build/lazy-manifest.d.ts.map +1 -0
  101. package/types/build/lazy-stubs.d.ts +5 -0
  102. package/types/build/lazy-stubs.d.ts.map +1 -0
  103. package/types/build/plugin.d.ts +1 -0
  104. package/types/build/plugin.d.ts.map +1 -1
  105. package/types/build/transform.d.ts +3 -1
  106. package/types/build/transform.d.ts.map +1 -1
  107. package/types/build/variants.d.ts.map +1 -1
  108. package/types/check/action-options.d.ts +3 -0
  109. package/types/check/action-options.d.ts.map +1 -0
  110. package/types/check/schema-json.d.ts +3 -0
  111. package/types/check/schema-json.d.ts.map +1 -0
  112. package/types/check/shadow-types.d.ts.map +1 -1
  113. package/types/compiler/codegen.d.ts +2 -0
  114. package/types/compiler/codegen.d.ts.map +1 -1
  115. package/types/compiler/deprecated-lints-1-105.d.ts +39 -0
  116. package/types/compiler/deprecated-lints-1-105.d.ts.map +1 -0
  117. package/types/compiler/deprecated-lints-1-106.d.ts +1 -1
  118. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  119. package/types/compiler/deprecated-lints-1-107.d.ts +12 -0
  120. package/types/compiler/deprecated-lints-1-107.d.ts.map +1 -0
  121. package/types/compiler/deprecated-lints.d.ts +36 -44
  122. package/types/compiler/deprecated-lints.d.ts.map +1 -1
  123. package/types/compiler/import-edits.d.ts +1 -0
  124. package/types/compiler/import-edits.d.ts.map +1 -1
  125. package/types/compiler/index.d.ts +2 -0
  126. package/types/compiler/index.d.ts.map +1 -1
  127. package/types/compiler/island-declaration.d.ts +5 -0
  128. package/types/compiler/island-declaration.d.ts.map +1 -1
  129. package/types/compiler/kay-exports.d.ts.map +1 -1
  130. package/types/compiler/lazy-imports.d.ts +33 -0
  131. package/types/compiler/lazy-imports.d.ts.map +1 -0
  132. package/types/compiler/lints.d.ts +44 -44
  133. package/types/compiler/route-lints.d.ts +8 -0
  134. package/types/compiler/route-lints.d.ts.map +1 -1
  135. package/types/compiler/schema-lints.d.ts +11 -0
  136. package/types/compiler/schema-lints.d.ts.map +1 -0
  137. package/types/compiler/script-server.d.ts.map +1 -1
  138. package/types/new.d.ts +1 -0
  139. package/types/new.d.ts.map +1 -1
  140. package/types/runtime/action.d.ts +26 -1
  141. package/types/runtime/action.d.ts.map +1 -1
  142. package/types/runtime/client.d.ts.map +1 -1
  143. package/types/runtime/dom-lazy.d.ts +6 -0
  144. package/types/runtime/dom-lazy.d.ts.map +1 -0
  145. package/types/runtime/field-errors.d.ts +4 -0
  146. package/types/runtime/field-errors.d.ts.map +1 -0
  147. package/types/runtime/field-refusal.d.ts +37 -0
  148. package/types/runtime/field-refusal.d.ts.map +1 -0
  149. package/types/runtime/form.d.ts +1 -1
  150. package/types/runtime/form.d.ts.map +1 -1
  151. package/types/runtime/html.d.ts.map +1 -1
  152. package/types/runtime/index.d.ts +2 -0
  153. package/types/runtime/index.d.ts.map +1 -1
  154. package/types/runtime/island.server.d.ts +2 -0
  155. package/types/runtime/island.server.d.ts.map +1 -1
  156. package/types/runtime/schema-record.d.ts.map +1 -1
  157. package/types/runtime/schema.client.d.ts.map +1 -1
  158. package/types/runtime/schema.d.ts +6 -1
  159. package/types/runtime/schema.d.ts.map +1 -1
  160. package/types/runtime/standard-schema.d.ts +37 -0
  161. package/types/runtime/standard-schema.d.ts.map +1 -0
  162. package/types/runtime/validate-run.client.d.ts +4 -0
  163. package/types/runtime/validate-run.client.d.ts.map +1 -0
  164. package/types/runtime/validate.client.d.ts +4 -0
  165. package/types/runtime/validate.client.d.ts.map +1 -0
  166. package/types/runtime/validate.d.ts +1 -21
  167. package/types/runtime/validate.d.ts.map +1 -1
  168. package/types/server/actions.d.ts.map +1 -1
  169. package/types/server/answer.d.ts +6 -0
  170. package/types/server/answer.d.ts.map +1 -0
  171. package/types/server/api-input.d.ts +19 -0
  172. package/types/server/api-input.d.ts.map +1 -0
  173. package/types/server/api.d.ts.map +1 -1
  174. package/types/server/app-stages.d.ts +4 -1
  175. package/types/server/app-stages.d.ts.map +1 -1
  176. package/types/server/app.d.ts +2 -0
  177. package/types/server/app.d.ts.map +1 -1
  178. package/types/server/client.d.ts +1 -0
  179. package/types/server/client.d.ts.map +1 -1
  180. package/types/server/dev.d.ts +1 -1
  181. package/types/server/dev.d.ts.map +1 -1
  182. package/types/server/file-limit.d.ts.map +1 -1
  183. package/types/server/host-allowlist.d.ts +3 -3
  184. package/types/server/host-allowlist.d.ts.map +1 -1
  185. package/types/server/index.d.ts +2 -0
  186. package/types/server/index.d.ts.map +1 -1
  187. package/types/server/kay-routes.d.ts +47 -0
  188. package/types/server/kay-routes.d.ts.map +1 -0
  189. package/types/server/kay-server.d.ts +25 -0
  190. package/types/server/kay-server.d.ts.map +1 -0
  191. package/types/server/kept-exports.d.ts.map +1 -1
  192. package/types/server/library.d.ts +0 -1
  193. package/types/server/library.d.ts.map +1 -1
  194. package/types/server/openapi.d.ts.map +1 -1
  195. package/types/server/phases.d.ts +36 -0
  196. package/types/server/phases.d.ts.map +1 -0
  197. package/types/server/protection.d.ts +3 -2
  198. package/types/server/protection.d.ts.map +1 -1
  199. package/types/server/proxy-key.d.ts +3 -3
  200. package/types/server/proxy-key.d.ts.map +1 -1
  201. package/types/server/query.d.ts.map +1 -1
  202. package/types/server/receive.d.ts +9 -0
  203. package/types/server/receive.d.ts.map +1 -0
  204. package/types/server/render-document.d.ts.map +1 -1
  205. package/types/server/request-context.d.ts +29 -0
  206. package/types/server/request-context.d.ts.map +1 -0
  207. package/types/server/schema-check.d.ts +1 -0
  208. package/types/server/schema-check.d.ts.map +1 -1
  209. package/types/server/socket.d.ts +3 -5
  210. package/types/server/socket.d.ts.map +1 -1
  211. package/types/server/validate.d.ts +26 -0
  212. package/types/server/validate.d.ts.map +1 -0
  213. package/types/test/mount.d.ts.map +1 -1
  214. package/src/check/schema-type.ts +0 -9
  215. package/src/compiler/deprecated-script-fence.ts +0 -26
  216. package/src/server/field-errors.ts +0 -136
  217. package/types/check/schema-type.d.ts +0 -3
  218. package/types/check/schema-type.d.ts.map +0 -1
  219. package/types/compiler/deprecated-script-fence.d.ts +0 -3
  220. package/types/compiler/deprecated-script-fence.d.ts.map +0 -1
  221. package/types/server/field-errors.d.ts +0 -6
  222. package/types/server/field-errors.d.ts.map +0 -1
@@ -1,14 +1,14 @@
1
1
  id = "kay"
2
2
  name = "Kay"
3
3
  description = "Highlighting and the kay language server for .kay components"
4
- version = "1.106.0"
4
+ version = "1.107.0"
5
5
  schema_version = 1
6
6
  authors = [ "Kaynooo" ]
7
7
  repository = "https://github.com/Kayno0o/kayjs"
8
8
 
9
9
  [grammars.kay]
10
10
  repository = "https://github.com/Kayno0o/kayjs"
11
- rev = "v1.106.0"
11
+ rev = "v1.107.0"
12
12
  path = "editors/tree-sitter-kay"
13
13
 
14
14
  [language_servers.kay]
@@ -88,7 +88,7 @@ See [Rate limits](rate-limits.md#limit-attempts-in-a-guard-or-an-api-route).
88
88
  - `minTime` is given `early` for a post sent too soon or `expired` for a stamp missing, forged or past `ttl`, as a page from before a restart sends.
89
89
  - `proofOfWork` is given `missing`, `expired` or `wrong` as below.
90
90
  - `maxSize` is given the most bytes a post may send, as a number whatever size `maxSize` was written as.
91
- - Each is a string or a function; `serverError` is given the error and the action's `ctx` (see [Refused posts](actions.md#refused-posts)). A function runs in the request's locale, so it may word the refusal with `t()`; `serverError` may be async.
91
+ - Each is a string or a function; `serverError` is given the error and the action's `ctx` (see [Refused posts](actions-refused-fields.md#refused-posts)). A function runs in the request's locale, so it may word the refusal with `t()`; `serverError` may be async.
92
92
 
93
93
  #### Proof of work
94
94
 
@@ -26,6 +26,28 @@
26
26
  - A field with a `bind:`, a spread, `disabled` or `multiple` keeps what the template gives, and one the page renders through another component is not the form's own.
27
27
  - On a page posting no refused form, every field renders as written.
28
28
 
29
+ ### Refused posts
30
+
31
+ - `ctx.deny(status, { message, errors, data })` is the one refusal of a guard, a page, an action and an endpoint, `refuse(status, { ... })` throws it from anywhere; `return` it so `form.failed()` types `data`. `ctx.fail` is its old spelling until 1.108 (`unreturned-fail`).
32
+ - A post the schema refuses, or whose handler denies with `ctx.deny(status, { data })`, is answered with the page it came from, rendered with the failure's status, rather than with a redirect.
33
+ - There `add.form.failed()` returns `{ status, message, values, errors, data }`, typed from the action, or `undefined`.
34
+ - `values` is what the form posted (fields named like a password left out).
35
+ - `errors` is a message per refused field, the schema's `error` option when set.
36
+ - `data` is what `ctx.deny` received.
37
+ - `return ctx.deny(409, { errors: { email: 'Already taken' } })` puts a message on a field, typed from the schema's keys, with `''` for the form's own, so `error email`, `aria-invalid`, `add.form.error('email')`, the value re-fill and an island's `ActionError.errors` (and a kayjs-ui `FormField` named `email`) follow it with and without JavaScript.
38
+ - A rate limit's refusal sits under `errors['']`, read by `add.form.error()`, and a text `data` is that message: `return ctx.deny(502, { data: 'Not sent; try again later' })`.
39
+ - The page renders as a visit of it would, through the app's plugins and the page's guards, and nothing the visitor typed is lost however long it is.
40
+ - Reloading it posts again, as after any form a server answers in place.
41
+ - The page is the one the post was sent from, as `ctx.params` reads it below, the home page when it names none or another site.
42
+ - Without the page swap the browser shows the action's URL, so the page carries a `base` naming its own URL, and its relative links lead where they did.
43
+ - Each form on it posting to an action names that page in a `kay_back` query parameter, so a post refused again renders the same page, however many times in a row, and one that goes through goes back to it.
44
+ - A handler that throws, a mail server down say, is logged as any server error, `onError` included, and answered as a refusal with status 500.
45
+ - A plain form post then renders its page with the message under the form and what was typed kept, read by `add.form.error()`, and a call answers `{ ok: false }` with it in `errors['']`.
46
+ - The message is `Something went wrong on our side; try again later` unless the site words it as `kay.action.serverError` ([Locales](locales-texts.md)) or the action words its own, `action(schema, handler, { messages: { serverError: 'Not sent; write to hello@example.com instead' } })`, so a handler needs no `try`/`catch` of its own to tell the visitor.
47
+ - `serverError` may be a function given the error and `ctx`, sync or async, to word it from what is loaded per request or the page's `ctx.locale`: `serverError: async () => 'Write to ' + (await settings.one()).email`. Its text is answered with the same status 500; one that throws, or answers a blank text, leaves kay's message (a throw logged beside the handler's error), and a redirect or denial thrown from it is no answer either.
48
+ - An action past its `timeout` (`serve.timeout` or the action's own) answers 504 the same way, worded `kay.action.timeout` (`This took too long; try again later`) and reported as a server error.
49
+ - A redirect or a guard's denial thrown is no error.
50
+
29
51
  ### Reading the outcome
30
52
 
31
53
  - `add.form.failed()`, `add.data()`, `add.status()` and `add.form.error('title')` read the outcome from any template, layout, component or island, and from the server fence. What a form shows is read from `add.form` (`failed()`, `error(field)`, `validate(form, field)`), apart from the call state on `add` itself (`pending()`, `status()`, `data()`, `progress()`, `settled()`, `track()`); `failed()`, `error()` and `validate()` on `add` work until 1.108 and `deprecated-action-readers` rewrites them.
package/llms/actions.md CHANGED
@@ -158,6 +158,8 @@ form(action={add})
158
158
  ```
159
159
 
160
160
  - `actions: { protect, maxSize, messages }` in `kay.config.ts` is the default of every action, `protect` key by key: an action's own `rateLimit` replaces the app's, and `protect: false` takes none of the app's checks (the app's `maxSize` and `messages` still apply). `actions: { beforeRun, onSuccess, onError }` hook every run, before the action's own hooks of the same name: [hooks](hooks.md#the-apps-own-hooks).
161
+ - Since 1.107 the options come first and hold the input: `action({ input: { title: s.string() }, maxSize: '1mb', guards }, handler)`, as an API route's do; `input` is a record of fields or any schema, and `action({ guards }, handler)` has none. `action(schema, handler, options)` and `action(handler, options)` work until 2.0 (`deprecated-action-options`).
162
+ - Input is read by `validate(schema, value, { source })`, the one path an action, an API route, a socket message, `defineEnv` and a collection share: a form is read as the numbers, booleans and lists it spells, and a call from an island (JSON) never is, so `'3'` for an int is refused there. An unknown key is refused in JSON; a form post drops the fields the schema does not name, as a browser sends controls the app does not own. A refusal is worded in the request's locale and carries the `kay.invalid.*` key it is worded under.
161
163
  - An action with no input leaves the schema out: `action(async (ctx) => { ... }, protection?)`, validated as an empty object, its handler getting the context alone, called as `signOut()`, `signOut(undefined, { refresh: false })` or `site.call(signOut)`, and posted by `form(action={signOut})`.
162
164
  - An action several pages and components share lives in an `_actions.kay` of a routes directory, a `--- server` fence alone, no closing `---` needed: it is served like a layout's actions, behind the guards of its directory and above, reading the params of every page below it, and `page = { guards: false }` opens it as a layout's.
163
165
  - A page or a component imports it by its path, `import { removeTissue } from '../routes/admin/_actions.kay'`, in the server fence of a page or an island alike; no route file is imported, and `kay build`, `kay check` and `kay routes` see it as they see a layout's actions.
@@ -226,28 +228,6 @@ form(action={add})
226
228
  - `label(field="name")` writes the label's `for` and the `id` of the one control of that field in the form, `<action>-<field>` (`save-name`), so `label(for="name")` and `input#name(field="name")` become two `field`. It is `form-misuse` when the form has no control of that field or several (a group of radios or boxes: write `for` and `id` yourself), when the label also writes `for`, or when the control writes its own `id`. Forms posting to one action, such as one per row, repeat the id: write `for` and `id` there.
227
229
  - `button(action={move.with({ id })})` outside a form posts that action: kay wraps it in a `form(action={...})` that has no box of its own (`display: contents`, set by a hashed `style` rule in the head, so a strict CSP holds), so a static page posts and an island calls it, with the `.with()` arguments; the button is then the only child of its form for `:first-child` and `first:` styles. In a `p` it is `invalid-nesting`. Inside a form it is `form-misuse`: the form's own button posts the form.
228
230
 
229
- ### Refused posts
230
-
231
- - `ctx.deny(status, { message, errors, data })` is the one refusal of a guard, a page, an action and an endpoint, `refuse(status, { ... })` throws it from anywhere; `return` it so `form.failed()` types `data`. `ctx.fail` is its old spelling until 1.108 (`unreturned-fail`).
232
- - A post the schema refuses, or whose handler denies with `ctx.deny(status, { data })`, is answered with the page it came from, rendered with the failure's status, rather than with a redirect.
233
- - There `add.form.failed()` returns `{ status, message, values, errors, data }`, typed from the action, or `undefined`.
234
- - `values` is what the form posted (fields named like a password left out).
235
- - `errors` is a message per refused field, the schema's `error` option when set.
236
- - `data` is what `ctx.deny` received.
237
- - `return ctx.deny(409, { errors: { email: 'Already taken' } })` puts a message on a field, typed from the schema's keys, with `''` for the form's own, so `error email`, `aria-invalid`, `add.form.error('email')`, the value re-fill and an island's `ActionError.errors` (and a kayjs-ui `FormField` named `email`) follow it with and without JavaScript.
238
- - A rate limit's refusal sits under `errors['']`, read by `add.form.error()`, and a text `data` is that message: `return ctx.deny(502, { data: 'Not sent; try again later' })`.
239
- - The page renders as a visit of it would, through the app's plugins and the page's guards, and nothing the visitor typed is lost however long it is.
240
- - Reloading it posts again, as after any form a server answers in place.
241
- - The page is the one the post was sent from, as `ctx.params` reads it below, the home page when it names none or another site.
242
- - Without the page swap the browser shows the action's URL, so the page carries a `base` naming its own URL, and its relative links lead where they did.
243
- - Each form on it posting to an action names that page in a `kay_back` query parameter, so a post refused again renders the same page, however many times in a row, and one that goes through goes back to it.
244
- - A handler that throws, a mail server down say, is logged as any server error, `onError` included, and answered as a refusal with status 500.
245
- - A plain form post then renders its page with the message under the form and what was typed kept, read by `add.form.error()`, and a call answers `{ ok: false }` with it in `errors['']`.
246
- - The message is `Something went wrong on our side; try again later` unless the site words it as `kay.action.serverError` ([Locales](locales-texts.md)) or the action words its own, `action(schema, handler, { messages: { serverError: 'Not sent; write to hello@example.com instead' } })`, so a handler needs no `try`/`catch` of its own to tell the visitor.
247
- - `serverError` may be a function given the error and `ctx`, sync or async, to word it from what is loaded per request or the page's `ctx.locale`: `serverError: async () => 'Write to ' + (await settings.one()).email`. Its text is answered with the same status 500; one that throws, or answers a blank text, leaves kay's message (a throw logged beside the handler's error), and a redirect or denial thrown from it is no answer either.
248
- - An action past its `timeout` (`serve.timeout` or the action's own) answers 504 the same way, worded `kay.action.timeout` (`This took too long; try again later`) and reported as a server error.
249
- - A redirect or a guard's denial thrown is no error.
250
-
251
231
  ### Params of the posting page
252
232
 
253
233
  - `ctx.params` holds the params of the page the action was posted from, matched against the route of the page exporting it, as its guards read them. In an action declared in a page, `kay check` types it from that page's route, a matcher's value as it gives it and an optional param `| undefined`, so `ctx.params.id` is a `number` under `[id=integer]` and a misspelled one is an error; a layout's or an `_actions.kay` action, and a guard, cover several routes and read `unknown`.
@@ -65,7 +65,7 @@ onMount(() => drawMap(center))
65
65
  - A read through `globalThis` is not seen, nor one in a chunk carrying a `process` polyfill of its own, which binds the name.
66
66
  - `kay dev` and `bun test` build the same way, so they refuse it too.
67
67
  - `kay check` reports the same refusal before any build, as `server-only-in-island` at each island's import of the module, one per island reaching it, or at the read in the island's own script: an island, or a module it reaches through relative imports, `.ts` modules with an angle-bracket cast too, that reads `process` or `Bun` as the module loads. A read inside a function is left to the build, as only the build knows whether the island calls it; `process.env.NODE_ENV` and a `typeof` guard pass.
68
- - In the browser kay's `s` builds inert stand-ins, so a module an island imports may build schemas as it loads and keep a schema beside its `Static` type, with no validator in the chunk. Reading a key of a schema at module scope, `Object.keys(SHAPE.properties)` say, throws as the island loads; validation stays on the server: [Schemas](schemas.md#schemas).
68
+ - In the browser kay's `s` builds the plain JSON Schema of each field, so a module an island imports may build schemas as it loads and keep a schema beside its `Static` type, and the island may call `validate(schema, value, { source })` from `kay` on it, the validator being a chunk the first call loads: [Schemas](schemas.md#schemas).
69
69
  - An island reaching a builtin a browser lacks, `bun:sqlite` or `async_hooks` through a database library say, is refused with the imports leading there, one line per island: `src/counter.kay -> src/links.ts -> src/db.ts -> bun:sqlite`, cut at the first package since the fix is never inside one. The message says an island cannot import a server module: keep the constants and types an island needs in a module importing no server code. `mountComponent` in `bun test` reports the same chain.
70
70
  - `kay check` reports it too, as `browser-builtin-import` at each of the island's imports leading there, with the same chain, once per distinct chain. It bundles the import for the browser as the build does, so a package's `browser` condition and field count, a type-only or unused import passes, and only the builtins the build refuses do: `async_hooks`, `worker_threads` and `bun:*`, not `node:path`, `events` or `node:crypto`. A package marked `sideEffects: false` is followed too, a `.kay` component the island renders is followed through its own imports and reported at the island's import of it, and an import that fails to bundle leaves the other imports' reports intact. One island gets one report per chain. Imports of `kay` and its entries are left out. In a project that never names `process` or `Bun` it follows the islands themselves, not the static components.
71
71
  - An island bundles all of a module it imports, so a helper beside a database the module opens as it loads brings the database along: move the helper to a module importing none of it.
@@ -20,6 +20,6 @@ for (const diagnostic of diagnostics)
20
20
 
21
21
  - `compileKay(source, filename, options?)` returns `{ tsx, map, island?, cause?, classes, diagnostics }`, `cause` being what makes the component an island: `{ kind, name, span, line, source? }`, `span` the offsets in the source and `source` the module of a `kay` value. `why` is the same cause as a sentence, deprecated for `cause`. A problem in the source is reported in `diagnostics`. `filename` is read for its base name and, with `root`, its island id: a `_layout.kay`, `_404.kay` or `_error.kay`, like a file with a `--- server` fence, is a route file the server renders, never an island.
22
22
  - `tsx` is the generated code: TSX for type checking by default, or with `output: 'html'` or `output: 'dom'` the server's or the browser's code that runs. `map` maps it back to the source, `island` is the component's island id when it renders as one, `classes` the `.class` shorthand names a CSS scanner cannot read off the template.
23
- - Options: `root` (island ids are paths relative to it), `includeServer: false` for a browser build, `params` and `paramTypes` typing `ctx.params`, `check: true` for the type-checking output's link, form field and island prop assertions plus the lints, with `lints` setting their levels, `inspect` for `data-kay-src`, and `hydratable`, `twinBuild`, `clientOnly`, `insideIsland` and `importedSignals` and `writtenProps`, which kay's own build sets.
23
+ - Options: `root` (island ids are paths relative to it), `includeServer: false` for a browser build, `params` and `paramTypes` typing `ctx.params`, `check: true` for the type-checking output's link, form field and island prop assertions plus the lints, with `lints` setting their levels, `inspect` for `data-kay-src`, and `hydratable`, `twinBuild`, `clientOnly`, `insideIsland`, `importedSignals`, `writtenProps` and `components`, which kay's own build sets.
24
24
  - A `Diagnostic` is `{ start, end, message, label?, related?, note?, help?, code?, severity?, fixes? }`, `start` and `end` offsets into `source`, `code` a lint's name, `severity` `'warning'` for a lint at the `warn` level.
25
25
  - `formatDiagnostic(source, filename, diagnostic, paint?)` prints it as `kay check` does, with the file, line and column, the source line and its `help`; `paint` is `(styles, text) => string` for colour, plain text without it.
@@ -134,7 +134,7 @@ ul
134
134
  | Fence | What it is | Allowed on |
135
135
  | --- | --- | --- |
136
136
  | `---` | The component script, run wherever the component renders | Every `.kay` file; written `--- <T>` for a generic component |
137
- | `--- script` | The same fence, for a script that follows a `--- server`, `--- module` or `--- style` fence, where a bare `---` would close that one; as a file's first fence it is the `deprecated-script-fence` lint | After another fence |
137
+ | `--- script` | The same fence, for a script that follows a `--- server`, `--- module` or `--- style` fence, where a bare `---` would close that one; as a file's first fence it is a `fence-invalid` error, write `---` | After another fence |
138
138
  | `--- server` | Code run on the server for each request, never sent to the browser | Pages, layouts and the other `_` route files; `fence-invalid` on a component |
139
139
  | `--- module` | Module-level code, run once per bundle, whose exports other files import | Every file; no props, and not on a browser-only component |
140
140
  | `--- style` | CSS scoped to the component | Every file |
@@ -12,10 +12,9 @@ The lints of the `deprecated` group, each the old form a minor replaced, reporte
12
12
 
13
13
  | Lint | Default | Group | Reports |
14
14
  | --- | --- | --- | --- |
15
- | `deprecated-schema-builders` | warn | deprecated | The PascalCase builders of `s` before 1.106, which kay's own lowercase builders replace, each taking the same field options (`optional`, `default`, `error`, `label`, `description`, `example`) and short names for the rest: `s.String` is `s.string` (`min`, `max`), `s.Integer` `s.int`, `s.Number` and `s.Numeric` `s.number`, `s.Boolean` and `s.BooleanString` `s.boolean`, `s.Array` `s.list`, `s.UnionEnum` and `s.UnionKeys` `s.enum`, and `s.Date`, `s.Literal`, `s.Union`, `s.Object`, `s.File`, `s.Files`, `s.Secret` and `s.Public` their lowercase names; `s.Optional(field)` is `optional: true` in the options of the field; an `s.Object({ ... })` that is the schema of an `action` or a `defineEnv` is the record of fields alone; and a file size written `'2m'` is `'2mb'`. The old names work until 2.0. Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. The fix renames the builder and the options that changed; an `s.Optional` around anything but one of these builders, such as a helper of `kay/content`, is left as it is. A lowercase `s.object` refuses a key its shape lacks where kay reads the schema itself (collection frontmatter, `defineEnv`), where `s.Object` let it by: write `{ extra: 'strip' }` where the old way is wanted. A query, the headers and the cookies of a request carry keys no schema names, so their unknown keys are dropped whatever the schema says. |
15
+ | `deprecated-action-options` | warn | deprecated | The arguments of `action` before 1.107, `action(schema, handler, options)` and `action(handler, options)`: the options come first, with the input in them, as an API route's do, `action({ input: schema, ...options }, handler)` and `action(options, handler)`. `input` is a plain record of fields or any schema. The old forms work until 2.0. Found on the `action` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files; the fix moves the arguments and keeps their text. |
16
+ | `deprecated-schema-builders` | warn | deprecated | The PascalCase builders of `s` before 1.106, which kay's own lowercase builders replace, each taking the same field options (`optional`, `default`, `error`, `label`, `description`, `example`) and short names for the rest: `s.String` is `s.string` (`min`, `max`), `s.Integer` `s.int`, `s.Number` and `s.Numeric` `s.number`, `s.Boolean` and `s.BooleanString` `s.boolean`, `s.Array` `s.list`, `s.UnionEnum` and `s.UnionKeys` `s.enum`, and `s.Date`, `s.Literal`, `s.Union`, `s.Object`, `s.File`, `s.Files`, `s.Secret` and `s.Public` their lowercase names; `s.Optional(field)` is `optional: true` in the options of the field; an `s.Object({ ... })` that is the schema of an `action` or a `defineEnv` is the record of fields alone; and a file size written `'2m'` is `'2mb'`. The old names work until 2.0. Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. The fix renames the builder and the options that changed; an `s.Optional` around anything but one of these builders, such as a helper of `kay/content`, is left as it is. A lowercase `s.object` refuses a key its shape lacks where kay reads the schema itself (an action's input, an API route's body, `defineEnv`, collection frontmatter), where `s.Object` let it by: write `{ extra: 'strip' }` where the old way is wanted. A query, the headers and the cookies of a request carry keys no schema names, so their unknown keys are dropped whatever the schema says. |
16
17
  | `deprecated-uncaught-await` | warn | deprecated | A `// kay-allow uncaught-await` comment or a `lints: { 'uncaught-await': ... }` entry of kay.config.ts, since 1.105: the `uncaught-await` lint is gone, as an `await` with no `catch` renders the `catch` of the `try` around it, else an alert (`data-kay-await-failed`, worded by the `kay.await.failed` message) in its place, the rejection reported either way. The fix removes the comment, or the name from a list of lints, or the config entry. |
17
- | `deprecated-script-fence` | warn | deprecated | `--- script` as the first fence of a file, since 1.102: `---`, the same fence, so a file has one spelling of it. `--- script` stays for a script that follows a `--- server`, `--- module` or `--- style` fence, where a bare `---` would close that fence. The old form works until 1.105. The fix drops the word, keeping the type parameters of `--- script <T>`. |
18
- | `deprecated-schema-type` | warn | deprecated | `TSchema` imported from `kay/library`, `Schema` since 1.103: kay's own name for what `s` builds and every schema option takes, so a signature of the app does not name TypeBox, whose type follows the Elysia kay is built on. The old name works until 1.106. Found on an import from `kay/library` in the TypeScript files and `.kay` files of the project. The fix renames the import and each use of it; a file that already has a `Schema` of its own is reported with no fix, and one that imports it aliased with only the import renamed. |
19
18
  | `deprecated-package-names` | warn | deprecated | A package of kay under the `@kaynooo` scope, `@kayjs` since 1.104: `@kaynooo/kayjs` is `@kayjs/kay`, and `@kaynooo/kayjs-ui`, `-auth`, `-mail`, `-cms` and `-ai` are `@kayjs/ui`, `@kayjs/auth`, `@kayjs/mail`, `@kayjs/cms` and `@kayjs/ai`. The old names stop at 1.103, which stays installable, so an app on them installs and checks as before until it moves; this lint goes in 1.107. Found where a name is an `import` or `export ... from` specifier, a `require()`, `import()` or `mock.module()` argument or a config key (a quoted name keyed to anything but a package name or a version, as `librarySettings`) of the project's TypeScript and `.kay` files, in the `@import` and `@plugin` paths of its CSS, and in its package.json and tsconfig files; a name in a comment or any other string, as data a tool reads or a table of renames, is left alone. The fix writes the new name, raising a package.json range below 1.104 to it, and `kay check` loads a `kay.config.ts` that still imports an old name no longer installed as if renamed, so an app that renamed `package.json` by hand can run `kay check --fix`; a package.json that lists the new name already is reported with a fix that is not safe, and `kay upgrade` does the whole move, package.json and install included. |
20
19
  | `deprecated-children-prop` | warn | deprecated | `children?: Snippet` in a props type beside a bare `slot`, since 1.105: the template types the children, so a component declares none. `children: Snippet` still requires them. The old declaration works until 1.108. The fix removes the member. |
21
20
  | `deprecated-link-flags` | warn | deprecated | `data-keep-scroll`, `data-no-transition` and `data-no-prefetch`, since 1.105 `data-scroll="keep"`, `data-transition="false"` and `data-prefetch="false"`, named as the options of `navigate()`. The old names work until 1.108. The fix writes the new attribute; a dynamic `data-no-transition` or `data-no-prefetch` has none. The app's test files (`*.test.*`, `*.spec.*`) are checked too: a selector `[data-keep-scroll]` is written `[data-scroll=keep]` by the fix, an attribute read by name (`getAttribute('data-keep-scroll')`) has a fix that is not safe, a read of `dataset.keepScroll` (and `noTransition`, `noPrefetch`) has one too, and a write of it and any other string naming an old flag have none. |
@@ -12,6 +12,7 @@
12
12
  | --- | --- | --- | --- |
13
13
  | `invalid-autocomplete` | deny | forms | An `autocomplete` value HTML does not define. |
14
14
  | `unbounded-string` | warn | forms | A string field of an action's schema named like a short value (`name`, `email`, `title`, `subject`, `slug`...) with no `maxLength` of its own, which takes the default bound of 10,000 characters, unless its `enum`, `const` or anchored bounded `pattern` already bounds it. |
15
+ | `schema-without-json-schema` | warn | forms | A Standard Schema validator with no `~standard.jsonSchema` where an action's `input` or an API route's `body`, `query`, `params`, `headers` or `cookie` takes a schema: it validates, but a form shows no constraints, a form or a query is not read as numbers and booleans, and OpenAPI and MCP show an open schema. Found in `.ts` modules and `.kay` fences for a hand-written `~standard` object and for valibot's builders, through a `const` and a relative import. |
15
16
  | `invalid-nesting` | warn | islands | Markup HTML forbids or the parser rewrites: a block in a `p`, `form` in `form`, `tr` in a `table`, a heading in a heading, an `option` outside a `select`, an `li` outside a list, a non-`li` in one. |
16
17
  | `positional-key` | deny | islands | `for todo, i of todos key={i}` whose rows read `todo.id`: keyed by position, a row added before others hands them its state. The fix drops the key. |
17
18
  | `unkeyed-rows` | deny | islands | A keyless `for` in a component or an island (not a page or a layout) over rows with no `id`: a copy is a new row, losing its focus. The offered fix writes `key={i}`; an `id` or a `key={row.slug}` is better. |
package/llms/islands.md CHANGED
@@ -237,7 +237,7 @@ if !connected()
237
237
  ### Islands
238
238
 
239
239
  - A component is interactive when any element in it has an `on*` handler, a `bind:` (on an element or a component) or a `ref`, or when its script uses a value from `kay`, such as `signal`; the rule is at the top.
240
- - `ActionError`, `ActionRedirectError`, `ApiError`, `apiUrl`, `byteCount`, `composing`, `ctx`, `defer`, `defineUi`, `describeField`, `durationMs`, `escapeHtml`, `formErrors`, `isEmail`, `lengthMs`, `localPath`, `postedChecked`, `postedValue`, `postedValues`, `publicEnv`, `recipe`, `route`, `s`, `sanitizeHtml`, `trustHtml`, `uid`, `withBase` and `withQuery` from `kay` compute the same on both sides and keep a component static; every other value of `kay` needs the browser (state, effects, lifecycle, browser readings, navigation: `navigate`, `refresh`, `call` and `logFrom` among them), and so does `relativeTime` of `kay/i18n`.
240
+ - `ActionError`, `ActionRedirectError`, `ApiError`, `apiUrl`, `byteCount`, `composing`, `ctx`, `defer`, `defineUi`, `describeField`, `durationMs`, `escapeHtml`, `formErrors`, `isEmail`, `lengthMs`, `localPath`, `postedChecked`, `postedValue`, `postedValues`, `publicEnv`, `recipe`, `route`, `s`, `sanitizeHtml`, `trustHtml`, `uid`, `validate`, `withBase` and `withQuery` from `kay` compute the same on both sides and keep a component static; every other value of `kay` needs the browser (state, effects, lifecycle, browser readings, navigation: `navigate`, `refresh`, `call` and `logFrom` among them), and so does `relativeTime` of `kay/i18n`.
241
241
  - A namespace or default import of `kay` or `kay/i18n` (`import * as i18n from 'kay/i18n'`) always makes an island, as the compiler cannot tell which names the component reads through it: import the names (`import { formatDate } from 'kay/i18n'`) to keep a component static that only formats.
242
242
  - An interactive component renders on the server and hydrates in the browser as an island.
243
243
  - Everything else ships no JavaScript, except the small script swapping pages in on a page posting a form to an action, and elsewhere one line keeping Back right after a reload (see [Navigation](navigation.md#navigation)).
@@ -280,4 +280,13 @@ if !connected()
280
280
 
281
281
  - The code that posts an action call and reads its answer loads with the first call, so an island that only declares or passes an action does not carry it. An island holding an action caller loads it at idle, so a call made as the page goes away finds it in; a chunk a deploy dropped reloads the page as other chunks do.
282
282
 
283
+ ### Components that load when they first draw
284
+
285
+ - A component an island imports loads on its own, with no declaration, when every tag using it sits where the island may not draw it at first paint: inside an `if`, `else`, `match` case or `@failed`, or in the lines or `@block` of a component that draws them only in such a branch (a closed `Dialog` and a `FormDialog` draw their body only when open). A tag also drawn outside a branch, a `snippet` read as a value, a dynamic tag or a server island keeps the import eager. A `for` body or a `pending` block inherits the position of the loop or `await` around it.
286
+ - What the server drew is loaded before the island hydrates (the page preloads its chunks, and the island names them in `data-lazy`), so its markup is claimed as it stands. What it did not draw loads when it first draws: a visitor reaching for the island (pointer over it, focus or touch inside it) loads every such component ahead, so the click finds the code in, except with `Save-Data`, which loads one when it opens.
287
+ - Until the code arrives the branch draws nothing, then the component in its place. A chunk that fails to load is tried again after 1 s and 3 s, a deploy that dropped it reloads the page as other chunks do, and a failure for good goes to `reportError` and `console.error`, not to `@failed`, which a render error of the branch reaches as ever; the branch tries again the next time it opens. A server-drawn chunk that fails to load leaves its island to draw that branch afresh.
288
+ - Only a component of 2,000 bytes of source or more loads this way, a chunk that only repeats code the islands load anyway is folded back into them after the bundle, so is every lazy chunk of a build when together they hold under 6,000 minified bytes (the lazy runtime would cost more), and an island that renders in the browser only (`clientOnly`) keeps its imports eager. A module with lazy imports awaits what the server drew at its top level, so a page without one carries none of this.
289
+ - A name inside a string or a whole-line comment of the file is no use of the component: only a tag or other code naming it keeps its import eager (a Table's `'Select all'` once kept its Select in every island). kayjs-ui's `Form`, `FormDialog` and `SaveForm` load the code that sends and reports a form (`forms-send`, with the toast it reports through) with the first send or blur check, tried once more when the chunk fails, so a page with a closed form-dialog does not carry it.
290
+ - `kay/dom-lazy` is the compiler's output contract for it, not API. `kay build --analyze` lists the modules of every island, a lazy component's apart from the eager ones.
291
+
283
292
  Shared and persisted state, transitions, error fallbacks, element size, context and unique ids are in [Islands: state to unique ids](islands-state-to-ids.md).
@@ -49,7 +49,7 @@ kay generate resource post title:string body:text published:boolean
49
49
  - The default `app` needs Bun alone: kayjs-auth keeps its users in `data/app.sqlite` and creates its tables when the app starts, `data` is ignored by git and docker, and `compose.prod.yaml` bind-mounts `data-prod`, a git- and docker-ignored folder to create owned by `nobody` (uid 65534), the user the image runs as, at `/app/data`, with no database service and no migration;
50
50
  - `--with postgres` (with `auth`, as in `--template app --with postgres`) swaps SQLite for Postgres: `src/db/tables.ts` lists `...authTables` among the tables, which `src/db/index.ts` builds `db` over and `pg-orm.config.ts` imports on their own, so the test preload points `DATABASE_URL` at its copy before anything builds `db`, `docker compose up -d --wait` starts the database `compose.dev.yaml` describes (on a port of its own per app name, its data in the git-ignored `data/postgres`), `bun run db:generate` writes the first migration for kayjs-auth's tables as the installed version declares them (and the next ones for yours), `bun run db:migrate` applies `migrations/`, its `bun run test` gives each test file a copy of the migrated database (see [Testing](testing.md)), its workflow runs Postgres as a service, and `compose.prod.yaml` runs the database (its data in `data-prod/postgres`, to create owned by the image's postgres uid 70) and a one-shot service applying the migrations before the app. Two Postgres roles split the work: the owner (`POSTGRES_USER`, connected by `MIGRATE_DATABASE_URL`, which `pg-orm.config.ts` reads before `DATABASE_URL`) changes the schema, and `app_rw` (the app's `DATABASE_URL`, password `APP_DB_PASSWORD`) reads and writes rows and cannot drop, alter or create anything. The database image creates `app_rw` from `db/roles.sh` when it first creates the database, with default privileges on tables, sequences and schemas, so a table a later migration creates needs no `GRANT`. An existing database runs `db/roles.sh` once, see [Upgrading](upgrading.md);
51
51
  - Every server preset's compose publishes the app on 127.0.0.1 alone, for a reverse proxy serving it over HTTPS, and its `kay.config.ts` sets `proxy: true` so rate limits count the visitor and not the proxy, its images and workflow use the Bun `kay new` ran under, and `.env` is ignored by git and docker and written readable by its owner alone;
52
- - `--kay` sets the `kay` dependency, by default `npm:@kayjs/kay@~<its version>`, or a packed copy when run from a checkout of kay.
52
+ - `--kay` sets the `kay` dependency, by default `npm:@kayjs/kay@~<its version>` (`^` from 2.0.0), or a packed copy when run from a checkout of kay.
53
53
  - The package is named after the directory, lower case with other characters turned into `-`.
54
54
  - Every template's `tsconfig.json` adds `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitOverride` and `noFallthroughCasesInSwitch` to `strict`, as kay does itself, so an optional field passed `undefined` must say `?: T | undefined`;
55
55
  - `server` and `app` carry a workflow checking, formatting (`bun run fmt:check`, `kay fmt --check`), linting, testing and building the project on every pull request commit and every push to `main`, and the `site` workflow tests it before building, which checks it, then checks the formatting and lints it (see [Linting](checks.md#linting)).
package/llms/project.md CHANGED
@@ -51,7 +51,7 @@ kay migrate astro ../my-astro-site --outdir ../my-kay-site
51
51
 
52
52
  ### Project setup
53
53
 
54
- - kay is published as `@kayjs/kay` to npm, and as a mirror to the Forgejo registry at `https://git.kaynooo.fr/api/packages/kaynooo/npm/`, its libraries as `@kayjs/ui`, `@kayjs/auth`, `@kayjs/mail`, `@kayjs/cms` and `@kayjs/ai` (`@kaynooo/kayjs*` up to 1.103, which `kay upgrade` moves an app off), and installed under the name its imports use: `"kay": "npm:@kayjs/kay@~<version>"` in `package.json`, a tilde since a minor release may break what the one before it took, each break listed in [Upgrading](upgrading.md) and every one `kay check` can recognise a `deprecated` lint with a fix, which `kay upgrade` applies as it moves the app, and a major is a rewrite. Every package a project installs, pg-orm and eslint included, is on npm, so a project carries no `.npmrc` and Bun needs no registry setup.
54
+ - kay is published as `@kayjs/kay` to npm, and as a mirror to the Forgejo registry at `https://git.kaynooo.fr/api/packages/kaynooo/npm/`, its libraries as `@kayjs/ui`, `@kayjs/auth`, `@kayjs/mail`, `@kayjs/cms` and `@kayjs/ai` (`@kaynooo/kayjs*` up to 1.103, which `kay upgrade` moves an app off), and installed under the name its imports use: `"kay": "npm:@kayjs/kay@~<version>"` in `package.json`. From 2.0.0 kay follows semver (a breaking change is a major, and `kay new` writes `^<version>`); through 1.x a minor may break what the one before it took, so `kay new` writes `~<version>`, each break listed in [Upgrading](upgrading.md) and every one `kay check` can recognise a `deprecated` lint with a fix, which `kay upgrade` applies as it moves the app. Every package a project installs, pg-orm and eslint included, is on npm, so a project carries no `.npmrc` and Bun needs no registry setup.
55
55
  - `bunx -p @kayjs/kay kay new my-app` writes a project that, after `cd my-app && bun install`, checks, builds and runs (`bun run dev`), both of those included: this setup, a layout, a page, a `_404.kay` and islands, or only what is picked of them (see [Commands](commands.md#commands) for the presets and features).
56
56
 
57
57
  - kay runs on Bun 1.4.4 or later, as its `engines` says: the CLI and `pages()` refuse an older one, naming its version, its path and the fix, `bun update bun` when it is the project's npm `bun` package, which a plugin's peer dependency installs and package scripts run ahead of the system Bun.
@@ -128,7 +128,7 @@ export default defineConfig({
128
128
  - It includes `src`, `tests`, `scripts`, the `*.config.ts` files beside it, such as `kay.config.ts`, `eslint.config.ts` and `pg-orm.config.ts`, and `.kay/types`, relative to the project's tsconfig.
129
129
  - A project adds its own `compilerOptions` beside `extends`, and an `include` of its own replaces kay's, so it lists `.kay/types` again; one setting up its tsconfig by hand needs `"jsx": "preserve"`, `"jsxImportSource": "kay"`, `"module": "Preserve"`, `"moduleResolution": "bundler"` and `"rootDirs": [".", ".kay/types"]`.
130
130
 
131
- - `kay/html`, `kay/dom`, `kay/dom-loop`, `kay/dom-await`, `kay/dom-try`, `kay/dom-spread`, `kay/dom-image`, `kay/pending`, `kay/i18n-links`, `kay/island`, `kay/await`, `kay/client`, `kay/arrival`, `kay/internal`, `kay/internal/title` and `kay/internal/server` are what compiled `.kay` files and kay's generated entries import, and `kay/jsx-runtime` is where TypeScript finds the JSX types of `jsxImportSource: "kay"`: the compiler's output contract rather than API, free to change in any release, never imported by an app. The root `kay` export also holds the compile-time types behind the generated shadow types, none of them for an app to name: `BindableMark`, `IslandBrand`, `HandedPart`, `HandsPart`, `HandedSignal`, `UnresolvedParameter`, `WidenedProps`, `CheckedHref`, `CheckedHtml`, `CheckedComputedHtml`, `BoundProp`, `BoundValue`, `PlainIslandProp`, `FunctionProp`, `Inferred`, `TemplateHelpers`, `TemplateValues` and `Truthy`, free to change in any release too.
131
+ - `kay/html`, `kay/dom`, `kay/dom-loop`, `kay/dom-await`, `kay/dom-lazy`, `kay/dom-try`, `kay/dom-spread`, `kay/dom-image`, `kay/pending`, `kay/i18n-links`, `kay/island`, `kay/await`, `kay/client`, `kay/arrival`, `kay/internal`, `kay/internal/title` and `kay/internal/server` are what compiled `.kay` files and kay's generated entries import, and `kay/jsx-runtime` is where TypeScript finds the JSX types of `jsxImportSource: "kay"`: the compiler's output contract rather than API, free to change in any release, never imported by an app. The root `kay` export also holds the compile-time types behind the generated shadow types, none of them for an app to name: `BindableMark`, `IslandBrand`, `HandedPart`, `HandsPart`, `HandedSignal`, `UnresolvedParameter`, `WidenedProps`, `CheckedHref`, `CheckedHtml`, `CheckedComputedHtml`, `BoundProp`, `BoundValue`, `PlainIslandProp`, `FunctionProp`, `Inferred`, `TemplateHelpers`, `TemplateValues` and `Truthy`, free to change in any release too.
132
132
  - A few entries also hold plumbing no page tells an app to call, free to change in any release: the paths, providers and tracker tags of `kay/analytics` (`ANALYTICS_PATH`, `ANALYTICS_SCRIPT_PATH`, `ANALYTICS_PROVIDERS`, `CUSTOM_COLLECT_PATH`, `CUSTOM_SCRIPT_PATH`, `NOTICE_SCRIPT_PATH`, `INTEGRITY`, `TRACKER_TAGS`, `isGated`, `LazyGuard`), the collection marker, publish times and cache key of `kay/content`, and the preview session reader of `kay/server`.
133
133
  - A name has one home: an entry beside a package's root exists for browser safety (`@kayjs/auth/rules`, `@kayjs/cms/form`, which an island imports without the server) and the root does not repeat its names. The copies in `kay/mount` and `kay/server` that 1.105 moved (`mount`, `s`, `RateLimit`, `sqliteCache`) stay as deprecated shims until 1.108.
134
134
  - `kay/library` is what kay's own libraries (kayjs-auth, kayjs-ui, kayjs-mail, kayjs-cms, kayjs-ai) share with kay for their server code, such as the sanitizer's lists, sealing, locale matching, escaping and the user a library names for a request (`nameUser(request, () => id)`, read back by `userOf(request)`: kayjs-auth names the signed-in user and kayjs-ai counts them) and `configError(option, value, takes)`, the `config-invalid` `KayError` a library throws for a setting it refuses at boot, so neither keeps a copy: not API either, free to change with any minor, never imported by an app. The libraries are released in lockstep with kay, each one's peer range on kay's minor, so the same holds for what a library imports from it.
package/llms/schemas.md CHANGED
@@ -45,13 +45,15 @@ const { initial } = props<{ initial: Choice }>()
45
45
  - `s` from `kay` is kay's own schema builder, over TypeBox so a schema stays JSON Schema data for OpenAPI, MCP and the form rules, under a name that leaves `t` to translations: lowercase builders with short options, there to save an import in server fences and server modules, `defineEnv` and API modules included.
46
46
  - The builders: `s.string({ min, max, pattern })`, `s.email()`, `s.url()`, `s.slug()`, `s.int({ min, max })`, `s.number({ min, max })`, `s.boolean()`, `s.date()` (read as a `Date`), `s.enum(values)` or `s.enum(record)` (a record gives its keys), `s.literal(value)`, `s.union([a, b])`, `s.object(shape)`, `s.record(value)`, `s.list(item, { min, max })`, `s.file({ type, minSize, maxSize })`, `s.files()`, `s.secret()` and `s.public(field)` (the last two for `defineEnv`).
47
47
  - Every builder takes the same field options: `optional: true` (the field may be left out, typed `T | undefined`), `default`, `error` (a text, or a function called in the request's locale), `label`, `description` and `example`. Any other option is a JSON Schema keyword, kept as written.
48
- - Strict by default: a string is at most 10,000 characters, a list at most 1,000 items and a file size is `'2mb'`, `'600kb'` or bytes, each unless the options give another; `s.object` marks its shape closed, and `s.object(shape, { extra: 'strip' })` leaves it open. What a closed shape does with a key it lacks depends on who reads it: kay refuses it where it reads the schema itself (collection frontmatter, `defineEnv`, a JSON Schema check by `ask`); a body, a response and a record of an action are read by Elysia, which drops it and answers 200 (refusing it is for a later minor); the search params of a page or an API route and a request's headers are dropped whatever the shape says, and an API route's `cookie` schema ignores the cookies it does not name, as a third party sets some.
48
+ - Strict by default: a string is at most 10,000 characters, a list at most 1,000 items and a file size is `'2mb'`, `'600kb'` or bytes, each unless the options give another; `s.object` marks its shape closed, and `s.object(shape, { extra: 'strip' })` leaves it open. What a closed shape does with a key it lacks depends on who reads it: kay refuses it in an action's input, an API route's body, a socket message, `defineEnv`, collection frontmatter and a JSON Schema check by `ask` (a form post drops the fields the schema does not name); a response is read by Elysia, which drops it; the search params of a page or an API route and a request's headers are dropped whatever the shape says, and an API route's `cookie` schema ignores the cookies it does not name, as a third party sets some.
49
49
  - A plain record of schemas is the object schema wherever a schema is taken: `action({ title: s.string() }, handler)` and `defineEnv({ PORT: s.int({ default: 3000 }) })`, so `s.object()` is rarely written. A record is strict as `s.object` is, and kay's own form fields (the honeypot, the stamp) are not its keys.
50
+ - Any Standard Schema validator (Zod 4.2+, ArkType 2.1.28+, Valibot) is accepted where a schema is: an action's `input` (typed by its output type) and an API route's `body`, `query`, `params`, `headers` and `cookie`. kay validates through `~standard.validate`, and reads constraints, OpenAPI and MCP from `~standard.jsonSchema.input({ target: 'draft-2020-12' })`; one without it still validates, but a form shows no constraints, a text source (a form, a query) is not read as numbers and booleans, and OpenAPI and MCP show an open schema; `kay check` names a hand-written or valibot one in those positions (`schema-without-json-schema`).
51
+ - `validate(schema, value, { source, locale })` from `kay/server` reads a value as its `source` says (`'form'`, `'query'`, `'params'` and `'env'` text is read as numbers, booleans and lists; `'json'` never is, and a form's or a query's text loses its surrounding spaces unless `trim: false`, as an API route reads it) and answers `{ value }` or, when `'errors' in result`, `{ errors: [{ path, key, params, message }], status: 422 }`: `path` is dotted (`tags.0`), `key` a `kay.invalid.*` message, `message` its text in the locale. `error` on a field is a text, a function, or a record by rule (`{ min, max, pattern, format, required, type, default }`). Nothing depends on `NODE_ENV`.
50
52
  - The PascalCase builders of 1.x, `s.String`, `s.Object`, `s.Optional(field)`, `s.UnionEnum`, `s.UnionKeys`, `s.Numeric` and the rest, are Elysia's under their old names and work until 2.0: `kay upgrade` rewrites them (`deprecated-schema-builders`). A schema built with Elysia's `t` is still a `Schema`.
51
53
  - `Schema` from `kay` is the type of what `s` builds, and what `action`, `defineEnv`, `collection`, an API route's `query` and a library's schema option take: name it in a signature, never TypeBox's `TSchema`. `Static<typeof schema>` reads the TypeScript type. Elysia and TypeBox are implementation details of kay: `s` has no door to TypeBox's own builders, and a schema it builds is JSON Schema data.
52
- - The browser has no Elysia, which reads `Bun`: there `s.object(...)` and the rest build an inert stand-in, so a module shared by the server and an island may build its schemas as it loads, with no validator in the island's chunk, only the calls and their literals.
53
- - The stand-in only passes into another builder: reading a key of one, or validating with it, throws in the browser. An island reads the type, `Static<typeof schema>`, and the server validates.
54
- - An island reads a schema's type, not its value: `import type { Choice } from '../schemas'`, or `import type { choice } from '../schemas'` for `Static<typeof choice>`, is erased from the browser build; a plain `import { choice }` works too, keeping the inert stand-in and the schema's literal in the chunk.
54
+ - The browser has no Elysia, which reads `Bun`: there `s.object(...)` and the rest build the plain JSON Schema of the field, a few lines each, so a module shared by the server and an island may build its schemas as it loads. The builders are a few small functions in the chunk of an island that imports a module building schemas as it loads; a module it imports as a type costs nothing. The PascalCase builders, deprecated, build a schema that accepts anything there.
55
+ - An island validates with the same schema: `validate(schema, value, { source })` from `kay` is the browser's `validate`, answering the same `{ value }` or `{ errors, status: 422 }`, worded in the page's locale (a `locale` option is the server's). Its code is a chunk of its own that the first call loads, so a page's eager JS does not grow and a page whose islands never call it never fetches it. A form is read as text (`'form'`), JSON as it is, defaults fill in, an unknown key is refused as on the server, and a Standard Schema validator is called as it is. A date stays the text it was given, and a file is checked by the server alone, which reads its bytes.
56
+ - An island may also read a schema's type alone: `import type { Choice } from '../schemas'`, or `import type { choice } from '../schemas'` for `Static<typeof choice>`, is erased from the browser build.
55
57
  - `Static<typeof schema>` and `InputOf<typeof action>` are types from `kay` and cost the browser nothing.
56
58
  - A module holding a value an island needs, a list of choices to draw as buttons, exports it apart from the schema, in a module with no `s`.
57
59
  - A schema shared by API modules, server fences and `_actions.kay` lives in a `.ts` module of `src/`, `src/schemas.ts` or a folder of them, imported by its path from each.
package/llms/upgrading.md CHANGED
@@ -1,6 +1,24 @@
1
1
  # Upgrading
2
2
 
3
- What each minor release breaks, and what an app changes to move to it. kay and its libraries share one version, so one section covers them all; a patch breaks nothing, and a minor missing here broke nothing.
3
+ What each release breaks, and what an app changes to move to it. kay and its libraries share one version, so one section covers them all; a patch breaks nothing, and a version missing here broke nothing. Through 1.x a breaking change ships in a minor; from 2.0.0 it ships in a major, and a minor or a patch breaks nothing.
4
+
5
+ ## 1.107.0
6
+
7
+ ### `TSchema` is gone from `kay/library`
8
+
9
+ Import `Schema` from `kay/library` instead, kay's own name for what `s` builds; `kay upgrade` on 1.106 rewrote the import and its uses. The `deprecated-schema-type` lint is gone with it.
10
+
11
+ ### `--- script` opening a file is an error
12
+
13
+ A file opens its script with `---`; `--- script` is only for a script that follows a `--- server`, `--- module` or `--- style` fence. The `deprecated-script-fence` lint is gone, and `--- script` first in a file is a `fence-invalid` error whose safe fix `kay check --fix` applies.
14
+
15
+ ### `action({ input, ...options }, handler)`
16
+
17
+ An action takes its options first, with its input in them, as an API route does: `action({ input: { title: s.string() }, maxSize: '1mb' }, handler)`. `action(schema, handler, options)` and `action(handler, options)` work until 2.0; `kay upgrade` rewrites them (`deprecated-action-options`).
18
+
19
+ ### One validation for every input
20
+
21
+ Actions, API routes, sockets and `defineEnv` read their input through one `validate(schema, value, { source })`. Text sources (a form, a query, path params, the environment) are read as the numbers, booleans and lists they spell, and a JSON body never is: an action called from an island, a socket message and an API route's JSON body that sent `'3'` for an int, or `'true'` for a boolean, are refused where Elysia's schemas let them by. An object refuses a key its shape lacks in JSON (`extra: 'strip'` drops it, as `s.Object` of the old builders still does); a query, the headers and the cookies of a request still drop theirs. A form post drops the fields the schema does not name (a named submit button, a widget), as a browser sends controls the app does not own. `validate` answers `{ errors: [{ path, key, params, message }], status: 422 }` worded in the request's locale and independent of `NODE_ENV`; an action's or API route's answer still carries `errors` as a `{ field: message }` map. An API route's refusal reaches an `onError` as an error with code `VALIDATION` whose `all` lists `path`, `message` and `summary`. No lint can find the app that sends such a key or such a JSON value, as it depends on what a request carries.
4
22
 
5
23
  ## 1.106.0
6
24
 
package/llms/whats-new.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  What each release of kay and its libraries adds, newest first, each feature with where it is documented. kay and its libraries share one version, so one section covers them all; what a release breaks is in [Upgrading](upgrading.md).
4
4
 
5
+ ## 1.107.0
6
+
7
+ - `--- script` as a file's first fence is a compile error naming `---`, and the `deprecated-script-fence` lint is gone ([components](components.md)).
8
+ - `kay new` pins kay with `^` from 2.0.0, when a breaking change is a major, and with `~` through 1.x, where a minor may break; the semver policy is stated in [Upgrading](upgrading.md) and the install pages ([project](project.md))
9
+ - `kay new` pins kay with `~` through 1.x and with `^` from 2.0.0, when a breaking change becomes a major ([Upgrading](upgrading.md))
10
+ - A component an island draws only where it may not render at first paint (inside an `if`, a `match` case, `@failed`, or the body of a closed `Dialog` or `FormDialog`) loads when that branch first draws, with nothing to declare: the page preloads what the server drew, a visitor reaching for the island loads the rest ahead, and a failed chunk is retried and reported; the code that posts an action call loads with its first call, retried after 1 s and 3 s when the load fails ([islands](islands.md#components-that-load-when-they-first-draw)).
11
+ - An island whose closed forms and dialogs hold words that are also component names loads less: a name in a string or a comment no longer keeps a component eager, and `Form`, `FormDialog` and `SaveForm` load their sending code on the first send. An island with a table, a closed form dialog and a select in it sheds 4.6 KB gzip of eager JS ([islands](islands.md))
12
+ - `action({ input, ...options }, handler)`: an action takes its options first with its input in them, as an API route does; the old argument order works until 2.0 and `kay upgrade` rewrites it ([actions](actions.md))
13
+ - One `validate(schema, value, { source })` reads every input of an app, an action's, an API route's, a socket's and `defineEnv`'s, and refuses with `{ errors: [{ path, key, params, message }], status: 422 }` worded in the request's locale; a JSON body is never coerced, and a Standard Schema validator (Zod, ArkType) is accepted where a schema is ([schemas](schemas.md))
14
+ - An island validates with the same schema: `validate(schema, value, { source })` from `kay` is the server's `validate` in the browser (JSON Schema built by the browser's `s`, a Standard Schema validator called as it is), its code a chunk the first call loads ([Schemas](schemas.md#schemas)).
15
+ - `kay check` names a Standard Schema validator with no `~standard.jsonSchema` (`schema-without-json-schema`) where an action's `input` or an API route's `body`, `query`, `params`, `headers` or `cookie` takes it, in `.ts` modules and `.kay` fences ([Schemas](schemas.md#schemas)).
16
+ - kayjs-ui's `Table` draws its failure row's retry as a plain button with a `retry` part, so an island holding a plain Table ships 6 KB less (the `Button`, its busy state and the icon set stay out unless the page uses them) ([restyle](https://git.kaynooo.fr/kaynooo/kayjs/src/branch/main/packages/ui/llms/restyle.md)).
17
+
5
18
  ## 1.106.0
6
19
 
7
20
  - kayjs-ui's `BarChart`, `LineChart` and `ScatterChart` take `goals`, a dashed rule across the value axis at each `value` with its `title` on it and read by screen readers, such as a pass mark ([BarChart](/ui/bar-chart#goals-and-a-fixed-scale)); `BarChart` takes `max`, fixing the top of its value axis
@@ -27,7 +40,7 @@ What each release of kay and its libraries adds, newest first, each feature with
27
40
  - kayjs-ui's `AudioPlayer` takes `@lead(chapter, index)` before each chapter's button, a `subtitle` on a chapter, `@status(chapter, index)` for the chapter playing in the bar after the time, and `peaks` on a chapter, drawn as bars split by chapter in place of the seek groove ([AudioPlayer](/ui/audio-player#a-waveform)).
28
41
  - `kay check --fix` rewrites what the 1.105 types refuse in an app still on the old forms: a function handed by name to a library component's callback (`deprecated-callback-handler`), an island call read as its data (`deprecated-call-result`, `.orThrow()` after the call), the `mcpKey` and `proxyKey` options of `testSite()`, and the `fonts`, `favicon` and `observe` keys in the `config` of an extension, which work until 1.108 ([upgrading](upgrading.md)).
29
42
  - `kay check --fix` rewrites an old package name only where it is a specifier, a `require()` or `import()` argument, a config key, a stylesheet `@import` or `@plugin` path or a package.json entry, no longer a string of data that names one; and `deprecated-link-flags` reaches the app's test files, rewriting `[data-keep-scroll]` selectors to `[data-scroll=keep]` and reporting an attribute read by name ([deprecated lints](deprecated-lints.md)).
30
- - `ctx.deny(status, { message })` in an action fails the post as `{ data }` does, the form showing the message and a call throwing an `ActionError` carrying it, in place of a bare status; the `deprecated-ctx-fail` fixer writes a text as `message` ([Refused posts](actions.md#refused-posts))
43
+ - `ctx.deny(status, { message })` in an action fails the post as `{ data }` does, the form showing the message and a call throwing an `ActionError` carrying it, in place of a bare status; the `deprecated-ctx-fail` fixer writes a text as `message` ([Refused posts](actions-refused-fields.md#refused-posts))
31
44
  - The former `/mcp` answers the MCP endpoint in place until 2.0 for an app that did not set `endpoints.mcp`, where 1.105 sent it to `/_kay/mcp` with a 308 an MCP client does not follow; a page or route of the app at `/mcp` keeps it ([MCP](mcp.md), [upgrading](upgrading.md)).
32
45
  - The installed app's icon badge shows the unread count: kayjs-ui's `Bell` sets it (`appBadge={false}` opts out) and a push from `notify()` carries the count for the worker to set (`notify(..., { badge: false })` opts out, `sendPush` takes `badge`) ([notifications](notifications.md)).
33
46
  - `assets.manifest.shareTarget` lists the installed app in a device's share sheet, posting the shared title, text, link and files to an action ([web manifest](sitemap-search-fonts.md#favicon-and-web-manifest)).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kayjs/kay",
3
3
  "type": "module",
4
- "version": "1.106.0",
4
+ "version": "1.107.0",
5
5
  "description": "A Bun web framework: one .kay file per component, pages rendered to plain HTML on the server, interactive islands in the browser",
6
6
  "author": "Kaynooo <https://github.com/Kayno0o>",
7
7
  "license": "MIT",
@@ -28,6 +28,11 @@
28
28
  "types": "./types/runtime/schema.d.ts",
29
29
  "browser": "./src/runtime/schema.client.ts",
30
30
  "default": "./src/runtime/schema.ts"
31
+ },
32
+ "#validate": {
33
+ "types": "./types/server/validate.d.ts",
34
+ "browser": "./src/runtime/validate.client.ts",
35
+ "default": "./src/server/validate.ts"
31
36
  }
32
37
  },
33
38
  "exports": {
@@ -117,6 +122,10 @@
117
122
  "types": "./types/runtime/dom-await.d.ts",
118
123
  "default": "./src/runtime/dom-await.ts"
119
124
  },
125
+ "./dom-lazy": {
126
+ "types": "./types/runtime/dom-lazy.d.ts",
127
+ "default": "./src/runtime/dom-lazy.ts"
128
+ },
120
129
  "./dom-try": {
121
130
  "types": "./types/runtime/dom-try.d.ts",
122
131
  "default": "./src/runtime/dom-try.ts"
@@ -299,11 +308,11 @@
299
308
  "@fontsource/inter": "^5.3.0",
300
309
  "@happy-dom/global-registrator": "^21.0.4",
301
310
  "@iconify-json/tabler": "^1.2.42",
302
- "@kayjs/ai": "1.106.0",
303
- "@kayjs/auth": "1.106.0",
304
- "@kayjs/cms": "1.106.0",
305
- "@kayjs/mail": "1.106.0",
306
- "@kayjs/ui": "1.106.0",
311
+ "@kayjs/ai": "1.107.0",
312
+ "@kayjs/auth": "1.107.0",
313
+ "@kayjs/cms": "1.107.0",
314
+ "@kayjs/mail": "1.107.0",
315
+ "@kayjs/ui": "1.107.0",
307
316
  "@kaynooo/eslint": "^8.0.3",
308
317
  "@kaynooo/pg-orm": "^8.1.4",
309
318
  "@oxc-parser/binding-wasm32-wasip1": "0.155.0",
@@ -30,13 +30,16 @@ import { ASSET_PREFIX, clientDir, DEV_MAPS_DIR, MAPS_DIR, outputDir } from './as
30
30
  import { AWAIT_ALERT_FILE } from './await-alert'
31
31
  import { pruneNodes, pruneUtilityLayer } from './class-rules'
32
32
  import { buildClassTable, mergesAtRuntime } from './class-table'
33
+ import { entryFile, KAY_OUTPUT, lazyEntryKey } from './entry-files'
33
34
  import { CSS_FILE, findKayFiles, findProjectFiles, forgetSources, inWalkScope, keepSources, liftSources, readSource, readSourcePaths, readText, writeIfChanged } from './files'
34
35
  import { Increments, realPaths, sameEntries } from './increments'
35
36
  import { keepBundleMapCached, pruneKeptMaps } from './kept-maps'
36
37
  import { hoistLayerOrder } from './layer-order'
38
+ import { eagerKeys, lazyKey } from './lazy-components'
39
+ import { noteLazy, staticClosure } from './lazy-manifest'
40
+ import { foldStubs, inRounds } from './lazy-stubs'
37
41
  import { fileWords, importEdges, libraryOf, reachedFrom, reachingAny } from './libraries'
38
42
  import { packagesOf } from './licenses'
39
- import { throughLinks } from './links'
40
43
  import { isPageFile, pageDirs } from './page-dirs'
41
44
  import { kay } from './plugin'
42
45
  import { unusedLibraryClasses } from './prune'
@@ -91,6 +94,7 @@ type Outputs = Record<string, MetafileOutput>
91
94
 
92
95
  const LEADING_DOT_SLASH = /^\.\//
93
96
  const JS_OUTPUT = /\.js$/
97
+
94
98
  const COMPILES_WASM = /\bWebAssembly\./
95
99
  const STARTS_WORKER = /\bnew\s+(?:Shared)?Worker\(/
96
100
  const OBJECT_URL = /\bcreateObjectURL\(/
@@ -501,7 +505,14 @@ export async function islandClassTableOf(root: string, sources: Pick<ClientSourc
501
505
  }
502
506
 
503
507
  // `inputs` holds the modules of each chunk, `maps` the source maps written.
504
- async function bundleIslands(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, classTable?: ClassTable, islandTable?: ClassTable): Promise<{ manifest: Omit<ClientManifest, 'styles'>, inputs: ChunkInputs, maps: string[] }> {
508
+ interface Bundled { manifest: Omit<ClientManifest, 'styles'>, inputs: ChunkInputs, maps: string[] }
509
+
510
+ async function bundleIslands(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, classTable?: ClassTable, islandTable?: ClassTable): Promise<Bundled> {
511
+ return inRounds(async last => bundleRound(root, islands, files, actionForms, actionProps, options, last, classTable, islandTable))
512
+ }
513
+
514
+ // One build of the islands, which `foldStubs` ends when lazy components that do not pay were left.
515
+ async function bundleRound(root: string, islands: Map<string, string>, files: string[], actionForms: boolean, actionProps: boolean, options: ClientOptions, last: boolean, classTable?: ClassTable, islandTable?: ClassTable): Promise<Bundled> {
505
516
  const navigation = options.client?.navigation ?? true
506
517
 
507
518
  if (islands.size === 0 && !navigation)
@@ -562,7 +573,7 @@ async function bundleIslands(root: string, islands: Map<string, string>, files:
562
573
 
563
574
  // Without the registry in the boot, each island is an entry point of its own.
564
575
  const islandFiles = options.hot ? [] : [...entries.values()]
565
- const chunk = await runtimeChunk(entryFile, { plugins: plugins(), define, external, islands: islandFiles, cache: { file: join(projectPaths(root).cache, `runtime-search-${options.hot ? 'dev' : 'build'}.json`), key: `${JSON.stringify([options.librarySettings, options.inspect, options.client?.navigation, trees, islandFiles])}\0${await Bun.file(bootFile).text()}` } })
576
+ const chunk = await runtimeChunk(entryFile, { plugins: plugins(), define, external, islands: islandFiles, cache: { file: join(projectPaths(root).cache, `runtime-search-${options.hot ? 'dev' : 'build'}.json`), key: `${JSON.stringify([options.librarySettings, options.inspect, options.client?.navigation, trees, islandFiles, eagerKeys()])}\0${await Bun.file(bootFile).text()}` } })
566
577
 
567
578
  // In development the entry keeps its own code, the islands it imports by their hashed names included: the runtime's chunk then stays as it was through an edit of an island, which swaps in alone.
568
579
  // A second entry point importing the runtime alone has Bun give it that chunk of its own, which it would otherwise merge into the entry's.
@@ -592,6 +603,8 @@ async function bundleIslands(root: string, islands: Map<string, string>, files:
592
603
  // A production page posting forms and holding no island loads navigation alone, from a build of its own: in the islands' build it would move the navigation code out of their runtime's chunk, adding a file to every page. A static export has no server to post to, and an app rendering no such form has no page loading it.
593
604
  const [build, nav] = await Promise.all([Bun.build({ ...config, outdir: clientDir(root) }), navigation && actionForms && !options.hot && options.exported !== true ? bundleNavigation(root, options, { ...config, plugins: plugins() }) : undefined])
594
605
 
606
+ await foldStubs(build, nav, last, lazyEntryKey(root, new Set(islands.values())))
607
+
595
608
  if (!build.success) {
596
609
  await refuseBuiltinImports(root, build.logs, islands.values(), config)
597
610
 
@@ -790,6 +803,10 @@ export function islandManifest(root: string, outputs: Outputs, islands: Map<stri
790
803
 
791
804
  const file = entryFile(root, meta.entryPoint, files)
792
805
 
806
+ // A `.kay` entry, an island or not, is a component another island may load lazily, which the page preloads when its server drew it.
807
+ if (KAY_OUTPUT.test(meta.entryPoint))
808
+ noteLazy(manifest, lazyKey(root, resolve(variantFile(meta.entryPoint))), meta.entryPoint, [...closure(output)].map(assetUrl))
809
+
793
810
  // Any other entry point is the entry, or a chunk some code imports dynamically, loaded when it asks for it.
794
811
  if (file === undefined)
795
812
  continue
@@ -819,20 +836,6 @@ export function islandManifest(root: string, outputs: Outputs, islands: Map<stri
819
836
  return manifest
820
837
  }
821
838
 
822
- // Every chunk a chunk needs before it can run, itself included.
823
- function staticClosure(outputs: Outputs, output: string, seen = new Set<string>()): Set<string> {
824
- if (seen.has(output))
825
- return seen
826
-
827
- seen.add(output)
828
- for (const imported of outputs[output]?.imports ?? []) {
829
- if (imported.kind === 'import-statement')
830
- staticClosure(outputs, imported.path, seen)
831
- }
832
-
833
- return seen
834
- }
835
-
836
839
  // The URL a page loads an entry by, and the chunks it imports statically, which the page preloads.
837
840
  function entryChunks(root: string, outputs: Outputs, entry: string): { entry: string, imports: string[] } | undefined {
838
841
  const entries = new Set([entry])
@@ -853,13 +856,6 @@ function islandPath(root: string, input: string): string {
853
856
  return relative(root, resolve(input)).replaceAll('\\', '/')
854
857
  }
855
858
 
856
- // Bun names entry points relative to the working directory, not the root: from a library holding a test app, its layout and the app's share a path.
857
- function entryFile(root: string, entryPoint: string, files: Set<string>): string | undefined {
858
- const point = resolve(variantFile(entryPoint))
859
-
860
- return [point, throughLinks(root, point)].find(file => files.has(file))
861
- }
862
-
863
859
  function assetUrl(output: string): string {
864
860
  return `${ASSET_PREFIX}${output.replace(LEADING_DOT_SLASH, '')}`
865
861
  }
@@ -0,0 +1,19 @@
1
+ import { resolve } from 'node:path'
2
+ import { lazyKey } from './lazy-components'
3
+ import { throughLinks } from './links'
4
+ import { variantFile } from './variants'
5
+
6
+ export const KAY_OUTPUT = /\.kay(?:\?uses=[^?]*)?$/
7
+
8
+ // Bun names entry points relative to the working directory, not the root: from a library holding a test app, its layout and the app's share a path.
9
+ // The file among `files` a build's entry point stands for, a variant or a link followed.
10
+ export function entryFile(root: string, entryPoint: string, files: Set<string>): string | undefined {
11
+ const point = resolve(variantFile(entryPoint))
12
+
13
+ return [point, throughLinks(root, point)].find(file => files.has(file))
14
+ }
15
+
16
+ // The lazy key of an entry point that is a component and no island.
17
+ export function lazyEntryKey(root: string, islandFiles: Set<string>): (entryPoint: string) => string | undefined {
18
+ return entryPoint => KAY_OUTPUT.test(entryPoint) && entryFile(root, entryPoint, islandFiles) === undefined ? lazyKey(root, resolve(variantFile(entryPoint))) : undefined
19
+ }