prunelle 0.1.1 → 0.5.3

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 (120) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +62 -0
  75. package/src/plugins/types.ts +32 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +128 -31
  90. package/src/server/index.ts +230 -260
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. 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][] = [
@@ -37,19 +41,31 @@ const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
37
41
 
38
42
  const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
39
43
  const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
44
+ const TSCONFIG_FILE_RE = /^tsconfig(?:\.[\w-]+)?\.json$/
40
45
  const CONFIG_FILE_RE = /^(?:tsconfig(?:\.[\w-]+)?\.json|bunfig\.toml|\.gitignore|\.dockerignore)$/
41
46
  const BUILD_FILE_RE = /^(?:Dockerfile(?:\.[\w-]+)?|[\w-]+\.Dockerfile|[Jj]ustfile|Makefile|(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml)$/
47
+ // The agent instructions `prunelle new` writes, which name the llms.txt to read and the CLI to run (#42).
48
+ const AGENT_FILE_RE = /^(?:AGENTS|CLAUDE)\.md$/
42
49
  const CI_DIRS = ['.forgejo/workflows', '.github/workflows', '.gitea/workflows']
43
50
  const CACHE_DIRS = ['.kay-cache', '.kay-dev']
44
51
  const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
52
+ const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
53
+ const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
54
+ const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
45
55
 
46
56
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
47
57
 
48
58
  /** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
49
59
  export function upgradeProject(root: string): UpgradeResult {
60
+ return upgradeDir(root)
61
+ }
62
+
63
+ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>): UpgradeResult {
50
64
  const v1 = kayV1Dependency(root)
51
65
  if (v1 !== undefined)
52
66
  return { changed: [], manual: [`package.json:1: ${v1} is kay v1: prunelle upgrade moves kay v2 apps, so this one is left as it is.`] }
67
+ const aliases = kayAliases(root, inheritedAliases)
68
+ const isApp = hasKayOrPrunelle(root)
53
69
  const changed: string[] = []
54
70
  const manual: string[] = []
55
71
  const write = (file: string, before: string, after: string): void => {
@@ -63,9 +79,13 @@ export function upgradeProject(root: string): UpgradeResult {
63
79
  const text = readFileSync(join(root, file), 'utf8')
64
80
  if (file === 'package.json')
65
81
  write(file, text, upgradePackageJson(text))
82
+ else if (TSCONFIG_FILE_RE.test(file))
83
+ write(file, text, upgradeTsconfig(text, aliases))
84
+ else if (file === '.gitignore')
85
+ write(file, text, upgradeGitignore(text, isApp))
66
86
  else if (CONFIG_FILE_RE.test(file))
67
87
  write(file, text, apply(text, PATH_RULES))
68
- else if (BUILD_FILE_RE.test(file))
88
+ else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
69
89
  write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
70
90
  }
71
91
  for (const dir of CI_DIRS) {
@@ -77,9 +97,10 @@ export function upgradeProject(root: string): UpgradeResult {
77
97
  write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
78
98
  }
79
99
  }
80
- for (const file of sourceFiles(root)) {
100
+ const publicDir = configuredPublicDir(root)
101
+ for (const file of sourceFiles(root, publicDir)) {
81
102
  const text = readFileSync(join(root, file), 'utf8')
82
- const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text) : text
103
+ const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
83
104
  const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
84
105
  write(file, text, next)
85
106
  if (SOURCE_FILE_RE.test(file) && next !== text)
@@ -91,8 +112,9 @@ export function upgradeProject(root: string): UpgradeResult {
91
112
  changed.push(`${dir}/`)
92
113
  }
93
114
  }
94
- for (const member of workspaceMembers(root)) {
95
- const res = upgradeProject(join(root, member))
115
+ // 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.
116
+ for (const member of workspaceMembers(root).filter(m => hasKayOrPrunelle(join(root, m)))) {
117
+ const res = upgradeDir(join(root, member), aliases)
96
118
  changed.push(...res.changed.map(file => `${member}/${file}`))
97
119
  manual.push(...res.manual.map(line => `${member}/${line}`))
98
120
  }
@@ -102,6 +124,83 @@ export function upgradeProject(root: string): UpgradeResult {
102
124
  const DEP_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
103
125
  const V1_RANGE_RE = /^[~^>=\s]*1\./
104
126
 
127
+ const KAY_OR_PRUNELLE_RE = /^(?:npm:)?(?:@kayjs\/|prunelle(?:@|$)|@prunellejs\/)/
128
+
129
+ function hasKayOrPrunelle(root: string): boolean {
130
+ if (!existsSync(join(root, 'package.json')))
131
+ return false
132
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
133
+ return DEP_FIELDS.some(field => Object.entries(json[field] ?? {}).some(([name, range]) => KAY_OR_PRUNELLE_RE.test(name) || KAY_OR_PRUNELLE_RE.test(range)))
134
+ }
135
+
136
+ function kayTargetPackage(name: string, version: string): string | undefined {
137
+ if (name.startsWith('@kayjs/'))
138
+ return apply(name, PATH_RULES)
139
+ const match = NPM_KAY_ALIAS_RE.exec(version)
140
+ return match === null ? undefined : apply(match[1]!, PATH_RULES)
141
+ }
142
+
143
+ function kayAliases(root: string, inherited?: ReadonlyMap<string, string>): Map<string, string> {
144
+ const aliases = new Map<string, string>(inherited)
145
+ if (!existsSync(join(root, 'package.json')))
146
+ return aliases
147
+ const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
148
+ for (const field of DEP_FIELDS) {
149
+ for (const [name, version] of Object.entries(json[field] ?? {})) {
150
+ if (name.startsWith('@kayjs/'))
151
+ continue
152
+ const match = NPM_KAY_ALIAS_RE.exec(version)
153
+ if (match !== null)
154
+ aliases.set(name, apply(match[1]!, PATH_RULES))
155
+ }
156
+ }
157
+ return aliases
158
+ }
159
+
160
+ function upgradeTsconfig(text: string, aliases: ReadonlyMap<string, string>): string {
161
+ let out = apply(text, PATH_RULES)
162
+ for (const [alias, target] of aliases) {
163
+ const escaped = alias.replace(ESCAPE_RE, '\\$&')
164
+ if (target === 'prunelle')
165
+ out = out.replace(new RegExp(`("jsxImportSource"\\s*:\\s*")${escaped}(")`, 'g'), `$1${target}$2`)
166
+ out = out.replace(/"types"\s*:\s*\[[^\]]*\]/g, block =>
167
+ block.replace(new RegExp(`"${escaped}((?:/[^"]*)?)"`, 'g'), `"${target}$1"`))
168
+ }
169
+ return out
170
+ }
171
+
172
+ function upgradeGitignore(text: string, addCache: boolean): string {
173
+ const next = apply(text, PATH_RULES)
174
+ if (!addCache || GITIGNORE_CACHE_RE.test(next))
175
+ return next
176
+ const eol = next.includes('\r\n') ? '\r\n' : '\n'
177
+ const sep = next === '' || next.endsWith('\n') ? '' : eol
178
+ return `${next}${sep}.prunelle-cache/${eol}`
179
+ }
180
+
181
+ // Reads `publicDir` statically from prunelle.config.ts (or kay.config.ts) so built scripts in `public/` are left alone (#43).
182
+ function configuredPublicDir(root: string): string {
183
+ const file = existsSync(join(root, 'prunelle.config.ts'))
184
+ ? 'prunelle.config.ts'
185
+ : existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
186
+ if (file === undefined)
187
+ return resolve(root, 'public')
188
+ const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
189
+ let value: string | undefined
190
+ walk(program.body, (node) => {
191
+ if (value !== undefined)
192
+ return false
193
+ if (node.type === 'Property' && !node.computed && node.key.type === 'Identifier' && node.key.name === 'publicDir') {
194
+ if (node.value.type === 'Literal' && typeof node.value.value === 'string')
195
+ value = node.value.value
196
+ else if (node.value.type === 'TemplateLiteral' && node.value.expressions.length === 0)
197
+ value = node.value.quasis[0]?.value.cooked ?? node.value.quasis[0]?.value.raw
198
+ }
199
+ return true
200
+ })
201
+ return resolve(root, value ?? 'public')
202
+ }
203
+
105
204
  // 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
205
  function kayV1Dependency(root: string): string | undefined {
107
206
  if (!existsSync(join(root, 'package.json')))
@@ -149,18 +248,33 @@ function rootFiles(root: string): string[] {
149
248
  return readdirSync(root, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()
150
249
  }
151
250
 
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[] {
251
+ // The entries of `dir`, none for a folder the user cannot read: a container's data, never source they edit.
252
+ function readableEntries(dir: string): Dirent[] {
253
+ try {
254
+ return readdirSync(dir, { withFileTypes: true })
255
+ }
256
+ catch (err) {
257
+ if ((err as NodeJS.ErrnoException).code === 'EACCES' || (err as NodeJS.ErrnoException).code === 'EPERM')
258
+ return []
259
+ throw err
260
+ }
261
+ }
262
+
263
+ // A folder holding its own package.json is another package, upgraded on its own; `publicDir` holds built static files left untouched (#43).
264
+ function sourceFiles(root: string, publicDir: string, dir = root, out: string[] = []): string[] {
154
265
  if (dir !== root && existsSync(join(dir, 'package.json')))
155
266
  return out
156
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
267
+ for (const entry of readableEntries(dir)) {
157
268
  if (isNotSourceDir(entry.name))
158
269
  continue
159
270
  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))
271
+ if (entry.isDirectory()) {
272
+ if (resolve(path) !== publicDir)
273
+ sourceFiles(root, publicDir, path, out)
274
+ }
275
+ else if (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name)) {
163
276
  out.push(relPosix(root, path))
277
+ }
164
278
  }
165
279
  return out.sort()
166
280
  }
@@ -173,10 +287,17 @@ function upgradePackageJson(text: string): string {
173
287
  const range = `^${pkg.version}`
174
288
  for (const field of DEP_FIELDS) {
175
289
  const deps = json[field] as Record<string, string> | undefined
176
- if (deps === undefined || !Object.keys(deps).some(name => name.startsWith('@kayjs/')))
290
+ if (deps === undefined || !Object.entries(deps).some(([name, version]) => kayTargetPackage(name, version) !== undefined))
177
291
  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!)))
292
+ const next = new Map<string, string>()
293
+ for (const [name, version] of Object.entries(deps)) {
294
+ const target = kayTargetPackage(name, version)
295
+ if (target !== undefined)
296
+ next.set(target, range)
297
+ else if (!next.has(name))
298
+ next.set(name, version)
299
+ }
300
+ json[field] = Object.fromEntries([...next.entries()].sort(([a], [b]) => a.localeCompare(b)))
180
301
  }
181
302
  const scripts = json.scripts as Record<string, string> | undefined
182
303
  if (scripts !== undefined)
@@ -3,16 +3,19 @@
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'
11
14
  import { resolveInteractivity } from './interactivity'
12
15
  import { findNodeEnvReads } from './node-env'
13
16
  import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
14
17
  import { walkScoped } from './scope'
15
- import { calleeName, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
18
+ import { calleeName, createExprContext, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
16
19
  import { checkBareSignals } from './signal-reads'
17
20
 
18
21
  const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction'])
@@ -46,7 +49,13 @@ export interface ModuleAnalysis extends Interactivity {
46
49
  hasJsx: boolean
47
50
  /** Precomputed set of AST nodes containing JSX (itself included), for O(1) subtree checks during codegen. */
48
51
  jsxNodes: WeakSet<Node>
52
+ /** Lazily cached expression type/primitivity context shared between SSR and DOM compilers. */
53
+ exprContext?: ExprContext | undefined
49
54
  hasPrerender: boolean
55
+ /** True when the module explicitly exports `prerender = false`. */
56
+ prerenderFalse: boolean
57
+ /** Parsed `export const cache = ...` policy when present and valid. */
58
+ cache?: RouteCacheSpec | undefined
50
59
  hasPaths: boolean
51
60
  usesRenderContext: boolean
52
61
  defaultHydrate: string | undefined
@@ -272,6 +281,7 @@ interface DeclarationScan {
272
281
  hasLoadExport: boolean
273
282
  hasPaths: boolean
274
283
  hasPrerender: boolean
284
+ prerenderFalse: boolean
275
285
  defaultHydrate: string | undefined
276
286
  exportedActions: string[]
277
287
  /** The action() calls prunelle gives a URL to: the initialisers of top-level `export const`s. */
@@ -281,7 +291,7 @@ interface DeclarationScan {
281
291
  }
282
292
 
283
293
  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: [] }
294
+ 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
295
  const collectInits = (decl: VariableDeclaration): void => {
286
296
  for (const d of decl.declarations) {
287
297
  if (d.id.type === 'Identifier' && d.init !== null)
@@ -358,8 +368,12 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
358
368
  continue
359
369
  const name = d.id.name
360
370
  addExport(name, name)
361
- if (name === 'prerender' && d.init?.type === 'Literal' && d.init.value === true)
362
- scan.hasPrerender = true
371
+ if (name === 'prerender' && d.init?.type === 'Literal') {
372
+ if (d.init.value === true)
373
+ scan.hasPrerender = true
374
+ else if (d.init.value === false)
375
+ scan.prerenderFalse = true
376
+ }
363
377
  if (name === 'hydrate' && d.init !== null)
364
378
  scan.defaultHydrate = checkExportHydrate(d.init, filename)
365
379
  if (d.init !== null && isActionCall(d.init, imports.actionLocalName, imports.serverNamespaces)) {
@@ -476,9 +490,9 @@ function scanBody(program: Program, filename: string, code: string, imports: Imp
476
490
  }
477
491
  else if (node.type === 'JSXOpeningElement') {
478
492
  scanOpeningElement(node, binding, body, imports, filename)
479
- const root = jsxTagName(node.name).split('.')[0]!
480
- if (isComponentTag(root))
481
- ref(binding, root, node.start)
493
+ const tag = jsxTagName(node.name)
494
+ if (isComponentTag(tag))
495
+ ref(binding, tag.split('.')[0]!, node.start)
482
496
  }
483
497
  else if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && freeIds.has(node.object.start) && node.property.type === 'Identifier') {
484
498
  memberObjStarts.add(node.object.start)
@@ -560,6 +574,21 @@ function stateExportsOf(decls: DeclarationScan, callees: ReadonlySet<string>, co
560
574
  return [...decls.exportLocals].filter(([, local]) => containsStateInit(decls.localInits.get(local), callees, containers)).map(([exported]) => exported)
561
575
  }
562
576
 
577
+ const exprContextCache = new WeakMap<Program, ExprContext>()
578
+
579
+ /** Lazily computes and caches `ExprContext` on `analysis` (and by `program` across shallow copies) so SSR and DOM compilation never build it twice. */
580
+ export function getExprContext(analysis: ModuleAnalysis): ExprContext {
581
+ if (analysis.exprContext !== undefined)
582
+ return analysis.exprContext
583
+ let ctx = exprContextCache.get(analysis.program)
584
+ if (ctx === undefined) {
585
+ ctx = createExprContext(analysis.program, analysis.jsxNodes)
586
+ exprContextCache.set(analysis.program, ctx)
587
+ }
588
+ analysis.exprContext = ctx
589
+ return ctx
590
+ }
591
+
563
592
  export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
564
593
  const imports = scanImports(program, filename)
565
594
  const decls = scanDeclarations(program, filename, imports)
@@ -567,9 +596,10 @@ export function analyzeModule(filename: string, code: string, program: Program =
567
596
  const loadNodes = loadDeclarations(program)
568
597
  const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes))
569
598
  checkBareSignals(program, imports.signalCallees, filename)
599
+ const jsxNodes = body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>()
570
600
  if (body.hasJsx) {
571
601
  checkCompliance(program, filename, code, warnings, tag => resolvePrunelleTag(tag, imports.imports))
572
- checkBrowserGlobals(program, code, filename, warnings)
602
+ checkBrowserGlobals(program, code, filename, warnings, jsxNodes)
573
603
  }
574
604
 
575
605
  for (const [name, init] of decls.localInits) {
@@ -584,6 +614,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
584
614
  if (interactivity.serverOnly !== undefined)
585
615
  guarded(interactivity.serverOnly.offset, () => { throw serverOnlyTagError(filename, interactivity.serverOnly!) })
586
616
 
617
+ const cacheExport = parseCacheExport(program)
587
618
  return {
588
619
  filename,
589
620
  program,
@@ -592,8 +623,10 @@ export function analyzeModule(filename: string, code: string, program: Program =
592
623
  hasAsyncDefault,
593
624
  hasLoadExport: decls.hasLoadExport || loadNodes.length > 0,
594
625
  hasJsx: body.hasJsx,
595
- jsxNodes: body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>(),
626
+ jsxNodes,
596
627
  hasPrerender: decls.hasPrerender,
628
+ prerenderFalse: decls.prerenderFalse,
629
+ ...(cacheExport.spec !== undefined ? { cache: cacheExport.spec } : {}),
597
630
  hasPaths: decls.hasPaths,
598
631
  usesRenderContext: body.usesRenderContext,
599
632
  defaultHydrate: decls.defaultHydrate,
@@ -1,6 +1,6 @@
1
1
  // Warns on a browser global read while a component renders or its module loads: the server has no `window`, so the first request throws.
2
2
 
3
- import type { ArrowFunctionExpression, Node, Function as OxcFunction, Program } from 'oxc-parser'
3
+ import type { ArrowFunctionExpression, Node, Function as OxcFunction, Program, Statement } from 'oxc-parser'
4
4
  import type { CompilerWarning } from './mistakes'
5
5
  import { walk } from './ast'
6
6
  import { walkScoped } from './scope'
@@ -20,14 +20,35 @@ const MENTIONS_RE = new RegExp(`\\b(?:${[...BROWSER_GLOBALS].join('|')})\\b`)
20
20
  // Array methods whose callback runs at once, so while the component renders.
21
21
  const EAGER_CALLBACK_METHODS = new Set(['map', 'flatMap', 'filter', 'forEach', 'reduce', 'some', 'every', 'find', 'findIndex', 'sort', 'toSorted'])
22
22
 
23
+ const DEFINED_TYPEOF_VALUES = new Set(['object', 'function'])
24
+
23
25
  type FunctionNode = ArrowFunctionExpression | OxcFunction
24
26
 
25
27
  interface Read { name: string, start: number }
26
28
 
29
+ interface GuardSpan {
30
+ start: number
31
+ end: number
32
+ globals: ReadonlySet<string>
33
+ }
34
+
35
+ interface GuardPolarity {
36
+ positive: Set<string>
37
+ negative: Set<string>
38
+ }
39
+
27
40
  function topLevelFunctions(program: Program): Map<string, FunctionNode> {
28
41
  const fns = new Map<string, FunctionNode>()
29
42
  for (const stmt of program.body) {
30
- const decl = (stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration') ? stmt.declaration : stmt
43
+ if (stmt.type === 'ExportDefaultDeclaration') {
44
+ const decl = unwrapTsExpr(stmt.declaration)
45
+ if (decl.type === 'FunctionDeclaration' || decl.type === 'FunctionExpression')
46
+ fns.set(decl.id?.name ?? 'default', decl)
47
+ else if (decl.type === 'ArrowFunctionExpression')
48
+ fns.set('default', decl)
49
+ continue
50
+ }
51
+ const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
31
52
  if (decl?.type === 'FunctionDeclaration' && decl.id !== null) {
32
53
  fns.set(decl.id.name, decl)
33
54
  }
@@ -62,15 +83,87 @@ export function topLevelNames(program: Program): Set<string> {
62
83
  return names
63
84
  }
64
85
 
65
- /** Warns on each browser global the module reads at its top level, or while one of its components renders, itself or through a top-level helper it calls. */
66
- export function checkBrowserGlobals(program: Program, code: string, filename: string, warnings: CompilerWarning[]): void {
67
- if (!MENTIONS_RE.test(code))
86
+ function typeofBrowserGlobal(node: Node): string | undefined {
87
+ const inner = unwrapTsExpr(node)
88
+ if (inner.type === 'UnaryExpression' && inner.operator === 'typeof' && inner.argument.type === 'Identifier' && BROWSER_GLOBALS.has(inner.argument.name))
89
+ return inner.argument.name
90
+ return undefined
91
+ }
92
+
93
+ function stringLiteralValue(node: Node): string | undefined {
94
+ const inner = unwrapTsExpr(node)
95
+ return inner.type === 'Literal' && typeof inner.value === 'string' ? inner.value : undefined
96
+ }
97
+
98
+ function extractTypeofGuard(node: Node): GuardPolarity {
99
+ const positive = new Set<string>()
100
+ const negative = new Set<string>()
101
+ const inner = unwrapTsExpr(node)
102
+ if (inner.type === 'UnaryExpression' && inner.operator === '!') {
103
+ const sub = extractTypeofGuard(inner.argument)
104
+ return { positive: sub.negative, negative: sub.positive }
105
+ }
106
+ if (inner.type === 'LogicalExpression') {
107
+ const left = extractTypeofGuard(inner.left)
108
+ const right = extractTypeofGuard(inner.right)
109
+ if (inner.operator === '&&') {
110
+ for (const g of left.positive) positive.add(g)
111
+ for (const g of right.positive) positive.add(g)
112
+ }
113
+ else if (inner.operator === '||') {
114
+ for (const g of left.negative) negative.add(g)
115
+ for (const g of right.negative) negative.add(g)
116
+ }
117
+ return { positive, negative }
118
+ }
119
+ if (inner.type === 'BinaryExpression' && (inner.operator === '===' || inner.operator === '==' || inner.operator === '!==' || inner.operator === '!=')) {
120
+ const g = typeofBrowserGlobal(inner.left) ?? typeofBrowserGlobal(inner.right)
121
+ const lit = typeofBrowserGlobal(inner.left) !== undefined ? stringLiteralValue(inner.right) : stringLiteralValue(inner.left)
122
+ if (g !== undefined && lit !== undefined) {
123
+ const isNeg = inner.operator === '!==' || inner.operator === '!='
124
+ if (lit === 'undefined')
125
+ (isNeg ? positive : negative).add(g)
126
+ else if (DEFINED_TYPEOF_VALUES.has(lit))
127
+ (isNeg ? negative : positive).add(g)
128
+ }
129
+ }
130
+ return { positive, negative }
131
+ }
132
+
133
+ function definitelyExits(stmt: Statement): boolean {
134
+ if (stmt.type === 'ReturnStatement' || stmt.type === 'ThrowStatement')
135
+ return true
136
+ if (stmt.type === 'BlockStatement')
137
+ return stmt.body.length > 0 && definitelyExits(stmt.body[stmt.body.length - 1]!)
138
+ if (stmt.type === 'IfStatement')
139
+ return stmt.alternate !== null && definitelyExits(stmt.consequent) && definitelyExits(stmt.alternate)
140
+ return false
141
+ }
142
+
143
+ function collectEarlyReturnGuards(stmts: readonly Statement[], guards: GuardSpan[]): void {
144
+ const lastEnd = stmts[stmts.length - 1]?.end
145
+ if (lastEnd === undefined)
68
146
  return
69
- const shadowing = topLevelNames(program)
70
- const helpers = topLevelFunctions(program)
147
+ for (let i = 0; i < stmts.length - 1; i++) {
148
+ const stmt = stmts[i]!
149
+ if (stmt.type !== 'IfStatement' || !definitelyExits(stmt.consequent))
150
+ continue
151
+ const { negative } = extractTypeofGuard(stmt.test)
152
+ if (negative.size > 0)
153
+ guards.push({ start: stmts[i + 1]!.start, end: lastEnd, globals: negative })
154
+ }
155
+ }
156
+
157
+ function collectProgramMetadata(program: Program): { eagerCallbacks: WeakSet<Node>, calleeStarts: Set<number>, guards: GuardSpan[] } {
71
158
  const eagerCallbacks = new WeakSet<Node>()
72
159
  const calleeStarts = new Set<number>()
73
- const guards: number[] = []
160
+ const guards: GuardSpan[] = []
161
+
162
+ const addGuard = (node: Node | null | undefined, globals: ReadonlySet<string>): void => {
163
+ if (node !== null && node !== undefined && globals.size > 0)
164
+ guards.push({ start: node.start, end: node.end, globals })
165
+ }
166
+
74
167
  walk(program, (node) => {
75
168
  if (node.type === 'CallExpression') {
76
169
  const callee = unwrapTsExpr(node.callee)
@@ -80,11 +173,38 @@ export function checkBrowserGlobals(program: Program, code: string, filename: st
80
173
  eagerCallbacks.add(unwrapTsExpr(node.arguments[0]))
81
174
  }
82
175
  else if (node.type === 'UnaryExpression' && node.operator === 'typeof' && node.argument.type === 'Identifier' && BROWSER_GLOBALS.has(node.argument.name)) {
83
- guards.push(node.start)
176
+ guards.push({ start: node.argument.start, end: node.argument.end, globals: new Set([node.argument.name]) })
177
+ }
178
+ else if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
179
+ const { positive, negative } = extractTypeofGuard(node.test)
180
+ addGuard(node.consequent, positive)
181
+ addGuard(node.alternate, negative)
182
+ }
183
+ else if (node.type === 'LogicalExpression') {
184
+ const { positive, negative } = extractTypeofGuard(node.left)
185
+ if (node.operator === '&&')
186
+ addGuard(node.right, positive)
187
+ else if (node.operator === '||')
188
+ addGuard(node.right, negative)
189
+ }
190
+ else if (node.type === 'BlockStatement' || node.type === 'Program') {
191
+ collectEarlyReturnGuards(node.body, guards)
84
192
  }
85
193
  })
86
- // Code that checks `typeof window` (or another browser global) is written for both sides, so none of its reads is reported.
87
- const isGuarded = (node: Node): boolean => guards.some(start => start >= node.start && start < node.end)
194
+
195
+ return { eagerCallbacks, calleeStarts, guards }
196
+ }
197
+
198
+ /** Warns on each browser global the module reads at its top level, or while one of its components renders, itself or through a top-level helper it calls. */
199
+ export function checkBrowserGlobals(program: Program, code: string, filename: string, warnings: CompilerWarning[], jsxNodes?: WeakSet<Node>): void {
200
+ if (!MENTIONS_RE.test(code))
201
+ return
202
+ const shadowing = topLevelNames(program)
203
+ const helpers = topLevelFunctions(program)
204
+ const { eagerCallbacks, calleeStarts, guards } = collectProgramMetadata(program)
205
+
206
+ const isNameGuarded = (offset: number, name: string): boolean =>
207
+ guards.some(g => offset >= g.start && offset < g.end && (g.globals.has(name) || g.globals.has('window')))
88
208
 
89
209
  const readsOf = new Map<Node, Read[]>()
90
210
  const collect = (root: Node): Read[] => {
@@ -93,18 +213,21 @@ export function checkBrowserGlobals(program: Program, code: string, filename: st
93
213
  return known
94
214
  const reads: Read[] = []
95
215
  readsOf.set(root, reads)
96
- if (isGuarded(root))
97
- return reads
98
216
  walkScoped(root, {
99
217
  onFunction: fn => !eagerCallbacks.has(fn),
100
218
  onIdentifier: (id) => {
101
219
  if (BROWSER_GLOBALS.has(id.name) && !shadowing.has(id.name)) {
102
- reads.push({ name: id.name, start: id.start })
220
+ if (!isNameGuarded(id.start, id.name))
221
+ reads.push({ name: id.name, start: id.start })
103
222
  return
104
223
  }
105
224
  const helper = calleeStarts.has(id.start) ? helpers.get(id.name) : undefined
106
- if (helper !== undefined)
107
- reads.push(...collect(helper))
225
+ if (helper !== undefined) {
226
+ for (const read of collect(helper)) {
227
+ if (!isNameGuarded(id.start, read.name))
228
+ reads.push(read)
229
+ }
230
+ }
108
231
  },
109
232
  })
110
233
  return reads
@@ -121,7 +244,7 @@ export function checkBrowserGlobals(program: Program, code: string, filename: st
121
244
  }
122
245
  report(collect(program), 'when the module loads')
123
246
  for (const [name, fn] of helpers) {
124
- if (containsJsx(fn))
247
+ if (containsJsx(fn, jsxNodes))
125
248
  report(collect(fn), `while <${name}> renders`)
126
249
  }
127
250
  }