@kayjs/kay 1.110.0 → 1.112.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 (137) hide show
  1. package/dist/eslint.js +160 -27
  2. package/editors/zed/extension.toml +2 -2
  3. package/llms/build-and-start.md +1 -1
  4. package/llms/checks.md +1 -0
  5. package/llms/component-libraries.md +1 -1
  6. package/llms/deprecated-lints.md +1 -1
  7. package/llms/dev-tool.md +1 -1
  8. package/llms/effects.md +1 -0
  9. package/llms/head.md +1 -1
  10. package/llms/images.md +2 -0
  11. package/llms/islands-lazy-components.md +23 -0
  12. package/llms/islands.md +2 -14
  13. package/llms/lints.md +1 -1
  14. package/llms/navigation.md +2 -2
  15. package/llms/performance-lints.md +1 -0
  16. package/llms/prerendering.md +1 -1
  17. package/llms/project-new-and-add.md +2 -2
  18. package/llms/project.md +1 -1
  19. package/llms/templates-elements-slots-snippets.md +2 -2
  20. package/llms/upgrading-archive.md +107 -58
  21. package/llms/upgrading.md +20 -124
  22. package/llms/whats-new-archive.md +31 -31
  23. package/llms/whats-new.md +36 -32
  24. package/llms.txt +3 -2
  25. package/package.json +11 -11
  26. package/src/build/client.ts +10 -8
  27. package/src/build/island-images.ts +277 -0
  28. package/src/build/pipeline.ts +10 -4
  29. package/src/build/static.ts +99 -24
  30. package/src/check/schema-builders.ts +113 -8
  31. package/src/check/shadow-types.ts +3 -3
  32. package/src/compiler/codegen.ts +1 -1
  33. package/src/compiler/dom.ts +4 -3
  34. package/src/compiler/handed-data.ts +15 -0
  35. package/src/compiler/helper-imports.ts +2 -2
  36. package/src/compiler/html.ts +3 -7
  37. package/src/compiler/index.ts +3 -1
  38. package/src/compiler/items.ts +162 -0
  39. package/src/compiler/jsx.ts +6 -8
  40. package/src/compiler/kay-exports.ts +1 -0
  41. package/src/compiler/lints.ts +1 -1
  42. package/src/compiler/markup.ts +10 -3
  43. package/src/compiler/rewrite-types.ts +2 -0
  44. package/src/compiler/rewrite.ts +4 -2
  45. package/src/compiler/route-lints.ts +8 -0
  46. package/src/compiler/template-walk.ts +2 -1
  47. package/src/config-shape.ts +4 -1
  48. package/src/config.ts +2 -2
  49. package/src/features.ts +1 -1
  50. package/src/new.ts +16 -4
  51. package/src/project.ts +3 -3
  52. package/src/runtime/await.server.ts +4 -2
  53. package/src/runtime/dev-tab-env.ts +28 -3
  54. package/src/runtime/dom-loop.ts +2 -4
  55. package/src/runtime/dom.ts +1 -1
  56. package/src/runtime/html.ts +52 -6
  57. package/src/runtime/image.ts +22 -4
  58. package/src/runtime/index.ts +1 -1
  59. package/src/runtime/island.server.ts +3 -3
  60. package/src/runtime/navigate.ts +5 -0
  61. package/src/runtime/navigation.ts +4 -0
  62. package/src/runtime/page-swap.ts +4 -1
  63. package/src/runtime/reactive.ts +72 -0
  64. package/src/runtime/row-key.ts +4 -0
  65. package/src/runtime/swap-focus.ts +56 -9
  66. package/src/runtime/swap-kept.ts +28 -0
  67. package/src/server/client.ts +3 -0
  68. package/src/server/dev.ts +2 -0
  69. package/src/server/image.ts +1 -1
  70. package/src/server/kept-exports.ts +1 -0
  71. package/src/server/render-document.ts +3 -2
  72. package/src/server/render.ts +2 -2
  73. package/src/template-styles.ts +2 -2
  74. package/types/build/client.d.ts +6 -0
  75. package/types/build/client.d.ts.map +1 -1
  76. package/types/build/island-images.d.ts +45 -0
  77. package/types/build/island-images.d.ts.map +1 -0
  78. package/types/build/pipeline.d.ts.map +1 -1
  79. package/types/build/static.d.ts.map +1 -1
  80. package/types/check/schema-builders.d.ts.map +1 -1
  81. package/types/compiler/dom.d.ts.map +1 -1
  82. package/types/compiler/handed-data.d.ts +5 -0
  83. package/types/compiler/handed-data.d.ts.map +1 -0
  84. package/types/compiler/html.d.ts.map +1 -1
  85. package/types/compiler/index.d.ts.map +1 -1
  86. package/types/compiler/items.d.ts +13 -0
  87. package/types/compiler/items.d.ts.map +1 -1
  88. package/types/compiler/jsx.d.ts.map +1 -1
  89. package/types/compiler/kay-exports.d.ts.map +1 -1
  90. package/types/compiler/lints.d.ts +9 -1
  91. package/types/compiler/lints.d.ts.map +1 -1
  92. package/types/compiler/markup.d.ts +2 -0
  93. package/types/compiler/markup.d.ts.map +1 -1
  94. package/types/compiler/rewrite-types.d.ts +1 -0
  95. package/types/compiler/rewrite-types.d.ts.map +1 -1
  96. package/types/compiler/route-lints.d.ts +8 -0
  97. package/types/compiler/route-lints.d.ts.map +1 -1
  98. package/types/compiler/template-walk.d.ts.map +1 -1
  99. package/types/config-shape.d.ts.map +1 -1
  100. package/types/config.d.ts +3 -1
  101. package/types/config.d.ts.map +1 -1
  102. package/types/new.d.ts.map +1 -1
  103. package/types/project.d.ts +2 -2
  104. package/types/project.d.ts.map +1 -1
  105. package/types/runtime/await.server.d.ts.map +1 -1
  106. package/types/runtime/dev-tab-env.d.ts.map +1 -1
  107. package/types/runtime/dom-loop.d.ts +2 -1
  108. package/types/runtime/dom-loop.d.ts.map +1 -1
  109. package/types/runtime/dom.d.ts +1 -1
  110. package/types/runtime/dom.d.ts.map +1 -1
  111. package/types/runtime/html.d.ts +5 -2
  112. package/types/runtime/html.d.ts.map +1 -1
  113. package/types/runtime/image.d.ts.map +1 -1
  114. package/types/runtime/index.d.ts +1 -1
  115. package/types/runtime/index.d.ts.map +1 -1
  116. package/types/runtime/navigate.d.ts.map +1 -1
  117. package/types/runtime/navigation.d.ts +2 -0
  118. package/types/runtime/navigation.d.ts.map +1 -1
  119. package/types/runtime/reactive.d.ts +5 -0
  120. package/types/runtime/reactive.d.ts.map +1 -1
  121. package/types/runtime/row-key.d.ts +2 -0
  122. package/types/runtime/row-key.d.ts.map +1 -0
  123. package/types/runtime/swap-focus.d.ts +2 -0
  124. package/types/runtime/swap-focus.d.ts.map +1 -1
  125. package/types/runtime/swap-kept.d.ts.map +1 -1
  126. package/types/server/app-stages.d.ts +3 -1
  127. package/types/server/app-stages.d.ts.map +1 -1
  128. package/types/server/app.d.ts +3 -1
  129. package/types/server/app.d.ts.map +1 -1
  130. package/types/server/client.d.ts +2 -0
  131. package/types/server/client.d.ts.map +1 -1
  132. package/types/server/dev.d.ts +1 -0
  133. package/types/server/dev.d.ts.map +1 -1
  134. package/types/server/kept-exports.d.ts.map +1 -1
  135. package/types/server/render-document.d.ts.map +1 -1
  136. package/types/server/render.d.ts +2 -2
  137. package/types/server/render.d.ts.map +1 -1
@@ -38,7 +38,7 @@ import { avifQuality, webpQuality, writeImageVariants, writeRemoteVariants } fro
38
38
  import { setImageColors } from '../server/image-color'
39
39
  import { assetFiles, hookPrerendered } from '../server/page-hook'
40
40
  import { prerenderPages } from '../server/prerender'
41
- import { remoteImages, remotePatterns } from '../server/remote'
41
+ import { remoteAllowed, remoteImages, remotePatterns } from '../server/remote'
42
42
  import { contextReadsOf, routeMounts, slashedPath } from '../server/routes'
43
43
  import { configuredFiles, linkStoredFiles } from '../server/storage'
44
44
  import { budgetLints, checkBudget, footprintLints } from './budget'
@@ -49,6 +49,7 @@ import { cachedCopies, cachedDictionaryCopies, pruneCopies, pruneDictionaryCopie
49
49
  import { writeCachedFavicons } from './favicons'
50
50
  import { inWalkScope } from './files'
51
51
  import { routeFootprints } from './footprint'
52
+ import { recordIslandImages } from './island-images'
52
53
  import { restoreKept, setAsideKept } from './kept'
53
54
  import { codecWarnings, iconSetPackages, iconSetWarnings, NOTICES_FILE, packagesOf, thirdPartyNotices } from './licenses'
54
55
  import { readStoredReport, storedReport, writeStoredReport } from './report'
@@ -403,7 +404,8 @@ async function bundleStage(project: Project, exported: boolean, analyze: boolean
403
404
  if (exported)
404
405
  refuseStaticConfig(config)
405
406
 
406
- const client = await buildClient(root, clientOptionsOf(config, project.mode, { exported, report: analyze || (project.config.budget?.js !== undefined && lintLevel('over-budget', project.config.lints) !== 'allow') ? 'modules' : 'sizes' }))
407
+ const patterns = exported ? await remotePatterns(config.assets?.images?.remote?.hosts) : []
408
+ const client = await buildClient(root, clientOptionsOf(config, project.mode, { exported, ...exported && { staticImages: { allowed: (src: string) => remoteAllowed(src, patterns) } }, report: analyze || (project.config.budget?.js !== undefined && lintLevel('over-budget', project.config.lints) !== 'allow') ? 'modules' : 'sizes' }))
407
409
 
408
410
  // A static host cannot pick a format by `Accept`, so an export links WebP alone.
409
411
  const avif = exported ? undefined : avifQuality(config.assets?.images)
@@ -475,11 +477,15 @@ async function outputStage(project: Project, exported: boolean, client: ClientBu
475
477
  // Read to point a redirect's lint at its line, only when there is one to point at.
476
478
  const configSource = checking && config.redirects !== undefined && await Bun.file(configFile).exists() ? await Bun.file(configFile).text() : undefined
477
479
 
480
+ const imagePatterns = await remotePatterns(config.assets?.images?.remote?.hosts)
481
+ // The pages recorded the variants they link, and the islands' own, which no page rendered, go in beside them.
482
+ const islandImageLints = await recordIslandImages(client.dir, client.islandImages, src => remoteAllowed(src, imagePatterns), { checking, lints: config.lints })
483
+
478
484
  // The heads are the check's to read, so a build without checking skips them with it.
479
- const linted = [...checking ? [...pageSeoLints(config, rendered, exported), ...siteSeoLints(config, rendered, others, { configFile, configSource, exported, unseen: hasUnseenPages(routes, rendered, others, exported, paths.routes), skipConfigChains: true }), ...unkeptPageLints(config, [...stops.values()]), ...pageStructureLints(config, rendered)] : [], ...budgetLints(config.budget, config.lints, sizes, routes, client.report)]
485
+ const linted = [...checking ? [...pageSeoLints(config, rendered, exported), ...siteSeoLints(config, rendered, others, { configFile, configSource, exported, unseen: hasUnseenPages(routes, rendered, others, exported, paths.routes), skipConfigChains: true }), ...unkeptPageLints(config, [...stops.values()]), ...pageStructureLints(config, rendered)] : [], ...islandImageLints, ...budgetLints(config.budget, config.lints, sizes, routes, client.report)]
480
486
 
481
487
  // Remote originals are kept between builds, revalidated as the image route does.
482
- const remote = remoteImages(cacheDir(root, 'remote'), await remotePatterns(config.assets?.images?.remote?.hosts), undefined, undefined, remoteLimits(config.assets?.images))
488
+ const remote = remoteImages(cacheDir(root, 'remote'), imagePatterns, undefined, undefined, remoteLimits(config.assets?.images))
483
489
 
484
490
  await writeImageVariants(client.dir, webpQuality(config.assets?.images), cacheDir(root, 'variants'), { avif: exported ? undefined : avifQuality(config.assets?.images), onImage: imageProgress(report) })
485
491
  report({ step: 'writing images, cards and favicons' })
@@ -3,7 +3,7 @@ import type { Project } from '../project'
3
3
  import type { ClientBuild } from '../server/client'
4
4
  import type { Redirects } from '../server/redirects'
5
5
  import { existsSync } from 'node:fs'
6
- import { cp, mkdir, readdir, rm } from 'node:fs/promises'
6
+ import { cp, mkdir, readdir, rename, rm } from 'node:fs/promises'
7
7
  import { dirname, join, relative, resolve, sep } from 'node:path'
8
8
  import process from 'node:process'
9
9
  import { Elysia } from 'elysia'
@@ -71,14 +71,36 @@ function inside(out: string, name: string): string {
71
71
  return file
72
72
  }
73
73
 
74
- // Writes the whole site to `outdir`, as any static host serves it: every prerendered page, the browser build under `/_kay/`, the public files, the sitemap, feeds and favicons, `404.html`, and a page for each redirect.
74
+ // Writes the whole site to a folder beside `outdir` and moves it over `outdir` once it is complete, so a host serving `outdir` always finds a whole export: the last one until the new one is in place, and still the last one when the export fails.
75
+ // The site is what any static host serves: every prerendered page, the browser build under `/_kay/`, the public files, the sitemap, feeds and favicons, `404.html`, and a page for each redirect.
75
76
  // Each page goes in as `about.html` and `about/index.html`, which every host finds for `/about` and `/about/` alike, beside the compressed copies a host may send as they are.
76
77
  export async function exportStatic(project: Project, client: ClientBuild, outdir: string): Promise<StaticExport> {
77
- const { root, config, paths: { public: publicDir, output } } = project
78
+ // Files still being written when one fails, which finish before the staged folder is removed.
79
+ const pending = new Set<Promise<unknown>>()
78
80
  const out = resolve(outdir)
79
81
 
80
- refuseStaticConfig(config)
81
- await clear(root, out)
82
+ refuseStaticConfig(project.config)
83
+ await checkOutput(project.root, out)
84
+ await removeLeftovers(out)
85
+ await mkdir(stagingOf(out), { recursive: true })
86
+ // Marked first, so the folder is one an export wrote once it is in place, and a later export may clear it.
87
+ await Bun.write(join(stagingOf(out), MARKER), '')
88
+
89
+ try {
90
+ const site = await writeSite(project, client, stagingOf(out), pending)
91
+
92
+ await swapIn(out)
93
+
94
+ return site
95
+ }
96
+ finally {
97
+ await Promise.allSettled(pending)
98
+ await rm(stagingOf(out), { recursive: true, force: true })
99
+ }
100
+ }
101
+
102
+ async function writeSite(project: Project, client: ClientBuild, out: string, pending: Set<Promise<unknown>>): Promise<StaticExport> {
103
+ const { root, config, paths: { public: publicDir, output } } = project
82
104
 
83
105
  const pagesDir = join(output, PRERENDERED_DIR)
84
106
  const built = [...client.pages]
@@ -90,19 +112,25 @@ export async function exportStatic(project: Project, client: ClientBuild, outdir
90
112
  const limit = limiter(FILES_AT_ONCE)
91
113
  let failed = false
92
114
  // The first failure stops the files still waiting for their turn, as a loop stopped at it.
93
- const writing = async <T>(task: () => Promise<T>): Promise<T | undefined> => limit(async () => {
94
- if (failed)
95
- return undefined
115
+ const writing = async <T>(task: () => Promise<T>): Promise<T | undefined> => {
116
+ const running = limit(async () => {
117
+ if (failed)
118
+ return undefined
96
119
 
97
- try {
98
- return await task()
99
- }
100
- catch (error) {
101
- failed = true
120
+ try {
121
+ return await task()
122
+ }
123
+ catch (error) {
124
+ failed = true
102
125
 
103
- throw error
104
- }
105
- })
126
+ throw error
127
+ }
128
+ })
129
+
130
+ pending.add(running)
131
+
132
+ return running
133
+ }
106
134
 
107
135
  await Promise.all(built.flatMap(([path, page]) => pageFiles(path).flatMap(target => ['', ...COPIES].map(async copy => writing(async () => {
108
136
  const source = join(pagesDir, `${page.file}${copy}`)
@@ -236,24 +264,71 @@ function overProject(root: string, out: string): boolean {
236
264
  return out === root || root.startsWith(out + sep) || out.startsWith(join(root, 'src') + sep) || out === join(root, 'src')
237
265
  }
238
266
 
239
- // The last export, which a build removes first so its pages, still in the folder, are no source of the stylesheets: only a folder an export wrote.
267
+ // Where an export is written before it replaces `out`, and where the last one waits to be removed: beside it, so the move is a rename on one filesystem.
268
+ function stagingOf(out: string): string {
269
+ return `${out}.kay-staging`
270
+ }
271
+
272
+ function asideOf(out: string): string {
273
+ return `${out}.kay-old`
274
+ }
275
+
276
+ // What an export killed halfway left beside `out`.
277
+ async function removeLeftovers(out: string): Promise<void> {
278
+ await Promise.all([stagingOf(out), asideOf(out)].map(async folder => rm(folder, { recursive: true, force: true })))
279
+ }
280
+
281
+ // Whether git ignores the folder, which Tailwind then leaves out of its scan of the project.
282
+ async function ignoredByGit(root: string, out: string): Promise<boolean> {
283
+ try {
284
+ const check = Bun.spawn(['git', '-C', root, 'check-ignore', '-q', '--', `${out}/`], { stdout: 'ignore', stderr: 'ignore', stdin: 'ignore' })
285
+
286
+ return await check.exited === 0
287
+ }
288
+ catch {
289
+ return false
290
+ }
291
+ }
292
+
293
+ // The last export, which a build removes first when Tailwind would scan its pages as sources of the stylesheets: only a folder an export wrote, and none git ignores, which stays for a host to serve until the new export replaces it.
240
294
  export async function removeLastExport(root: string, out: string): Promise<void> {
241
- if (!overProject(root, out) && existsSync(join(out, MARKER)))
295
+ if (overProject(root, out))
296
+ return
297
+
298
+ await removeLeftovers(out)
299
+
300
+ if (existsSync(join(out, MARKER)) && !await ignoredByGit(root, out))
242
301
  await rm(out, { recursive: true, force: true })
243
302
  }
244
303
 
304
+ // The staged export in place of the last one: that one moved aside, the new one renamed in, the old one removed.
305
+ async function swapIn(out: string): Promise<void> {
306
+ const aside = asideOf(out)
307
+
308
+ if (existsSync(out))
309
+ await rename(out, aside)
310
+
311
+ try {
312
+ await rename(stagingOf(out), out)
313
+ }
314
+ catch (error) {
315
+ // The last export goes back, so a failed move leaves it in place.
316
+ if (existsSync(aside))
317
+ await rename(aside, out)
318
+
319
+ throw error
320
+ }
321
+
322
+ await rm(aside, { recursive: true, force: true })
323
+ }
324
+
245
325
  // A directory kay may write to: never the project or what holds it, and one with files in it only when an export wrote them.
246
- async function clear(root: string, out: string): Promise<void> {
326
+ async function checkOutput(root: string, out: string): Promise<void> {
247
327
  if (overProject(root, out))
248
328
  throw new KayError('export-output-dir', `kay: a static export into ${relative(process.cwd(), out) || '.'} would write over the project; give it a directory of its own, such as dist`)
249
329
 
250
330
  if (existsSync(out) && (await readdir(out)).length > 0 && !existsSync(join(out, MARKER)))
251
331
  throw new KayError('export-output-dir', `kay: ${relative(process.cwd(), out)} holds files a static export did not write; empty it or give another directory`)
252
-
253
- await rm(out, { recursive: true, force: true })
254
- await mkdir(out, { recursive: true })
255
- // Marked first, so an export failing halfway leaves a directory the next one may clear.
256
- await Bun.write(join(out, MARKER), '')
257
332
  }
258
333
 
259
334
  // The files a page path is written to: `/` as `index.html`, any other both ways.
@@ -112,24 +112,29 @@ function renames(call: Call, base: number): Edit[] {
112
112
  return edits
113
113
  }
114
114
 
115
- // The options the lowercase builder needs to read as the PascalCase one did: a list takes `max` where it had none (the lowercase one stops at 1,000 items, except a list of files), and an object `extra: 'strip'` (the lowercase one refuses a key its shape lacks). Undefined when the options are not an object literal of known keys, which the fix cannot add to.
116
- function keptOptions(call: Call): string[] | undefined {
115
+ // The options the lowercase builder needs to read as the PascalCase one did: a string takes `max` where it had none, as the lowercase one stops at 10,000 characters, unless it is in an action's input or an API body, which capped it there already; a list takes `max` where it had none (the lowercase one stops at 1,000 items, except a list of files), and an object `extra: 'strip'` (the lowercase one refuses a key its shape lacks). Undefined when the options are not an object literal of known keys, which the fix cannot add to.
116
+ function keptOptions(call: Call, bounded: boolean): string[] | undefined {
117
117
  const index = BUILDERS[call.name]!.options
118
118
  const options = call.node.arguments[index]
119
119
  const keys = new Set<string>()
120
+ // The builders whose old behaviour the fix must write an option for; a string only outside the contexts that capped it already.
121
+ const writes = call.name === 'Array' || call.name === 'Object' || (call.name === 'String' && !bounded)
120
122
 
121
123
  if (options !== undefined && options.type !== 'ObjectExpression')
122
- return call.name === 'Array' || call.name === 'Object' ? undefined : []
124
+ return writes ? undefined : []
123
125
 
124
126
  for (const entry of options?.properties ?? []) {
125
127
  const name = keyName(entry)
126
128
 
127
129
  if (name === undefined)
128
- return call.name === 'Array' || call.name === 'Object' ? undefined : []
130
+ return writes ? undefined : []
129
131
 
130
132
  keys.add(name)
131
133
  }
132
134
 
135
+ if (call.name === 'String')
136
+ return bounded || keys.has('max') || keys.has('maxLength') ? [] : ['max: Number.MAX_SAFE_INTEGER']
137
+
133
138
  if (call.name === 'Object')
134
139
  return keys.has('extra') ? [] : ['extra: \'strip\'']
135
140
 
@@ -141,6 +146,105 @@ function keptOptions(call: Call): string[] | undefined {
141
146
  return keys.has('max') || keys.has('maxItems') || (item && FILES.has(builderCallName(item))) ? [] : ['max: Number.MAX_SAFE_INTEGER']
142
147
  }
143
148
 
149
+ const BODY_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete'])
150
+
151
+ // The schemas that are the `const` of a file at its top level, by name, and the names the file exports, whose uses beyond it are unknown.
152
+ function topLevelSchemas(ast: Program): { bound: Map<string, Node>, exported: Set<string> } {
153
+ const bound = new Map<string, Node>()
154
+ const exported = new Set<string>()
155
+
156
+ for (const statement of ast.body) {
157
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
158
+
159
+ if (statement.type === 'ExportNamedDeclaration') {
160
+ for (const specifier of statement.specifiers)
161
+ exported.add((specifier.local as { name?: string }).name ?? '')
162
+ }
163
+
164
+ if (declaration?.type !== 'VariableDeclaration' || declaration.kind !== 'const')
165
+ continue
166
+
167
+ for (const entry of declaration.declarations) {
168
+ if (entry.id.type !== 'Identifier' || !entry.init)
169
+ continue
170
+
171
+ bound.set(entry.id.name, entry.init)
172
+
173
+ if (statement.type === 'ExportNamedDeclaration')
174
+ exported.add(entry.id.name)
175
+ }
176
+ }
177
+
178
+ return { bound, exported }
179
+ }
180
+
181
+ // The nodes of the schemas kay caps an unbounded string in at 10,000 characters already: an action's input, and the `body` of an API route (a call of a method taking a path literal first, which leaves out `client.post(url, { body })`). A schema held in a top-level `const` is capped when every use of the name is one of those and the file does not export it. What it cannot tell is left out, so the fix writes the bound that keeps the old behaviour there.
182
+ function cappedByKay(ast: Program, actions: Set<string>): Set<Node> {
183
+ const capped = new Set<Node>()
184
+ const uses = new Set<Node>()
185
+ const take = (schema: Node) => {
186
+ if (schema.type === 'Identifier')
187
+ uses.add(schema)
188
+ else
189
+ walk(schema, node => capped.add(node))
190
+ }
191
+
192
+ walk(ast, (node) => {
193
+ if (node.type !== 'CallExpression')
194
+ return
195
+
196
+ const [first, ...rest] = node.arguments
197
+
198
+ if (node.callee.type === 'Identifier' && actions.has(node.callee.name) && first)
199
+ take(first)
200
+
201
+ if (node.callee.type !== 'MemberExpression' || node.callee.computed || node.callee.property.type !== 'Identifier' || !BODY_METHODS.has(node.callee.property.name))
202
+ return
203
+
204
+ if (first?.type !== 'Literal' || typeof first.value !== 'string' || !first.value.startsWith('/'))
205
+ return
206
+
207
+ for (const argument of rest) {
208
+ if (argument.type !== 'ObjectExpression')
209
+ continue
210
+
211
+ for (const entry of argument.properties) {
212
+ if (entry.type === 'Property' && keyName(entry) === 'body')
213
+ take(entry.value)
214
+ }
215
+ }
216
+ })
217
+
218
+ const { bound, exported } = topLevelSchemas(ast)
219
+ const declared = new Set<Node>()
220
+
221
+ for (const statement of ast.body) {
222
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement
223
+
224
+ if (declaration?.type === 'VariableDeclaration') {
225
+ for (const entry of declaration.declarations)
226
+ declared.add(entry.id)
227
+ }
228
+ }
229
+
230
+ const references = new Map<string, number>()
231
+
232
+ walk(ast, (node) => {
233
+ if (node.type === 'Identifier' && bound.has(node.name) && !declared.has(node))
234
+ references.set(node.name, (references.get(node.name) ?? 0) + 1)
235
+ })
236
+
237
+ for (const [name, init] of bound) {
238
+ const total = references.get(name) ?? 0
239
+ const cappedUses = [...uses].filter(use => use.type === 'Identifier' && use.name === name).length
240
+
241
+ if (total > 0 && total === cappedUses && !exported.has(name))
242
+ walk(init, node => capped.add(node))
243
+ }
244
+
245
+ return capped
246
+ }
247
+
144
248
  function builderCallName(node: Node): string {
145
249
  return node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && node.callee.property.type === 'Identifier' ? node.callee.property.name : ''
146
250
  }
@@ -232,7 +336,7 @@ function envRecord(node: Node, records: Set<string>, receivers: Set<string>, bas
232
336
  }
233
337
 
234
338
  // The PascalCase builders of `s`, which kay 1.106 replaces with its own lowercase ones, and the `'2m'` sizes of a file field, which are `'2mb'` as every size is.
235
- // Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. `s.Optional(x)` of one of these builders is `optional: true` in its options; an `s.Array` takes `max: Number.MAX_SAFE_INTEGER` and an `s.Object` `extra: 'strip'`, which keeps what they did.
339
+ // Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. `s.Optional(x)` of one of these builders is `optional: true` in its options; an `s.Array`, and an `s.String` with no bound outside an action's input and an API body, takes `max: Number.MAX_SAFE_INTEGER`, and an `s.Object` `extra: 'strip'`, which keeps what they did.
236
340
  export async function schemaBuilders(root: string, options: CheckOptions): Promise<CheckDiagnostic[]> {
237
341
  if (lintLevel('deprecated-schema-builders', options.lints) === 'allow')
238
342
  return []
@@ -241,6 +345,7 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
241
345
  for (const { ast, base, text } of parsed) {
242
346
  const receivers = importsOf(ast, source => KAY.test(source), 's').locals
243
347
  const records = importsOf(ast, source => KAY.test(source), 'defineEnv').locals
348
+ const capped = cappedByKay(ast, importsOf(ast, source => KAY.test(source), 'action').locals)
244
349
 
245
350
  if (receivers.size === 0)
246
351
  continue
@@ -264,7 +369,7 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
264
369
  const [inner, ...others] = call.node.arguments
265
370
  const wrapped = inner === undefined ? undefined : builderCall(inner, receivers)
266
371
  const known = wrapped && wrapped.name !== 'Public' && BUILDERS[wrapped.name] && !taken.has(inner!)
267
- const kept = known ? keptOptions(wrapped) : undefined
372
+ const kept = known ? keptOptions(wrapped, capped.has(wrapped.node)) : undefined
268
373
  const edit = known && kept ? addOptions(wrapped, base, ['optional: true', ...kept]) : undefined
269
374
 
270
375
  // Anything but a builder of `s`, such as the `imageField()` of kay/content, has no `optional` option to write yet.
@@ -311,12 +416,12 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
311
416
  }
312
417
 
313
418
  if (builder && !taken.has(node)) {
314
- const kept = keptOptions(call)
419
+ const kept = keptOptions(call, capped.has(node))
315
420
  const edit = kept && kept.length > 0 ? addOptions(call, base, kept) : undefined
316
421
  const object = call.name === 'Object' ? 'unknown keys are refused by `s.object` where kay reads the schema itself, where `s.Object` let them by, so the fix writes `extra: \'strip\'` to keep the old way' : ''
317
422
  const message = call.name === 'UnionKeys' || call.name === 'UnionEnum'
318
423
  ? '`s.enum()` takes the values, or a record whose keys are the values, since 1.106, in place of `s.UnionEnum` and `s.UnionKeys`; the old forms work until 2.0'
319
- : `\`s.${call.name}\` is \`s.${builder.name}\` since 1.106, kay's own lowercase builders with short options (\`min\`, \`max\`, \`optional\`) replacing the PascalCase ones of TypeBox${object ? `; ${object}` : ''}; the old form works until 2.0${call.name === 'Array' ? '; `s.list` is at most 1,000 items where `s.Array` had no limit, so the fix writes `max: Number.MAX_SAFE_INTEGER`' : ''}`
424
+ : `\`s.${call.name}\` is \`s.${builder.name}\` since 1.106, kay's own lowercase builders with short options (\`min\`, \`max\`, \`optional\`) replacing the PascalCase ones of TypeBox${object ? `; ${object}` : ''}; the old form works until 2.0${call.name === 'Array' ? '; `s.list` is at most 1,000 items where `s.Array` had no limit, so the fix writes `max: Number.MAX_SAFE_INTEGER`' : ''}${call.name === 'String' ? '; `s.string` is at most 10,000 characters where `s.String` had no limit, which an action\'s input and an API body already had, so the fix writes `max: Number.MAX_SAFE_INTEGER` anywhere else' : ''}`
320
425
 
321
426
  // Without the option that keeps the old behaviour the rename would change it, so the fix is left to the app.
322
427
  const keeps = kept !== undefined && (kept.length === 0 || edit !== undefined)
@@ -323,11 +323,11 @@ async function libraryShadows(root: string, options: CheckOptions, own: string[]
323
323
  })])
324
324
  const unreached = new Set<string>()
325
325
 
326
- await Promise.all(followed.filter(library => library.extension).map(async (library) => {
326
+ await Promise.all(followed.map(async (library) => {
327
327
  const own = programs.some(program => program.library === library)
328
328
 
329
329
  // A link left from a run in which the package was a program of its own would take what is written under `node_modules` to that program's folder.
330
- if (!own)
330
+ if (!own && library.extension)
331
331
  await dropLink(dirname(shadowPath(root, join(library.dir, 'x'))))
332
332
 
333
333
  await linkDependencies(root, library, own, tree)
@@ -423,7 +423,7 @@ async function dropLink(path: string) {
423
423
  catch {}
424
424
  }
425
425
 
426
- // A bare import climbs from the shadow, not from the package, so the dependencies the package installs are linked beside its shadows: its own `node_modules`, and the ones above it that the app's ancestors do not include.
426
+ // A bare import climbs from the shadow, not from the package, so the dependencies the package installs are linked beside its shadows, under bun's isolated install, where they sit beside the package's real path in `node_modules/.bun` and not in the app's `node_modules`, so an app need not list them: its own `node_modules`, and the ones above it that the app's ancestors do not include.
427
427
  async function linkDependencies(root: string, { dir, realDir }: KayLibrary, own: boolean, tree: ShadowTree) {
428
428
  const types = projectPaths(root).types
429
429
  // The package of a program is shadowed beside its real path.
@@ -187,7 +187,7 @@ export function generate(file: KayFile, script: ScriptAnalysis, server: ServerAn
187
187
  // The module around a template, alike for every output mode: its imports, the server fence's `load`, the component's signature, props and script, and its export; the template renders through the writer of the mode.
188
188
  class ModuleShell {
189
189
  private readonly b: CodeBuilder
190
- private readonly sites: Sites = { rows: new Set(), consts: new Map(), loopItems: new Set(), snippets: new Set(), props: new Map() }
190
+ private readonly sites: Sites = { rows: new Set(), blocks: new Set(), consts: new Map(), loopItems: new Set(), snippets: new Set(), props: new Map() }
191
191
  private readonly src: string
192
192
  private readonly mode: OutputMode
193
193
  private readonly kind: IslandKind
@@ -11,7 +11,7 @@ import { FormHere } from './dom-here'
11
11
  import { propertyBindings } from './dom-property'
12
12
  import { addHandler, listenerOptions } from './event-modifiers'
13
13
  import { decodeEntities, isFunctionAt } from './expression'
14
- import { addKeyParameters, addRowItem, childItems, constDeclaration, contentOf, errorParagraphArguments, isDeclaration, rowKeying, slotValue, soleDynamic } from './items'
14
+ import { addKeyParameters, addRowItem, addSlotCall, childItems, constDeclaration, contentOf, errorParagraphArguments, isDeclaration, rowKeying, slotValue, soleDynamic } from './items'
15
15
  import { addBindWrite, bindRead, END_MARKER, escapeStaticAttribute, escapeText, helperName, RAW_ELEMENTS, START_MARKER, TemplateWriter, VOID_ELEMENTS } from './markup'
16
16
  import { SUBJECT } from './names'
17
17
  import { addGroupChecked, checksMarkup, groupValue, staticAttributeText } from './plan'
@@ -157,7 +157,8 @@ export class DomTemplate extends TemplateWriter {
157
157
  b.add(`${helperName(this.scoping)}((`).addSource(form).add('), () => ')
158
158
 
159
159
  if (item.node.outlet) {
160
- slotValue(b, item.node)
160
+ if (!addSlotCall(b, this.src, item.node, helperName('slotCall')))
161
+ slotValue(b, item.node)
161
162
  }
162
163
  else {
163
164
  b.add('{ const KayC = ')
@@ -167,7 +168,7 @@ export class DomTemplate extends TemplateWriter {
167
168
 
168
169
  b.add(')')
169
170
  }
170
- else {
171
+ else if (!addSlotCall(b, this.src, item.node, helperName('slotCall'))) {
171
172
  slotValue(b, item.node)
172
173
  }
173
174
 
@@ -0,0 +1,15 @@
1
+ import type { KayFile } from './ast'
2
+ import type { ScriptAnalysis } from './script'
3
+ import type { ServerAnalysis } from './script-server'
4
+ import { templateWords } from './template-reads'
5
+
6
+ // The fence of a page that is an island with only the server values its script or template read, for the HTML output that builds the island's props: a value only the fence reads stays on the server.
7
+ // The analysis pass tells the reads from scopes, so a dynamic access cannot hide one; it leaves out the template's handlers, refs, transitions and loop keys, so any name a template expression writes stays too, and a fence that did not parse hands every one over.
8
+ export function handedServer(island: boolean, output: string | undefined, file: KayFile, script: ScriptAnalysis, server: ServerAnalysis | undefined, unread: ReadonlySet<number>): ServerAnalysis | undefined {
9
+ if (!island || output !== 'html' || !server || script.unparsed !== undefined || server.unparsed !== undefined)
10
+ return server
11
+
12
+ const words = new Set(templateWords(file))
13
+
14
+ return { ...server, data: server.data.filter(data => !unread.has(data.local.start) || words.has(data.name)) }
15
+ }
@@ -2,10 +2,10 @@ import type { AwaitAlert } from './names'
2
2
  import { helperName } from './markup'
3
3
 
4
4
  // The `kay/html` helpers static server output calls, each imported under a `Kay` name.
5
- const HTML_HELPERS = ['attempt', 'attribute', 'checkedMarkup', 'child', 'className', 'component', 'componentClass', 'currentPage', 'dynamic', 'element', 'errorParagraph', 'fieldDescribed', 'formConstraints', 'formKey', 'formOptions', 'formType', 'handParts', 'head', 'html', 'imageAttributes', 'innerMarkup', 'leadingNewline', 'linkHref', 'localHref', 'loop', 'memo', 'merge', 'nonEmptyAttribute', 'omit', 'outsideLink', 'partClass', 'partHanded', 'partProps', 'raw', 'rawData', 'rawTyped', 'refillOptions', 'schemaFill', 'selectOptions', 'serverIsland', 'show', 'spreadAttributes', 'spreadWith', 'style', 'untrack']
5
+ const HTML_HELPERS = ['attempt', 'attribute', 'checkedMarkup', 'child', 'className', 'component', 'componentClass', 'currentPage', 'dynamic', 'element', 'errorParagraph', 'fieldDescribed', 'formConstraints', 'formKey', 'formOptions', 'formType', 'handParts', 'head', 'html', 'imageAttributes', 'innerMarkup', 'leadingNewline', 'linkHref', 'localHref', 'loop', 'memo', 'merge', 'nonEmptyAttribute', 'omit', 'outsideLink', 'param', 'partClass', 'partHanded', 'partProps', 'raw', 'rawData', 'rawTyped', 'refillOptions', 'rowKey', 'schemaFill', 'selectOptions', 'serverIsland', 'show', 'spreadAttributes', 'spreadWith', 'style', 'untrack']
6
6
 
7
7
  // The `kay/dom` helpers browser output calls, each imported under a `Kay` name.
8
- const DOM_HELPERS = ['append', 'attribute', 'branches', 'checkedMarkup', 'choose', 'close', 'component', 'componentClass', 'effect', 'errorParagraph', 'fragment', 'handParts', 'holdSubmits', 'insert', 'listen', 'listenSubmit', 'listenSubmitWith', 'listenWith', 'markers', 'memo', 'merge', 'omit', 'outside', 'part', 'partClass', 'partHanded', 'partProps', 'property', 'ref', 'setClass', 'setStyle', 'spreadAttributes', 'spreadWith', 'template', 'text', 'transition', 'untrack']
8
+ const DOM_HELPERS = ['append', 'attribute', 'branches', 'checkedMarkup', 'choose', 'close', 'component', 'componentClass', 'effect', 'errorParagraph', 'fragment', 'handParts', 'holdSubmits', 'insert', 'listen', 'listenSubmit', 'listenSubmitWith', 'listenWith', 'markers', 'memo', 'merge', 'omit', 'outside', 'param', 'part', 'partClass', 'partHanded', 'partProps', 'property', 'ref', 'setClass', 'setStyle', 'slotCall', 'spreadAttributes', 'spreadWith', 'template', 'text', 'transition', 'untrack']
9
9
  // The helpers in modules of their own, as their runtimes weigh on a page whose islands use none of them: the module of each is only loaded by a page with an island that compiles to it.
10
10
  const APART = [['kay/dom-loop', ['loop', 'rowKey']], ['kay/dom-await', ['awaited']], ['kay/dom-try', ['attempt']], ['kay/dom-spread', ['dynamic', 'spread']], ['kay/dom-image', ['image']], ['kay/pending', ['pendingCall']]] as const
11
11
 
@@ -12,7 +12,7 @@ import { valuesOf } from './form-info'
12
12
  import { addClassAttribute, addFieldFill, addSchemaOptions, listsFromSchema, schemaTypeCall } from './html-fields'
13
13
  import { addInitial } from './html-initial'
14
14
  import { Markup } from './html-parts'
15
- import { addRowItem, childItems, constDeclaration, contentOf, errorParagraphArguments, fixedSource, isDeclaration, rowKeying, slotValue, soleDynamic } from './items'
15
+ import { addLoopTail, addRowItem, childItems, constDeclaration, contentOf, errorParagraphArguments, fixedSource, isDeclaration, slotValue, soleDynamic } from './items'
16
16
  import { END_MARKER, escapeStaticAttribute, escapeText, fromRoot, helperName, RAW_ELEMENTS, START_MARKER, TemplateWriter, VOID_ELEMENTS } from './markup'
17
17
  import { LOAD_KEY, PROPS, SUBJECT } from './names'
18
18
  import { addGroupChecked, BEHAVIOUR, checkedContent, describedValue, fieldAriaOf, groupValue } from './plan'
@@ -74,6 +74,7 @@ export class HtmlTemplate extends TemplateWriter {
74
74
 
75
75
  constructor(b: CodeBuilder, src: string, facts: TemplateFacts, ownMarkup: (name: string, at: number) => boolean, private readonly options: HtmlOptions = {}) {
76
76
  super(b, src, facts, ownMarkup)
77
+ this.accessorBlocks = options.accessorLoops === true
77
78
  this.mergesAtRuntime = options.classMerge === true
78
79
  }
79
80
 
@@ -336,13 +337,8 @@ export class HtmlTemplate extends TemplateWriter {
336
337
  b.add(', () => ')
337
338
  this.markup(node.fallback)
338
339
  }
339
- else if (this.options.accessorLoops) {
340
- b.add(', undefined')
341
- }
342
-
343
- if (this.options.accessorLoops)
344
- b.add(rowKeying(node, this.src).kind === 'positional' ? ', "positional"' : ', "keyed"')
345
340
 
341
+ addLoopTail(b, node, this.src, this.options.accessorLoops === true, helperName('rowKey'))
346
342
  b.add(')')
347
343
  })
348
344
  }
@@ -17,6 +17,7 @@ import { wrapActionButtons } from './button-forms'
17
17
  import { generate, isInteractive, islandCause, lineOf } from './codegen'
18
18
  import { asyncReplies, cssImportsWithoutText, missingCaptchas, onceReadProps, separatePageSettings, serverOnlyImports, unboundedFields } from './fence-checks'
19
19
  import { openRedirects } from './fence-redirects'
20
+ import { handedServer } from './handed-data'
20
21
  import { cwd, scopeStorage } from './host'
21
22
  import { ignoredIslandExport, islandMessages, withAlertKeys } from './island-arguments'
22
23
  import { describeCause } from './island-cause'
@@ -342,7 +343,7 @@ export function compileKay(original: string, filename: string, options: CompileO
342
343
  const found = findRewrites({ code: analysis.builder.code, map: analysis.builder.map(), sites: analysis.sites, values, dom: options.output === 'dom', source, templateStart: file.templateStart, imported, component: componentName(filename), check: options.check, fixedPage: routeFile })
343
344
  const fences = [file.script, file.server, file.module].map(span => span ? source.slice(span.start, span.end) : '').join('\n')
344
345
  const name = freeName(componentName(filename), fences, found.findings.globalReads)
345
- const final = generate(file, script, server, { ...generateOptions, name, rewrites: found.plan.rewrites, writes: found.plan.writes, values: found.plan.values })
346
+ const final = generate(file, script, handedServer(island !== undefined, options.output, file, script, server, found.findings.unread), { ...generateOptions, name, rewrites: found.plan.rewrites, writes: found.plan.writes, values: found.plan.values })
346
347
  // A fence that did not parse at all reaches the code unanalysed, so what the rewrites say of its names is only noise beside its syntax error.
347
348
  const unparsed = script.unparsed !== undefined || server?.unparsed !== undefined
348
349
  const diagnostics = [
@@ -469,6 +470,7 @@ function takeBlock(file: KayFile, filename: string, options: CompileOptions, scr
469
470
  return undefined
470
471
 
471
472
  file.template.splice(index, 1)
473
+ file.facts = undefined
472
474
 
473
475
  let lineStart = block.start
474
476
  const written = file.source.slice(block.start, block.end).split('\n').map((text) => {