prunelle 0.1.1 → 0.7.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -1,11 +1,13 @@
1
1
  // `prunelle upgrade`: moves an app written for kay v2 (`@kayjs/kay`) onto prunelle: its dependencies, config file, imports, the names it imports and the names the browser receives.
2
2
 
3
+ import type { Dirent } from 'node:fs'
3
4
  import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
- import { dirname, join } from 'node:path'
5
+ import { dirname, join, resolve } from 'node:path'
5
6
  import pkg from '../../package.json' with { type: 'json' }
6
7
  import { isNotSourceDir, relPosix } from '../build/files'
7
8
  import { resolvePrunelleSpecifier } from '../build/resolve'
8
9
  import { parseTsx } from '../compiler/analyze'
10
+ import { walk } from '../compiler/ast'
9
11
  import { renameKayNames } from './upgrade-names'
10
12
 
11
13
  export interface UpgradeResult {
@@ -17,11 +19,13 @@ export interface UpgradeResult {
17
19
 
18
20
  // The specifiers and file names every kind of file may name.
19
21
  const PATH_RULES: [RegExp, string][] = [
22
+ // A kay v2 version written beside a package, as notes do, names no prunelle release: the current one replaces it.
23
+ [/(@kayjs\/[\w-]+)@[\^~]?2\.\d+\.\d+[\w.-]*/g, `$1@^${pkg.version}`],
20
24
  [/@kayjs\/kay(?![\w-])/g, 'prunelle'],
21
25
  [/@kayjs\//g, '@prunellejs/'],
22
26
  [/\.kay-(cache|dev)\b/g, '.prunelle-$1'],
23
27
  [/\bkay\.config\b/g, 'prunelle.config'],
24
- [/\bkay v2\b/g, 'prunelle'],
28
+ [/\bkay v2\b/gi, 'prunelle'],
25
29
  ]
26
30
  // The names kay sent the browser, as app code and styles may spell them.
27
31
  const WIRE_RULES: [RegExp, string][] = [
@@ -32,24 +36,50 @@ const WIRE_RULES: [RegExp, string][] = [
32
36
  [/\bkay:(consent|navigate|region)\b/g, 'pru:$1'],
33
37
  [/\bkay_(session|consent)\b/g, 'pru_$1'],
34
38
  ]
35
- // The kay CLI run as a command; the PATH_RULES run first, so `kay.config` and `.kay-cache` are gone by then.
39
+ // The kay CLI in a script or the agent instructions, which name nothing else kay; the PATH_RULES run first, so `kay.config` and `.kay-cache` are gone by then.
36
40
  const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
41
+ // The kay CLI where a build or CI file runs it, after a runner or before one of its commands, so a user or a runner label named kay stays (#142).
42
+ const KAY_COMMAND = String.raw`(?:new|check|inspect|docs|render|mcp|dev|build|eco|start|upgrade|test|[a-z]+-[a-z-]+)(?![\w:-])`
43
+ const RUN_CLI_RULES: [RegExp, string][] = [
44
+ [/(?<=\b(?:bunx|npx|bun(?:\s+(?:x|run))?)\s+|"bunx",\s*")kay(?![\w.:/-])/g, 'prunelle'],
45
+ [new RegExp(String.raw`(?<![\w.@/-])kay(?=(?:\s+|",\s*")${KAY_COMMAND})`, 'g'), 'prunelle'],
46
+ ]
37
47
 
38
48
  const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
39
49
  const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
50
+ const TSCONFIG_FILE_RE = /^tsconfig(?:\.[\w-]+)?\.json$/
40
51
  const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
41
52
  const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
53
+ // The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
54
+ const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
42
55
  const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
43
56
  const CACHE_DIRS = ['.kay-cache', '.kay-dev']
44
57
  const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
58
+ const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
59
+ const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
60
+ const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
45
61
 
46
62
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
47
63
 
64
+ /** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
65
+ export function notAnApp(root: string): string | undefined {
66
+ if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
67
+ return undefined
68
+ const manifest = existsSync(join(root, 'package.json')) ? 'its package.json names neither @kayjs/kay nor prunelle' : 'it has no package.json'
69
+ return `${root} is not a kay v2 app: ${manifest}, and it has no kay.config.ts`
70
+ }
71
+
48
72
  /** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
49
73
  export function upgradeProject(root: string): UpgradeResult {
74
+ return upgradeDir(root)
75
+ }
76
+
77
+ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>): UpgradeResult {
50
78
  const v1 = kayV1Dependency(root)
51
79
  if (v1 !== undefined)
52
80
  return { changed: [], manual: [`package.json:1: ${v1} is kay v1: prunelle upgrade moves kay v2 apps, so this one is left as it is.`] }
81
+ const aliases = kayAliases(root, inheritedAliases)
82
+ const isApp = hasKayOrPrunelle(root)
53
83
  const changed: string[] = []
54
84
  const manual: string[] = []
55
85
  const write = (file: string, before: string, after: string): void => {
@@ -63,23 +93,30 @@ export function upgradeProject(root: string): UpgradeResult {
63
93
  const text = readFileSync(join(root, file), 'utf8')
64
94
  if (file === 'package.json')
65
95
  write(file, text, upgradePackageJson(text))
96
+ else if (TSCONFIG_FILE_RE.test(file))
97
+ write(file, text, upgradeTsconfig(text, aliases))
98
+ else if (file === '.gitignore')
99
+ write(file, text, upgradeGitignore(text, isApp))
66
100
  else if (CONFIG_FILE_RE.test(file))
67
101
  write(file, text, apply(text, PATH_RULES))
68
102
  else if (BUILD_FILE_RE.test(file))
103
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
104
+ else if (AGENT_FILE_RE.test(file))
69
105
  write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
70
106
  }
71
107
  for (const dir of CI_DIRS) {
72
108
  if (!existsSync(join(root, dir)))
73
109
  continue
74
- for (const name of readdirSync(join(root, dir)).sort()) {
110
+ for (const name of readdirSync(join(root, dir), { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()) {
75
111
  const file = `${dir}/${name}`
76
112
  const text = readFileSync(join(root, file), 'utf8')
77
- write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
113
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
78
114
  }
79
115
  }
80
- for (const file of sourceFiles(root)) {
116
+ const publicDir = configuredPublicDir(root)
117
+ for (const file of sourceFiles(root, publicDir)) {
81
118
  const text = readFileSync(join(root, file), 'utf8')
82
- const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text) : text
119
+ const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
83
120
  const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
84
121
  write(file, text, next)
85
122
  if (SOURCE_FILE_RE.test(file) && next !== text)
@@ -91,8 +128,9 @@ export function upgradeProject(root: string): UpgradeResult {
91
128
  changed.push(`${dir}/`)
92
129
  }
93
130
  }
94
- for (const member of workspaceMembers(root)) {
95
- const res = upgradeProject(join(root, member))
131
+ // A member on neither kay nor prunelle, a plain Bun app or a tool, has nothing to move; one already on prunelle may keep names an earlier upgrade missed.
132
+ for (const member of workspaceMembers(root).filter(m => hasKayOrPrunelle(join(root, m)))) {
133
+ const res = upgradeDir(join(root, member), aliases)
96
134
  changed.push(...res.changed.map(file => `${member}/${file}`))
97
135
  manual.push(...res.manual.map(line => `${member}/${line}`))
98
136
  }
@@ -102,6 +140,83 @@ export function upgradeProject(root: string): UpgradeResult {
102
140
  const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
103
141
  const V1_RANGE_RE = /^[~^>=\s]*1\./
104
142
 
143
+ const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
144
+
145
+ function hasKayOrPrunelle(root: string): boolean {
146
+ if (!existsSync(join(root, 'package.json')))
147
+ return false
148
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
149
+ return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
150
+ }
151
+
152
+ function kayTargetPackage(name: string, version: string): string | undefined {
153
+ if (name.startsWith('@kayjs/'))
154
+ return apply(name, PATH_RULES)
155
+ const match = NPM_KAY_ALIAS_RE.exec(version)
156
+ return match === null ? undefined : apply(match[1]!, PATH_RULES)
157
+ }
158
+
159
+ function kayAliases(root: string, inherited?: ReadonlyMap<string, string>): Map<string, string> {
160
+ const aliases = new Map<string, string>(inherited)
161
+ if (!existsSync(join(root, 'package.json')))
162
+ return aliases
163
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
164
+ for (const field of DEP_FIELDS) {
165
+ for (const [name, version] of Object.entries(json[field] ?? {})) {
166
+ if (name.startsWith('@kayjs/'))
167
+ continue
168
+ const match = NPM_KAY_ALIAS_RE.exec(version)
169
+ if (match !== null)
170
+ aliases.set(name, apply(match[1]!, PATH_RULES))
171
+ }
172
+ }
173
+ return aliases
174
+ }
175
+
176
+ function upgradeTsconfig(text: string, aliases: ReadonlyMap<string, string>): string {
177
+ let out = apply(text, PATH_RULES)
178
+ for (const [alias, target] of aliases) {
179
+ const escaped = alias.replace(ESCAPE_RE, '\\$&')
180
+ if (target === 'prunelle')
181
+ out = out.replace(new RegExp(`("jsxImportSource"\\s*:\\s*")${escaped}(")`, 'g'), `$1${target}$2`)
182
+ out = out.replace(/"types"\s*:\s*\[[^\]]*\]/g, block =>
183
+ block.replace(new RegExp(`"${escaped}((?:/[^"]*)?)"`, 'g'), `"${target}$1"`))
184
+ }
185
+ return out
186
+ }
187
+
188
+ function upgradeGitignore(text: string, addCache: boolean): string {
189
+ const next = apply(text, PATH_RULES)
190
+ if (!addCache || GITIGNORE_CACHE_RE.test(next))
191
+ return next
192
+ const eol = next.includes('\r\n') ? '\r\n' : '\n'
193
+ const sep = next === '' || next.endsWith('\n') ? '' : eol
194
+ return `${next}${sep}.prunelle-cache/${eol}`
195
+ }
196
+
197
+ // Reads `publicDir` statically from prunelle.config.ts (or kay.config.ts) so built scripts in `public/` are left alone (#43).
198
+ function configuredPublicDir(root: string): string {
199
+ const file = existsSync(join(root, 'prunelle.config.ts'))
200
+ ? 'prunelle.config.ts'
201
+ : existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
202
+ if (file === undefined)
203
+ return resolve(root, 'public')
204
+ const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
205
+ let value: string | undefined
206
+ walk(program.body, (node) => {
207
+ if (value !== undefined)
208
+ return false
209
+ if (node.type === 'Property' && !node.computed && node.key.type === 'Identifier' && node.key.name === 'publicDir') {
210
+ if (node.value.type === 'Literal' && typeof node.value.value === 'string')
211
+ value = node.value.value
212
+ else if (node.value.type === 'TemplateLiteral' && node.value.expressions.length === 0)
213
+ value = node.value.quasis[0]?.value.cooked ?? node.value.quasis[0]?.value.raw
214
+ }
215
+ return true
216
+ })
217
+ return resolve(root, value ?? 'public')
218
+ }
219
+
105
220
  // kay's core at a 1.x range, as `@kayjs/kay` or an `npm:@kayjs/kay@` alias: an app of `.kay` files prunelle cannot take.
106
221
  function kayV1Dependency(root: string): string | undefined {
107
222
  if (!existsSync(join(root, 'package.json')))
@@ -149,18 +264,34 @@ function rootFiles(root: string): string[] {
149
264
  return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
150
265
  }
151
266
 
152
- // A folder holding its own package.json is another package, upgraded on its own.
153
- function sourceFiles(root: string, dir = root, out: string[] = []): string[] {
267
+ // The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
268
+ function readableEntries(dir: string): Dirent[] {
269
+ try {
270
+ return readdirSync(dir, { withFileTypes: true })
271
+ }
272
+ catch (err) {
273
+ if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
274
+ return []
275
+ throw err
276
+ }
277
+ }
278
+
279
+ // A folder holding its own package.json is another package, upgraded on its own; `publicDir` holds built static files left untouched (#43).
280
+ function sourceFiles(root: string, publicDir: string, dir = root, out: string[] = []): string[] {
154
281
  if (dir !== root && existsSync(join(dir, 'package.json')))
155
282
  return out
156
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
283
+ for (const entry of readableEntries(dir)) {
157
284
  if (isNotSourceDir(entry.name))
158
285
  continue
159
286
  const path = join(dir, entry.name)
160
- if (entry.isDirectory())
161
- sourceFiles(root, path, out)
162
- else if ((SOURCE_FILE_RE.test(entry.name) && !entry.name.endsWith('.d.ts')) || STYLE_OR_SCRIPT_RE.test(entry.name))
287
+ if (entry.isDirectory()) {
288
+ if (resolve(path) !== publicDir)
289
+ sourceFiles(root, publicDir, path, out)
290
+ }
291
+ // A link is skipped: its target may lie outside the app, or be a file the app reaches twice.
292
+ else if (entry.isFile() && (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name))) {
163
293
  out.push(relPosix(root, path))
294
+ }
164
295
  }
165
296
  return out.sort()
166
297
  }
@@ -173,10 +304,17 @@ function upgradePackageJson(text: string): string {
173
304
  const range = `^${pkg.version}`
174
305
  for (const field of DEP_FIELDS) {
175
306
  const deps = json[field] as Record<string, string> | undefined
176
- if (deps === undefined || !Object.keys(deps).some(name => name.startsWith('@kayjs/')))
307
+ if (deps === undefined || !Object.entries(deps).some(([name, version]) => kayTargetPackage(name, version) !== undefined))
177
308
  continue
178
- const entries = Object.entries(deps).map(([name, version]) => name.startsWith('@kayjs/') ? [apply(name, PATH_RULES), range] : [name, version])
179
- json[field] = Object.fromEntries(entries.sort(([a], [b]) => a!.localeCompare(b!)))
309
+ const next = new Map<string, string>()
310
+ for (const [name, version] of Object.entries(deps)) {
311
+ const target = kayTargetPackage(name, version)
312
+ if (target !== undefined)
313
+ next.set(target, range)
314
+ else if (!next.has(name))
315
+ next.set(name, version)
316
+ }
317
+ json[field] = Object.fromEntries([...next.entries()].sort(([a], [b]) => a.localeCompare(b)))
180
318
  }
181
319
  const scripts = json.scripts as Record<string, string> | undefined
182
320
  if (scripts !== undefined)
@@ -3,16 +3,21 @@
3
3
  import type { CallExpression, ExportNamedDeclaration, Function as OxcFunction, Node, Program, Statement, VariableDeclaration } from 'oxc-parser'
4
4
  import { parseSync } from 'oxc-parser'
5
5
  import { computeJsxNodes, walk } from './ast'
6
+ import type { RouteCacheSpec } from '../server/route-cache'
6
7
  import type { BindingFacts, Interactivity } from './interactivity'
7
8
  import type { CompilerWarning } from './mistakes'
9
+ import type { ExprContext } from './shared'
8
10
  import { checkBrowserGlobals } from './browser-globals'
11
+ import { parseCacheExport } from './cacheability'
9
12
  import { analyzeDefaultDataKeys } from './data-keys'
10
13
  import { checkCompliance } from './compliance'
14
+ import { assertNoForeignImport } from './foreign-imports'
11
15
  import { resolveInteractivity } from './interactivity'
12
16
  import { findNodeEnvReads } from './node-env'
13
- import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
17
+ import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, frontmatterMistake, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
14
18
  import { walkScoped } from './scope'
15
- import { calleeName, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
19
+ import { calleeName, createExprContext, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
20
+ import { checkBodyPropsDestructure } from './props-body'
16
21
  import { checkBareSignals } from './signal-reads'
17
22
 
18
23
  const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction'])
@@ -21,8 +26,8 @@ const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
21
26
  const PRUNELLE_SOURCES = new Set(['prunelle'])
22
27
  const PRUNELLE_SSR_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
23
28
  const PRUNELLE_SERVER_SOURCES = new Set(['prunelle/server'])
24
- const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'createContext', 'provideContext', 'useContext', 'useId'])
25
- const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate'])
29
+ const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'createContext', 'provideContext', 'useContext', 'useId'])
30
+ const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
26
31
 
27
32
  export interface ImportInfo {
28
33
  source: string
@@ -46,7 +51,13 @@ export interface ModuleAnalysis extends Interactivity {
46
51
  hasJsx: boolean
47
52
  /** Precomputed set of AST nodes containing JSX (itself included), for O(1) subtree checks during codegen. */
48
53
  jsxNodes: WeakSet<Node>
54
+ /** Lazily cached expression type/primitivity context shared between SSR and DOM compilers. */
55
+ exprContext?: ExprContext | undefined
49
56
  hasPrerender: boolean
57
+ /** True when the module explicitly exports `prerender = false`. */
58
+ prerenderFalse: boolean
59
+ /** Parsed `export const cache = ...` policy when present and valid. */
60
+ cache?: RouteCacheSpec | undefined
50
61
  hasPaths: boolean
51
62
  usesRenderContext: boolean
52
63
  defaultHydrate: string | undefined
@@ -133,10 +144,15 @@ function decodeAttributeEntities(program: Program): void {
133
144
  })
134
145
  }
135
146
 
147
+ const FRONTMATTER_RE = /^\s*---[ \t]*\r?\n/
148
+
136
149
  export function parseTsx(filename: string, code: string): Program {
137
150
  const lang = /\.[cm]?ts$/i.test(filename) ? 'ts' : 'tsx'
138
151
  const result = parseSync(filename, code, { lang, sourceType: 'module' })
139
152
  if (result.errors.length > 0) {
153
+ const frontmatter = FRONTMATTER_RE.exec(code)
154
+ if (frontmatter !== null)
155
+ throw frontmatterMistake(filename, frontmatter[0].indexOf('---'))
140
156
  const first = result.errors[0]!
141
157
  const label = first.labels?.[0]
142
158
  const offset = label?.start ?? 0
@@ -241,6 +257,7 @@ function scanImports(program: Program, filename: string): ImportScan {
241
257
  }
242
258
 
243
259
  function scanPrunelleImport(scan: ImportScan, source: string, imported: string, local: string, filename: string, start: number): void {
260
+ guarded(start, () => assertNoForeignImport(source, imported, filename))
244
261
  if (PRUNELLE_SOURCES.has(source)) {
245
262
  if (REACTIVE_IMPORTS.has(imported))
246
263
  scan.reactiveLocals.set(local, `uses ${imported}`)
@@ -272,6 +289,7 @@ interface DeclarationScan {
272
289
  hasLoadExport: boolean
273
290
  hasPaths: boolean
274
291
  hasPrerender: boolean
292
+ prerenderFalse: boolean
275
293
  defaultHydrate: string | undefined
276
294
  exportedActions: string[]
277
295
  /** The action() calls prunelle gives a URL to: the initialisers of top-level `export const`s. */
@@ -281,7 +299,7 @@ interface DeclarationScan {
281
299
  }
282
300
 
283
301
  function scanDeclarations(program: Program, filename: string, imports: ImportScan): DeclarationScan {
284
- const scan: DeclarationScan = { localInits: new Map(), exportLocals: new Map(), asyncLocals: new Set(), defaultLocal: undefined, hasAsyncDefault: false, hasLoadExport: false, hasPaths: false, hasPrerender: false, defaultHydrate: undefined, exportedActions: [], registeredActions: new Set(), reexports: [], exportedNames: [] }
302
+ const scan: DeclarationScan = { localInits: new Map(), exportLocals: new Map(), asyncLocals: new Set(), defaultLocal: undefined, hasAsyncDefault: false, hasLoadExport: false, hasPaths: false, hasPrerender: false, prerenderFalse: false, defaultHydrate: undefined, exportedActions: [], registeredActions: new Set(), reexports: [], exportedNames: [] }
285
303
  const collectInits = (decl: VariableDeclaration): void => {
286
304
  for (const d of decl.declarations) {
287
305
  if (d.id.type === 'Identifier' && d.init !== null)
@@ -358,8 +376,12 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
358
376
  continue
359
377
  const name = d.id.name
360
378
  addExport(name, name)
361
- if (name === 'prerender' && d.init?.type === 'Literal' && d.init.value === true)
362
- scan.hasPrerender = true
379
+ if (name === 'prerender' && d.init?.type === 'Literal') {
380
+ if (d.init.value === true)
381
+ scan.hasPrerender = true
382
+ else if (d.init.value === false)
383
+ scan.prerenderFalse = true
384
+ }
363
385
  if (name === 'hydrate' && d.init !== null)
364
386
  scan.defaultHydrate = checkExportHydrate(d.init, filename)
365
387
  if (d.init !== null && isActionCall(d.init, imports.actionLocalName, imports.serverNamespaces)) {
@@ -476,9 +498,9 @@ function scanBody(program: Program, filename: string, code: string, imports: Imp
476
498
  }
477
499
  else if (node.type === 'JSXOpeningElement') {
478
500
  scanOpeningElement(node, binding, body, imports, filename)
479
- const root = jsxTagName(node.name).split('.')[0]!
480
- if (isComponentTag(root))
481
- ref(binding, root, node.start)
501
+ const tag = jsxTagName(node.name)
502
+ if (isComponentTag(tag))
503
+ ref(binding, tag.split('.')[0]!, node.start)
482
504
  }
483
505
  else if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && freeIds.has(node.object.start) && node.property.type === 'Identifier') {
484
506
  memberObjStarts.add(node.object.start)
@@ -560,6 +582,29 @@ function stateExportsOf(decls: DeclarationScan, callees: ReadonlySet<string>, co
560
582
  return [...decls.exportLocals].filter(([, local]) => containsStateInit(decls.localInits.get(local), callees, containers)).map(([exported]) => exported)
561
583
  }
562
584
 
585
+ const exprContextCache = new WeakMap<Program, ExprContext>()
586
+
587
+ /** Lazily computes and caches `ExprContext` on `analysis` (and by `program` across shallow copies) so SSR and DOM compilation never build it twice. */
588
+ export function getExprContext(analysis: ModuleAnalysis): ExprContext {
589
+ if (analysis.exprContext !== undefined)
590
+ return analysis.exprContext
591
+ let ctx = exprContextCache.get(analysis.program)
592
+ if (ctx === undefined) {
593
+ ctx = createExprContext(analysis.program, analysis.jsxNodes)
594
+ exprContextCache.set(analysis.program, ctx)
595
+ }
596
+ analysis.exprContext = ctx
597
+ return ctx
598
+ }
599
+
600
+ // An island page whose reads of `data` the compiler cannot follow ships the whole `load()` result, personal data it never shows included.
601
+ function wholeLoadShippedWarning(filename: string, start: number): CompilerWarning {
602
+ return {
603
+ start,
604
+ message: `prunelle compiler: the island page in ${filename} uses \`data\` in a way the compiler cannot follow, so the whole load() result is sent to the browser: export \`clientData\` listing the keys the page reads (\`export const clientData = ['title']\`), or \`(data) => data\` to send all of it on purpose.`,
605
+ }
606
+ }
607
+
563
608
  export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
564
609
  const imports = scanImports(program, filename)
565
610
  const decls = scanDeclarations(program, filename, imports)
@@ -567,9 +612,11 @@ export function analyzeModule(filename: string, code: string, program: Program =
567
612
  const loadNodes = loadDeclarations(program)
568
613
  const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes))
569
614
  checkBareSignals(program, imports.signalCallees, filename)
615
+ checkBodyPropsDestructure(program, code, body.bindings, filename, warnings)
616
+ const jsxNodes = body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>()
570
617
  if (body.hasJsx) {
571
618
  checkCompliance(program, filename, code, warnings, tag => resolvePrunelleTag(tag, imports.imports))
572
- checkBrowserGlobals(program, code, filename, warnings)
619
+ checkBrowserGlobals(program, code, filename, warnings, jsxNodes)
573
620
  }
574
621
 
575
622
  for (const [name, init] of decls.localInits) {
@@ -584,16 +631,23 @@ export function analyzeModule(filename: string, code: string, program: Program =
584
631
  if (interactivity.serverOnly !== undefined)
585
632
  guarded(interactivity.serverOnly.offset, () => { throw serverOnlyTagError(filename, interactivity.serverOnly!) })
586
633
 
634
+ const cacheExport = parseCacheExport(program)
635
+ const hasLoadExport = decls.hasLoadExport || loadNodes.length > 0
636
+ const defaultDataKeys = page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined
637
+ if (page?.interactive === true && hasLoadExport && defaultDataKeys === undefined && !decls.exportedNames.includes('clientData'))
638
+ warnings.push(wholeLoadShippedWarning(filename, decls.localInits.get(decls.defaultLocal ?? '')?.start ?? page.offset ?? 0))
587
639
  return {
588
640
  filename,
589
641
  program,
590
642
  warnings,
591
643
  ...interactivity,
592
644
  hasAsyncDefault,
593
- hasLoadExport: decls.hasLoadExport || loadNodes.length > 0,
645
+ hasLoadExport,
594
646
  hasJsx: body.hasJsx,
595
- jsxNodes: body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>(),
647
+ jsxNodes,
596
648
  hasPrerender: decls.hasPrerender,
649
+ prerenderFalse: decls.prerenderFalse,
650
+ ...(cacheExport.spec !== undefined ? { cache: cacheExport.spec } : {}),
597
651
  hasPaths: decls.hasPaths,
598
652
  usesRenderContext: body.usesRenderContext,
599
653
  defaultHydrate: decls.defaultHydrate,
@@ -603,7 +657,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
603
657
  asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get('default') ?? 'default']) : decls.asyncLocals,
604
658
  stateExports: stateExportsOf(decls, imports.stateCallees, true),
605
659
  signalExports: stateExportsOf(decls, imports.signalCallees, false),
606
- defaultDataKeys: page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined,
660
+ defaultDataKeys,
607
661
  exportedActions: decls.exportedActions,
608
662
  imports: imports.imports,
609
663
  dynamicImports: body.dynamicImports,