@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
@@ -0,0 +1,130 @@
1
+ import type { ImportedComponent, ImportedComponents } from '../compiler/lazy-imports'
2
+ import type { ImportBinding } from '../compiler/script-shared'
3
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
4
+ import { basename, relative } from 'node:path'
5
+ import { deferredProps, eagerReach, lazyImports } from '../compiler/lazy-imports'
6
+ import { parseKay } from '../compiler/parser'
7
+ import { resolveFrom } from './files'
8
+ import { fences } from './libraries'
9
+
10
+ // A default import of a `.kay` module, as a script writes it on a line of its own.
11
+ const KAY_IMPORT = /^[ \t]*import\s+([\w$]+)\s+from\s*(['"])([^'"]+\.kay)\2/gm
12
+
13
+ interface Facts {
14
+ // The own stamp of the module and of each module its answer reads: the facts are read again once any changes.
15
+ stamps: Map<string, string>
16
+ deferred: string[]
17
+ size: number
18
+ // The paths of the components the module loads with it, which a module importing it does not need a chunk for.
19
+ reach: string[]
20
+ }
21
+
22
+ // What a key may not hold, as the page writes keys apart by a space inside an attribute.
23
+ const UNSAFE_KEY = /[^\w.-]/g
24
+
25
+ const known = new Map<string, Facts>()
26
+
27
+ function stampOf(path: string): string | undefined {
28
+ const stats = statSync(path, { throwIfNoEntry: false })
29
+
30
+ return stats ? `${stats.mtimeMs}-${stats.size}` : undefined
31
+ }
32
+
33
+ function importsOf(source: string): ImportBinding[] {
34
+ return [...fences(source).matchAll(KAY_IMPORT)].map(([line, local, , specifier]) => ({ local: local!, imported: 'default', source: specifier!, typeOnly: false, span: { start: 0, end: 0 }, declaration: { start: source.indexOf(line), end: source.indexOf(line) + line.trimEnd().length } }))
35
+ }
36
+
37
+ // The props a component draws only where a branch may not render, which hold when each module it passes a block to says the same of that block: a wrapper of a dialog defers what the dialog does.
38
+ function factsOf(path: string, visiting: ReadonlySet<string>): Facts | undefined {
39
+ const stamp = stampOf(path)
40
+
41
+ if (stamp === undefined || visiting.has(path))
42
+ return undefined
43
+
44
+ const kept = known.get(path)
45
+
46
+ if (kept && [...kept.stamps].every(([module, expected]) => stampOf(module) === expected))
47
+ return kept
48
+
49
+ const source = readFileSync(path, 'utf8')
50
+ const stamps = new Map([[path, stamp]])
51
+ const inside = new Set([...visiting, path])
52
+ const file = parseKay(source)
53
+ const imports = importsOf(source)
54
+ const children: Record<string, ImportedComponent> = {}
55
+
56
+ for (const { source: specifier } of imports) {
57
+ const found = resolveFrom(specifier, path)
58
+ const facts = found === undefined ? undefined : factsOf(found, inside)
59
+
60
+ for (const [module, other] of facts?.stamps ?? [])
61
+ stamps.set(module, other)
62
+
63
+ if (found !== undefined && facts !== undefined)
64
+ children[specifier] = { key: found, deferred: facts.deferred, size: facts.size, reach: facts.reach }
65
+ }
66
+
67
+ const deferred = deferredProps(file, imports, specifier => children[specifier])
68
+ const reach = eagerReach(imports, children, lazyImports(file, imports, children))
69
+ const facts = { stamps, deferred, size: source.length, reach }
70
+
71
+ known.set(path, facts)
72
+
73
+ return facts
74
+ }
75
+
76
+ // What names a lazy component's chunk to the page that draws it and to the build's manifest: the file's name and a hash of its path from the root, the same wherever it is read from.
77
+ export function lazyKey(root: string, path: string): string {
78
+ const name = basename(path, '.kay').replaceAll(UNSAFE_KEY, '_')
79
+
80
+ return `${name}-${Bun.hash(relative(realOf(root), realOf(path)).replaceAll('\\', '/')).toString(36).slice(0, 6)}`
81
+ }
82
+
83
+ // The components whose lazy chunk the build found to be a stub, which then load with the code drawing them.
84
+ const eager = new Set<string>()
85
+
86
+ // Marks components as loading with their importers; whether any was not marked already.
87
+ export function keepEager(keys: Iterable<string>): boolean {
88
+ const before = eager.size
89
+
90
+ for (const key of keys)
91
+ eager.add(key)
92
+
93
+ return eager.size > before
94
+ }
95
+
96
+ // The keys marked so far, which a cache of what depends on the imports the islands make has to key on.
97
+ export function eagerKeys(): string[] {
98
+ return [...eager].sort()
99
+ }
100
+
101
+ // Its path with the links resolved, or as it is when no file is there.
102
+ function realOf(path: string): string {
103
+ try {
104
+ return realpathSync(path)
105
+ }
106
+ catch {
107
+ return path
108
+ }
109
+ }
110
+
111
+ // The `.kay` components a file imports that its templates may draw lazily: each with the key naming its chunk (its path from the root) and the props it draws only inside a branch that may not render.
112
+ export function importedComponents(file: string, source: string, root: string): ImportedComponents {
113
+ const found: Record<string, ImportedComponent> = {}
114
+ const self = realOf(file)
115
+
116
+ for (const { source: specifier } of importsOf(source)) {
117
+ const path = resolveFrom(specifier, file)
118
+
119
+ // A component drawing itself stays eager whatever its import is written as: its module is the one loading, so a chunk would only make its nested draws late.
120
+ if (path !== undefined && realOf(path) === self)
121
+ continue
122
+
123
+ const facts = path === undefined ? undefined : factsOf(path, new Set())
124
+
125
+ if (path !== undefined && facts !== undefined)
126
+ found[specifier] = { key: lazyKey(root, path), deferred: facts.deferred, size: eager.has(lazyKey(root, path)) ? 0 : facts.size, reach: facts.reach.map(other => lazyKey(root, other)) }
127
+ }
128
+
129
+ return found
130
+ }
@@ -0,0 +1,56 @@
1
+ type Outputs = Record<string, { imports: { kind: string, path: string }[] }>
2
+
3
+ // A component's chunk by its key; two files that hash to one key would load each other's code, so that is refused.
4
+ export function noteLazy(manifest: { lazies?: Record<string, string[]> | undefined }, key: string, file: string, chunks: string[]): void {
5
+ const lazies = manifest.lazies ??= {}
6
+
7
+ if (lazies[key] !== undefined && lazies[key].join() !== chunks.join())
8
+ throw new Error(`${file} and another component share the lazy key ${key}: rename one of the files`)
9
+
10
+ lazies[key] = chunks
11
+ }
12
+
13
+ // Every chunk a chunk needs before it can run, itself included.
14
+ export function staticClosure(outputs: Outputs, output: string, seen = new Set<string>()): Set<string> {
15
+ if (seen.has(output))
16
+ return seen
17
+
18
+ seen.add(output)
19
+ for (const imported of outputs[output]?.imports ?? []) {
20
+ if (imported.kind === 'import-statement')
21
+ staticClosure(outputs, imported.path, seen)
22
+ }
23
+
24
+ return seen
25
+ }
26
+
27
+ type Entries = Record<string, { entryPoint?: string | undefined, inputs?: Record<string, { bytesInOutput?: number | undefined }> | undefined }>
28
+
29
+ // What the lazy runtime and a request cost a page, minified: the lazy chunks of a build holding less than this between them leave a page heavier than the code they keep off it.
30
+ const LAZY_PAYOFF = 6000
31
+
32
+ // The keys of the lazy components that do not pay: a chunk that is only a stub, its code sitting in chunks the islands load up front, or all of them when the chunks with code of their own weigh less than `LAZY_PAYOFF` together. The build runs again with these imports eager.
33
+ export function stubKeys(outputs: Entries, keyOf: (entryPoint: string) => string | undefined): string[] {
34
+ const stubs: string[] = []
35
+ const held: string[] = []
36
+ let bytes = 0
37
+
38
+ for (const meta of Object.values(outputs)) {
39
+ const key = meta.entryPoint === undefined ? undefined : keyOf(meta.entryPoint)
40
+
41
+ if (key === undefined)
42
+ continue
43
+
44
+ const own = Object.values(meta.inputs ?? {}).reduce((sum, input) => sum + (input.bytesInOutput ?? 0), 0)
45
+
46
+ if (own === 0) {
47
+ stubs.push(key)
48
+ }
49
+ else {
50
+ held.push(key)
51
+ bytes += own
52
+ }
53
+ }
54
+
55
+ return bytes < LAZY_PAYOFF ? [...stubs, ...held] : stubs
56
+ }
@@ -0,0 +1,31 @@
1
+ import { rm } from 'node:fs/promises'
2
+ import { keepEager } from './lazy-components'
3
+ import { stubKeys } from './lazy-manifest'
4
+
5
+ // The last round builds whatever it finds.
6
+ const ROUNDS = 3
7
+
8
+ class Folded extends Error {}
9
+
10
+ // Marks the lazy components of the build that do not pay (see `stubKeys`) to load with the code drawing them, and ends the round, its files removed, when there were some: what the runtime chunk holds follows the imports the islands make, so the build is searched and run again.
11
+ export async function foldStubs(build: Bun.BuildOutput, nav: { build: Bun.BuildOutput } | undefined, last: boolean, keyOf: (entryPoint: string) => string | undefined): Promise<void> {
12
+ if (last || !build.success || !keepEager(stubKeys(build.metafile!.outputs, keyOf)))
13
+ return
14
+
15
+ await Promise.all([build, nav?.build].flatMap(each => each?.outputs ?? []).map(async output => rm(output.path, { force: true })))
16
+
17
+ throw new Folded()
18
+ }
19
+
20
+ // Runs a build, again when a round folded stubs; the run is told when it is the last.
21
+ export async function inRounds<T>(run: (last: boolean) => Promise<T>): Promise<T> {
22
+ for (let round = 0; ; round++) {
23
+ try {
24
+ return await run(round === ROUNDS - 1)
25
+ }
26
+ catch (error) {
27
+ if (!(error instanceof Folded))
28
+ throw error
29
+ }
30
+ }
31
+ }
@@ -48,6 +48,8 @@ export interface KayPluginOptions {
48
48
  inspect?: boolean | undefined
49
49
  // The classes a later Tailwind class overrides, with which an island's literal classes resolve while compiling.
50
50
  classTable?: ClassTable | undefined
51
+ // False draws every component at once: the bundle of a component mounted by a test, which has no server markup to claim and nothing to wait for.
52
+ lazy?: boolean | undefined
51
53
  // A browser build's API trees, whose modules islands get as stubs, and the modules it leaves to the page, which a worker's bundle takes as the islands do.
52
54
  api?: RouteMount[] | undefined
53
55
  external?: string[] | undefined
@@ -263,7 +265,7 @@ export function kayPlugin(options: KayPluginOptions, workers: string[]): BunPlug
263
265
  const original = await Bun.file(withoutTwin(file)).text()
264
266
  const source = features === undefined ? original : specializedSource(original, features, withoutTwin(file))
265
267
 
266
- const compiled = await transformKayCached(source, file, { target, hydratable: options.hydratable ?? true, root: options.root, pages: options.pages, cacheDir: options.cacheDir, inspect: options.inspect, classTable: options.classTable, variant: features === undefined ? undefined : `${[...features].sort().join('.')}${written === undefined ? '' : `~${[...written].sort().join('.')}`}`, writtenProps: written })
268
+ const compiled = await transformKayCached(source, file, { target, hydratable: options.hydratable ?? true, root: options.root, pages: options.pages, cacheDir: options.cacheDir, inspect: options.inspect, classTable: options.classTable, lazy: options.lazy, variant: features === undefined ? undefined : `${[...features].sort().join('.')}${written === undefined ? '' : `~${[...written].sort().join('.')}`}`, writtenProps: written })
267
269
  const code = target === 'dom' ? await variantIndex.variantImports(compiled, withoutTwin(file), original) : compiled
268
270
  const contents = await pointed(await shippingFiles(expandGlobs(code, withoutTwin(file), root, 'ts'), withoutTwin(file), 'ts'))
269
271
 
@@ -28,7 +28,7 @@ const KAY_SPECIFIER = /^kay(?:\/|$)/
28
28
  // Lazy modules whose imports of the runtime stay with them rather than join the chunk a page loads: the code reviving an action, which only a page passing an island one loads, carries the action runtime along, the code posting an action call, which the first call loads, and the reader of a streaming action's answer, whose `ended()`, `onData()` and `retry()` a page with no such action does not carry.
29
29
  const STANDALONE = new Set([resolve(RUNTIME_DIR, 'action-reviver.ts'), resolve(RUNTIME_DIR, 'action-stream.ts'), resolve(RUNTIME_DIR, 'action-post.ts')])
30
30
  // Entries of the runtime that bundle a package, or that few pages use, which stay in the chunks of the islands importing them rather than weigh on every page: the `for`, `await` and `try` blocks, the spread and the localizing of the links an island writes, which most islands do without.
31
- const OWN_CHUNK = new Set(['kay/markdown', 'kay/internal/title', 'kay/dom-loop', 'kay/dom-await', 'kay/dom-try', 'kay/dom-spread', 'kay/i18n-links'])
31
+ const OWN_CHUNK = new Set(['kay/markdown', 'kay/internal/title', 'kay/dom-loop', 'kay/dom-await', 'kay/dom-try', 'kay/dom-spread', 'kay/dom-lazy', 'kay/i18n-links'])
32
32
  const RELATIVE = /^\.\.?\//
33
33
  const EXTENSIONS = ['.ts', '.tsx', '/index.ts']
34
34
  const ALL = '*'
@@ -1,6 +1,7 @@
1
1
  import type { Diagnostic, SourceMap } from '../compiler'
2
2
  import type { ErrorName } from '../compiler/errors'
3
3
  import type { IslandCause } from '../compiler/island-cause'
4
+ import type { ImportedComponents } from '../compiler/lazy-imports'
4
5
  import type { LintLevels } from '../compiler/lints'
5
6
  import type { ImportedSignals } from '../compiler/module-signals'
6
7
  import type { ClassTable } from '../runtime/class-table'
@@ -17,6 +18,7 @@ import { projectPaths } from '../project'
17
18
  import { awaitAlertOf } from './await-alert'
18
19
  import { countCache, pruneCache, readCacheEntry, writeCacheEntry } from './cache'
19
20
  import { compilerFingerprint } from './fingerprint'
21
+ import { importedComponents } from './lazy-components'
20
22
  import { throughLinks } from './links'
21
23
  import { namedRefresh } from './named-refresh'
22
24
  import { isPageFile, realpathOrSelf } from './page-dirs'
@@ -65,6 +67,8 @@ export interface TransformOptions {
65
67
  writtenProps?: ReadonlySet<string> | undefined
66
68
  // The server's build of an app with Tailwind, which merges a shorthand beside a static `class` while rendering; set by `transformKayCached` from the app's stylesheets.
67
69
  classMerge?: boolean | undefined
70
+ // False keeps every component's import eager.
71
+ lazy?: boolean | undefined
68
72
  }
69
73
 
70
74
  interface Compiled {
@@ -102,8 +106,8 @@ export class KayCompileError extends Error {
102
106
  }
103
107
 
104
108
  // .kay source to TypeScript building HTML strings on the server and DOM nodes in the browser; Bun strips the types when it loads the result.
105
- export function transformKay(source: string, filename: string, options: TransformOptions, signals?: ImportedSignals): string {
106
- const { code, map } = compile(source, filename, options, signals)
109
+ export function transformKay(source: string, filename: string, options: TransformOptions, signals?: ImportedSignals, components?: ImportedComponents): string {
110
+ const { code, map } = compile(source, filename, options, signals, components)
107
111
 
108
112
  registerSourceMap(filename, { source, tsx: code, map }, options.target === 'dom')
109
113
 
@@ -123,9 +127,10 @@ export async function transformKayCached(original: string, filename: string, giv
123
127
 
124
128
  // Read once: it is part of the cache key and, on a miss, what the compile reads too.
125
129
  const signals = importedSignals(withoutTwin(filename), source)
130
+ const components = componentsOf(source, filename, options)
126
131
  const hydratable = options.hydratable ?? false
127
132
  const root = options.root ?? process.cwd()
128
- const entry = cacheEntry(options.cacheDir, filename, `${options.target}${hydratable ? '-hydratable' : ''}${options.inspect === true ? '-inspect' : ''}${options.variant === undefined ? '' : `-uses-${Bun.hash(options.variant).toString(36)}`}`, `${options.target}\0${hydratable}\0${options.pages?.join(',')}\0${options.clientOnly === true}\0${options.inspect === true}\0${tableFingerprint(options.classTable)}\0${classMerge === true}\0${root}\0${throughLinks(root, filename)}\0${uiKeyOf(root, withoutTwin(filename))}\0${JSON.stringify(awaitAlertOf(root))}\0${JSON.stringify(signals)}\0${options.target === 'ssr' && namedRefresh(withoutTwin(filename), root)}\0${source}`)
133
+ const entry = cacheEntry(options.cacheDir, filename, `${options.target}${hydratable ? '-hydratable' : ''}${options.inspect === true ? '-inspect' : ''}${options.variant === undefined ? '' : `-uses-${Bun.hash(options.variant).toString(36)}`}`, `${options.target}\0${hydratable}\0${options.pages?.join(',')}\0${options.clientOnly === true}\0${options.inspect === true}\0${tableFingerprint(options.classTable)}\0${classMerge === true}\0${root}\0${throughLinks(root, filename)}\0${uiKeyOf(root, withoutTwin(filename))}\0${JSON.stringify(awaitAlertOf(root))}\0${JSON.stringify(signals)}\0${JSON.stringify(components)}\0${options.target === 'ssr' && namedRefresh(withoutTwin(filename), root)}\0${source}`)
129
134
  const cached = await readCacheEntry<string>(entry)
130
135
 
131
136
  countCache('components', cached !== undefined)
@@ -134,7 +139,7 @@ export async function transformKayCached(original: string, filename: string, giv
134
139
  if (cached !== undefined) {
135
140
  if (!hasSourceMapOf(filename, source, cached, options.target === 'dom')) {
136
141
  registerSourceMap(filename, () => {
137
- const { code, map } = compile(source, filename, options, signals)
142
+ const { code, map } = compile(source, filename, options, signals, components)
138
143
 
139
144
  return { source, tsx: code, map }
140
145
  }, options.target === 'dom')
@@ -143,7 +148,7 @@ export async function transformKayCached(original: string, filename: string, giv
143
148
  return cached
144
149
  }
145
150
 
146
- const code = transformKay(source, filename, options, signals)
151
+ const code = transformKay(source, filename, options, signals, components)
147
152
 
148
153
  await writeCacheEntry(entry, code)
149
154
 
@@ -247,8 +252,13 @@ export function cacheEntry(cacheDir: string, filename: string, kind: string, inp
247
252
  }
248
253
  }
249
254
 
255
+ // The imported components a file may draw lazily: for the browser's build and the server's hydratable one, the only two that split them.
256
+ function componentsOf(source: string, filename: string, options: TransformOptions) {
257
+ return options.lazy !== false && (options.target === 'dom' || options.hydratable === true) ? importedComponents(withoutTwin(filename), source, options.root ?? process.cwd()) : undefined
258
+ }
259
+
250
260
  // `filename` may name a static component's `?island` twin, the build of it that renders inside islands.
251
- function compile(source: string, filename: string, options: TransformOptions, signals = importedSignals(withoutTwin(filename), source)): Compiled {
261
+ function compile(source: string, filename: string, options: TransformOptions, signals = importedSignals(withoutTwin(filename), source), components = componentsOf(source, filename, options)): Compiled {
252
262
  const server = options.target === 'ssr'
253
263
  const file = withoutTwin(filename)
254
264
  const isTwin = file !== filename
@@ -256,7 +266,7 @@ function compile(source: string, filename: string, options: TransformOptions, si
256
266
  const root = options.root ?? process.cwd()
257
267
  // A page of the routes directory, whose root `@failed` fills a layout outlet rather than being a component's own block.
258
268
  const page = isPageFile(file, options.pages ?? [projectPaths(root).routes]) ? true : undefined
259
- const { tsx, map, diagnostics } = compileKay(source, throughLinks(root, file), { root: options.root, page, includeServer: server, output: server ? 'html' : 'dom', hydratable, twinBuild: isTwin, clientOnly: options.clientOnly, inspect: options.inspect, classTable: options.target === 'dom' ? options.classTable : undefined, classMerge: server ? options.classMerge : undefined, awaitAlert: awaitAlertOf(root, file), importedSignals: signals, namedRefresh: server && namedRefresh(file, root), ui: uiEntryOf(options.root ?? process.cwd(), file), writtenProps: options.writtenProps })
269
+ const { tsx, map, diagnostics } = compileKay(source, throughLinks(root, file), { root: options.root, page, includeServer: server, output: server ? 'html' : 'dom', hydratable, twinBuild: isTwin, clientOnly: options.clientOnly, inspect: options.inspect, classTable: options.target === 'dom' ? options.classTable : undefined, classMerge: server ? options.classMerge : undefined, awaitAlert: awaitAlertOf(root, file), importedSignals: signals, components, namedRefresh: server && namedRefresh(file, root), ui: uiEntryOf(options.root ?? process.cwd(), file), writtenProps: options.writtenProps })
260
270
 
261
271
  if (diagnostics.length > 0)
262
272
  throw new KayCompileError(diagnostics.map(diagnostic => ({ ...diagnostic, file, source })))
@@ -9,6 +9,8 @@ import { parseExpanded } from '../compiler/markdown-block'
9
9
  // A component names the features an app may leave out with `uses('selectable')`, the `uses` it imports from kayjs-ui's marker module: a call that is true while the prop is there to be written, and that a browser build replaces with `true` or `false` once it has read the props the files of the project write at their call sites. See `specializedSource`.
10
10
  const USES_CALL = /\buses\(\s*'(\w+)'(\s*,\s*true)?\s*\)/y
11
11
  const KAY_IMPORT = /^import\s+(\w+)\s+from\s+(["'])([^"'\n]+\.kay)\2/gm
12
+ // A component the compiler imports lazily, `KayLazy(key, () => import("./it.kay"))`.
13
+ const LAZY_IMPORT = /\bimport\(\s*(["'])([^"'\n]+\.kay)\1\s*\)/g
12
14
  const USES_IMPORT = /^import\s*\{[^}]*\buses\b[^}]*\}\s*from\s*(["'])([^"'\n]+)\1/m
13
15
  // The marker module, by where the library keeps it: an app's own `uses` is another function.
14
16
  const MARKER_FILE = /(?:packages\/ui|@kayjs\/ui)\/src\/uses\.ts$/
@@ -452,11 +454,11 @@ interface Candidate {
452
454
  async function candidatesOf(code: string, file: string): Promise<Candidate[]> {
453
455
  const found: Candidate[] = []
454
456
 
455
- for (const [, local, , specifier] of code.matchAll(KAY_IMPORT)) {
457
+ for (const [local, specifier] of [...code.matchAll(KAY_IMPORT).map(([, name, , from]) => [name!, from!] as const), ...code.matchAll(LAZY_IMPORT).map(([, , from]) => ['', from!] as const)]) {
456
458
  let path: string
457
459
 
458
460
  try {
459
- path = Bun.resolveSync(specifier!, dirname(file))
461
+ path = Bun.resolveSync(specifier, dirname(file))
460
462
  }
461
463
  catch {
462
464
  continue
@@ -465,7 +467,7 @@ async function candidatesOf(code: string, file: string): Promise<Candidate[]> {
465
467
  const { names: features, defaults } = await declaredFeatures(path)
466
468
 
467
469
  if (features.length > 0)
468
- found.push({ local: local!, specifier: specifier!, path, features, defaults })
470
+ found.push({ local, specifier, path, features, defaults })
469
471
  }
470
472
 
471
473
  return found
@@ -503,7 +505,7 @@ export class VariantIndex {
503
505
  }
504
506
 
505
507
  private async read(file: string, source: string): Promise<void> {
506
- const candidates = await candidatesOf(source, file)
508
+ const candidates = (await candidatesOf(source, file)).filter(candidate => candidate.local !== '')
507
509
 
508
510
  if (candidates.length === 0)
509
511
  return
@@ -563,6 +565,7 @@ export class VariantIndex {
563
565
  const used = this.usedOf(path, features, defaults)
564
566
 
565
567
  result = result.replace(new RegExp(`^(import\\s+\\w+\\s+from\\s+)(["'])${RegExp.escape(specifier)}\\2`, 'm'), (_import, head: string, quote: string) => `${head}${quote}${specifier}?uses=${used}${quote}`)
568
+ result = result.replace(new RegExp(`(\\bimport\\(\\s*)(["'])${RegExp.escape(specifier)}\\2`, 'g'), (_import, head: string, quote: string) => `${head}${quote}${specifier}?uses=${used}${quote}`)
566
569
  }
567
570
 
568
571
  return result
@@ -0,0 +1,56 @@
1
+ import type { CheckDiagnostic, CheckOptions } from '.'
2
+ import type { Node } from '../compiler/estree'
3
+ import { lintLevel } from '../compiler/lints'
4
+ import { importsOf, walk } from './ast'
5
+ import { scan } from './renamed-exports'
6
+
7
+ const KAY = /^kay(?:\/|$)/
8
+ const NEEDLE = /\baction\s*\(/
9
+ const TRAILING_COMMA = /,$/
10
+ const FUNCTIONS = new Set(['ArrowFunctionExpression', 'FunctionExpression'])
11
+
12
+ // `action(schema, handler, options)` and `action(handler, options)` as kay 1.107 replaces them: the options come first, with the input in them, as an API route's do: `action({ input: schema, ...options }, handler)`.
13
+ // 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.
14
+ export async function actionOptions(root: string, options: CheckOptions): Promise<CheckDiagnostic[]> {
15
+ if (lintLevel('deprecated-action-options', options.lints) === 'allow')
16
+ return []
17
+
18
+ return scan(root, options, 'deprecated-action-options', NEEDLE, ({ parsed, report }) => {
19
+ for (const { ast, base, text } of parsed) {
20
+ const locals = importsOf(ast, source => KAY.test(source), 'action').locals
21
+
22
+ if (locals.size === 0)
23
+ continue
24
+
25
+ const slice = (node: Node): string => text.slice(node.start, node.end)
26
+
27
+ walk(ast, (node) => {
28
+ if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || !locals.has(node.callee.name))
29
+ return
30
+
31
+ const [first, second, third] = node.arguments
32
+
33
+ if (first === undefined || second === undefined || node.arguments.length > 3 || node.arguments.some(argument => argument.type === 'SpreadElement'))
34
+ return
35
+
36
+ // `action(handler, options)`
37
+ if (FUNCTIONS.has(first.type)) {
38
+ if (third !== undefined || FUNCTIONS.has(second.type))
39
+ return
40
+
41
+ report(base + node.start, base + node.end, 'an action takes its options before the handler since 1.107, as an API route does, `action(options, handler)`; the old order works until 2.0', 'write the options first', [{ start: base + first.start, end: base + second.end, text: `${slice(second)}, ${slice(first)}` }])
42
+
43
+ return
44
+ }
45
+
46
+ // `action(schema, handler, options)`
47
+ if (third === undefined)
48
+ return
49
+
50
+ const inner = third.type === 'ObjectExpression' ? text.slice(third.start + 1, third.end - 1).trim().replace(TRAILING_COMMA, '') : `...${slice(third)}`
51
+
52
+ report(base + node.start, base + node.end, 'an action takes its input and its options in one object before the handler since 1.107, `action({ input, ...options }, handler)`; the old form works until 2.0', 'write the input and the options first', [{ start: base + first.start, end: base + third.end, text: `{ input: ${slice(first)}${inner === '' ? '' : `, ${inner}`} }, ${slice(second)}` }])
53
+ })
54
+ }
55
+ })
56
+ }