prunelle 0.9.0 → 0.10.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 (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
@@ -110,19 +110,29 @@ function headerOwner(obj: Node): string {
110
110
  return inner.type === 'MemberExpression' && inner.object.type === 'Identifier' && inner.object.name === 'ctx' ? 'ctx' : 'request'
111
111
  }
112
112
 
113
+ // `request`, `req`, `ctx`, `ctx.request` or an alias the walk tracked: a `.headers` of anything else (a fetch `Response`, a local record) is not the visitor's.
114
+ function isRequestExpr(node: Node, lookupAlias: (name: string) => AliasKind | undefined): boolean {
115
+ const inner = unwrapTsExpr(node)
116
+ if (inner.type === 'Identifier') {
117
+ const kind = lookupAlias(inner.name)
118
+ return kind === 'request' || kind === 'param' || (kind === undefined && (inner.name === 'request' || inner.name === 'req' || inner.name === 'ctx'))
119
+ }
120
+ return inner.type === 'MemberExpression' && memberPropName(inner) === 'request'
121
+ }
122
+
113
123
  function isHeadersExpr(node: Node, lookupAlias: (name: string) => AliasKind | undefined, allowBareHeaders: boolean): boolean {
114
124
  const inner = unwrapTsExpr(node)
115
125
  if (inner.type === 'Identifier') {
116
126
  const kind = lookupAlias(inner.name)
117
127
  return kind === 'headers' || (allowBareHeaders && kind === undefined && inner.name === 'headers')
118
128
  }
119
- return inner.type === 'MemberExpression' && memberPropName(inner) === 'headers'
129
+ return inner.type === 'MemberExpression' && memberPropName(inner) === 'headers' && isRequestExpr(inner.object, lookupAlias)
120
130
  }
121
131
 
122
132
  export function checkHeaderCall(
123
133
  node: Extract<Node, { type: 'CallExpression' }>,
124
134
  lookupAlias: (name: string) => AliasKind | undefined = () => undefined,
125
- allowBareHeaders = true,
135
+ allowBareHeaders = false,
126
136
  ): string | undefined {
127
137
  const callee = unwrapTsExpr(node.callee)
128
138
  if (callee.type !== 'MemberExpression' || !isHeadersExpr(callee.object, lookupAlias, allowBareHeaders))
@@ -297,7 +307,7 @@ function exprAliasKind(node: Node, lookup: (name: string) => AliasKind | undefin
297
307
  const obj = unwrapTsExpr(inner.object)
298
308
  if (key === 'request' && obj.type === 'Identifier' && lookup(obj.name) === 'param')
299
309
  return 'request'
300
- if (key === 'headers')
310
+ if (key === 'headers' && isRequestExpr(obj, lookup))
301
311
  return 'headers'
302
312
  }
303
313
  return undefined
@@ -31,7 +31,11 @@ const SELECTOR_SCHEME_RE = /\[data-theme\s*=\s*["']?(light|dark)["']?\s*\]|\.(li
31
31
  const OPAQUE_AT_RULE_RE = /^@(?:keyframes|-webkit-keyframes|font-face|property|page|counter-style|font-feature-values)\b/
32
32
  const HEX_RE = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i
33
33
  const FUNCTION_COLOR_RE = /^(rgba?|hsla?)\(([^()]*)\)$/i
34
- const FONT_SIZE_RE = /^([\d.]+)(px|rem|pt)$/
34
+ const FONT_SIZE_RE = /^([\d.]+)(px|rem|em|pt)$/
35
+ const BOLD_RE = /^(?:bold|bolder|\d{3,4})$/
36
+ const SIZE_KEYWORDS: Record<string, number> = {
37
+ 'xx-small': 9, 'x-small': 10, 'small': 13, 'medium': 16, 'large': 18, 'x-large': 24, 'xx-large': 32, 'xxx-large': 48,
38
+ }
35
39
  // The 17 colours of CSS 2.1 and their common aliases; a name outside them is not resolved, so its rule is skipped.
36
40
  const NAMED: Record<string, Rgb> = {
37
41
  black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
@@ -218,10 +222,27 @@ export function parseColor(raw: string): Rgb | undefined {
218
222
  return undefined
219
223
  if (fn[1]!.startsWith('rgb')) {
220
224
  const [r, g, b] = [channel(parts[0]!, 255), channel(parts[1]!, 255), channel(parts[2]!, 255)]
221
- return r === undefined || g === undefined || b === undefined ? undefined : [Math.round(r), Math.round(g), Math.round(b)]
225
+ return r === undefined || g === undefined || b === undefined ? undefined : [clamp255(r), clamp255(g), clamp255(b)]
226
+ }
227
+ const [h, s, l] = [hueDegrees(parts[0]!), channel(parts[1]!, 1), channel(parts[2]!, 1)]
228
+ return h === undefined || s === undefined || l === undefined ? undefined : hslToRgb(((h % 360) + 360) % 360, clamp01(s), clamp01(l))
229
+ }
230
+
231
+ const clamp255 = (n: number): number => Math.max(0, Math.min(255, Math.round(n)))
232
+ const clamp01 = (n: number): number => Math.max(0, Math.min(1, n))
233
+
234
+ // A hue in degrees: a bare number or `deg`, or `grad`, `rad` and `turn`; any other unit is not read.
235
+ function hueDegrees(raw: string): number | undefined {
236
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/.exec(raw)
237
+ if (match === null)
238
+ return undefined
239
+ const n = Number.parseFloat(match[1]!)
240
+ switch (match[2]) {
241
+ case 'grad': return n * 0.9
242
+ case 'rad': return n * 180 / Math.PI
243
+ case 'turn': return n * 360
244
+ default: return n
222
245
  }
223
- const [h, s, l] = [Number.parseFloat(parts[0]!), channel(parts[1]!, 1), channel(parts[2]!, 1)]
224
- return Number.isNaN(h) || s === undefined || l === undefined ? undefined : hslToRgb(((h % 360) + 360) % 360, s, l)
225
246
  }
226
247
 
227
248
  function luminance(rgb: Rgb): number {
@@ -238,14 +259,31 @@ export function contrastRatio(a: Rgb, b: Rgb): number {
238
259
  return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
239
260
  }
240
261
 
241
- // Text from 24px, or from 18.66px when bold, needs 3:1 instead of 4.5:1.
242
- function isLargeText(decls: ReadonlyMap<string, string>): boolean {
243
- const size = FONT_SIZE_RE.exec(decls.get('font-size') ?? '')
262
+ // A font size in px: a length (`em` read against the 16px default) or a keyword.
263
+ function pxOfSize(token: string): number | undefined {
264
+ if (Object.hasOwn(SIZE_KEYWORDS, token))
265
+ return SIZE_KEYWORDS[token]
266
+ const size = FONT_SIZE_RE.exec(token)
244
267
  if (size === null)
268
+ return undefined
269
+ return Number.parseFloat(size[1]!) * (size[2] === 'rem' || size[2] === 'em' ? 16 : size[2] === 'pt' ? 4 / 3 : 1)
270
+ }
271
+
272
+ // Text from 24px, or from 18.66px when bold, needs 3:1 instead of 4.5:1; the size and weight come from `font-size` and `font-weight`, else from the `font` shorthand.
273
+ function isLargeText(decls: ReadonlyMap<string, string>): boolean {
274
+ const shorthand = (decls.get('font') ?? '').toLowerCase().split(/\s+/)
275
+ let px = pxOfSize((decls.get('font-size') ?? '').toLowerCase())
276
+ if (px === undefined) {
277
+ for (const token of shorthand) {
278
+ px = pxOfSize(token.split('/')[0]!)
279
+ if (px !== undefined)
280
+ break
281
+ }
282
+ }
283
+ if (px === undefined)
245
284
  return false
246
- const px = Number.parseFloat(size[1]!) * (size[2] === 'rem' ? 16 : size[2] === 'pt' ? 4 / 3 : 1)
247
- const weight = decls.get('font-weight') ?? ''
248
- const bold = weight === 'bold' || weight === 'bolder' || Number.parseInt(weight, 10) >= 700
285
+ const weight = (decls.get('font-weight') ?? shorthand.find(token => BOLD_RE.test(token)) ?? '').toLowerCase()
286
+ const bold = BOLD_RE.test(weight) && (weight === 'bold' || weight === 'bolder' || Number.parseInt(weight, 10) >= 700)
249
287
  return px >= 24 || (bold && px >= 18.66)
250
288
  }
251
289
 
@@ -0,0 +1,72 @@
1
+ // The rule ids `compliance.ignore` and `prunelle-ignore` comments name, and the config that silences them.
2
+
3
+ import type { ContrastRule } from './compliance-contrast'
4
+ import type { EcoJsxRule } from './compliance-eco'
5
+ import type { RgaaJsxRule } from './compliance-rgaa'
6
+ import type { RgaaPageRule } from './compliance-rgaa-pages'
7
+ import type { PrunellePluginRules } from '../plugins/public'
8
+ import { ECO_JSX_RULES } from './compliance-eco'
9
+ import { RGAA_JSX_RULES } from './compliance-rgaa'
10
+
11
+ export type ComplianceRule =
12
+ | RgaaJsxRule
13
+ | RgaaPageRule
14
+ | ContrastRule
15
+ | EcoJsxRule
16
+ | 'rgesn/large-public-file'
17
+ | 'rgesn/declaration'
18
+ | 'rgesn/island-by-value'
19
+ | 'rgpd/third-party-url'
20
+ | 'rgpd/consent-retention'
21
+ | 'rgpd/consent-preferences'
22
+ | 'rgpd/cookie-category'
23
+ | 'rgpd/cookie-purpose'
24
+ | 'rgpd/privacy-notice'
25
+ | 'lcen/legal-notice'
26
+ | 'rgaa/document-lang'
27
+ | 'rgaa/accessibility-statement'
28
+ | 'security/csrf-off'
29
+ | 'security/proxy-no-site'
30
+ | 'security/html-sink'
31
+ | FormWarningRule
32
+
33
+ /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
34
+ export type FormWarningRule = 'action/unguarded-public-form' | 'form/invalid-option' | 'form/schema-unsupported' | 'form/unchecked'
35
+
36
+ export interface ComplianceConfig {
37
+ /** Compliance rules to silence across the app, the warning rules of the plugins it uses included. */
38
+ ignore?: readonly (ComplianceRule | keyof PrunellePluginRules)[] | undefined
39
+ /** Set `true` for French public-sector sites (RGAA requires an accessibility statement page). */
40
+ publicBody?: boolean | undefined
41
+ /** Custom route path for the legal notice page, or `false` to silence `lcen/legal-notice`. */
42
+ legalNotice?: string | false | undefined
43
+ /** Custom route path for the privacy notice page, or `false` to silence `rgpd/privacy-notice`. */
44
+ privacyNotice?: string | false | undefined
45
+ }
46
+
47
+ export const COMPLIANCE_RULES = new Set<ComplianceRule>([
48
+ ...RGAA_JSX_RULES,
49
+ ...ECO_JSX_RULES,
50
+ 'rgesn/large-public-file',
51
+ 'rgesn/declaration',
52
+ 'rgesn/island-by-value',
53
+ 'rgpd/third-party-url',
54
+ 'rgpd/consent-retention',
55
+ 'rgpd/consent-preferences',
56
+ 'rgpd/cookie-category',
57
+ 'rgpd/cookie-purpose',
58
+ 'rgpd/privacy-notice',
59
+ 'lcen/legal-notice',
60
+ 'rgaa/document-lang',
61
+ 'rgaa/accessibility-statement',
62
+ 'rgaa/skip-link',
63
+ 'rgaa/page-title',
64
+ 'rgaa/contrast',
65
+ 'security/csrf-off',
66
+ 'security/proxy-no-site',
67
+ 'security/html-sink',
68
+ 'action/unguarded-public-form',
69
+ 'form/invalid-option',
70
+ 'form/schema-unsupported',
71
+ 'form/unchecked',
72
+ ])
@@ -4,9 +4,9 @@ import type { JSXElement, Node, Program } from 'oxc-parser'
4
4
  import type { ModuleAnalysis } from './analyze'
5
5
  import type { EcoJsxRule } from './compliance-eco'
6
6
  import type { RgaaJsxRule, RgaaScope } from './compliance-rgaa'
7
- import type { ContrastRule } from './compliance-contrast'
8
- import type { RgaaPageRule } from './compliance-rgaa-pages'
7
+
9
8
  import type { CompilerWarning } from './mistakes'
9
+ import type { ComplianceConfig, ComplianceRule } from './compliance-rules'
10
10
  import { existsSync, readFileSync } from 'node:fs'
11
11
  import { basename, join } from 'node:path'
12
12
  import { parseSync, visitorKeys } from 'oxc-parser'
@@ -23,11 +23,12 @@ import {
23
23
  hasNonEmptyAttr,
24
24
  INTERACTIVE_ANCESTORS,
25
25
  mergeRgaaScope,
26
- RGAA_JSX_RULES,
26
+
27
27
  staticStringValueOf,
28
28
  } from './compliance-rgaa'
29
29
  import { STATEMENT_PLACEHOLDER } from '../a11y/declaration'
30
- import { checkEcoElement, ECO_JSX_RULES, largePublicFileWarnings } from './compliance-eco'
30
+ import { checkEcoElement, largePublicFileWarnings } from './compliance-eco'
31
+ import { COMPLIANCE_RULES } from './compliance-rules'
31
32
  import { contrastFindings } from './compliance-contrast'
32
33
  import { rendersNoText } from './compliance-empty'
33
34
  import { rgaaPageFindings } from './compliance-rgaa-pages'
@@ -35,68 +36,7 @@ import { checkThirdPartyComponent, checkThirdPartyElement } from './compliance-t
35
36
  import { CSS_IMPORT_RE, CSS_URL_RE, parseOrigin, thirdPartyOrigin } from './compliance-urls'
36
37
  import { formatDiagnostic, formatLoc, getLineStarts, isComponentTag, jsxTagName, lineIndexAtOffset, unwrapTsExpr } from './shared'
37
38
 
38
- export type ComplianceRule =
39
- | RgaaJsxRule
40
- | RgaaPageRule
41
- | ContrastRule
42
- | EcoJsxRule
43
- | 'rgesn/large-public-file'
44
- | 'rgesn/declaration'
45
- | 'rgesn/island-by-value'
46
- | 'rgpd/third-party-url'
47
- | 'rgpd/consent-retention'
48
- | 'rgpd/consent-preferences'
49
- | 'rgpd/cookie-category'
50
- | 'rgpd/cookie-purpose'
51
- | 'rgpd/privacy-notice'
52
- | 'lcen/legal-notice'
53
- | 'rgaa/document-lang'
54
- | 'rgaa/accessibility-statement'
55
- | 'security/csrf-off'
56
- | 'security/proxy-no-site'
57
- | 'security/html-sink'
58
- | FormWarningRule
59
-
60
- /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
61
- export type FormWarningRule = 'action/unguarded-public-form' | 'form/invalid-option' | 'form/schema-unsupported' | 'form/unchecked'
62
-
63
- export interface ComplianceConfig {
64
- /** Compliance rules to silence across the app. */
65
- ignore?: readonly ComplianceRule[] | undefined
66
- /** Set `true` for French public-sector sites (RGAA requires an accessibility statement page). */
67
- publicBody?: boolean | undefined
68
- /** Custom route path for the legal notice page, or `false` to silence `lcen/legal-notice`. */
69
- legalNotice?: string | false | undefined
70
- /** Custom route path for the privacy notice page, or `false` to silence `rgpd/privacy-notice`. */
71
- privacyNotice?: string | false | undefined
72
- }
73
-
74
- const COMPLIANCE_RULES = new Set<ComplianceRule>([
75
- ...RGAA_JSX_RULES,
76
- ...ECO_JSX_RULES,
77
- 'rgesn/large-public-file',
78
- 'rgesn/declaration',
79
- 'rgesn/island-by-value',
80
- 'rgpd/third-party-url',
81
- 'rgpd/consent-retention',
82
- 'rgpd/consent-preferences',
83
- 'rgpd/cookie-category',
84
- 'rgpd/cookie-purpose',
85
- 'rgpd/privacy-notice',
86
- 'lcen/legal-notice',
87
- 'rgaa/document-lang',
88
- 'rgaa/accessibility-statement',
89
- 'rgaa/skip-link',
90
- 'rgaa/page-title',
91
- 'rgaa/contrast',
92
- 'security/csrf-off',
93
- 'security/proxy-no-site',
94
- 'security/html-sink',
95
- 'action/unguarded-public-form',
96
- 'form/invalid-option',
97
- 'form/schema-unsupported',
98
- 'form/unchecked',
99
- ])
39
+ export type { ComplianceConfig, ComplianceRule, FormWarningRule } from './compliance-rules'
100
40
 
101
41
  // The CNIL recommends keeping a cookie choice, consent or refusal, 6 months before asking again.
102
42
  const CNIL_CHOICE_MAX_AGE = 15_552_000
@@ -4,23 +4,143 @@ import type { JSXElement, Node, Program } from 'oxc-parser'
4
4
  import { walk } from './ast'
5
5
  import { DELEGATED_EVENTS } from './emit'
6
6
  import { isStaticPropExpr } from './props'
7
- import {
8
- cleanJsxText,
9
- collectPatternNames,
10
- DOM_PROPS,
11
- escapeRawText,
12
- escapeStaticAttr,
13
- EVENT_ATTR,
14
- filterMeaningfulChildren,
15
- isBlockedAttr,
16
- isStringBoolAttr,
17
- isUnsafeUrlAttr,
18
- jsxTagName,
19
- unwrapTsExpr,
20
- } from './shared'
7
+ import { cleanJsxText, collectPatternNames, DOM_PROPS, escapeRawText, escapeStaticAttr, EVENT_ATTR, filterMeaningfulChildren, isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr, jsxTagName, unwrapTsExpr } from './shared'
21
8
  import { formatStaticAttrValue, formatStaticStyleExpr, staticLiteralOrTemplate } from './ssr-helpers'
22
9
 
23
10
  const SIMPLE_CALLEE_RE = /^[A-Za-z_$][\w$.]*$/
11
+ const PURE_CALL_GLOBALS = new Set(['String', 'Number', 'Boolean', 'parseInt', 'parseFloat', 'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent'])
12
+ const PURE_UNARY_OPS = new Set(['!', '+', '-', '~', 'typeof', 'void'])
13
+ const ROW_SIGNAL_RE = /^_(?:r|i)\d+\.value$/
14
+ const SIMPLE_PROP_RE = /^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*$/
15
+ const LEAF_DOM_OPS = ['setText', 'setClass', 'setAttr', 'setStyle'] as const
16
+ const DELEGATED_EVENT_OP_RE = /^_e\d+\.\$\$[a-z]+ = /
17
+
18
+ function collectMemberDepKeys(node: Extract<Node, { type: 'MemberExpression' }>, scopeRewrites: ReadonlyMap<string, string>, keys: Set<string>): boolean {
19
+ const segments: { computed: boolean, name?: string, expr?: Node }[] = []
20
+ let cur: Node = node
21
+ while (cur.type === 'MemberExpression' || cur.type === 'ChainExpression') {
22
+ if (cur.type === 'ChainExpression') {
23
+ cur = unwrapTsExpr(cur.expression)
24
+ continue
25
+ }
26
+ if (cur.computed)
27
+ segments.push({ computed: true, expr: cur.property })
28
+ else if (cur.property.type === 'Identifier')
29
+ segments.push({ computed: false, name: cur.property.name })
30
+ else
31
+ return false
32
+ cur = unwrapTsExpr(cur.object)
33
+ }
34
+ if (cur.type !== 'Identifier')
35
+ return false
36
+ segments.reverse()
37
+ if (segments.some(s => s.computed && !collectLeafDepKeys(s.expr!, scopeRewrites, keys)))
38
+ return false
39
+ const rw = scopeRewrites.get(cur.name)
40
+ if (rw !== undefined) {
41
+ if (ROW_SIGNAL_RE.test(rw)) {
42
+ keys.add(`row:${rw}`)
43
+ return true
44
+ }
45
+ if (!SIMPLE_PROP_RE.test(rw) || segments.some(s => s.computed))
46
+ return false
47
+ keys.add(`rw:${rw}.${segments.map(s => s.name).join('.')}`)
48
+ return true
49
+ }
50
+ if (!segments[0]!.computed && segments[0]!.name === 'value') {
51
+ keys.add(`sig:${cur.name}`)
52
+ return true
53
+ }
54
+ if (segments.some(s => s.computed))
55
+ return false
56
+ const path = segments.map(s => s.name!)
57
+ keys.add(path[path.length - 1] === 'value' ? `sig:${cur.name}.${path.slice(0, -1).join('.')}` : `mem:${cur.name}.${path.join('.')}`)
58
+ return true
59
+ }
60
+
61
+ function collectLeafDepKeys(rawNode: Node, scopeRewrites: ReadonlyMap<string, string>, keys: Set<string>): boolean {
62
+ const node = unwrapTsExpr(rawNode)
63
+ switch (node.type) {
64
+ case 'Literal': return true
65
+ case 'ChainExpression': return collectLeafDepKeys(node.expression, scopeRewrites, keys)
66
+ case 'TemplateLiteral': return node.expressions.every(e => collectLeafDepKeys(e, scopeRewrites, keys))
67
+ case 'UnaryExpression': return PURE_UNARY_OPS.has(node.operator) && collectLeafDepKeys(node.argument, scopeRewrites, keys)
68
+ case 'BinaryExpression':
69
+ case 'LogicalExpression': return collectLeafDepKeys(node.left, scopeRewrites, keys) && collectLeafDepKeys(node.right, scopeRewrites, keys)
70
+ case 'ConditionalExpression': return collectLeafDepKeys(node.test, scopeRewrites, keys) && collectLeafDepKeys(node.consequent, scopeRewrites, keys) && collectLeafDepKeys(node.alternate, scopeRewrites, keys)
71
+ case 'ObjectExpression': return node.properties.every(p => p.type === 'Property' && p.kind === 'init' && (!p.computed || collectLeafDepKeys(p.key, scopeRewrites, keys)) && collectLeafDepKeys(p.value, scopeRewrites, keys))
72
+ case 'ArrayExpression': return node.elements.every(el => el === null || (el.type !== 'SpreadElement' && collectLeafDepKeys(el, scopeRewrites, keys)))
73
+ case 'CallExpression': {
74
+ const c = node.callee
75
+ const isPure = (c.type === 'Identifier' && PURE_CALL_GLOBALS.has(c.name))
76
+ || (c.type === 'MemberExpression' && !c.computed && c.object.type === 'Identifier' && c.object.name === 'Math' && c.property.type === 'Identifier')
77
+ return isPure && node.arguments.every(a => a.type !== 'SpreadElement' && collectLeafDepKeys(a, scopeRewrites, keys))
78
+ }
79
+ case 'Identifier': {
80
+ const rw = scopeRewrites.get(node.name)
81
+ if (rw === undefined)
82
+ return true
83
+ if (ROW_SIGNAL_RE.test(rw)) { keys.add(`row:${rw}`); return true }
84
+ if (SIMPLE_PROP_RE.test(rw)) { keys.add(`rw:${rw}`); return true }
85
+ return false
86
+ }
87
+ case 'MemberExpression': return collectMemberDepKeys(node, scopeRewrites, keys)
88
+ default: return false
89
+ }
90
+ }
91
+
92
+ /** Returns a canonical key when `rawNode` is a pure leaf expression subscribing to exactly one reactive root/path, or `undefined` when coalescing could break fine-grained updates or hide calls. */
93
+ export function extractLeafDepKey(rawNode: Node, scopeRewrites: ReadonlyMap<string, string>, isStyle = false): string | undefined {
94
+ if (isStyle) {
95
+ const root = unwrapTsExpr(rawNode)
96
+ if (root.type === 'Identifier' || root.type === 'MemberExpression' || root.type === 'ChainExpression')
97
+ return undefined
98
+ }
99
+ const keys = new Set<string>()
100
+ return collectLeafDepKeys(rawNode, scopeRewrites, keys) && keys.size === 1 ? keys.values().next().value : undefined
101
+ }
102
+
103
+ /** Merges barrier-free leaf DOM effects sharing the exact same single reactive dependency key into one `__effect` placed at the last op of the group. */
104
+ export function coalesceLeafEffects(ops: string[], depKeys: ReadonlyMap<number, string>, alias: (name: string) => string): void {
105
+ if (depKeys.size < 2)
106
+ return
107
+ const effPrefix = `${alias('effect')}(() => `
108
+ const effSuffix = ');'
109
+ const leafPrefixes = LEAF_DOM_OPS.map(name => `${alias(name)}(`)
110
+ const isNonBarrier = (op: string): boolean => {
111
+ if (op.startsWith('const _txt') || DELEGATED_EVENT_OP_RE.test(op))
112
+ return true
113
+ const body = op.startsWith(effPrefix) && op.endsWith(effSuffix) ? op.slice(effPrefix.length, -effSuffix.length) : op
114
+ return leafPrefixes.some(p => body.startsWith(p))
115
+ }
116
+ const groups = new Map<string, number[]>()
117
+ let merged = false
118
+ const flush = (): void => {
119
+ for (const indices of groups.values()) {
120
+ if (indices.length < 2)
121
+ continue
122
+ const stmts = indices.map(idx => ops[idx]!.slice(effPrefix.length, -effSuffix.length))
123
+ for (let j = 0; j < indices.length - 1; j++)
124
+ ops[indices[j]!] = ''
125
+ ops[indices[indices.length - 1]!] = `${effPrefix}{ ${stmts.join('; ')}; }${effSuffix}`
126
+ merged = true
127
+ }
128
+ groups.clear()
129
+ }
130
+ for (let i = 0; i < ops.length; i++) {
131
+ const op = ops[i]!
132
+ if (!isNonBarrier(op)) {
133
+ flush()
134
+ continue
135
+ }
136
+ const key = depKeys.get(i)
137
+ if (key !== undefined && op.startsWith(effPrefix) && op.endsWith(effSuffix))
138
+ groups.set(key, [...(groups.get(key) ?? []), i])
139
+ }
140
+ flush()
141
+ if (merged)
142
+ ops.splice(0, ops.length, ...ops.filter(op => op !== ''))
143
+ }
24
144
 
25
145
  function isPlainInitObject(node: Node): boolean {
26
146
  const cur = unwrapTsExpr(node)
@@ -88,6 +208,29 @@ function wrapDomOp(stmt: string, isStatic: boolean, use: (name: string) => strin
88
208
  return isStatic ? `${stmt};` : `${use('effect')}(() => ${stmt});`
89
209
  }
90
210
 
211
+ function pushLeafDomOp(
212
+ ops: string[],
213
+ depKeys: Map<number, string> | undefined,
214
+ stmt: string,
215
+ expr: Node,
216
+ scopeRewrites: ReadonlyMap<string, string>,
217
+ use: (name: string) => string,
218
+ isStyle = false,
219
+ staticStyleNames?: ReadonlySet<string>,
220
+ ): void {
221
+ if (isStaticDomExpr(expr, scopeRewrites, isStyle, staticStyleNames)) {
222
+ ops.push(`${stmt};`)
223
+ return
224
+ }
225
+ const idx = ops.length
226
+ ops.push(`${use('effect')}(() => ${stmt});`)
227
+ if (depKeys !== undefined) {
228
+ const key = extractLeafDepKey(expr, scopeRewrites, isStyle)
229
+ if (key !== undefined)
230
+ depKeys.set(idx, key)
231
+ }
232
+ }
233
+
91
234
  export function formatSetTextOp(
92
235
  targetVar: string,
93
236
  exprCode: string,
@@ -98,6 +241,18 @@ export function formatSetTextOp(
98
241
  return wrapDomOp(`${use('setText')}(${targetVar}, ${exprCode})`, isStaticDomExpr(expr, scopeRewrites), use)
99
242
  }
100
243
 
244
+ export function pushTextSlotOp(
245
+ ops: string[],
246
+ depKeys: Map<number, string>,
247
+ targetVar: string,
248
+ exprCode: string,
249
+ expr: Node,
250
+ scopeRewrites: ReadonlyMap<string, string>,
251
+ use: (name: string) => string,
252
+ ): void {
253
+ pushLeafDomOp(ops, depKeys, `${use('setText')}(${targetVar}, ${exprCode})`, expr, scopeRewrites, use)
254
+ }
255
+
101
256
  /** Rewrites a JSX component tag's root identifier through `scopeRewrites` (`<Icon />` -> `__p.Icon`, `<ui.Icon />` -> `__p.ui.Icon`). */
102
257
  export function resolveComponentCallee(tag: string, scopeRewrites: ReadonlyMap<string, string>): string {
103
258
  const dot = tag.indexOf('.')
@@ -116,6 +271,7 @@ export interface ElementAttrCompileContext {
116
271
  scopeRewrites: ReadonlyMap<string, string>
117
272
  staticStyleNames?: ReadonlySet<string> | undefined
118
273
  ops: string[]
274
+ depKeys?: Map<number, string> | undefined
119
275
  postChildOps: string[]
120
276
  delegatedEvents: Set<string>
121
277
  use: (name: string) => string
@@ -129,14 +285,14 @@ function emitDomExprAttr(
129
285
  expr: Node,
130
286
  isSelect: boolean,
131
287
  ): string {
132
- const { tag, elVar, scopeRewrites, staticStyleNames, ops, postChildOps, use, compileExpression } = ctx
288
+ const { tag, elVar, scopeRewrites, staticStyleNames, ops, depKeys, postChildOps, use, compileExpression } = ctx
133
289
 
134
290
  if (name === 'style') {
135
291
  const staticStyle = formatStaticStyleExpr(expr)
136
292
  if (staticStyle !== undefined)
137
293
  return staticStyle
138
294
  const exprCode = compileExpression(expr, scopeRewrites)
139
- ops.push(wrapDomOp(`${use('setStyle')}(${elVar}, ${exprCode})`, isStaticDomExpr(expr, scopeRewrites, true, staticStyleNames), use))
295
+ pushLeafDomOp(ops, depKeys, `${use('setStyle')}(${elVar}, ${exprCode})`, expr, scopeRewrites, use, true, staticStyleNames)
140
296
  return ''
141
297
  }
142
298
 
@@ -150,19 +306,19 @@ function emitDomExprAttr(
150
306
  }
151
307
 
152
308
  const exprCode = compileExpression(expr, scopeRewrites)
153
- const isStatic = isStaticDomExpr(expr, scopeRewrites)
154
309
  if (name === 'class') {
155
- ops.push(wrapDomOp(`${use('setClass')}(${elVar}, ${exprCode})`, isStatic, use))
310
+ pushLeafDomOp(ops, depKeys, `${use('setClass')}(${elVar}, ${exprCode})`, expr, scopeRewrites, use)
156
311
  }
157
312
  else if (DOM_PROPS.has(name)) {
158
- const targetOps = isSelect && name === 'value' ? postChildOps : ops
313
+ const isSelectVal = isSelect && name === 'value'
314
+ const targetOps = isSelectVal ? postChildOps : ops
159
315
  // Only a <select multiple> pulls in setSelectValues, so other pages ship none of it.
160
- const multiple = isSelect && name === 'value' && ctx.el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
316
+ const multiple = isSelectVal && ctx.el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
161
317
  const call = multiple ? `${use('setSelectValues')}(${elVar}, ${exprCode})` : `${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`
162
- targetOps.push(wrapDomOp(call, isStatic, use))
318
+ pushLeafDomOp(targetOps, undefined, call, expr, scopeRewrites, use)
163
319
  }
164
320
  else {
165
- ops.push(wrapDomOp(`${use('setAttr')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
321
+ pushLeafDomOp(ops, depKeys, `${use('setAttr')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, expr, scopeRewrites, use)
166
322
  }
167
323
  return ''
168
324
  }