prunelle 0.1.1 → 0.7.2

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 (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
package/ts-plugin.cjs ADDED
@@ -0,0 +1,4277 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // packages/prunelle/src/ts-plugin/index.ts
40
+ var exports_ts_plugin = {};
41
+ __export(exports_ts_plugin, {
42
+ PRUNELLE_CODE: () => PRUNELLE_CODE,
43
+ PRUNELLE_DIAG_SOURCE: () => PRUNELLE_DIAG_SOURCE,
44
+ PRUNELLE_FIXABLE_CODES: () => PRUNELLE_FIXABLE_CODES,
45
+ collectPrunelleDiagnostics: () => collectPrunelleDiagnostics,
46
+ createPrunellePlugin: () => createPrunellePlugin,
47
+ default: () => ts_plugin_default,
48
+ getPrunelleCodeFixes: () => getPrunelleCodeFixes,
49
+ getPrunelleDiagnostics: () => getPrunelleDiagnostics
50
+ });
51
+ module.exports = __toCommonJS(exports_ts_plugin);
52
+
53
+ // packages/prunelle/src/ts-plugin/diagnostics.ts
54
+ var import_node_fs = require("node:fs");
55
+ var import_node_path2 = require("node:path");
56
+ var import_oxc_parser8 = require("oxc-parser");
57
+
58
+ // packages/prunelle/src/build/files.ts
59
+ var import_node_path = require("node:path");
60
+ var BACKSLASH_RE = /\\/g;
61
+ var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
62
+ function relPosix(from, to) {
63
+ return import_node_path.relative(from, to).replace(BACKSLASH_RE, "/");
64
+ }
65
+ function isInNodeModules(file) {
66
+ return NODE_MODULES_RE.test(file);
67
+ }
68
+
69
+ // packages/prunelle/src/compiler/analyze.ts
70
+ var import_oxc_parser7 = require("oxc-parser");
71
+
72
+ // packages/prunelle/src/compiler/ast.ts
73
+ var import_oxc_parser = require("oxc-parser");
74
+ function computeJsxNodes(program) {
75
+ const jsxNodes = new WeakSet;
76
+ const visit = (node) => {
77
+ if (node === null || typeof node !== "object")
78
+ return false;
79
+ if (Array.isArray(node)) {
80
+ let any = false;
81
+ for (let i = 0;i < node.length; i++) {
82
+ if (visit(node[i]))
83
+ any = true;
84
+ }
85
+ return any;
86
+ }
87
+ const ast = node;
88
+ const type = ast.type;
89
+ if (typeof type !== "string")
90
+ return false;
91
+ let found = type === "JSXElement" || type === "JSXFragment";
92
+ const keys = import_oxc_parser.visitorKeys[type];
93
+ if (keys !== undefined) {
94
+ const rec = ast;
95
+ for (let i = 0;i < keys.length; i++) {
96
+ const val = rec[keys[i]];
97
+ if (val !== null && typeof val === "object" && visit(val))
98
+ found = true;
99
+ }
100
+ } else {
101
+ for (const [key, val] of Object.entries(ast)) {
102
+ if (key === "start" || key === "end" || key === "type")
103
+ continue;
104
+ if (val !== null && typeof val === "object" && visit(val))
105
+ found = true;
106
+ }
107
+ }
108
+ if (found)
109
+ jsxNodes.add(ast);
110
+ return found;
111
+ };
112
+ visit(program);
113
+ return jsxNodes;
114
+ }
115
+ function walk(node, visit) {
116
+ if (node === null || typeof node !== "object")
117
+ return;
118
+ if (Array.isArray(node)) {
119
+ for (let i = 0;i < node.length; i++)
120
+ walk(node[i], visit);
121
+ return;
122
+ }
123
+ const ast = node;
124
+ const type = ast.type;
125
+ if (typeof type !== "string")
126
+ return;
127
+ if (visit(ast) === false)
128
+ return;
129
+ const keys = import_oxc_parser.visitorKeys[type];
130
+ if (keys !== undefined) {
131
+ const rec = ast;
132
+ for (let i = 0;i < keys.length; i++) {
133
+ const val = rec[keys[i]];
134
+ if (val !== null && typeof val === "object")
135
+ walk(val, visit);
136
+ }
137
+ return;
138
+ }
139
+ for (const [key, val] of Object.entries(ast)) {
140
+ if (key === "start" || key === "end" || key === "type")
141
+ continue;
142
+ if (val !== null && typeof val === "object")
143
+ walk(val, visit);
144
+ }
145
+ }
146
+
147
+ // packages/prunelle/src/compiler/scope.ts
148
+ var import_oxc_parser2 = require("oxc-parser");
149
+
150
+ // packages/prunelle/src/attrs.ts
151
+ var URL_ATTRS = new Set(["href", "src", "action", "formaction", "xlink:href", "data"]);
152
+ var UNSAFE_URL_RE = /^(?:javascript|vbscript):/i;
153
+ var SAFE_IMAGE_DATA_URL_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|ico|x-icon|vnd\.microsoft\.icon|svg\+xml)[;,]/i;
154
+ var STRING_BOOL_ATTRS = new Set(["draggable", "spellcheck", "contenteditable"]);
155
+ var DOM_PROPS = new Set(["value", "checked", "selected", "muted", "indeterminate"]);
156
+ function isUnsafeUrlAttr(name, value, tag) {
157
+ const lower = name.toLowerCase();
158
+ if (!URL_ATTRS.has(lower))
159
+ return false;
160
+ const cleaned = String(value).replace(/[\u0000-\u0020]+/g, "");
161
+ if (UNSAFE_URL_RE.test(cleaned))
162
+ return true;
163
+ if (!/^data:/i.test(cleaned))
164
+ return false;
165
+ if (lower === "src" || lower === "href" && tag?.toLowerCase() === "link")
166
+ return !SAFE_IMAGE_DATA_URL_RE.test(cleaned);
167
+ return true;
168
+ }
169
+ // packages/prunelle/src/compiler/shared.ts
170
+ var VOID_ELEMENTS = new Set([
171
+ "area",
172
+ "base",
173
+ "br",
174
+ "col",
175
+ "embed",
176
+ "hr",
177
+ "img",
178
+ "input",
179
+ "link",
180
+ "meta",
181
+ "param",
182
+ "source",
183
+ "track",
184
+ "wbr"
185
+ ]);
186
+ var RAW_TEXT_ELEMENTS = new Set(["style", "script"]);
187
+ var EVENT_ATTR = /^on([A-Z]\w*)$/;
188
+ var LINE_BREAK_RE = /\r\n|\n|\r/;
189
+ var HTML_ENTITIES = {
190
+ amp: "&",
191
+ lt: "<",
192
+ gt: ">",
193
+ quot: '"',
194
+ apos: "'",
195
+ nbsp: " ",
196
+ ensp: " ",
197
+ emsp: " ",
198
+ thinsp: " ",
199
+ zwnj: "‌",
200
+ zwj: "‍",
201
+ lrm: "‎",
202
+ rlm: "‏",
203
+ shy: "­",
204
+ ndash: "–",
205
+ mdash: "—",
206
+ lsquo: "‘",
207
+ rsquo: "’",
208
+ sbquo: "‚",
209
+ ldquo: "“",
210
+ rdquo: "”",
211
+ bdquo: "„",
212
+ hellip: "…",
213
+ bull: "•",
214
+ middot: "·",
215
+ laquo: "«",
216
+ raquo: "»",
217
+ lsaquo: "‹",
218
+ rsaquo: "›",
219
+ prime: "′",
220
+ Prime: "″",
221
+ sect: "§",
222
+ para: "¶",
223
+ dagger: "†",
224
+ Dagger: "‡",
225
+ permil: "‰",
226
+ iexcl: "¡",
227
+ iquest: "¿",
228
+ brvbar: "¦",
229
+ macr: "¯",
230
+ acute: "´",
231
+ cedil: "¸",
232
+ uml: "¨",
233
+ ordf: "ª",
234
+ ordm: "º",
235
+ not: "¬",
236
+ loz: "◊",
237
+ spades: "♠",
238
+ clubs: "♣",
239
+ hearts: "♥",
240
+ diams: "♦",
241
+ star: "☆",
242
+ check: "✓",
243
+ checkmark: "✓",
244
+ cross: "✗",
245
+ copy: "©",
246
+ reg: "®",
247
+ trade: "™",
248
+ euro: "€",
249
+ pound: "£",
250
+ yen: "¥",
251
+ cent: "¢",
252
+ curren: "¤",
253
+ deg: "°",
254
+ plusmn: "±",
255
+ times: "×",
256
+ divide: "÷",
257
+ frac12: "½",
258
+ frac14: "¼",
259
+ frac34: "¾",
260
+ sup1: "¹",
261
+ sup2: "²",
262
+ sup3: "³",
263
+ micro: "µ",
264
+ minus: "−",
265
+ ne: "≠",
266
+ le: "≤",
267
+ ge: "≥",
268
+ approx: "≈",
269
+ infin: "∞",
270
+ sum: "∑",
271
+ prod: "∏",
272
+ radic: "√",
273
+ int: "∫",
274
+ part: "∂",
275
+ empty: "∅",
276
+ nabla: "∇",
277
+ isin: "∈",
278
+ notin: "∉",
279
+ ni: "∋",
280
+ cap: "∩",
281
+ cup: "∪",
282
+ sub: "⊂",
283
+ sup: "⊃",
284
+ nsub: "⊄",
285
+ sube: "⊆",
286
+ supe: "⊇",
287
+ oplus: "⊕",
288
+ otimes: "⊗",
289
+ perp: "⊥",
290
+ sdot: "⋅",
291
+ equiv: "≡",
292
+ cong: "≅",
293
+ asymp: "≈",
294
+ prop: "∝",
295
+ and: "∧",
296
+ or: "∨",
297
+ forall: "∀",
298
+ exist: "∃",
299
+ larr: "←",
300
+ uarr: "↑",
301
+ rarr: "→",
302
+ darr: "↓",
303
+ harr: "↔",
304
+ crarr: "↵",
305
+ lArr: "⇐",
306
+ uArr: "⇑",
307
+ rArr: "⇒",
308
+ dArr: "⇓",
309
+ hArr: "⇔",
310
+ Alpha: "Α",
311
+ Beta: "Β",
312
+ Gamma: "Γ",
313
+ Delta: "Δ",
314
+ Epsilon: "Ε",
315
+ Zeta: "Ζ",
316
+ Eta: "Η",
317
+ Theta: "Θ",
318
+ Iota: "Ι",
319
+ Kappa: "Κ",
320
+ Lambda: "Λ",
321
+ Mu: "Μ",
322
+ Nu: "Ν",
323
+ Xi: "Ξ",
324
+ Omicron: "Ο",
325
+ Pi: "Π",
326
+ Rho: "Ρ",
327
+ Sigma: "Σ",
328
+ Tau: "Τ",
329
+ Upsilon: "Υ",
330
+ Phi: "Φ",
331
+ Chi: "Χ",
332
+ Psi: "Ψ",
333
+ Omega: "Ω",
334
+ alpha: "α",
335
+ beta: "β",
336
+ gamma: "γ",
337
+ delta: "δ",
338
+ epsilon: "ε",
339
+ zeta: "ζ",
340
+ eta: "η",
341
+ theta: "θ",
342
+ iota: "ι",
343
+ kappa: "κ",
344
+ lambda: "λ",
345
+ mu: "μ",
346
+ nu: "ν",
347
+ xi: "ξ",
348
+ omicron: "ο",
349
+ pi: "π",
350
+ rho: "ρ",
351
+ sigmaf: "ς",
352
+ sigma: "σ",
353
+ tau: "τ",
354
+ upsilon: "υ",
355
+ phi: "φ",
356
+ chi: "χ",
357
+ psi: "ψ",
358
+ omega: "ω",
359
+ Agrave: "À",
360
+ Aacute: "Á",
361
+ Acirc: "Â",
362
+ Atilde: "Ã",
363
+ Auml: "Ä",
364
+ Aring: "Å",
365
+ AElig: "Æ",
366
+ Ccedil: "Ç",
367
+ Egrave: "È",
368
+ Eacute: "É",
369
+ Ecirc: "Ê",
370
+ Euml: "Ë",
371
+ Igrave: "Ì",
372
+ Iacute: "Í",
373
+ Icirc: "Î",
374
+ Iuml: "Ï",
375
+ ETH: "Ð",
376
+ Ntilde: "Ñ",
377
+ Ograve: "Ò",
378
+ Oacute: "Ó",
379
+ Ocirc: "Ô",
380
+ Otilde: "Õ",
381
+ Ouml: "Ö",
382
+ Oslash: "Ø",
383
+ Ugrave: "Ù",
384
+ Uacute: "Ú",
385
+ Ucirc: "Û",
386
+ Uuml: "Ü",
387
+ Yacute: "Ý",
388
+ THORN: "Þ",
389
+ szlig: "ß",
390
+ agrave: "à",
391
+ aacute: "á",
392
+ acirc: "â",
393
+ atilde: "ã",
394
+ auml: "ä",
395
+ aring: "å",
396
+ aelig: "æ",
397
+ ccedil: "ç",
398
+ egrave: "è",
399
+ eacute: "é",
400
+ ecirc: "ê",
401
+ euml: "ë",
402
+ igrave: "ì",
403
+ iacute: "í",
404
+ icirc: "î",
405
+ iuml: "ï",
406
+ eth: "ð",
407
+ ntilde: "ñ",
408
+ ograve: "ò",
409
+ oacute: "ó",
410
+ ocirc: "ô",
411
+ otilde: "õ",
412
+ ouml: "ö",
413
+ oslash: "ø",
414
+ ugrave: "ù",
415
+ uacute: "ú",
416
+ ucirc: "û",
417
+ uuml: "ü",
418
+ yacute: "ý",
419
+ thorn: "þ",
420
+ yuml: "ÿ",
421
+ OElig: "Œ",
422
+ oelig: "œ",
423
+ Scaron: "Š",
424
+ scaron: "š",
425
+ Yuml: "Ÿ"
426
+ };
427
+ var ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));/g;
428
+ function decodeHtmlEntities(str) {
429
+ if (!str.includes("&"))
430
+ return str;
431
+ return str.replace(ENTITY_RE, (match, dec, hex, named) => {
432
+ if (dec !== undefined) {
433
+ const cp = Number.parseInt(dec, 10);
434
+ return cp === 0 || cp > 1114111 || cp >= 55296 && cp <= 57343 ? "�" : String.fromCodePoint(cp);
435
+ }
436
+ if (hex !== undefined) {
437
+ const cp = Number.parseInt(hex, 16);
438
+ return cp === 0 || cp > 1114111 || cp >= 55296 && cp <= 57343 ? "�" : String.fromCodePoint(cp);
439
+ }
440
+ if (named !== undefined && Object.hasOwn(HTML_ENTITIES, named))
441
+ return HTML_ENTITIES[named];
442
+ return match;
443
+ });
444
+ }
445
+ function offsetToLineCol(code, offset) {
446
+ let line = 1;
447
+ let col = 1;
448
+ const end = Math.min(Math.max(0, offset), code.length);
449
+ for (let i = 0;i < end; i++) {
450
+ if (code.charCodeAt(i) === 10) {
451
+ line++;
452
+ col = 1;
453
+ } else {
454
+ col++;
455
+ }
456
+ }
457
+ return { line, col };
458
+ }
459
+ function formatLoc(filename, code, offset) {
460
+ if (offset === undefined || offset < 0)
461
+ return filename;
462
+ const { line, col } = offsetToLineCol(code, offset);
463
+ return `${filename}:${line}:${col}`;
464
+ }
465
+ function formatCodeFrame(code, offset, endOffset) {
466
+ if (code.length === 0)
467
+ return "";
468
+ const clamped = Math.min(Math.max(0, offset), code.length);
469
+ const { line, col } = offsetToLineCol(code, clamped);
470
+ const lines = code.split(/\r?\n/);
471
+ const lineIdx = Math.min(line - 1, lines.length - 1);
472
+ const startIdx = Math.max(0, lineIdx - 1);
473
+ const endIdx = Math.min(lines.length - 1, lineIdx + 1);
474
+ const gutterWidth = String(endIdx + 1).length;
475
+ const pad = (n) => String(n).padStart(gutterWidth, " ");
476
+ const targetLine = lines[lineIdx] ?? "";
477
+ const maxSpan = Math.max(1, targetLine.length - (col - 1));
478
+ const rawSpan = endOffset !== undefined && endOffset > clamped ? endOffset - clamped : 1;
479
+ const caretLen = Math.max(1, Math.min(rawSpan, maxSpan));
480
+ const out = [];
481
+ for (let i = startIdx;i <= endIdx; i++) {
482
+ const text = lines[i] ?? "";
483
+ out.push(` ${pad(i + 1)} | ${text}`);
484
+ if (i === lineIdx)
485
+ out.push(` ${pad("")} | ${" ".repeat(Math.max(0, col - 1))}${"^".repeat(caretLen)}`);
486
+ }
487
+ return out.join(`
488
+ `);
489
+ }
490
+ function formatDiagnostic(loc, message, severity = "error") {
491
+ return `${loc}: ${severity}: ${message}`;
492
+ }
493
+ function cleanJsxText(raw) {
494
+ if (!LINE_BREAK_RE.test(raw))
495
+ return raw;
496
+ const lines = raw.split(LINE_BREAK_RE);
497
+ let out = "";
498
+ for (let i = 0;i < lines.length; i++) {
499
+ let line = lines[i].replace(/\t/g, " ");
500
+ if (i > 0)
501
+ line = line.replace(/^ +/, "");
502
+ if (i < lines.length - 1)
503
+ line = line.replace(/ +$/, "");
504
+ if (line !== "") {
505
+ if (out !== "")
506
+ out += " ";
507
+ out += line;
508
+ }
509
+ }
510
+ return out;
511
+ }
512
+ function jsxTagName(node) {
513
+ if (node.type === "JSXIdentifier")
514
+ return node.name;
515
+ if (node.type === "JSXMemberExpression")
516
+ return `${jsxTagName(node.object)}.${node.property.name}`;
517
+ if (node.type === "JSXNamespacedName")
518
+ return `${node.namespace.name}:${node.name.name}`;
519
+ return "";
520
+ }
521
+ function isComponentTag(tag) {
522
+ const first = tag.charCodeAt(0);
523
+ return first >= 65 && first <= 90 || tag.includes(".");
524
+ }
525
+ function unwrapParens(node) {
526
+ let cur = node;
527
+ while (cur.type === "ParenthesizedExpression")
528
+ cur = cur.expression;
529
+ return cur;
530
+ }
531
+ function calleeName(callee) {
532
+ if (callee.type === "Identifier")
533
+ return callee.name;
534
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.property.type === "Identifier")
535
+ return `${callee.object.name}.${callee.property.name}`;
536
+ return "";
537
+ }
538
+ function unwrapTsExpr(node) {
539
+ let cur = node;
540
+ while (cur.type === "ParenthesizedExpression" || cur.type === "TSAsExpression" || cur.type === "TSSatisfiesExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion") {
541
+ cur = cur.expression;
542
+ }
543
+ return cur;
544
+ }
545
+ function staticLiteral(node) {
546
+ const n = unwrapParens(node);
547
+ if (n.type === "Literal") {
548
+ const v = n.value;
549
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v === null)
550
+ return { ok: true, value: v };
551
+ }
552
+ if (n.type === "UnaryExpression" && n.operator === "-" && n.argument.type === "Literal" && typeof n.argument.value === "number")
553
+ return { ok: true, value: -n.argument.value };
554
+ return { ok: false };
555
+ }
556
+ function isJsxNode(node) {
557
+ return node?.type === "JSXElement" || node?.type === "JSXFragment";
558
+ }
559
+ function containsJsx(node, jsxNodes) {
560
+ if (node === null || node === undefined)
561
+ return false;
562
+ if (jsxNodes !== undefined)
563
+ return jsxNodes.has(node);
564
+ let found = false;
565
+ walk(node, (child) => {
566
+ if (found)
567
+ return false;
568
+ if (isJsxNode(child))
569
+ found = true;
570
+ return;
571
+ });
572
+ return found;
573
+ }
574
+ function filterMeaningfulChildren(children) {
575
+ return children.filter((c) => {
576
+ if (c.type === "JSXText")
577
+ return cleanJsxText(c.value) !== "";
578
+ if (c.type === "JSXExpressionContainer" && c.expression.type === "JSXEmptyExpression")
579
+ return false;
580
+ if (c.type === "JSXExpressionContainer" && c.expression.type === "Literal" && c.expression.value === "")
581
+ return false;
582
+ return true;
583
+ });
584
+ }
585
+ function collectPatternNames(pattern, out) {
586
+ if (pattern === null || pattern === undefined)
587
+ return;
588
+ switch (pattern.type) {
589
+ case "Identifier":
590
+ out.add(pattern.name);
591
+ return;
592
+ case "AssignmentPattern":
593
+ collectPatternNames(pattern.left, out);
594
+ return;
595
+ case "RestElement":
596
+ collectPatternNames(pattern.argument, out);
597
+ return;
598
+ case "TSParameterProperty":
599
+ collectPatternNames(pattern.parameter, out);
600
+ return;
601
+ case "ArrayPattern":
602
+ for (const el of pattern.elements) {
603
+ if (el !== null)
604
+ collectPatternNames(el, out);
605
+ }
606
+ return;
607
+ case "ObjectPattern":
608
+ for (const prop of pattern.properties) {
609
+ if (prop.type === "RestElement")
610
+ collectPatternNames(prop.argument, out);
611
+ else
612
+ collectPatternNames(prop.value, out);
613
+ }
614
+ }
615
+ }
616
+ var PRUNELLE_TAGS = new Set(["Head", "Region", "Suspense", "ConsentGate", "Catch"]);
617
+ function resolvePrunelleTag(tag, imports) {
618
+ let boundElsewhere = false;
619
+ for (const imp of imports) {
620
+ const isPrunelle = imp.source === "prunelle";
621
+ for (const spec of imp.specifiers) {
622
+ if (isPrunelle) {
623
+ if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
624
+ return spec.imported;
625
+ if (spec.imported === "*" && tag.startsWith(`${spec.local}.`)) {
626
+ const member = tag.slice(spec.local.length + 1);
627
+ if (PRUNELLE_TAGS.has(member))
628
+ return member;
629
+ }
630
+ } else if (spec.local === tag) {
631
+ boundElsewhere = true;
632
+ }
633
+ }
634
+ }
635
+ if (!boundElsewhere && PRUNELLE_TAGS.has(tag))
636
+ return tag;
637
+ return;
638
+ }
639
+
640
+ // packages/prunelle/src/compiler/scope.ts
641
+ function walkScoped(rootNode, callbacks) {
642
+ const { shouldStop, onIdentifier, onWrite, onShorthandProperty, onJsx, onFunction } = callbacks;
643
+ const reportPatternWrites = (target, shadowed) => {
644
+ if (onWrite === undefined)
645
+ return;
646
+ const written = new Set;
647
+ collectPatternNames(target, written);
648
+ for (const name of written) {
649
+ if (!shadowed.has(name))
650
+ onWrite(name, shadowed);
651
+ }
652
+ };
653
+ function visitPatternDefaults(pattern, shadowed) {
654
+ if (pattern === null || pattern === undefined || shouldStop?.())
655
+ return;
656
+ switch (pattern.type) {
657
+ case "AssignmentPattern":
658
+ visitPatternDefaults(pattern.left, shadowed);
659
+ visit(pattern.right, shadowed);
660
+ return;
661
+ case "RestElement":
662
+ visitPatternDefaults(pattern.argument, shadowed);
663
+ return;
664
+ case "TSParameterProperty":
665
+ visitPatternDefaults(pattern.parameter, shadowed);
666
+ return;
667
+ case "ArrayPattern":
668
+ for (const el of pattern.elements)
669
+ visitPatternDefaults(el, shadowed);
670
+ return;
671
+ case "ObjectPattern":
672
+ for (const prop of pattern.properties) {
673
+ if (prop.type === "RestElement") {
674
+ visitPatternDefaults(prop.argument, shadowed);
675
+ } else {
676
+ if (prop.computed)
677
+ visit(prop.key, shadowed);
678
+ visitPatternDefaults(prop.value, shadowed);
679
+ }
680
+ }
681
+ }
682
+ }
683
+ function visit(node, shadowed) {
684
+ if (node === null || node === undefined || shouldStop?.())
685
+ return;
686
+ if (onJsx !== undefined && isJsxNode(node)) {
687
+ onJsx(node, shadowed);
688
+ return;
689
+ }
690
+ switch (node.type) {
691
+ case "Identifier": {
692
+ if (!shadowed.has(node.name))
693
+ onIdentifier?.(node, shadowed);
694
+ return;
695
+ }
696
+ case "MemberExpression": {
697
+ visit(node.object, shadowed);
698
+ if (node.computed)
699
+ visit(node.property, shadowed);
700
+ return;
701
+ }
702
+ case "MetaProperty":
703
+ case "BreakStatement":
704
+ case "ContinueStatement":
705
+ return;
706
+ case "LabeledStatement": {
707
+ visit(node.body, shadowed);
708
+ return;
709
+ }
710
+ case "Property": {
711
+ if (node.computed)
712
+ visit(node.key, shadowed);
713
+ if (node.shorthand && node.value.type === "Identifier" && onShorthandProperty?.(node, shadowed) === true)
714
+ return;
715
+ visit(node.value, shadowed);
716
+ return;
717
+ }
718
+ case "MethodDefinition":
719
+ case "PropertyDefinition": {
720
+ if (node.computed)
721
+ visit(node.key, shadowed);
722
+ visit(node.value, shadowed);
723
+ return;
724
+ }
725
+ case "ClassDeclaration":
726
+ case "ClassExpression": {
727
+ const next = new Set(shadowed);
728
+ if (node.id !== null)
729
+ next.add(node.id.name);
730
+ visit(node.superClass, shadowed);
731
+ visit(node.body, next);
732
+ return;
733
+ }
734
+ case "CatchClause": {
735
+ const next = new Set(shadowed);
736
+ visitPatternDefaults(node.param, next);
737
+ collectPatternNames(node.param, next);
738
+ visit(node.body, next);
739
+ return;
740
+ }
741
+ case "ForStatement": {
742
+ const next = new Set(shadowed);
743
+ if (node.init !== null) {
744
+ if (node.init.type === "VariableDeclaration") {
745
+ for (const d of node.init.declarations) {
746
+ visit(d.init, next);
747
+ visitPatternDefaults(d.id, next);
748
+ collectPatternNames(d.id, next);
749
+ }
750
+ } else {
751
+ visit(node.init, next);
752
+ }
753
+ }
754
+ visit(node.test, next);
755
+ visit(node.update, next);
756
+ visit(node.body, next);
757
+ return;
758
+ }
759
+ case "AssignmentExpression": {
760
+ reportPatternWrites(node.left, shadowed);
761
+ visit(node.left, shadowed);
762
+ visit(node.right, shadowed);
763
+ return;
764
+ }
765
+ case "UpdateExpression": {
766
+ if (onWrite !== undefined && node.argument.type === "Identifier" && !shadowed.has(node.argument.name))
767
+ onWrite(node.argument.name, shadowed);
768
+ visit(node.argument, shadowed);
769
+ return;
770
+ }
771
+ case "ForInStatement":
772
+ case "ForOfStatement": {
773
+ visit(node.right, shadowed);
774
+ const next = new Set(shadowed);
775
+ if (node.left.type === "VariableDeclaration") {
776
+ for (const d of node.left.declarations) {
777
+ visitPatternDefaults(d.id, next);
778
+ collectPatternNames(d.id, next);
779
+ }
780
+ } else {
781
+ reportPatternWrites(node.left, next);
782
+ visit(node.left, next);
783
+ }
784
+ visit(node.body, next);
785
+ return;
786
+ }
787
+ case "SwitchStatement": {
788
+ visit(node.discriminant, shadowed);
789
+ const caseShadow = new Set(shadowed);
790
+ for (const c of node.cases) {
791
+ for (const stmt of c.consequent) {
792
+ if (stmt.type === "FunctionDeclaration" && stmt.id !== null)
793
+ caseShadow.add(stmt.id.name);
794
+ else if (stmt.type === "ClassDeclaration" && stmt.id !== null)
795
+ caseShadow.add(stmt.id.name);
796
+ }
797
+ }
798
+ for (const c of node.cases) {
799
+ visit(c.test, caseShadow);
800
+ for (const stmt of c.consequent) {
801
+ if (stmt.type === "VariableDeclaration") {
802
+ for (const d of stmt.declarations) {
803
+ visit(d.init, caseShadow);
804
+ visitPatternDefaults(d.id, caseShadow);
805
+ collectPatternNames(d.id, caseShadow);
806
+ }
807
+ } else {
808
+ visit(stmt, caseShadow);
809
+ }
810
+ }
811
+ }
812
+ return;
813
+ }
814
+ case "ArrowFunctionExpression":
815
+ case "FunctionExpression":
816
+ case "FunctionDeclaration": {
817
+ if (node !== rootNode && onFunction?.(node, shadowed) === true)
818
+ return;
819
+ const nextShadow = new Set(shadowed);
820
+ if (node.type !== "ArrowFunctionExpression" && node.id !== null)
821
+ nextShadow.add(node.id.name);
822
+ for (const p of node.params) {
823
+ visitPatternDefaults(p, nextShadow);
824
+ collectPatternNames(p, nextShadow);
825
+ }
826
+ visit(node.body, nextShadow);
827
+ return;
828
+ }
829
+ case "BlockStatement": {
830
+ const nextShadow = new Set(shadowed);
831
+ for (const stmt of node.body) {
832
+ if (stmt.type === "FunctionDeclaration" && stmt.id !== null)
833
+ nextShadow.add(stmt.id.name);
834
+ else if (stmt.type === "ClassDeclaration" && stmt.id !== null)
835
+ nextShadow.add(stmt.id.name);
836
+ }
837
+ for (const stmt of node.body) {
838
+ if (stmt.type === "VariableDeclaration") {
839
+ for (const d of stmt.declarations) {
840
+ visit(d.init, nextShadow);
841
+ visitPatternDefaults(d.id, nextShadow);
842
+ collectPatternNames(d.id, nextShadow);
843
+ }
844
+ } else {
845
+ visit(stmt, nextShadow);
846
+ }
847
+ }
848
+ return;
849
+ }
850
+ case "VariableDeclaration": {
851
+ const nextShadow = new Set(shadowed);
852
+ for (const d of node.declarations) {
853
+ visit(d.init, nextShadow);
854
+ visitPatternDefaults(d.id, nextShadow);
855
+ collectPatternNames(d.id, nextShadow);
856
+ }
857
+ return;
858
+ }
859
+ case "VariableDeclarator": {
860
+ visit(node.init, shadowed);
861
+ visitPatternDefaults(node.id, shadowed);
862
+ return;
863
+ }
864
+ case "TSAsExpression":
865
+ case "TSNonNullExpression":
866
+ case "TSSatisfiesExpression":
867
+ case "TSTypeAssertion":
868
+ case "TSInstantiationExpression": {
869
+ visit(node.expression, shadowed);
870
+ return;
871
+ }
872
+ default: {
873
+ if (node.type.startsWith("TS"))
874
+ return;
875
+ const keys = import_oxc_parser2.visitorKeys[node.type];
876
+ if (keys !== undefined) {
877
+ const rec = node;
878
+ for (let i = 0;i < keys.length; i++) {
879
+ const val = rec[keys[i]];
880
+ if (Array.isArray(val)) {
881
+ for (let j = 0;j < val.length; j++) {
882
+ const item = val[j];
883
+ if (item !== null && typeof item === "object" && "type" in item)
884
+ visit(item, shadowed);
885
+ }
886
+ } else if (val !== null && typeof val === "object" && "type" in val) {
887
+ visit(val, shadowed);
888
+ }
889
+ }
890
+ return;
891
+ }
892
+ for (const [key, val] of Object.entries(node)) {
893
+ if (key === "start" || key === "end" || key === "type")
894
+ continue;
895
+ if (Array.isArray(val)) {
896
+ for (let i = 0;i < val.length; i++) {
897
+ const item = val[i];
898
+ if (item !== null && typeof item === "object" && "type" in item)
899
+ visit(item, shadowed);
900
+ }
901
+ } else if (val !== null && typeof val === "object" && "type" in val) {
902
+ visit(val, shadowed);
903
+ }
904
+ }
905
+ }
906
+ }
907
+ }
908
+ visit(rootNode, new Set);
909
+ }
910
+
911
+ // packages/prunelle/src/compiler/browser-globals.ts
912
+ var BROWSER_GLOBALS = new Set([
913
+ "window",
914
+ "document",
915
+ "localStorage",
916
+ "sessionStorage",
917
+ "location",
918
+ "history",
919
+ "screen",
920
+ "indexedDB",
921
+ "caches",
922
+ "customElements",
923
+ "matchMedia",
924
+ "requestAnimationFrame",
925
+ "cancelAnimationFrame",
926
+ "getComputedStyle",
927
+ "getSelection",
928
+ "innerWidth",
929
+ "innerHeight",
930
+ "scrollX",
931
+ "scrollY",
932
+ "devicePixelRatio",
933
+ "visualViewport",
934
+ "IntersectionObserver",
935
+ "ResizeObserver",
936
+ "MutationObserver",
937
+ "HTMLElement",
938
+ "Notification"
939
+ ]);
940
+ var MENTIONS_RE = new RegExp(`\\b(?:${[...BROWSER_GLOBALS].join("|")})\\b`);
941
+ var EAGER_CALLBACK_METHODS = new Set(["map", "flatMap", "filter", "forEach", "reduce", "some", "every", "find", "findIndex", "sort", "toSorted"]);
942
+ function topLevelFunctions(program) {
943
+ const fns = new Map;
944
+ for (const stmt of program.body) {
945
+ const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
946
+ if (decl?.type === "FunctionDeclaration" && decl.id !== null) {
947
+ fns.set(decl.id.name, decl);
948
+ } else if (decl?.type === "VariableDeclaration") {
949
+ for (const d of decl.declarations) {
950
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init);
951
+ if (d.id.type === "Identifier" && (init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression"))
952
+ fns.set(d.id.name, init);
953
+ }
954
+ }
955
+ }
956
+ return fns;
957
+ }
958
+ function topLevelNames(program) {
959
+ const names = new Set;
960
+ for (const stmt of program.body) {
961
+ const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
962
+ if (decl?.type === "ImportDeclaration") {
963
+ for (const spec of decl.specifiers)
964
+ names.add(spec.local.name);
965
+ } else if (decl?.type === "VariableDeclaration") {
966
+ for (const d of decl.declarations)
967
+ collectPatternNames(d.id, names);
968
+ } else if ((decl?.type === "FunctionDeclaration" || decl?.type === "ClassDeclaration") && decl.id !== null) {
969
+ names.add(decl.id.name);
970
+ }
971
+ }
972
+ return names;
973
+ }
974
+ function checkBrowserGlobals(program, code, filename, warnings) {
975
+ if (!MENTIONS_RE.test(code))
976
+ return;
977
+ const shadowing = topLevelNames(program);
978
+ const helpers = topLevelFunctions(program);
979
+ const eagerCallbacks = new WeakSet;
980
+ const calleeStarts = new Set;
981
+ const guards = [];
982
+ walk(program, (node) => {
983
+ if (node.type === "CallExpression") {
984
+ const callee = unwrapTsExpr(node.callee);
985
+ if (callee.type === "Identifier")
986
+ calleeStarts.add(callee.start);
987
+ else if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && EAGER_CALLBACK_METHODS.has(callee.property.name) && node.arguments[0] !== undefined)
988
+ eagerCallbacks.add(unwrapTsExpr(node.arguments[0]));
989
+ } else if (node.type === "UnaryExpression" && node.operator === "typeof" && node.argument.type === "Identifier" && BROWSER_GLOBALS.has(node.argument.name)) {
990
+ guards.push(node.start);
991
+ }
992
+ });
993
+ const isGuarded = (node) => guards.some((start) => start >= node.start && start < node.end);
994
+ const readsOf = new Map;
995
+ const collect = (root) => {
996
+ const known = readsOf.get(root);
997
+ if (known !== undefined)
998
+ return known;
999
+ const reads = [];
1000
+ readsOf.set(root, reads);
1001
+ if (isGuarded(root))
1002
+ return reads;
1003
+ walkScoped(root, {
1004
+ onFunction: (fn) => !eagerCallbacks.has(fn),
1005
+ onIdentifier: (id) => {
1006
+ if (BROWSER_GLOBALS.has(id.name) && !shadowing.has(id.name)) {
1007
+ reads.push({ name: id.name, start: id.start });
1008
+ return;
1009
+ }
1010
+ const helper = calleeStarts.has(id.start) ? helpers.get(id.name) : undefined;
1011
+ if (helper !== undefined)
1012
+ reads.push(...collect(helper));
1013
+ }
1014
+ });
1015
+ return reads;
1016
+ };
1017
+ const reported = new Set;
1018
+ const report = (reads, when) => {
1019
+ for (const read of reads) {
1020
+ if (reported.has(read.start))
1021
+ continue;
1022
+ reported.add(read.start);
1023
+ warnings.push({ start: read.start, message: `prunelle compiler: \`${read.name}\` read ${when} in ${filename}: the server has no \`${read.name}\`, so it throws; read it in onMount() or an event handler, or check \`typeof ${read.name} !== 'undefined'\` first.` });
1024
+ }
1025
+ };
1026
+ report(collect(program), "when the module loads");
1027
+ for (const [name, fn] of helpers) {
1028
+ if (containsJsx(fn))
1029
+ report(collect(fn), `while <${name}> renders`);
1030
+ }
1031
+ }
1032
+
1033
+ // packages/prunelle/src/compiler/cacheability.ts
1034
+ var import_oxc_parser3 = require("oxc-parser");
1035
+
1036
+ // packages/prunelle/src/server/route-cache.ts
1037
+ var DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
1038
+ var DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i;
1039
+ var UNIT_MS = {
1040
+ ms: 1,
1041
+ s: 1000,
1042
+ m: 60000,
1043
+ h: 3600000,
1044
+ d: 86400000
1045
+ };
1046
+ function parseCacheDuration(value, allowZero = false) {
1047
+ if (typeof value === "number") {
1048
+ if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
1049
+ return;
1050
+ return Math.round(value * 1000);
1051
+ }
1052
+ if (typeof value !== "string")
1053
+ return;
1054
+ const match = DURATION_RE.exec(value.trim());
1055
+ if (match === null)
1056
+ return;
1057
+ const amount = Number(match[1]);
1058
+ const unit = UNIT_MS[match[2].toLowerCase()];
1059
+ if (!Number.isFinite(amount) || unit === undefined)
1060
+ return;
1061
+ const ms = Math.round(amount * unit);
1062
+ if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
1063
+ return;
1064
+ return ms;
1065
+ }
1066
+ function buildRouteCacheSpec(maxAgeMs, swrMs = maxAgeMs) {
1067
+ const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000));
1068
+ const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000));
1069
+ return {
1070
+ maxAgeMs,
1071
+ swrMs,
1072
+ cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`
1073
+ };
1074
+ }
1075
+
1076
+ // packages/prunelle/src/compiler/cacheability.ts
1077
+ var CACHE_HELP = "write a duration such as '30s', '5m', '1h', '1d', a positive number of seconds, or { maxAge: '1h', staleWhileRevalidate?: '1d' }";
1078
+ var DYNAMIC_PROPS = new Set(["params", "url", "locals", "cookies", "headers", "request", "consent", "ip"]);
1079
+ var PRIVATE_CTX_PROPS = new Set(["cookies", "locals", "consent"]);
1080
+ var PRIVATE_PAGE_PROPS = new Set(["locals", "cookies", "consent"]);
1081
+ var PRIVATE_SERVER_IMPORTS = new Set(["getActionError", "currentRequest"]);
1082
+ var DYNAMIC_TAGS = new Set(["ConsentGate", "Suspense"]);
1083
+ var PRIVATE_TAGS = new Set(["ConsentGate"]);
1084
+ var CLIENT_CALLBACK_CALLEES = new Set(["onMount", "effect", "onCleanup"]);
1085
+ var TS_EXPR_WRAPPERS = new Set(["TSAsExpression", "TSNonNullExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSInstantiationExpression"]);
1086
+ function staticStringOrNumber(node) {
1087
+ const inner = unwrapTsExpr(node);
1088
+ if (inner.type === "TemplateLiteral" && inner.expressions.length === 0 && inner.quasis.length === 1)
1089
+ return { ok: true, value: inner.quasis[0].value.cooked ?? inner.quasis[0].value.raw };
1090
+ const lit = staticLiteral(inner);
1091
+ if (!lit.ok)
1092
+ return { ok: false, isLiteral: false };
1093
+ return typeof lit.value === "string" || typeof lit.value === "number" ? { ok: true, value: lit.value } : { ok: false, isLiteral: true };
1094
+ }
1095
+ function propKeyName(prop) {
1096
+ if (prop.type !== "Property")
1097
+ return;
1098
+ if (!prop.computed && prop.key.type === "Identifier")
1099
+ return prop.key.name;
1100
+ return prop.key.type === "Literal" && typeof prop.key.value === "string" ? prop.key.value : undefined;
1101
+ }
1102
+ function parseCacheObjectNode(node) {
1103
+ let maxAgeMs;
1104
+ let swrMs;
1105
+ let swrKeyCount = 0;
1106
+ for (const prop of node.properties) {
1107
+ if (prop.type !== "Property" || prop.kind !== "init")
1108
+ return { problem: `cache object must use static properties: ${CACHE_HELP}` };
1109
+ const key = propKeyName(prop);
1110
+ if (key === undefined)
1111
+ return { problem: `cache object has a dynamic key: ${CACHE_HELP}` };
1112
+ if (key !== "maxAge" && key !== "staleWhileRevalidate" && key !== "swr")
1113
+ return { problem: `unknown cache option "${key}": ${CACHE_HELP}` };
1114
+ const parsed = staticStringOrNumber(prop.value);
1115
+ if (!parsed.ok)
1116
+ return { problem: parsed.isLiteral ? `cache.${key} must be a duration string or number of seconds: ${CACHE_HELP}` : `cache.${key} set at runtime: ${CACHE_HELP}` };
1117
+ const ms = parseCacheDuration(parsed.value, key !== "maxAge");
1118
+ if (ms === undefined)
1119
+ return { problem: `invalid cache.${key} value ${JSON.stringify(parsed.value)}: ${CACHE_HELP}` };
1120
+ if (key === "maxAge") {
1121
+ maxAgeMs = ms;
1122
+ } else {
1123
+ swrKeyCount++;
1124
+ swrMs = ms;
1125
+ }
1126
+ }
1127
+ if (maxAgeMs === undefined)
1128
+ return { problem: `cache object is missing "maxAge": ${CACHE_HELP}` };
1129
+ if (swrKeyCount > 1)
1130
+ return { problem: `specify either "staleWhileRevalidate" or "swr", not both: ${CACHE_HELP}` };
1131
+ return { spec: buildRouteCacheSpec(maxAgeMs, swrMs ?? maxAgeMs) };
1132
+ }
1133
+ function parseCacheExport(program) {
1134
+ const localInits = new Map;
1135
+ let exportedLocal;
1136
+ let exportInit;
1137
+ let offset = 0;
1138
+ let hasExport = false;
1139
+ for (const stmt of program.body) {
1140
+ if (stmt.type === "VariableDeclaration") {
1141
+ for (const d of stmt.declarations) {
1142
+ if (d.id.type === "Identifier" && d.init !== null)
1143
+ localInits.set(d.id.name, d.init);
1144
+ }
1145
+ continue;
1146
+ }
1147
+ if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type")
1148
+ continue;
1149
+ if (stmt.declaration?.type === "VariableDeclaration") {
1150
+ for (const d of stmt.declaration.declarations) {
1151
+ if (d.id.type === "Identifier" && d.id.name === "cache") {
1152
+ hasExport = true;
1153
+ offset = d.start;
1154
+ exportInit = d.init ?? undefined;
1155
+ }
1156
+ }
1157
+ } else if (stmt.declaration !== null && "id" in stmt.declaration && stmt.declaration.id?.type === "Identifier" && stmt.declaration.id.name === "cache") {
1158
+ return { hasExport: true, offset: stmt.declaration.start, problem: `invalid cache export: ${CACHE_HELP}` };
1159
+ }
1160
+ for (const spec of stmt.specifiers) {
1161
+ const exp = spec.exported.type === "Identifier" ? spec.exported.name : spec.exported.value;
1162
+ if (exp === "cache" && spec.exportKind !== "type") {
1163
+ hasExport = true;
1164
+ offset = spec.start;
1165
+ if (stmt.source === null && spec.local.type === "Identifier")
1166
+ exportedLocal = spec.local.name;
1167
+ }
1168
+ }
1169
+ }
1170
+ if (!hasExport)
1171
+ return { hasExport: false, offset: 0 };
1172
+ const init = exportInit ?? (exportedLocal !== undefined ? localInits.get(exportedLocal) : undefined);
1173
+ if (init === undefined)
1174
+ return { hasExport: true, offset, problem: `cache set at runtime: ${CACHE_HELP}` };
1175
+ const inner = unwrapTsExpr(init);
1176
+ if (inner.type === "ObjectExpression") {
1177
+ const res = parseCacheObjectNode(inner);
1178
+ return "spec" in res ? { hasExport: true, offset, spec: res.spec } : { hasExport: true, offset, problem: res.problem };
1179
+ }
1180
+ const scalar = staticStringOrNumber(inner);
1181
+ if (!scalar.ok)
1182
+ return { hasExport: true, offset, problem: scalar.isLiteral ? `invalid cache export: ${CACHE_HELP}` : `cache set at runtime: ${CACHE_HELP}` };
1183
+ const ms = parseCacheDuration(scalar.value);
1184
+ if (ms === undefined)
1185
+ return { hasExport: true, offset, problem: `invalid cache duration ${JSON.stringify(scalar.value)}: ${CACHE_HELP}` };
1186
+ return { hasExport: true, offset, spec: buildRouteCacheSpec(ms) };
1187
+ }
1188
+
1189
+ // packages/prunelle/src/compiler/data-keys.ts
1190
+ var import_oxc_parser4 = require("oxc-parser");
1191
+ function staticPropKey(prop) {
1192
+ if (prop.type !== "Property")
1193
+ return;
1194
+ if (!prop.computed && prop.key.type === "Identifier")
1195
+ return prop.key.name;
1196
+ if (prop.key.type === "Literal" && typeof prop.key.value === "string")
1197
+ return prop.key.value;
1198
+ return;
1199
+ }
1200
+ function extractObjectPatternKeys(pat) {
1201
+ if (pat.type !== "ObjectPattern")
1202
+ return;
1203
+ const keys = [];
1204
+ for (const prop of pat.properties) {
1205
+ if (prop.type === "RestElement")
1206
+ return;
1207
+ const k = staticPropKey(prop);
1208
+ if (k === undefined)
1209
+ return;
1210
+ keys.push(k);
1211
+ }
1212
+ return keys;
1213
+ }
1214
+ function memberKeyName(node) {
1215
+ if (node.type !== "MemberExpression")
1216
+ return;
1217
+ if (!node.computed && node.property.type === "Identifier")
1218
+ return node.property.name;
1219
+ if (node.computed && node.property.type === "Literal" && typeof node.property.value === "string")
1220
+ return node.property.value;
1221
+ return;
1222
+ }
1223
+ function unwrapParamPattern(param) {
1224
+ return param.type === "AssignmentPattern" ? param.left : param;
1225
+ }
1226
+ function resolveDefaultFunction(program, defaultLocal, localInits) {
1227
+ const localFns = new Map;
1228
+ for (const stmt of program.body) {
1229
+ if (stmt.type === "FunctionDeclaration" && stmt.id !== null)
1230
+ localFns.set(stmt.id.name, stmt);
1231
+ else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration?.type === "FunctionDeclaration" && stmt.declaration.id !== null)
1232
+ localFns.set(stmt.declaration.id.name, stmt.declaration);
1233
+ }
1234
+ const unwrapTarget = (node, depth = 0) => {
1235
+ if (node === undefined || depth > 4)
1236
+ return;
1237
+ const inner = unwrapTsExpr(node);
1238
+ if (inner.type === "FunctionDeclaration" || inner.type === "FunctionExpression" || inner.type === "ArrowFunctionExpression")
1239
+ return inner;
1240
+ if (inner.type === "Identifier")
1241
+ return localFns.get(inner.name) ?? unwrapTarget(localInits.get(inner.name), depth + 1);
1242
+ return;
1243
+ };
1244
+ for (const stmt of program.body) {
1245
+ if (stmt.type === "ExportDefaultDeclaration")
1246
+ return unwrapTarget(stmt.declaration);
1247
+ }
1248
+ if (defaultLocal !== undefined)
1249
+ return localFns.get(defaultLocal) ?? unwrapTarget(localInits.get(defaultLocal));
1250
+ return;
1251
+ }
1252
+ var TS_EXPR_WRAPPERS2 = new Set([
1253
+ "TSAsExpression",
1254
+ "TSNonNullExpression",
1255
+ "TSSatisfiesExpression",
1256
+ "TSTypeAssertion",
1257
+ "TSInstantiationExpression"
1258
+ ]);
1259
+ function analyzeDefaultDataKeys(program, defaultLocal, localInits) {
1260
+ const fn = resolveDefaultFunction(program, defaultLocal, localInits);
1261
+ if (fn === undefined || fn.body === null)
1262
+ return;
1263
+ if (fn.params.length === 0)
1264
+ return [];
1265
+ const firstParam = unwrapParamPattern(fn.params[0]);
1266
+ const keys = new Set;
1267
+ let escaped = false;
1268
+ let dataVar;
1269
+ let propsVar;
1270
+ if (firstParam.type === "ObjectPattern") {
1271
+ let dataProp;
1272
+ for (const prop of firstParam.properties) {
1273
+ if (prop.type === "RestElement")
1274
+ return;
1275
+ const key = staticPropKey(prop);
1276
+ if (key === undefined)
1277
+ return;
1278
+ if (key === "data")
1279
+ dataProp = prop;
1280
+ }
1281
+ if (dataProp === undefined || dataProp.type !== "Property")
1282
+ return [];
1283
+ const binding = unwrapParamPattern(dataProp.value);
1284
+ if (binding.type === "ObjectPattern") {
1285
+ const nested = extractObjectPatternKeys(binding);
1286
+ if (nested === undefined)
1287
+ return;
1288
+ return [...new Set(nested)].sort();
1289
+ }
1290
+ if (binding.type !== "Identifier")
1291
+ return;
1292
+ dataVar = binding.name;
1293
+ } else if (firstParam.type === "Identifier") {
1294
+ propsVar = firstParam.name;
1295
+ } else {
1296
+ return;
1297
+ }
1298
+ const ancestors = [];
1299
+ const walkWithParents = (node) => {
1300
+ if (escaped || node === null || typeof node !== "object")
1301
+ return;
1302
+ if (Array.isArray(node)) {
1303
+ for (let i = 0;i < node.length; i++)
1304
+ walkWithParents(node[i]);
1305
+ return;
1306
+ }
1307
+ const ast = node;
1308
+ const type = ast.type;
1309
+ if (typeof type !== "string")
1310
+ return;
1311
+ if (type.startsWith("TS")) {
1312
+ if (TS_EXPR_WRAPPERS2.has(type))
1313
+ walkWithParents(ast.expression);
1314
+ return;
1315
+ }
1316
+ if (ast !== fn && (type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression")) {
1317
+ const innerFn = ast;
1318
+ const shadowed = new Set;
1319
+ if (innerFn.type !== "ArrowFunctionExpression" && innerFn.id !== null)
1320
+ shadowed.add(innerFn.id.name);
1321
+ let isShadowed = dataVar !== undefined && shadowed.has(dataVar) || propsVar !== undefined && shadowed.has(propsVar);
1322
+ for (const p of innerFn.params) {
1323
+ if (isShadowed)
1324
+ return;
1325
+ walkPatternDefaults(p);
1326
+ collectPatternNames(p, shadowed);
1327
+ if (dataVar !== undefined && shadowed.has(dataVar) || propsVar !== undefined && shadowed.has(propsVar))
1328
+ isShadowed = true;
1329
+ }
1330
+ if (!isShadowed && innerFn.body !== null)
1331
+ walkWithParents(innerFn.body);
1332
+ return;
1333
+ }
1334
+ if (type === "Identifier") {
1335
+ const parent = ancestors[ancestors.length - 1];
1336
+ const grand = ancestors[ancestors.length - 2];
1337
+ const isNonRef = parent !== undefined && (parent.type === "MemberExpression" && !parent.computed && parent.property === ast || parent.type === "Property" && !parent.computed && parent.key === ast && !parent.shorthand || parent.type === "VariableDeclarator" && parent.id === ast || parent.type === "LabeledStatement" && parent.label === ast || parent.type === "FunctionDeclaration" && parent.id === ast || parent.type === "FunctionExpression" && parent.id === ast);
1338
+ if (!isNonRef && dataVar !== undefined && ast.name === dataVar) {
1339
+ if (parent?.type === "MemberExpression" && parent.object === ast) {
1340
+ const k = memberKeyName(parent);
1341
+ if (k === undefined)
1342
+ escaped = true;
1343
+ else
1344
+ keys.add(k);
1345
+ } else if (parent?.type === "VariableDeclarator" && parent.init === ast) {
1346
+ const nested = extractObjectPatternKeys(parent.id);
1347
+ if (nested === undefined)
1348
+ escaped = true;
1349
+ else
1350
+ for (const k of nested)
1351
+ keys.add(k);
1352
+ } else {
1353
+ escaped = true;
1354
+ }
1355
+ } else if (!isNonRef && propsVar !== undefined && ast.name === propsVar) {
1356
+ if (parent?.type === "MemberExpression" && parent.object === ast) {
1357
+ const propName = memberKeyName(parent);
1358
+ if (propName === undefined) {
1359
+ escaped = true;
1360
+ } else if (propName === "data") {
1361
+ const holder = grand?.type === "ChainExpression" ? ancestors[ancestors.length - 3] : grand;
1362
+ const target = grand?.type === "ChainExpression" ? grand : parent;
1363
+ if (holder?.type === "MemberExpression" && holder.object === target) {
1364
+ const k = memberKeyName(holder);
1365
+ if (k === undefined)
1366
+ escaped = true;
1367
+ else
1368
+ keys.add(k);
1369
+ } else if (holder?.type === "VariableDeclarator" && holder.init === target) {
1370
+ const nested = extractObjectPatternKeys(holder.id);
1371
+ if (nested === undefined)
1372
+ escaped = true;
1373
+ else
1374
+ for (const k of nested)
1375
+ keys.add(k);
1376
+ } else {
1377
+ escaped = true;
1378
+ }
1379
+ }
1380
+ } else {
1381
+ escaped = true;
1382
+ }
1383
+ }
1384
+ }
1385
+ ancestors.push(ast);
1386
+ const childKeys = import_oxc_parser4.visitorKeys[type];
1387
+ if (childKeys !== undefined) {
1388
+ const rec = ast;
1389
+ for (let i = 0;i < childKeys.length; i++) {
1390
+ const val = rec[childKeys[i]];
1391
+ if (val !== null && typeof val === "object")
1392
+ walkWithParents(val);
1393
+ }
1394
+ }
1395
+ ancestors.pop();
1396
+ };
1397
+ const walkPatternDefaults = (pattern) => {
1398
+ if (escaped || pattern === null || pattern === undefined)
1399
+ return;
1400
+ switch (pattern.type) {
1401
+ case "AssignmentPattern":
1402
+ walkPatternDefaults(pattern.left);
1403
+ walkWithParents(pattern.right);
1404
+ return;
1405
+ case "RestElement":
1406
+ walkPatternDefaults(pattern.argument);
1407
+ return;
1408
+ case "TSParameterProperty":
1409
+ walkPatternDefaults(pattern.parameter);
1410
+ return;
1411
+ case "ArrayPattern":
1412
+ for (const el of pattern.elements)
1413
+ walkPatternDefaults(el);
1414
+ return;
1415
+ case "ObjectPattern":
1416
+ for (const prop of pattern.properties) {
1417
+ if (prop.type === "RestElement") {
1418
+ walkPatternDefaults(prop.argument);
1419
+ } else {
1420
+ if (prop.computed)
1421
+ walkWithParents(prop.key);
1422
+ walkPatternDefaults(prop.value);
1423
+ }
1424
+ }
1425
+ }
1426
+ };
1427
+ for (const p of fn.params)
1428
+ walkPatternDefaults(p);
1429
+ walkWithParents(fn.body);
1430
+ return escaped ? undefined : [...keys].sort();
1431
+ }
1432
+
1433
+ // packages/prunelle/src/compiler/compliance.ts
1434
+ var import_oxc_parser5 = require("oxc-parser");
1435
+
1436
+ // packages/prunelle/src/compiler/compliance-rgaa.ts
1437
+ var RGAA_JSX_RULES = [
1438
+ "rgaa/img-alt",
1439
+ "rgaa/form-label",
1440
+ "rgaa/accessible-name",
1441
+ "rgaa/duplicate-id",
1442
+ "rgaa/positive-tabindex",
1443
+ "rgaa/nested-control",
1444
+ "rgaa/link-as-button",
1445
+ "rgaa/unknown-role",
1446
+ "rgaa/unknown-aria",
1447
+ "rgaa/invalid-aria-value",
1448
+ "rgaa/skipped-heading",
1449
+ "rgaa/table-without-header",
1450
+ "rgaa/fieldset-without-legend",
1451
+ "rgaa/click-without-key",
1452
+ "rgaa/autofocus",
1453
+ "rgaa/meta-refresh"
1454
+ ];
1455
+ var NON_LABELLED_INPUT_TYPES = new Set(["hidden", "submit", "reset", "button", "image"]);
1456
+ var INTERACTIVE_ANCESTORS = new Set(["a", "button", "summary"]);
1457
+ var INTERACTIVE_DESCENDANTS = new Set(["a", "button", "input", "select", "textarea", "summary"]);
1458
+ var NATIVE_CLICKABLE_TAGS = new Set(["a", "button", "input", "select", "textarea", "summary", "label", "option", "dialog", "area"]);
1459
+ var TABLE_STRUCTURAL_TAGS = new Set(["thead", "tbody", "tfoot", "tr"]);
1460
+ var HEADING_LEVELS = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 };
1461
+ var PRESENTATIONAL_ROLES = new Set(["presentation", "none"]);
1462
+ var INT_RE = /^-?\d+$/;
1463
+ var NUM_RE = /^-?(?:\d+\.?\d*|\.\d+)$/;
1464
+ var TABINDEX_NUM_RE = /^[+-]?\d+(?:\.\d+)?$/;
1465
+ var VALID_ARIA_ROLES = new Set(("alert alertdialog application article associationlist associationlistitemkey associationlistitemvalue " + "banner blockquote button caption cell checkbox code columnheader combobox comment complementary contentinfo " + "definition deletion dialog directory document emphasis feed figure form generic " + "graphics-document graphics-object graphics-symbol grid gridcell group heading image img insertion " + "link list listbox listitem log main mark marquee math menu menubar menuitem menuitemcheckbox menuitemradio " + "meter navigation none note option paragraph presentation progressbar radio radiogroup region row rowgroup rowheader " + "scrollbar search searchbox separator slider spinbutton status strong subscript suggestion superscript switch " + "tab table tablist tabpanel term textbox time timer toolbar tooltip tree treegrid treeitem").split(" "));
1466
+ var VALID_ARIA_ATTRS = new Set(("aria-activedescendant aria-atomic aria-autocomplete aria-braillelabel aria-brailleroledescription " + "aria-busy aria-checked aria-colcount aria-colindex aria-colindextext aria-colspan aria-controls " + "aria-current aria-describedby aria-description aria-details aria-disabled aria-dropeffect " + "aria-errormessage aria-expanded aria-flowto aria-grabbed aria-haspopup aria-hidden aria-invalid " + "aria-keyshortcuts aria-label aria-labelledby aria-level aria-live aria-modal aria-multiline " + "aria-multiselectable aria-orientation aria-owns aria-placeholder aria-posinset aria-pressed " + "aria-readonly aria-relevant aria-required aria-roledescription aria-rowcount aria-rowindex " + "aria-rowindextext aria-rowspan aria-selected aria-setsize aria-sort aria-valuemax aria-valuemin " + "aria-valuenow aria-valuetext").split(" "));
1467
+ var ARIA_BOOL_ATTRS = new Set(("aria-atomic aria-busy aria-disabled aria-expanded aria-grabbed aria-hidden " + "aria-modal aria-multiline aria-multiselectable aria-readonly aria-required aria-selected").split(" "));
1468
+ var ARIA_TRISTATE_ATTRS = new Set(["aria-checked", "aria-pressed"]);
1469
+ var ARIA_INT_ATTRS = new Set(("aria-level aria-posinset aria-setsize aria-colcount aria-rowcount " + "aria-colindex aria-rowindex aria-colspan aria-rowspan").split(" "));
1470
+ var ARIA_NUM_ATTRS = new Set(["aria-valuemin", "aria-valuemax", "aria-valuenow"]);
1471
+ var ARIA_RELEVANT_TOKENS = new Set(["additions", "removals", "text", "all"]);
1472
+ var ARIA_ENUM_ATTRS = {
1473
+ "aria-live": new Set(["off", "polite", "assertive"]),
1474
+ "aria-orientation": new Set(["horizontal", "vertical"]),
1475
+ "aria-sort": new Set(["none", "ascending", "descending", "other"]),
1476
+ "aria-current": new Set(["page", "step", "location", "date", "time", "true", "false"]),
1477
+ "aria-haspopup": new Set(["false", "true", "menu", "listbox", "tree", "grid", "dialog"]),
1478
+ "aria-invalid": new Set(["grammar", "false", "spelling", "true"]),
1479
+ "aria-autocomplete": new Set(["inline", "list", "both", "none"])
1480
+ };
1481
+ function createRgaaScope() {
1482
+ return { seenIds: new Set, lastHeading: 0 };
1483
+ }
1484
+ function cloneRgaaScope(scope) {
1485
+ return { seenIds: new Set(scope.seenIds), lastHeading: scope.lastHeading };
1486
+ }
1487
+ function mergeRgaaScope(target, branch) {
1488
+ for (const id of branch.seenIds)
1489
+ target.seenIds.add(id);
1490
+ if (branch.lastHeading > target.lastHeading)
1491
+ target.lastHeading = branch.lastHeading;
1492
+ }
1493
+ function findAttr(attributes, name) {
1494
+ for (const attr of attributes) {
1495
+ if (attr.type === "JSXAttribute" && attr.name.type === "JSXIdentifier" && attr.name.name === name)
1496
+ return attr;
1497
+ }
1498
+ return;
1499
+ }
1500
+ function findAttrLower(attributes, lowerName) {
1501
+ for (const attr of attributes) {
1502
+ if (attr.type === "JSXAttribute" && attr.name.type === "JSXIdentifier" && attr.name.name.toLowerCase() === lowerName)
1503
+ return attr;
1504
+ }
1505
+ return;
1506
+ }
1507
+ function hasSpread(attributes) {
1508
+ return attributes.some((a) => a.type === "JSXSpreadAttribute");
1509
+ }
1510
+ function staticStringValueOf(value) {
1511
+ if (value === null)
1512
+ return;
1513
+ if (value.type === "Literal" && typeof value.value === "string")
1514
+ return value.value;
1515
+ if (value.type === "JSXExpressionContainer" && value.expression.type !== "JSXEmptyExpression") {
1516
+ const expr = unwrapTsExpr(value.expression);
1517
+ if (expr.type === "Literal" && typeof expr.value === "string")
1518
+ return expr.value;
1519
+ if (expr.type === "TemplateLiteral" && expr.expressions.length === 0)
1520
+ return expr.quasis[0]?.value.cooked ?? undefined;
1521
+ }
1522
+ return;
1523
+ }
1524
+ function attrTargetKey(attr) {
1525
+ if (attr === undefined || attr.value === null)
1526
+ return;
1527
+ const str = staticStringValueOf(attr.value);
1528
+ if (str !== undefined && str.trim() !== "")
1529
+ return `s:${str}`;
1530
+ if (attr.value.type === "JSXExpressionContainer" && attr.value.expression.type !== "JSXEmptyExpression") {
1531
+ const expr = unwrapTsExpr(attr.value.expression);
1532
+ if (expr.type === "Identifier")
1533
+ return `i:${expr.name}`;
1534
+ }
1535
+ return;
1536
+ }
1537
+ function hasNonEmptyAttr(attributes, name) {
1538
+ const attr = findAttr(attributes, name);
1539
+ if (attr === undefined || attr.value === null)
1540
+ return false;
1541
+ const str = staticStringValueOf(attr.value);
1542
+ if (str !== undefined)
1543
+ return str.trim() !== "";
1544
+ if (attr.value.type === "JSXExpressionContainer" && attr.value.expression.type !== "JSXEmptyExpression") {
1545
+ const expr = unwrapParens(attr.value.expression);
1546
+ if (expr.type === "Literal" && (expr.value === null || expr.value === false || expr.value === ""))
1547
+ return false;
1548
+ if (expr.type === "Identifier" && expr.name === "undefined")
1549
+ return false;
1550
+ return true;
1551
+ }
1552
+ return false;
1553
+ }
1554
+ function isExplicitlyFalsyExpr(value) {
1555
+ if (value === null || value.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression")
1556
+ return false;
1557
+ const expr = unwrapTsExpr(value.expression);
1558
+ if (expr.type === "Literal" && (expr.value === false || expr.value === null))
1559
+ return true;
1560
+ return expr.type === "Identifier" && expr.name === "undefined";
1561
+ }
1562
+ function hasLabelAttr(attributes) {
1563
+ return hasNonEmptyAttr(attributes, "aria-label") || hasNonEmptyAttr(attributes, "aria-labelledby") || hasNonEmptyAttr(attributes, "title");
1564
+ }
1565
+ function isAriaHidden(attributes) {
1566
+ const attr = findAttr(attributes, "aria-hidden");
1567
+ if (attr === undefined)
1568
+ return false;
1569
+ if (attr.value === null)
1570
+ return true;
1571
+ if (attr.value.type === "Literal")
1572
+ return attr.value.value === "true";
1573
+ if (attr.value.type === "JSXExpressionContainer" && attr.value.expression.type !== "JSXEmptyExpression") {
1574
+ const expr = unwrapParens(attr.value.expression);
1575
+ return expr.type === "Literal" && (expr.value === true || expr.value === "true");
1576
+ }
1577
+ return false;
1578
+ }
1579
+ function isPresentational(attributes) {
1580
+ const raw = staticStringValueOf(findAttr(attributes, "role")?.value ?? null);
1581
+ return raw !== undefined && raw.trim().split(/\s+/).some((token) => PRESENTATIONAL_ROLES.has(token));
1582
+ }
1583
+ function hasMeaningfulExpression(expr) {
1584
+ const inner = unwrapParens(expr);
1585
+ if (inner.type === "Literal")
1586
+ return typeof inner.value === "string" ? inner.value.trim() !== "" : typeof inner.value === "number";
1587
+ return !(inner.type === "Identifier" && inner.name === "undefined");
1588
+ }
1589
+ function hasAccessibleName(children) {
1590
+ for (const child of children) {
1591
+ if (child.type === "JSXText") {
1592
+ if (cleanJsxText(child.value).trim() !== "")
1593
+ return true;
1594
+ } else if (child.type === "JSXExpressionContainer") {
1595
+ if (child.expression.type !== "JSXEmptyExpression" && hasMeaningfulExpression(child.expression))
1596
+ return true;
1597
+ } else if (child.type === "JSXFragment") {
1598
+ if (hasAccessibleName(child.children))
1599
+ return true;
1600
+ } else if (child.type === "JSXElement") {
1601
+ const attrs = child.openingElement.attributes;
1602
+ if (isAriaHidden(attrs))
1603
+ continue;
1604
+ const tag = jsxTagName(child.openingElement.name);
1605
+ if (hasSpread(attrs) || hasLabelAttr(attrs))
1606
+ return true;
1607
+ if (tag === "img") {
1608
+ if (hasNonEmptyAttr(attrs, "alt"))
1609
+ return true;
1610
+ continue;
1611
+ }
1612
+ if (tag === "svg") {
1613
+ if (child.children.some((c) => c.type === "JSXElement" && jsxTagName(c.openingElement.name) === "title" && hasAccessibleName(c.children)))
1614
+ return true;
1615
+ continue;
1616
+ }
1617
+ if (isComponentTag(tag)) {
1618
+ if (hasNonEmptyAttr(attrs, "label") || hasAccessibleName(child.children))
1619
+ return true;
1620
+ continue;
1621
+ }
1622
+ if (hasAccessibleName(child.children))
1623
+ return true;
1624
+ }
1625
+ }
1626
+ return false;
1627
+ }
1628
+ function extractStaticAttrValue(attr) {
1629
+ if (attr.value === null)
1630
+ return { kind: "bool", value: true };
1631
+ if (attr.value.type === "Literal" && typeof attr.value.value === "string")
1632
+ return { kind: "string", value: attr.value.value };
1633
+ if (attr.value.type !== "JSXExpressionContainer" || attr.value.expression.type === "JSXEmptyExpression")
1634
+ return;
1635
+ const expr = unwrapTsExpr(attr.value.expression);
1636
+ if (expr.type === "Identifier" && expr.name === "undefined")
1637
+ return;
1638
+ if (expr.type === "TemplateLiteral" && expr.expressions.length === 0)
1639
+ return { kind: "string", value: expr.quasis[0]?.value.cooked ?? "" };
1640
+ if (expr.type === "UnaryExpression" && expr.operator === "+" && expr.argument.type === "Literal" && typeof expr.argument.value === "number")
1641
+ return { kind: "number", value: expr.argument.value };
1642
+ const lit = staticLiteral(expr);
1643
+ if (!lit.ok || lit.value === null)
1644
+ return;
1645
+ if (typeof lit.value === "boolean")
1646
+ return { kind: "bool", value: lit.value };
1647
+ if (typeof lit.value === "number")
1648
+ return { kind: "number", value: lit.value };
1649
+ return { kind: "string", value: lit.value };
1650
+ }
1651
+ function validateAriaValue(name, val) {
1652
+ if (ARIA_BOOL_ATTRS.has(name))
1653
+ return val.kind === "bool" || val.kind === "string" && (val.value === "true" || val.value === "false") ? undefined : 'expected "true" or "false"';
1654
+ if (ARIA_TRISTATE_ATTRS.has(name))
1655
+ return val.kind === "bool" || val.kind === "string" && (val.value === "true" || val.value === "false" || val.value === "mixed") ? undefined : 'expected "true", "false", or "mixed"';
1656
+ const enumSet = ARIA_ENUM_ATTRS[name];
1657
+ if (enumSet !== undefined) {
1658
+ const token = val.kind === "bool" ? String(val.value) : val.kind === "string" ? val.value : undefined;
1659
+ return token !== undefined && enumSet.has(token) ? undefined : `expected one of ${[...enumSet].join(", ")}`;
1660
+ }
1661
+ if (name === "aria-relevant") {
1662
+ const tokens = val.kind === "string" ? val.value.trim().split(/\s+/).filter(Boolean) : [];
1663
+ return tokens.length > 0 && tokens.every((t) => ARIA_RELEVANT_TOKENS.has(t)) ? undefined : "expected space-separated tokens from additions, removals, text, all";
1664
+ }
1665
+ if (ARIA_INT_ATTRS.has(name))
1666
+ return val.kind === "number" && Number.isInteger(val.value) || val.kind === "string" && INT_RE.test(val.value.trim()) ? undefined : "expected an integer";
1667
+ if (ARIA_NUM_ATTRS.has(name))
1668
+ return val.kind === "number" && Number.isFinite(val.value) || val.kind === "string" && NUM_RE.test(val.value.trim()) ? undefined : "expected a number";
1669
+ return;
1670
+ }
1671
+ function emitWarning(ctx, rule, elementStart, message, attrStart) {
1672
+ if (!ctx.isIgnored(rule, elementStart, attrStart))
1673
+ ctx.warnings.push({ rule, start: attrStart ?? elementStart, message });
1674
+ }
1675
+ function checkRoleAndAria(element, tag, ctx) {
1676
+ const attrs = element.openingElement.attributes;
1677
+ const roleAttr = findAttr(attrs, "role");
1678
+ if (roleAttr !== undefined) {
1679
+ const raw = staticStringValueOf(roleAttr.value);
1680
+ if (raw !== undefined) {
1681
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
1682
+ const invalid = tokens.filter((t) => !VALID_ARIA_ROLES.has(t));
1683
+ if (tokens.length === 0 || invalid.length > 0) {
1684
+ const detail = tokens.length === 0 ? "an empty role" : `unknown WAI-ARIA role "${invalid[0]}"`;
1685
+ emitWarning(ctx, "rgaa/unknown-role", element.start, `[rgaa/unknown-role] <${tag} role="${raw}"> in ${ctx.filename} uses ${detail}: use a valid WAI-ARIA role or remove the attribute.`, roleAttr.start);
1686
+ }
1687
+ }
1688
+ }
1689
+ for (const attr of attrs) {
1690
+ if (attr.type !== "JSXAttribute" || attr.name.type !== "JSXIdentifier" || !attr.name.name.startsWith("aria-"))
1691
+ continue;
1692
+ const name = attr.name.name;
1693
+ if (!VALID_ARIA_ATTRS.has(name)) {
1694
+ emitWarning(ctx, "rgaa/unknown-aria", element.start, `[rgaa/unknown-aria] <${tag} ${name}> in ${ctx.filename} is not a valid WAI-ARIA attribute: check the spelling or remove it.`, attr.start);
1695
+ continue;
1696
+ }
1697
+ const val = extractStaticAttrValue(attr);
1698
+ if (val === undefined)
1699
+ continue;
1700
+ const err = validateAriaValue(name, val);
1701
+ if (err !== undefined) {
1702
+ const shown = val.kind === "string" ? `"${val.value}"` : String(val.value);
1703
+ emitWarning(ctx, "rgaa/invalid-aria-value", element.start, `[rgaa/invalid-aria-value] <${tag} ${name}=${shown}> in ${ctx.filename} has an invalid value (${err}).`, attr.start);
1704
+ }
1705
+ }
1706
+ }
1707
+ function checkExprForChild(expr, checkElement, checkFragment) {
1708
+ const inner = unwrapTsExpr(expr);
1709
+ if (inner.type === "Literal" || inner.type === "Identifier" && inner.name === "undefined")
1710
+ return false;
1711
+ if (inner.type === "JSXElement")
1712
+ return checkElement(inner);
1713
+ if (inner.type === "JSXFragment")
1714
+ return checkFragment(inner.children);
1715
+ if (inner.type === "LogicalExpression") {
1716
+ return inner.operator === "&&" ? checkExprForChild(inner.right, checkElement, checkFragment) : checkExprForChild(inner.left, checkElement, checkFragment) || checkExprForChild(inner.right, checkElement, checkFragment);
1717
+ }
1718
+ if (inner.type === "ConditionalExpression")
1719
+ return checkExprForChild(inner.consequent, checkElement, checkFragment) || checkExprForChild(inner.alternate, checkElement, checkFragment);
1720
+ return true;
1721
+ }
1722
+ function tableMayHaveHeader(children) {
1723
+ const checkEl = (el) => {
1724
+ const tag = jsxTagName(el.openingElement.name);
1725
+ if (tag === "th" || isComponentTag(tag))
1726
+ return true;
1727
+ return TABLE_STRUCTURAL_TAGS.has(tag) && tableMayHaveHeader(el.children);
1728
+ };
1729
+ for (const child of children) {
1730
+ if (child.type === "JSXElement" && checkEl(child))
1731
+ return true;
1732
+ if (child.type === "JSXFragment" && tableMayHaveHeader(child.children))
1733
+ return true;
1734
+ if (child.type === "JSXExpressionContainer" && child.expression.type !== "JSXEmptyExpression" && checkExprForChild(child.expression, checkEl, tableMayHaveHeader))
1735
+ return true;
1736
+ }
1737
+ return false;
1738
+ }
1739
+ function fieldsetMayHaveLegend(children, isDirect) {
1740
+ const checkEl = (el) => {
1741
+ const tag = jsxTagName(el.openingElement.name);
1742
+ if (tag === "legend")
1743
+ return true;
1744
+ if (tag === "fieldset")
1745
+ return false;
1746
+ return isDirect && isComponentTag(tag) || fieldsetMayHaveLegend(el.children, false);
1747
+ };
1748
+ for (const child of children) {
1749
+ if (child.type === "JSXElement" && checkEl(child))
1750
+ return true;
1751
+ if (child.type === "JSXFragment" && fieldsetMayHaveLegend(child.children, isDirect))
1752
+ return true;
1753
+ if (isDirect && child.type === "JSXExpressionContainer" && child.expression.type !== "JSXEmptyExpression" && checkExprForChild(child.expression, checkEl, (cs) => fieldsetMayHaveLegend(cs, true)))
1754
+ return true;
1755
+ }
1756
+ return false;
1757
+ }
1758
+ function checkFocusAndInteraction(element, tag, spread, ctx) {
1759
+ const attrs = element.openingElement.attributes;
1760
+ const tabAttr = findAttrLower(attrs, "tabindex");
1761
+ if (tabAttr !== undefined) {
1762
+ const val = extractStaticAttrValue(tabAttr);
1763
+ const num = val?.kind === "number" ? val.value : val?.kind === "string" && TABINDEX_NUM_RE.test(val.value.trim()) ? Number(val.value.trim()) : undefined;
1764
+ if (num !== undefined && Number.isFinite(num) && num > 0) {
1765
+ const attrName = tabAttr.name.type === "JSXIdentifier" ? tabAttr.name.name : "tabindex";
1766
+ emitWarning(ctx, "rgaa/positive-tabindex", element.start, `[rgaa/positive-tabindex] <${tag} ${attrName}={${num}}> in ${ctx.filename} uses a positive tabindex: use 0, -1, or reorder the DOM to preserve natural keyboard order.`, tabAttr.start);
1767
+ }
1768
+ }
1769
+ const autoFocusAttr = findAttrLower(attrs, "autofocus");
1770
+ if (autoFocusAttr !== undefined && !isExplicitlyFalsyExpr(autoFocusAttr.value)) {
1771
+ const attrName = autoFocusAttr.name.type === "JSXIdentifier" ? autoFocusAttr.name.name : "autofocus";
1772
+ emitWarning(ctx, "rgaa/autofocus", element.start, `[rgaa/autofocus] <${tag} ${attrName}> in ${ctx.filename} steals focus on load and can disorient keyboard and screen-reader users: remove ${attrName} or manage focus explicitly.`, autoFocusAttr.start);
1773
+ }
1774
+ if (ctx.interactiveAncestor !== undefined && INTERACTIVE_DESCENDANTS.has(tag)) {
1775
+ const inputType = tag === "input" ? staticStringValueOf(findAttr(attrs, "type")?.value ?? null)?.toLowerCase() : undefined;
1776
+ if (inputType !== "hidden")
1777
+ emitWarning(ctx, "rgaa/nested-control", element.start, `[rgaa/nested-control] <${tag}> in ${ctx.filename} is nested inside <${ctx.interactiveAncestor}>: interactive controls must not be nested; place them as siblings.`);
1778
+ }
1779
+ const onClickAttr = findAttr(attrs, "onClick");
1780
+ const hasClick = onClickAttr !== undefined && !isExplicitlyFalsyExpr(onClickAttr.value);
1781
+ if (tag === "a" && !spread && hasClick && !hasNonEmptyAttr(attrs, "href"))
1782
+ emitWarning(ctx, "rgaa/link-as-button", element.start, `[rgaa/link-as-button] <a> with onClick and no href in ${ctx.filename}: use <button type="button"> for actions, or add a valid href for navigation.`);
1783
+ if (hasClick && !spread && !NATIVE_CLICKABLE_TAGS.has(tag) && !isPresentational(attrs)) {
1784
+ const hasKey = findAttr(attrs, "onKeyDown") !== undefined || findAttr(attrs, "onKeyUp") !== undefined || findAttr(attrs, "onKeyPress") !== undefined;
1785
+ if (!hasKey)
1786
+ emitWarning(ctx, "rgaa/click-without-key", element.start, `[rgaa/click-without-key] <${tag} onClick={...}> in ${ctx.filename} is not keyboard-accessible: use <button type="button">, or add onKeyDown/onKeyUp with an appropriate role and tabIndex.`, onClickAttr.start);
1787
+ }
1788
+ }
1789
+ function checkStructureAndIdentity(element, tag, spread, ctx) {
1790
+ const attrs = element.openingElement.attributes;
1791
+ const idAttr = findAttr(attrs, "id");
1792
+ const id = idAttr !== undefined ? staticStringValueOf(idAttr.value) : undefined;
1793
+ if (id !== undefined && id !== "") {
1794
+ if (ctx.scope.seenIds.has(id))
1795
+ emitWarning(ctx, "rgaa/duplicate-id", element.start, `[rgaa/duplicate-id] Duplicate id="${id}" on <${tag}> in ${ctx.filename}: every id in a document must be unique.`, idAttr.start);
1796
+ else
1797
+ ctx.scope.seenIds.add(id);
1798
+ }
1799
+ const headingLevel = HEADING_LEVELS[tag];
1800
+ if (headingLevel !== undefined) {
1801
+ if (ctx.scope.lastHeading > 0 && headingLevel > ctx.scope.lastHeading + 1)
1802
+ emitWarning(ctx, "rgaa/skipped-heading", element.start, `[rgaa/skipped-heading] <h${headingLevel}> in ${ctx.filename} skips heading level(s) after <h${ctx.scope.lastHeading}>: use <h${ctx.scope.lastHeading + 1}> to keep the heading hierarchy continuous.`);
1803
+ ctx.scope.lastHeading = headingLevel;
1804
+ }
1805
+ if (tag === "table" && !isPresentational(attrs) && !(element.children.length === 0 && spread) && !tableMayHaveHeader(element.children))
1806
+ emitWarning(ctx, "rgaa/table-without-header", element.start, `[rgaa/table-without-header] <table> in ${ctx.filename} has no <th> header cell: add <th> headers or role="presentation" if used for layout.`);
1807
+ if (tag === "fieldset" && !(element.children.length === 0 && spread) && !fieldsetMayHaveLegend(element.children, true))
1808
+ emitWarning(ctx, "rgaa/fieldset-without-legend", element.start, `[rgaa/fieldset-without-legend] <fieldset> in ${ctx.filename} has no <legend>: add a <legend> child to label the form group.`);
1809
+ if (tag === "meta") {
1810
+ const httpEquivAttr = findAttrLower(attrs, "http-equiv") ?? findAttrLower(attrs, "httpequiv");
1811
+ if (httpEquivAttr !== undefined && staticStringValueOf(httpEquivAttr.value)?.trim().toLowerCase() === "refresh")
1812
+ emitWarning(ctx, "rgaa/meta-refresh", element.start, `[rgaa/meta-refresh] <meta http-equiv="refresh"> in ${ctx.filename} redirects or reloads without user control: use an HTTP redirect or an explicit user action.`, httpEquivAttr.start);
1813
+ }
1814
+ }
1815
+ function checkRgaaElement(element, tag, ctx) {
1816
+ const attrs = element.openingElement.attributes;
1817
+ const spread = hasSpread(attrs);
1818
+ if (tag === "img" && !spread && findAttr(attrs, "alt") === undefined)
1819
+ emitWarning(ctx, "rgaa/img-alt", element.start, `[rgaa/img-alt] <img> in ${ctx.filename} is missing an alt attribute: add alt="description" or alt="" for decorative images.`);
1820
+ if ((tag === "input" || tag === "select" || tag === "textarea") && !spread && !ctx.inLabel && !hasLabelAttr(attrs)) {
1821
+ const inputType = tag === "input" ? staticStringValueOf(findAttr(attrs, "type")?.value ?? null)?.toLowerCase() : undefined;
1822
+ const idKey = attrTargetKey(findAttr(attrs, "id"));
1823
+ const linked = idKey !== undefined && ctx.labelTargets.has(idKey);
1824
+ if ((inputType === undefined || !NON_LABELLED_INPUT_TYPES.has(inputType)) && !linked)
1825
+ emitWarning(ctx, "rgaa/form-label", element.start, `[rgaa/form-label] <${tag}> in ${ctx.filename} has no associated label: wrap it in <label>, link <label for="id">, or add aria-label="..." / aria-labelledby="...".`);
1826
+ }
1827
+ if ((tag === "button" || tag === "a") && !spread && !hasLabelAttr(attrs) && !hasAccessibleName(element.children))
1828
+ emitWarning(ctx, "rgaa/accessible-name", element.start, `[rgaa/accessible-name] <${tag}> in ${ctx.filename} has no accessible name: add visible text or aria-label="...".`);
1829
+ checkRoleAndAria(element, tag, ctx);
1830
+ checkFocusAndInteraction(element, tag, spread, ctx);
1831
+ checkStructureAndIdentity(element, tag, spread, ctx);
1832
+ }
1833
+
1834
+ // packages/prunelle/src/compiler/compliance.ts
1835
+ var COMPLIANCE_RULES = new Set([
1836
+ ...RGAA_JSX_RULES,
1837
+ "rgpd/third-party-url",
1838
+ "lcen/legal-notice",
1839
+ "rgaa/accessibility-statement"
1840
+ ]);
1841
+ var THIRD_PARTY_LINK_RELS = new Set(["stylesheet", "preload", "preconnect", "dns-prefetch"]);
1842
+ var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"]);
1843
+ var DEFAULT_LEGAL_PATHS = new Set(["/mentions-legales", "/legal", "/legal-notice", "/imprint", "/impressum", "/cgu", "/cgv"]);
1844
+ var ACCESSIBILITY_PATHS = new Set(["/accessibilite", "/accessibility", "/declaration-accessibilite", "/accessibility-statement"]);
1845
+ var LINE_IGNORE_RE = /(?:^|[\s{;(,])\/\/\s*prunelle-ignore(-file)?[ \t]+([^\r\n]+)/g;
1846
+ var BLOCK_IGNORE_RE = /\/\*\s*prunelle-ignore(-file)?\s+([\s\S]*?)\*\//g;
1847
+ function buildLineStarts(code) {
1848
+ const starts = [0];
1849
+ for (let i = 0;i < code.length; i++) {
1850
+ if (code.charCodeAt(i) === 10)
1851
+ starts.push(i + 1);
1852
+ }
1853
+ return starts;
1854
+ }
1855
+ function offsetToLine(lineStarts, offset) {
1856
+ let lo = 0;
1857
+ let hi = lineStarts.length - 1;
1858
+ while (lo < hi) {
1859
+ const mid = lo + hi + 1 >> 1;
1860
+ if (lineStarts[mid] <= offset)
1861
+ lo = mid;
1862
+ else
1863
+ hi = mid - 1;
1864
+ }
1865
+ return lo + 1;
1866
+ }
1867
+ function extractRules(text) {
1868
+ const out = [];
1869
+ for (const token of text.trim().split(/[\s,]+/)) {
1870
+ if (COMPLIANCE_RULES.has(token))
1871
+ out.push(token);
1872
+ }
1873
+ return out;
1874
+ }
1875
+ function parsePrunelleIgnores(code) {
1876
+ const lineStarts = buildLineStarts(code);
1877
+ const fileRules = new Set;
1878
+ const lineRules = new Map;
1879
+ const record = (isFile, start, end, rawRules) => {
1880
+ const rules = extractRules(rawRules);
1881
+ if (rules.length === 0)
1882
+ return;
1883
+ if (isFile) {
1884
+ for (const r of rules)
1885
+ fileRules.add(r);
1886
+ return;
1887
+ }
1888
+ const startLine = offsetToLine(lineStarts, start);
1889
+ const endLine = offsetToLine(lineStarts, end);
1890
+ for (const line of [startLine, endLine, endLine + 1]) {
1891
+ let set = lineRules.get(line);
1892
+ if (set === undefined) {
1893
+ set = new Set;
1894
+ lineRules.set(line, set);
1895
+ }
1896
+ for (const r of rules)
1897
+ set.add(r);
1898
+ }
1899
+ };
1900
+ for (const re of [LINE_IGNORE_RE, BLOCK_IGNORE_RE]) {
1901
+ re.lastIndex = 0;
1902
+ for (let m = re.exec(code);m !== null; m = re.exec(code))
1903
+ record(m[1] === "-file", m.index, m.index + m[0].length, m[2]);
1904
+ }
1905
+ return { lineStarts, fileRules, lineRules };
1906
+ }
1907
+ function isIgnoredAt(ignores, rule, offset) {
1908
+ if (ignores.fileRules.has(rule))
1909
+ return true;
1910
+ const line = offsetToLine(ignores.lineStarts, offset);
1911
+ return ignores.lineRules.get(line)?.has(rule) === true;
1912
+ }
1913
+ function isRuleIgnored(rule, compliance) {
1914
+ if (rule === "lcen/legal-notice" && compliance?.legalNotice === false)
1915
+ return true;
1916
+ return compliance?.ignore?.includes(rule) === true;
1917
+ }
1918
+ function parseOrigin(url) {
1919
+ if (url === undefined || url.trim() === "")
1920
+ return;
1921
+ try {
1922
+ return new URL(url.trim()).origin;
1923
+ } catch {
1924
+ return;
1925
+ }
1926
+ }
1927
+ function thirdPartyOrigin(rawUrl) {
1928
+ const trimmed = rawUrl.trim();
1929
+ if (!/^(?:https?:)?\/\//i.test(trimmed))
1930
+ return;
1931
+ try {
1932
+ const parsed = new URL(trimmed.startsWith("//") ? `https:${trimmed}` : trimmed);
1933
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
1934
+ return;
1935
+ const host = parsed.hostname.toLowerCase();
1936
+ if (LOCAL_HOSTS.has(host) || host.endsWith(".localhost"))
1937
+ return;
1938
+ return parsed.origin;
1939
+ } catch {
1940
+ return;
1941
+ }
1942
+ }
1943
+ function shouldEmitWarning(warning, compliance, site) {
1944
+ if (warning.rule !== undefined && isRuleIgnored(warning.rule, compliance))
1945
+ return false;
1946
+ if (warning.rule === "rgpd/third-party-url" && warning.urlOrigin !== undefined) {
1947
+ const siteOrigin = parseOrigin(site);
1948
+ if (siteOrigin !== undefined && warning.urlOrigin === siteOrigin)
1949
+ return false;
1950
+ }
1951
+ return true;
1952
+ }
1953
+ function walkAst(value, enter) {
1954
+ if (value === null || typeof value !== "object")
1955
+ return;
1956
+ if (Array.isArray(value)) {
1957
+ for (let i = 0;i < value.length; i++)
1958
+ walkAst(value[i], enter);
1959
+ return;
1960
+ }
1961
+ const node = value;
1962
+ if (typeof node.type !== "string")
1963
+ return;
1964
+ enter(node);
1965
+ const keys = import_oxc_parser5.visitorKeys[node.type];
1966
+ if (keys !== undefined) {
1967
+ for (let i = 0;i < keys.length; i++)
1968
+ walkAst(node[keys[i]], enter);
1969
+ }
1970
+ }
1971
+ function collectLabelTargets(program) {
1972
+ const targets = new Set;
1973
+ walkAst(program, (node) => {
1974
+ if (node.type !== "JSXElement")
1975
+ return;
1976
+ const tag = jsxTagName(node.openingElement.name);
1977
+ if (tag !== "label")
1978
+ return;
1979
+ const attrs = node.openingElement.attributes;
1980
+ const key = attrTargetKey(findAttr(attrs, "for") ?? findAttr(attrs, "htmlFor"));
1981
+ if (key !== undefined)
1982
+ targets.add(key);
1983
+ });
1984
+ return targets;
1985
+ }
1986
+ function checkThirdPartyElement(element, tag, filename, ignores, warnings) {
1987
+ const attrs = element.openingElement.attributes;
1988
+ let attr;
1989
+ let attrName = "";
1990
+ if (tag === "script" || tag === "iframe") {
1991
+ attr = findAttr(attrs, "src");
1992
+ attrName = "src";
1993
+ } else if (tag === "link") {
1994
+ const relVal = staticStringValueOf(findAttr(attrs, "rel")?.value ?? null);
1995
+ if (relVal === undefined)
1996
+ return;
1997
+ const rels = relVal.toLowerCase().split(/\s+/);
1998
+ if (!rels.some((r) => THIRD_PARTY_LINK_RELS.has(r)))
1999
+ return;
2000
+ attr = findAttr(attrs, "href");
2001
+ attrName = "href";
2002
+ }
2003
+ if (attr === undefined)
2004
+ return;
2005
+ const url = staticStringValueOf(attr.value);
2006
+ if (url === undefined)
2007
+ return;
2008
+ const origin = thirdPartyOrigin(url);
2009
+ if (origin === undefined || isIgnoredAt(ignores, "rgpd/third-party-url", attr.start))
2010
+ return;
2011
+ warnings.push({
2012
+ rule: "rgpd/third-party-url",
2013
+ urlOrigin: origin,
2014
+ start: attr.start,
2015
+ message: `[rgpd/third-party-url] <${tag} ${attrName}="${url}"> in ${filename} loads a third-party resource without consent: self-host it (e.g. @prunellejs/seo fonts or public/) or wrap it in <ConsentGate category="...">.`
2016
+ });
2017
+ }
2018
+ function definitelyExits(stmt) {
2019
+ if (stmt.type === "ReturnStatement" || stmt.type === "ThrowStatement")
2020
+ return true;
2021
+ if (stmt.type === "BlockStatement")
2022
+ return stmt.body.length > 0 && definitelyExits(stmt.body[stmt.body.length - 1]);
2023
+ if (stmt.type === "IfStatement")
2024
+ return stmt.alternate !== null && definitelyExits(stmt.consequent) && definitelyExits(stmt.alternate);
2025
+ return false;
2026
+ }
2027
+ function checkCompliance(program, filename, code, warnings, resolveTag) {
2028
+ const ignores = parsePrunelleIgnores(code);
2029
+ const labelTargets = collectLabelTargets(program);
2030
+ const isIgnored = (rule, elementStart, attrStart) => isIgnoredAt(ignores, rule, elementStart) || attrStart !== undefined && isIgnoredAt(ignores, rule, attrStart);
2031
+ const visitChildren = (node, ancestors, scope) => {
2032
+ const keys = import_oxc_parser5.visitorKeys[node.type];
2033
+ if (keys === undefined)
2034
+ return;
2035
+ const rec = node;
2036
+ for (let i = 0;i < keys.length; i++)
2037
+ visit(rec[keys[i]], ancestors, scope);
2038
+ };
2039
+ const visit = (value, ancestors, scope) => {
2040
+ if (value === null || typeof value !== "object")
2041
+ return;
2042
+ if (Array.isArray(value)) {
2043
+ for (let i = 0;i < value.length; i++)
2044
+ visit(value[i], ancestors, scope);
2045
+ return;
2046
+ }
2047
+ const node = value;
2048
+ if (typeof node.type !== "string")
2049
+ return;
2050
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
2051
+ visitChildren(node, ancestors, createRgaaScope());
2052
+ return;
2053
+ }
2054
+ if (node.type === "ConditionalExpression") {
2055
+ visit(node.test, ancestors, scope);
2056
+ const branchA = cloneRgaaScope(scope);
2057
+ const branchB = cloneRgaaScope(scope);
2058
+ visit(node.consequent, ancestors, branchA);
2059
+ visit(node.alternate, ancestors, branchB);
2060
+ mergeRgaaScope(scope, branchA);
2061
+ mergeRgaaScope(scope, branchB);
2062
+ return;
2063
+ }
2064
+ if (node.type === "IfStatement") {
2065
+ visit(node.test, ancestors, scope);
2066
+ const branchA = cloneRgaaScope(scope);
2067
+ visit(node.consequent, ancestors, branchA);
2068
+ const branchB = cloneRgaaScope(scope);
2069
+ if (node.alternate !== null)
2070
+ visit(node.alternate, ancestors, branchB);
2071
+ if (!definitelyExits(node.consequent))
2072
+ mergeRgaaScope(scope, branchA);
2073
+ if (node.alternate !== null && !definitelyExits(node.alternate))
2074
+ mergeRgaaScope(scope, branchB);
2075
+ return;
2076
+ }
2077
+ if (node.type === "JSXElement") {
2078
+ const tag = jsxTagName(node.openingElement.name);
2079
+ const attrs = node.openingElement.attributes;
2080
+ if (tag !== "" && !isComponentTag(tag)) {
2081
+ checkRgaaElement(node, tag, {
2082
+ filename,
2083
+ inLabel: ancestors.labelDepth > 0,
2084
+ interactiveAncestor: ancestors.interactiveAncestor,
2085
+ labelTargets,
2086
+ scope,
2087
+ isIgnored,
2088
+ warnings
2089
+ });
2090
+ if (ancestors.consentGateDepth === 0)
2091
+ checkThirdPartyElement(node, tag, filename, ignores, warnings);
2092
+ }
2093
+ visit(attrs, ancestors, scope);
2094
+ const opensLabel = tag === "label" || isComponentTag(tag) && hasNonEmptyAttr(attrs, "label");
2095
+ const opensConsentGate = resolveTag(tag) === "ConsentGate";
2096
+ const nextInteractive = INTERACTIVE_ANCESTORS.has(tag) ? tag : ancestors.interactiveAncestor;
2097
+ const childAncestors = opensLabel || opensConsentGate || nextInteractive !== ancestors.interactiveAncestor ? {
2098
+ labelDepth: ancestors.labelDepth + (opensLabel ? 1 : 0),
2099
+ consentGateDepth: ancestors.consentGateDepth + (opensConsentGate ? 1 : 0),
2100
+ interactiveAncestor: nextInteractive
2101
+ } : ancestors;
2102
+ visit(node.children, childAncestors, scope);
2103
+ return;
2104
+ }
2105
+ visitChildren(node, ancestors, scope);
2106
+ };
2107
+ visit(program, { labelDepth: 0, consentGateDepth: 0, interactiveAncestor: undefined }, createRgaaScope());
2108
+ }
2109
+
2110
+ // packages/prunelle/src/compiler/interactivity.ts
2111
+ function resolveInteractivity(bindings, exportLocals, reads = new Map) {
2112
+ const named = new Map;
2113
+ for (const b of bindings) {
2114
+ if (b.name !== "")
2115
+ named.set(b.name, b);
2116
+ }
2117
+ const facts = spreadFacts(bindings, named, reads);
2118
+ const exported = new Set(exportLocals.values());
2119
+ const serverSide = new Set;
2120
+ const stack = bindings.filter((b) => !facts.has(b) && (b.name === "" || exported.has(b.name)));
2121
+ for (let b = stack.pop();b !== undefined; b = stack.pop()) {
2122
+ if (serverSide.has(b))
2123
+ continue;
2124
+ serverSide.add(b);
2125
+ for (const ref of b.refs.keys()) {
2126
+ const dep = named.get(ref);
2127
+ if (dep !== undefined && !facts.has(dep))
2128
+ stack.push(dep);
2129
+ }
2130
+ }
2131
+ const exports2 = new Map;
2132
+ for (const [name, local] of exportLocals) {
2133
+ const binding = named.get(local);
2134
+ const fact = binding === undefined ? undefined : facts.get(binding);
2135
+ exports2.set(name, fact === undefined ? { interactive: false } : { interactive: true, reason: fact.reason, offset: fact.offset });
2136
+ }
2137
+ const staticJsxTags = new Set([...serverSide].flatMap((b) => [...b.tags]));
2138
+ const localIslands = new Map;
2139
+ for (const [binding, fact] of facts) {
2140
+ if (binding.name !== "" && staticJsxTags.has(binding.name))
2141
+ localIslands.set(binding.name, fact);
2142
+ }
2143
+ const first = bindings.find((b) => facts.has(b));
2144
+ const firstFact = first === undefined ? undefined : facts.get(first);
2145
+ return {
2146
+ isInteractive: facts.size > 0,
2147
+ interactiveReason: firstFact?.reason,
2148
+ interactiveOffset: firstFact?.offset,
2149
+ exports: exports2,
2150
+ localIslands,
2151
+ staticJsxTags,
2152
+ islandSpans: bindings.filter((b) => !serverSide.has(b)).map((b) => [b.start, b.end]),
2153
+ browserSpans: [...reachedFrom([...facts.keys()], named)].map((b) => [b.start, b.end]),
2154
+ serverOnly: serverOnlyInIsland(bindings, named, facts)
2155
+ };
2156
+ }
2157
+ function spreadFacts(bindings, named, reads) {
2158
+ const facts = new Map;
2159
+ let moduleFact;
2160
+ for (const b of bindings) {
2161
+ let own = b.fact;
2162
+ for (const [ref, offset] of b.valueRefs) {
2163
+ if (own !== undefined)
2164
+ break;
2165
+ const reason = reads.get(ref);
2166
+ if (reason !== undefined) {
2167
+ own = { reason, offset };
2168
+ continue;
2169
+ }
2170
+ const members = b.memberRefs.get(ref);
2171
+ if (members !== undefined) {
2172
+ for (const m of members) {
2173
+ const mReason = reads.get(`${ref}.${m}`);
2174
+ if (mReason !== undefined) {
2175
+ own = { reason: mReason, offset };
2176
+ break;
2177
+ }
2178
+ }
2179
+ }
2180
+ }
2181
+ if (own !== undefined)
2182
+ facts.set(b, own);
2183
+ if (b.name === "")
2184
+ moduleFact ??= own;
2185
+ }
2186
+ if (moduleFact !== undefined) {
2187
+ for (const b of named.values()) {
2188
+ if (!facts.has(b))
2189
+ facts.set(b, moduleFact);
2190
+ }
2191
+ }
2192
+ for (let changed = true;changed; ) {
2193
+ changed = false;
2194
+ for (const b of named.values()) {
2195
+ if (facts.has(b))
2196
+ continue;
2197
+ for (const [ref, offset] of b.refs) {
2198
+ if (b.tags.has(ref) && !b.valueRefs.has(ref))
2199
+ continue;
2200
+ const dep = named.get(ref);
2201
+ const depFact = dep === undefined ? undefined : facts.get(dep);
2202
+ if (depFact !== undefined) {
2203
+ facts.set(b, { reason: `uses ${ref}, which ${depFact.reason}`, offset });
2204
+ changed = true;
2205
+ break;
2206
+ }
2207
+ }
2208
+ }
2209
+ }
2210
+ return facts;
2211
+ }
2212
+ function serverOnlyInIsland(bindings, named, facts) {
2213
+ for (const island of bindings) {
2214
+ const fact = facts.get(island);
2215
+ if (fact === undefined)
2216
+ continue;
2217
+ const seen = new Set;
2218
+ const stack = [island];
2219
+ for (let b = stack.pop();b !== undefined; b = stack.pop()) {
2220
+ if (seen.has(b))
2221
+ continue;
2222
+ seen.add(b);
2223
+ if (b.serverOnlyTag !== undefined) {
2224
+ const name = island.name === "" ? "the module" : island.name === "default" ? "the default export" : island.name;
2225
+ return { tag: b.serverOnlyTag, island: name, reason: fact.reason, offset: fact.offset };
2226
+ }
2227
+ for (const ref of b.refs.keys()) {
2228
+ const dep = named.get(ref);
2229
+ if (dep !== undefined)
2230
+ stack.push(dep);
2231
+ }
2232
+ }
2233
+ }
2234
+ return;
2235
+ }
2236
+ function reachedFrom(roots, named) {
2237
+ const seen = new Set;
2238
+ const stack = [...roots];
2239
+ for (let b = stack.pop();b !== undefined; b = stack.pop()) {
2240
+ if (seen.has(b))
2241
+ continue;
2242
+ seen.add(b);
2243
+ for (const ref of b.refs.keys()) {
2244
+ const dep = named.get(ref);
2245
+ if (dep !== undefined)
2246
+ stack.push(dep);
2247
+ }
2248
+ }
2249
+ return seen;
2250
+ }
2251
+
2252
+ // packages/prunelle/src/compiler/node-env.ts
2253
+ var MENTIONS_RE2 = /\bNODE_ENV\b/;
2254
+ function keyOf(member) {
2255
+ if (!member.computed && member.property.type === "Identifier")
2256
+ return member.property.name;
2257
+ if (member.computed && member.property.type === "Literal" && typeof member.property.value === "string")
2258
+ return member.property.value;
2259
+ return;
2260
+ }
2261
+ function isProcessEnv(node, shadowing) {
2262
+ const env = unwrapTsExpr(node);
2263
+ if (env.type !== "MemberExpression" || keyOf(env) !== "env")
2264
+ return false;
2265
+ const proc = unwrapTsExpr(env.object);
2266
+ if (proc.type === "Identifier")
2267
+ return proc.name === "process" && !shadowing.has("process");
2268
+ if (proc.type !== "MemberExpression" || keyOf(proc) !== "process")
2269
+ return false;
2270
+ const base = unwrapTsExpr(proc.object);
2271
+ return base.type === "Identifier" && base.name === "globalThis" && !shadowing.has("globalThis");
2272
+ }
2273
+ function findNodeEnvReads(program, code) {
2274
+ if (!MENTIONS_RE2.test(code))
2275
+ return [];
2276
+ const shadowing = topLevelNames(program);
2277
+ const reads = [];
2278
+ walk(program, (node) => {
2279
+ if (node.type === "MemberExpression" && keyOf(node) === "NODE_ENV" && isProcessEnv(node.object, shadowing)) {
2280
+ reads.push(node.start);
2281
+ } else if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init !== null && isProcessEnv(node.init, shadowing)) {
2282
+ for (const prop of node.id.properties) {
2283
+ if (prop.type === "Property" && !prop.computed && prop.key.type === "Identifier" && prop.key.name === "NODE_ENV")
2284
+ reads.push(prop.start);
2285
+ }
2286
+ }
2287
+ });
2288
+ return reads;
2289
+ }
2290
+
2291
+ // packages/prunelle/src/compiler/mistakes.ts
2292
+ var EVENT_PROPS = new Map(Object.entries({
2293
+ abort: "onAbort",
2294
+ animationcancel: "onAnimationCancel",
2295
+ animationend: "onAnimationEnd",
2296
+ animationiteration: "onAnimationIteration",
2297
+ animationstart: "onAnimationStart",
2298
+ auxclick: "onAuxClick",
2299
+ beforeinput: "onBeforeInput",
2300
+ beforetoggle: "onBeforeToggle",
2301
+ blur: "onBlur",
2302
+ cancel: "onCancel",
2303
+ canplay: "onCanPlay",
2304
+ canplaythrough: "onCanPlayThrough",
2305
+ change: "onChange",
2306
+ click: "onClick",
2307
+ close: "onClose",
2308
+ compositionend: "onCompositionEnd",
2309
+ compositionstart: "onCompositionStart",
2310
+ compositionupdate: "onCompositionUpdate",
2311
+ contextmenu: "onContextMenu",
2312
+ copy: "onCopy",
2313
+ cut: "onCut",
2314
+ dblclick: "onDblClick",
2315
+ drag: "onDrag",
2316
+ dragend: "onDragEnd",
2317
+ dragenter: "onDragEnter",
2318
+ dragleave: "onDragLeave",
2319
+ dragover: "onDragOver",
2320
+ dragstart: "onDragStart",
2321
+ drop: "onDrop",
2322
+ durationchange: "onDurationChange",
2323
+ emptied: "onEmptied",
2324
+ ended: "onEnded",
2325
+ error: "onError",
2326
+ focus: "onFocus",
2327
+ focusin: "onFocusIn",
2328
+ focusout: "onFocusOut",
2329
+ formdata: "onFormData",
2330
+ gotpointercapture: "onGotPointerCapture",
2331
+ input: "onInput",
2332
+ invalid: "onInvalid",
2333
+ keydown: "onKeyDown",
2334
+ keypress: "onKeyPress",
2335
+ keyup: "onKeyUp",
2336
+ load: "onLoad",
2337
+ loadeddata: "onLoadedData",
2338
+ loadedmetadata: "onLoadedMetadata",
2339
+ loadstart: "onLoadStart",
2340
+ lostpointercapture: "onLostPointerCapture",
2341
+ mousedown: "onMouseDown",
2342
+ mouseenter: "onMouseEnter",
2343
+ mouseleave: "onMouseLeave",
2344
+ mousemove: "onMouseMove",
2345
+ mouseout: "onMouseOut",
2346
+ mouseover: "onMouseOver",
2347
+ mouseup: "onMouseUp",
2348
+ paste: "onPaste",
2349
+ pause: "onPause",
2350
+ play: "onPlay",
2351
+ playing: "onPlaying",
2352
+ pointercancel: "onPointerCancel",
2353
+ pointerdown: "onPointerDown",
2354
+ pointerenter: "onPointerEnter",
2355
+ pointerleave: "onPointerLeave",
2356
+ pointermove: "onPointerMove",
2357
+ pointerout: "onPointerOut",
2358
+ pointerover: "onPointerOver",
2359
+ pointerup: "onPointerUp",
2360
+ progress: "onProgress",
2361
+ ratechange: "onRateChange",
2362
+ reset: "onReset",
2363
+ resize: "onResize",
2364
+ scroll: "onScroll",
2365
+ scrollend: "onScrollEnd",
2366
+ securitypolicyviolation: "onSecurityPolicyViolation",
2367
+ seeked: "onSeeked",
2368
+ seeking: "onSeeking",
2369
+ select: "onSelect",
2370
+ selectionchange: "onSelectionChange",
2371
+ selectstart: "onSelectStart",
2372
+ slotchange: "onSlotChange",
2373
+ stalled: "onStalled",
2374
+ submit: "onSubmit",
2375
+ suspend: "onSuspend",
2376
+ timeupdate: "onTimeUpdate",
2377
+ toggle: "onToggle",
2378
+ touchcancel: "onTouchCancel",
2379
+ touchend: "onTouchEnd",
2380
+ touchmove: "onTouchMove",
2381
+ touchstart: "onTouchStart",
2382
+ transitioncancel: "onTransitionCancel",
2383
+ transitionend: "onTransitionEnd",
2384
+ transitionrun: "onTransitionRun",
2385
+ transitionstart: "onTransitionStart",
2386
+ volumechange: "onVolumeChange",
2387
+ waiting: "onWaiting",
2388
+ wheel: "onWheel",
2389
+ afterprint: "onAfterPrint",
2390
+ beforeprint: "onBeforePrint",
2391
+ beforeunload: "onBeforeUnload",
2392
+ hashchange: "onHashChange",
2393
+ message: "onMessage",
2394
+ offline: "onOffline",
2395
+ online: "onOnline",
2396
+ pagehide: "onPageHide",
2397
+ pageshow: "onPageShow",
2398
+ popstate: "onPopState",
2399
+ storage: "onStorage",
2400
+ unload: "onUnload",
2401
+ fullscreenchange: "onFullscreenChange",
2402
+ fullscreenerror: "onFullscreenError",
2403
+ loadend: "onLoadEnd",
2404
+ search: "onSearch",
2405
+ beforematch: "onBeforeMatch",
2406
+ command: "onCommand",
2407
+ cuechange: "onCueChange",
2408
+ encrypted: "onEncrypted",
2409
+ waitingforkey: "onWaitingForKey",
2410
+ pointerrawupdate: "onPointerRawUpdate",
2411
+ contextlost: "onContextLost",
2412
+ contextrestored: "onContextRestored",
2413
+ contentvisibilityautostatechange: "onContentVisibilityAutoStateChange"
2414
+ }));
2415
+ var RENAMED_EVENTS = new Map([["doubleclick", "dblclick"]]);
2416
+ var CAPTURE_SUFFIX = "capture";
2417
+ var LOWERCASE_EVENT = /^on[a-z]/;
2418
+ function eventProp(event) {
2419
+ return EVENT_PROPS.get(event) ?? `on${event.charAt(0).toUpperCase()}${event.slice(1)}`;
2420
+ }
2421
+
2422
+ class PrunelleMistake extends Error {
2423
+ start = undefined;
2424
+ }
2425
+ function mistake(what, filename, fix) {
2426
+ return new PrunelleMistake(`prunelle compiler: ${what} in ${filename}: ${fix}.`);
2427
+ }
2428
+ var collected;
2429
+ function guarded(start, check) {
2430
+ try {
2431
+ check();
2432
+ } catch (err) {
2433
+ if (!(err instanceof PrunelleMistake))
2434
+ throw err;
2435
+ err.start ??= start;
2436
+ if (collected === undefined)
2437
+ throw err;
2438
+ collected.push(err);
2439
+ }
2440
+ }
2441
+ function collectMistakes(fn) {
2442
+ const prev = collected;
2443
+ const mistakes = [];
2444
+ collected = mistakes;
2445
+ try {
2446
+ return { value: fn(), mistakes, error: undefined };
2447
+ } catch (error) {
2448
+ return { value: undefined, mistakes, error };
2449
+ } finally {
2450
+ collected = prev;
2451
+ }
2452
+ }
2453
+ function islandRemoved(filename, start) {
2454
+ const err = mistake("island()", filename, "it is gone; write export const hydrate = 'visible' in the component's file, or set $hydrate where it renders");
2455
+ err.start = start;
2456
+ return err;
2457
+ }
2458
+ function serverOnlyTagError(filename, { tag, island, reason, offset }) {
2459
+ const err = mistake(`<${tag}> in an island`, filename, `${island} is an island because it ${reason}; move <${tag}> to the page or a layout, outside any component with state or handlers`);
2460
+ err.start = offset;
2461
+ return err;
2462
+ }
2463
+ var KAY_SOURCE_RE = /^@kayjs\/(kay(?=\/|$))?/;
2464
+ function assertNoKayImport(source, filename) {
2465
+ const match = KAY_SOURCE_RE.exec(source);
2466
+ if (match !== null)
2467
+ throw mistake(`import from '${source}'`, filename, `write '${source.replace(KAY_SOURCE_RE, match[1] === undefined ? "@prunellejs/" : "prunelle")}' (prunelle upgrade rewrites every import)`);
2468
+ }
2469
+ var HYDRATE_MODES = new Set(["load", "visible", "idle", "interaction", "client"]);
2470
+ var MEDIA_MODE = /^media\(.+\)$/;
2471
+ function checkHydrateMode(mode, what, filename) {
2472
+ if (mode !== "*" && !HYDRATE_MODES.has(mode) && !MEDIA_MODE.test(mode))
2473
+ throw mistake(what, filename, "use load, visible, idle, interaction, client or media(<query>)");
2474
+ }
2475
+ function staticStringValue(node) {
2476
+ if (node === null || node === undefined)
2477
+ return;
2478
+ const val = unwrapTsExpr(node);
2479
+ if (val.type === "Literal" && typeof val.value === "string")
2480
+ return val.value;
2481
+ return val.type === "TemplateLiteral" && val.expressions.length === 0 ? val.quasis[0]?.value.cooked ?? undefined : undefined;
2482
+ }
2483
+ function checkExportHydrate(init, filename) {
2484
+ if (init === null || init === undefined)
2485
+ return;
2486
+ const mode = staticStringValue(init);
2487
+ if (mode !== undefined) {
2488
+ guarded(init.start, () => checkHydrateMode(mode, `hydrate = "${mode}"`, filename));
2489
+ return mode;
2490
+ }
2491
+ const val = unwrapTsExpr(init);
2492
+ if (val.type === "Literal" || val.type === "ArrayExpression" || val.type === "ObjectExpression" || val.type === "Identifier" && val.name === "undefined")
2493
+ guarded(init.start, () => {
2494
+ throw mistake("hydrate", filename, "use load, visible, idle, interaction, client or media(<query>)");
2495
+ });
2496
+ return;
2497
+ }
2498
+ function checkHandler(name, value, filename, code) {
2499
+ if (value === null)
2500
+ throw mistake(name, filename, `pass a function, ${name}={() => ...}`);
2501
+ if (value.type === "Literal")
2502
+ throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`);
2503
+ if (value.type !== "JSXExpressionContainer")
2504
+ return;
2505
+ const expr = unwrapParens(value.expression);
2506
+ if (expr.type === "Literal" && typeof expr.value === "string" || expr.type === "TemplateLiteral")
2507
+ throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`);
2508
+ if (expr.type === "UpdateExpression" || expr.type === "AssignmentExpression") {
2509
+ const source = code.slice(expr.start, expr.end);
2510
+ throw mistake(`${name} runs ${source} at render`, filename, `write ${name}={() => ${source}}`);
2511
+ }
2512
+ }
2513
+ var KEBAB_SVG_ATTRS = new Set([
2514
+ "alignment-baseline",
2515
+ "baseline-shift",
2516
+ "clip-path",
2517
+ "clip-rule",
2518
+ "color-interpolation",
2519
+ "color-interpolation-filters",
2520
+ "dominant-baseline",
2521
+ "enable-background",
2522
+ "fill-opacity",
2523
+ "fill-rule",
2524
+ "flood-color",
2525
+ "flood-opacity",
2526
+ "font-family",
2527
+ "font-size",
2528
+ "font-size-adjust",
2529
+ "font-stretch",
2530
+ "font-style",
2531
+ "font-variant",
2532
+ "font-weight",
2533
+ "image-rendering",
2534
+ "letter-spacing",
2535
+ "lighting-color",
2536
+ "marker-end",
2537
+ "marker-mid",
2538
+ "marker-start",
2539
+ "paint-order",
2540
+ "pointer-events",
2541
+ "shape-rendering",
2542
+ "stop-color",
2543
+ "stop-opacity",
2544
+ "stroke-dasharray",
2545
+ "stroke-dashoffset",
2546
+ "stroke-linecap",
2547
+ "stroke-linejoin",
2548
+ "stroke-miterlimit",
2549
+ "stroke-opacity",
2550
+ "stroke-width",
2551
+ "text-anchor",
2552
+ "text-decoration",
2553
+ "text-rendering",
2554
+ "transform-origin",
2555
+ "unicode-bidi",
2556
+ "vector-effect",
2557
+ "word-spacing",
2558
+ "writing-mode"
2559
+ ]);
2560
+ var CAMEL_HUMP = /[A-Z]/g;
2561
+ var REACT_DEFAULTS = new Map([["defaultValue", "value"], ["defaultChecked", "checked"]]);
2562
+ var BOOLEAN_ATTRS = new Set([
2563
+ "allowfullscreen",
2564
+ "async",
2565
+ "autofocus",
2566
+ "autoplay",
2567
+ "checked",
2568
+ "controls",
2569
+ "default",
2570
+ "defer",
2571
+ "disabled",
2572
+ "formnovalidate",
2573
+ "hidden",
2574
+ "inert",
2575
+ "ismap",
2576
+ "loop",
2577
+ "multiple",
2578
+ "muted",
2579
+ "nomodule",
2580
+ "novalidate",
2581
+ "open",
2582
+ "playsinline",
2583
+ "readonly",
2584
+ "required",
2585
+ "reversed",
2586
+ "selected"
2587
+ ]);
2588
+ function checkRef(value, filename) {
2589
+ if (value === null)
2590
+ throw mistake("ref", filename, "pass a function, ref={el => ...}");
2591
+ if (value.type === "Literal")
2592
+ throw mistake('ref="..."', filename, "pass a function, ref={el => ...}");
2593
+ if (value.type === "JSXExpressionContainer" && unwrapParens(value.expression).type === "ObjectExpression")
2594
+ throw mistake("ref={{ ... }}", filename, "pass a function, ref={el => ...}, prunelle has no ref objects");
2595
+ }
2596
+ var CAMEL_ARIA = /^aria[A-Z]/;
2597
+ function checkSpelling(name, value, filename) {
2598
+ if (CAMEL_ARIA.test(name))
2599
+ throw mistake(name, filename, `write aria-${name.slice(4).toLowerCase()}={...}, ARIA attributes use kebab-case`);
2600
+ const kebab = name.replace(CAMEL_HUMP, (hump) => `-${hump.toLowerCase()}`);
2601
+ if (kebab !== name && KEBAB_SVG_ATTRS.has(kebab))
2602
+ throw mistake(name, filename, `write ${kebab}={...}, SVG attributes are case-sensitive`);
2603
+ if (name === "xlinkHref")
2604
+ throw mistake(name, filename, "write xlink:href={...}, or href={...}");
2605
+ const attribute = REACT_DEFAULTS.get(name);
2606
+ if (attribute !== undefined)
2607
+ throw mistake(name, filename, `write ${attribute}={...}`);
2608
+ if (value?.type === "Literal" && value.value === "false" && BOOLEAN_ATTRS.has(name.toLowerCase()))
2609
+ throw mistake(`${name}="false"`, filename, `write ${name}={false}, any string turns it on`);
2610
+ }
2611
+ var CLIENT_DIRECTIVES = new Map([["load", "load"], ["visible", "visible"], ["idle", "idle"], ["only", "client"], ["media", "media(<query>)"]]);
2612
+ var XML_NAMESPACES = new Set(["xlink", "xml", "xmlns"]);
2613
+ function checkNamespacedAttribute(namespace, name, filename) {
2614
+ if (XML_NAMESPACES.has(namespace))
2615
+ return;
2616
+ const what = `${namespace}:${name}`;
2617
+ if (namespace === "on")
2618
+ throw mistake(what, filename, `write ${eventProp(name.toLowerCase())}={...}`);
2619
+ if (namespace === "client")
2620
+ throw mistake(what, filename, `write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? "load"}"`);
2621
+ if (what === "class:list")
2622
+ throw mistake(what, filename, "pass one string to class, joining the names yourself");
2623
+ if (what === "set:html")
2624
+ throw mistake(what, filename, "write innerHTML={...}");
2625
+ if (what === "set:text")
2626
+ throw mistake(what, filename, "write the text as children");
2627
+ if (namespace === "use")
2628
+ throw mistake(what, filename, `call ${name} in a ref`);
2629
+ if (namespace === "prop" || namespace === "attr" || namespace === "bool")
2630
+ throw mistake(what, filename, `write ${name}={...}`);
2631
+ throw mistake(what, filename, `prunelle has no ${namespace}: directives`);
2632
+ }
2633
+ function reactHtmlSource(value, code) {
2634
+ if (value?.type !== "JSXExpressionContainer")
2635
+ return;
2636
+ const expr = unwrapParens(value.expression);
2637
+ if (expr.type !== "ObjectExpression")
2638
+ return;
2639
+ for (const p of expr.properties) {
2640
+ if (p.type !== "Property")
2641
+ continue;
2642
+ const keyName = p.key.type === "Identifier" ? p.key.name : p.key.type === "Literal" ? String(p.key.value) : undefined;
2643
+ if (keyName === "__html")
2644
+ return code.slice(p.value.start, p.value.end);
2645
+ }
2646
+ return;
2647
+ }
2648
+ function checkInnerHtml(element, tag, attr, filename, code) {
2649
+ const html = reactHtmlSource(attr.value, code);
2650
+ if (html !== undefined)
2651
+ throw mistake("innerHTML={{ __html }}", filename, `write innerHTML={${html}}, prunelle takes the HTML string itself`);
2652
+ if (VOID_ELEMENTS.has(tag))
2653
+ throw mistake(`innerHTML on <${tag}>`, filename, "a void element has no content, drop innerHTML");
2654
+ if (filterMeaningfulChildren(element.children).length > 0)
2655
+ throw mistake("innerHTML with children", filename, "keep one, the children or innerHTML");
2656
+ }
2657
+ function staticStringAttr(value) {
2658
+ if (value === null)
2659
+ return;
2660
+ if (value.type === "Literal" && typeof value.value === "string")
2661
+ return value.value;
2662
+ if (value.type === "JSXExpressionContainer" && value.expression.type !== "JSXEmptyExpression") {
2663
+ const expr = unwrapParens(value.expression);
2664
+ if (expr.type === "Literal" && typeof expr.value === "string")
2665
+ return expr.value;
2666
+ if (expr.type === "TemplateLiteral" && expr.expressions.length === 0)
2667
+ return expr.quasis[0]?.value.cooked ?? undefined;
2668
+ }
2669
+ return;
2670
+ }
2671
+ function checkElementAttribute(attr, tag, isCustomElement, filename, code, warnings) {
2672
+ if (attr.name.type !== "JSXIdentifier")
2673
+ return;
2674
+ const name = attr.name.name;
2675
+ if (name === "$hydrate")
2676
+ throw mistake(`$hydrate on <${tag}>`, filename, "only components can be islands; drop $hydrate, or move it onto a component tag");
2677
+ if (name.toLowerCase() === "srcdoc")
2678
+ throw mistake(`${name} on <${tag}>`, filename, "prunelle blocks srcdoc for XSS safety; serve the document from a route and load it with src");
2679
+ if (name === "dangerouslySetInnerHTML")
2680
+ throw mistake(name, filename, `write innerHTML={${reactHtmlSource(attr.value, code) ?? "..."}}`);
2681
+ if (name === "classList")
2682
+ throw mistake(name, filename, "pass one string to class, joining the names yourself");
2683
+ if (name === "ref")
2684
+ return checkRef(attr.value, filename);
2685
+ checkSpelling(name, attr.value, filename);
2686
+ if (URL_ATTRS.has(name.toLowerCase())) {
2687
+ const urlText = staticStringAttr(attr.value);
2688
+ if (urlText !== undefined && isUnsafeUrlAttr(name, urlText, tag))
2689
+ warnings.push({ message: `prunelle compiler: unsafe URL in ${name} on <${tag}> in ${filename}; prunelle strips javascript:, vbscript:, and non-image data: URLs.`, start: attr.start });
2690
+ }
2691
+ if (LOWERCASE_EVENT.test(name) && EVENT_PROPS.has(name.slice(2)))
2692
+ throw mistake(name, filename, `write ${eventProp(name.slice(2))}={...}, prunelle binds camelCase event props only`);
2693
+ if (!EVENT_ATTR.test(name))
2694
+ return;
2695
+ checkHandler(name, attr.value, filename, code);
2696
+ if (!isCustomElement)
2697
+ checkEventName(name, filename);
2698
+ }
2699
+ function checkEventName(name, filename) {
2700
+ const event = name.slice(2).toLowerCase();
2701
+ if (EVENT_PROPS.has(event))
2702
+ return;
2703
+ const renamed = RENAMED_EVENTS.get(event);
2704
+ if (renamed !== undefined)
2705
+ throw mistake(name, filename, `write ${eventProp(renamed)}={...}`);
2706
+ if (event.endsWith(CAPTURE_SUFFIX) && EVENT_PROPS.has(event.slice(0, -CAPTURE_SUFFIX.length)))
2707
+ throw mistake(name, filename, `prunelle has no capture props, call addEventListener('${event.slice(0, -CAPTURE_SUFFIX.length)}', fn, { capture: true }) in a ref`);
2708
+ throw mistake(name, filename, `no DOM event is named "${event}"; for a custom event, call addEventListener in a ref`);
2709
+ }
2710
+ var UNFOCUSABLE_TAGS = new Set([
2711
+ "article",
2712
+ "aside",
2713
+ "div",
2714
+ "fieldset",
2715
+ "footer",
2716
+ "form",
2717
+ "header",
2718
+ "label",
2719
+ "li",
2720
+ "main",
2721
+ "nav",
2722
+ "ol",
2723
+ "p",
2724
+ "section",
2725
+ "span",
2726
+ "table",
2727
+ "tbody",
2728
+ "td",
2729
+ "th",
2730
+ "thead",
2731
+ "tr",
2732
+ "ul"
2733
+ ]);
2734
+ var FOCUS_EVENTS = new Map([["onFocus", "onFocusIn"], ["onBlur", "onFocusOut"]]);
2735
+ var TEXT_INPUT_TYPES = new Set(["text", "search", "email", "url", "tel", "password", "number"]);
2736
+ function staticAttr(attributes, name) {
2737
+ for (const a of attributes) {
2738
+ if (a.type === "JSXAttribute" && a.name.type === "JSXIdentifier" && a.name.name === name)
2739
+ return a;
2740
+ }
2741
+ return;
2742
+ }
2743
+ function checkFocusAndChange(tag, attributes, filename, warnings) {
2744
+ const canFocus = !UNFOCUSABLE_TAGS.has(tag) || attributes.some((a) => a.type === "JSXSpreadAttribute" || a.name.type === "JSXIdentifier" && ["tabIndex", "tabindex", "contentEditable", "contenteditable"].includes(a.name.name));
2745
+ for (const [prop, bubbling] of FOCUS_EVENTS) {
2746
+ const attr = canFocus ? undefined : staticAttr(attributes, prop);
2747
+ if (attr !== undefined)
2748
+ guarded(attr.start, () => {
2749
+ throw mistake(`${prop} on <${tag}>`, filename, `focus does not bubble, write ${bubbling}={...}, or give the <${tag}> a tabIndex`);
2750
+ });
2751
+ }
2752
+ const onChange = staticAttr(attributes, "onChange");
2753
+ if (onChange === undefined)
2754
+ return;
2755
+ const type = staticAttr(attributes, "type")?.value;
2756
+ const isTextField = tag === "textarea" || tag === "input" && (type === undefined || type?.type === "Literal" && typeof type.value === "string" && TEXT_INPUT_TYPES.has(type.value));
2757
+ if (isTextField)
2758
+ warnings.push({ message: `prunelle compiler: onChange on <${tag}> in ${filename} fires when the field loses focus, not per keystroke; write onInput={...} for every keystroke.`, start: onChange.start });
2759
+ }
2760
+ function checkMistakes(element, filename, code, warnings, resolveTag = (t) => t === "Suspense" || t === "Region" ? t : undefined) {
2761
+ const tag = jsxTagName(element.openingElement.name);
2762
+ const canonical = resolveTag(tag);
2763
+ const isElement = tag !== "" && !isComponentTag(tag);
2764
+ const isCustomElement = tag.includes("-");
2765
+ if (canonical === "Suspense") {
2766
+ const children = filterMeaningfulChildren(element.children).length;
2767
+ if (children > 1)
2768
+ guarded(element.start, () => {
2769
+ throw mistake(`<Suspense> with ${children} children`, filename, "give it one child, and one <Suspense> per async component");
2770
+ });
2771
+ }
2772
+ const attributes = element.openingElement.attributes;
2773
+ guarded(element.start, () => checkRegionMarkup(tag, canonical, isElement, attributes, filename, element, resolveTag));
2774
+ if (isElement)
2775
+ guarded(element.start, () => checkKeepScroll(element, attributes, filename));
2776
+ if (isElement && VOID_ELEMENTS.has(tag) && (filterMeaningfulChildren(element.children).length > 0 || staticAttr(attributes, "children") !== undefined))
2777
+ guarded(element.start, () => {
2778
+ throw mistake(`<${tag}> with children`, filename, `a void element has no content; write <${tag} />`);
2779
+ });
2780
+ const className = isElement && staticAttr(attributes, "class") !== undefined ? staticAttr(attributes, "className") : undefined;
2781
+ if (className !== undefined)
2782
+ guarded(className.start, () => {
2783
+ throw mistake("class and className", filename, "keep one, they set the same attribute");
2784
+ });
2785
+ const htmlFor = isElement && staticAttr(attributes, "for") !== undefined ? staticAttr(attributes, "htmlFor") : undefined;
2786
+ if (htmlFor !== undefined)
2787
+ guarded(htmlFor.start, () => {
2788
+ throw mistake("for and htmlFor", filename, "keep one, they set the same attribute");
2789
+ });
2790
+ if (isElement)
2791
+ checkFocusAndChange(tag, attributes, filename, warnings);
2792
+ for (const attr of attributes) {
2793
+ if (attr.type !== "JSXAttribute")
2794
+ continue;
2795
+ guarded(attr.start, () => {
2796
+ if (attr.name.type === "JSXNamespacedName")
2797
+ checkNamespacedAttribute(attr.name.namespace.name, attr.name.name.name, filename);
2798
+ else if (isElement && attr.name.name === "innerHTML")
2799
+ checkInnerHtml(element, tag, attr, filename, code);
2800
+ else if (isElement)
2801
+ checkElementAttribute(attr, tag, isCustomElement, filename, code, warnings);
2802
+ });
2803
+ }
2804
+ }
2805
+ function literalText(attr) {
2806
+ return attr.value?.type === "Literal" && typeof attr.value.value === "string" ? attr.value.value : undefined;
2807
+ }
2808
+ function checkRegionNesting(element, attributes, filename, resolveTag) {
2809
+ const outer = staticAttr(attributes, "name");
2810
+ const name = outer === undefined ? undefined : literalText(outer);
2811
+ if (name === undefined)
2812
+ return;
2813
+ walk(element.children, (node) => {
2814
+ if (node.type !== "JSXElement" || resolveTag(jsxTagName(node.openingElement.name)) !== "Region")
2815
+ return;
2816
+ const inner = staticAttr(node.openingElement.attributes, "name");
2817
+ if (inner !== undefined && literalText(inner) === name)
2818
+ throw mistake(`<Region name="${name}"> inside <Region name="${name}">`, filename, "give the inner one its own name");
2819
+ });
2820
+ }
2821
+ function checkRegionMarkup(tag, canonical, isElement, attributes, filename, element, resolveTag) {
2822
+ if (canonical === "Region")
2823
+ checkRegionNesting(element, attributes, filename, resolveTag);
2824
+ if (canonical === "Region" && staticAttr(attributes, "name") === undefined && !attributes.some((a) => a.type === "JSXSpreadAttribute"))
2825
+ throw mistake("<Region> without a name", filename, 'write <Region name="pane">, the name a link names in data-pru-target');
2826
+ if (!isElement)
2827
+ return;
2828
+ const target = staticAttr(attributes, "data-pru-target");
2829
+ if (target !== undefined && tag !== "a" && tag !== "form")
2830
+ throw mistake(`data-pru-target on <${tag}>`, filename, "put it on the <a href> or the <form> that should swap the region");
2831
+ const method = tag === "form" && target !== undefined ? staticAttr(attributes, "method") : undefined;
2832
+ const methodText = method === undefined ? undefined : literalText(method);
2833
+ if (methodText !== undefined && methodText.toLowerCase() !== "get" && staticAttr(attributes, "data-pru-live") !== undefined)
2834
+ throw mistake(`data-pru-live on a <form method="${methodText}">`, filename, 'a form that swaps while typing is a GET: use method="get", or drop data-pru-live');
2835
+ if (target === undefined && staticAttr(attributes, "data-pru-append") !== undefined)
2836
+ throw mistake("data-pru-append without data-pru-target", filename, 'name the region the next page is appended to: data-pru-target="results"');
2837
+ if (staticAttr(attributes, "data-pru-live") !== undefined && (tag !== "form" || target === undefined))
2838
+ throw mistake("data-pru-live", filename, 'it belongs on a <form method="get" data-pru-target="..."> that swaps while typing');
2839
+ }
2840
+ function checkKeepScroll(element, attributes, filename) {
2841
+ const attr = staticAttr(attributes, "data-pru-keep-scroll");
2842
+ if (attr === undefined)
2843
+ return;
2844
+ const keyOf = (a) => a.value?.type === "JSXExpressionContainer" ? staticStringValue(a.value.expression) : literalText(a);
2845
+ const key = keyOf(attr);
2846
+ if (key === undefined || key.trim() === "" || /["<>&]/.test(key))
2847
+ throw mistake("data-pru-keep-scroll without a literal key", filename, 'write data-pru-keep-scroll="side": a plain string naming the panel, with no quote, < > or &');
2848
+ walk(element.children, (node) => {
2849
+ if (node.type !== "JSXElement")
2850
+ return;
2851
+ const inner = staticAttr(node.openingElement.attributes, "data-pru-keep-scroll");
2852
+ if (inner !== undefined && keyOf(inner) === key)
2853
+ throw mistake(`data-pru-keep-scroll="${key}" inside data-pru-keep-scroll="${key}"`, filename, "give each panel its own key");
2854
+ });
2855
+ }
2856
+ var DIRECTIVE_FIXES = {
2857
+ "use client": "delete it, prunelle makes a component an island by itself when it uses state or handlers",
2858
+ "use server": "delete it, a server function is an action() exported from its own file"
2859
+ };
2860
+ function checkHabits(node, isEffect, filename) {
2861
+ if (node.type === "ExpressionStatement" && "directive" in node && typeof node.directive === "string") {
2862
+ const fix = DIRECTIVE_FIXES[node.directive];
2863
+ if (fix !== undefined)
2864
+ guarded(node.start, () => {
2865
+ throw mistake(`'${node.directive}'`, filename, fix);
2866
+ });
2867
+ return;
2868
+ }
2869
+ if (node.type !== "CallExpression" || !isEffect(calleeName(node.callee)))
2870
+ return;
2871
+ const fn = node.arguments[0];
2872
+ if ((fn?.type === "ArrowFunctionExpression" || fn?.type === "FunctionExpression") && fn.async)
2873
+ guarded(fn.start, () => {
2874
+ throw mistake("effect(async ...)", filename, "effect tracks only what it reads before the first await and takes a cleanup function, not a Promise; start the async work inside a plain effect");
2875
+ });
2876
+ }
2877
+
2878
+ // packages/prunelle/src/compiler/signal-reads.ts
2879
+ var import_oxc_parser6 = require("oxc-parser");
2880
+ function bindPattern(scope, pattern, isSignal = false) {
2881
+ if (pattern === null || pattern === undefined)
2882
+ return;
2883
+ if (pattern.type === "Identifier") {
2884
+ scope.set(pattern.name, isSignal);
2885
+ return;
2886
+ }
2887
+ walk(pattern, (node) => {
2888
+ if (node.type === "Identifier")
2889
+ scope.set(node.name, false);
2890
+ if (node.type === "AssignmentPattern")
2891
+ bindPattern(scope, node.left);
2892
+ else if (node.type === "Property")
2893
+ bindPattern(scope, node.value);
2894
+ return node.type !== "AssignmentPattern" && node.type !== "Property";
2895
+ });
2896
+ }
2897
+ function bindStatements(scope, statements, signalCallees, importedSignals) {
2898
+ for (const stmt of statements) {
2899
+ const decl = stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportDefaultDeclaration" ? stmt.declaration : stmt;
2900
+ if (decl?.type === "VariableDeclaration") {
2901
+ for (const d of decl.declarations) {
2902
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init);
2903
+ bindPattern(scope, d.id, init?.type === "CallExpression" && signalCallees.has(calleeName(init.callee)));
2904
+ }
2905
+ } else if ((decl?.type === "FunctionDeclaration" || decl?.type === "ClassDeclaration") && decl.id !== null) {
2906
+ scope.set(decl.id.name, false);
2907
+ } else if (decl?.type === "ImportDeclaration") {
2908
+ for (const spec of decl.specifiers)
2909
+ scope.set(spec.local.name, importedSignals?.has(spec.local.name) === true);
2910
+ }
2911
+ }
2912
+ }
2913
+ function scopeOf(node, signalCallees, importedSignals) {
2914
+ const scope = new Map;
2915
+ switch (node.type) {
2916
+ case "Program":
2917
+ bindStatements(scope, node.body, signalCallees, importedSignals);
2918
+ return scope;
2919
+ case "BlockStatement":
2920
+ case "StaticBlock":
2921
+ bindStatements(scope, node.body, signalCallees);
2922
+ return scope;
2923
+ case "FunctionDeclaration":
2924
+ case "FunctionExpression":
2925
+ case "ArrowFunctionExpression":
2926
+ if (node.type === "FunctionExpression" && node.id !== null)
2927
+ scope.set(node.id.name, false);
2928
+ for (const param of node.params)
2929
+ bindPattern(scope, param);
2930
+ return scope;
2931
+ case "ForStatement":
2932
+ case "ForInStatement":
2933
+ case "ForOfStatement": {
2934
+ const head = node.type === "ForStatement" ? node.init : node.left;
2935
+ if (head?.type === "VariableDeclaration")
2936
+ bindStatements(scope, [head], signalCallees);
2937
+ return scope;
2938
+ }
2939
+ case "CatchClause":
2940
+ bindPattern(scope, node.param);
2941
+ return scope;
2942
+ case "SwitchStatement":
2943
+ for (const c of node.cases)
2944
+ bindStatements(scope, c.consequent, signalCallees);
2945
+ return scope;
2946
+ default:
2947
+ return;
2948
+ }
2949
+ }
2950
+ function walkWithSignals(program, signalCallees, importedSignals, importedSignalMembers, visit) {
2951
+ const scopes = [];
2952
+ const lookup = {
2953
+ isSignal(name) {
2954
+ for (let i = scopes.length - 1;i >= 0; i--) {
2955
+ const found = scopes[i].get(name);
2956
+ if (found !== undefined)
2957
+ return found;
2958
+ }
2959
+ return false;
2960
+ },
2961
+ isSignalMember(obj, prop) {
2962
+ const members = importedSignalMembers.get(obj);
2963
+ if (members === undefined || !members.has(prop))
2964
+ return false;
2965
+ for (let i = scopes.length - 1;i >= 1; i--) {
2966
+ if (scopes[i].has(obj))
2967
+ return false;
2968
+ }
2969
+ return true;
2970
+ }
2971
+ };
2972
+ const visitor = (node) => {
2973
+ visit(node, lookup);
2974
+ const scope = scopeOf(node, signalCallees, importedSignals);
2975
+ if (scope === undefined)
2976
+ return;
2977
+ scopes.push(scope);
2978
+ for (const key of import_oxc_parser6.visitorKeys[node.type] ?? [])
2979
+ walk(node[key], visitor);
2980
+ scopes.pop();
2981
+ return false;
2982
+ };
2983
+ walk(program, visitor);
2984
+ }
2985
+ function bareSignal(expr, lookup) {
2986
+ const node = unwrapTsExpr(expr);
2987
+ if (node.type === "Identifier")
2988
+ return lookup.isSignal(node.name) ? { name: node.name, start: node.start } : undefined;
2989
+ if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.property.type === "Identifier") {
2990
+ if (lookup.isSignalMember(node.object.name, node.property.name))
2991
+ return { name: `${node.object.name}.${node.property.name}`, start: node.start };
2992
+ return;
2993
+ }
2994
+ if (node.type === "LogicalExpression" || node.type === "BinaryExpression")
2995
+ return bareSignal(node.left, lookup) ?? bareSignal(node.right, lookup);
2996
+ if (node.type === "ConditionalExpression")
2997
+ return bareSignal(node.test, lookup) ?? bareSignal(node.consequent, lookup) ?? bareSignal(node.alternate, lookup);
2998
+ if (node.type === "UnaryExpression")
2999
+ return bareSignal(node.argument, lookup);
3000
+ if (node.type === "TemplateLiteral") {
3001
+ for (const part of node.expressions) {
3002
+ const found = bareSignal(part, lookup);
3003
+ if (found !== undefined)
3004
+ return found;
3005
+ }
3006
+ }
3007
+ return;
3008
+ }
3009
+ function jsxReads(node) {
3010
+ if (node.type !== "JSXElement" && node.type !== "JSXFragment")
3011
+ return [];
3012
+ const reads = [];
3013
+ for (const child of node.children) {
3014
+ if (child.type === "JSXExpressionContainer" && child.expression.type !== "JSXEmptyExpression")
3015
+ reads.push(child.expression);
3016
+ }
3017
+ if (node.type !== "JSXElement" || isComponentTag(jsxTagName(node.openingElement.name)))
3018
+ return reads;
3019
+ for (const attr of node.openingElement.attributes) {
3020
+ if (attr.type !== "JSXAttribute" || attr.name.type !== "JSXIdentifier")
3021
+ continue;
3022
+ const name = attr.name.name;
3023
+ if (name !== "" && name !== "ref" && name !== "key" && !EVENT_ATTR.test(name) && attr.value?.type === "JSXExpressionContainer" && attr.value.expression.type !== "JSXEmptyExpression")
3024
+ reads.push(attr.value.expression);
3025
+ }
3026
+ return reads;
3027
+ }
3028
+ function codeTests(node) {
3029
+ switch (node.type) {
3030
+ case "IfStatement":
3031
+ case "WhileStatement":
3032
+ case "DoWhileStatement":
3033
+ case "ConditionalExpression":
3034
+ return [node.test];
3035
+ case "ForStatement":
3036
+ return node.test === null ? [] : [node.test];
3037
+ case "UnaryExpression":
3038
+ return node.operator === "!" ? [node.argument] : [];
3039
+ default:
3040
+ return [];
3041
+ }
3042
+ }
3043
+ function destructuredSignal(node, lookup) {
3044
+ if (node.type !== "VariableDeclarator" || node.id.type !== "ObjectPattern" || node.init === null)
3045
+ return;
3046
+ const init = unwrapTsExpr(node.init);
3047
+ const name = init.type === "Identifier" && lookup.isSignal(init.name) ? init.name : init.type === "MemberExpression" && !init.computed && init.object.type === "Identifier" && init.property.type === "Identifier" && lookup.isSignalMember(init.object.name, init.property.name) ? `${init.object.name}.${init.property.name}` : undefined;
3048
+ if (name === undefined)
3049
+ return;
3050
+ const takesValue = node.id.properties.some((p) => p.type === "Property" && !p.computed && p.key.type === "Identifier" && p.key.name === "value");
3051
+ return takesValue ? name : undefined;
3052
+ }
3053
+ function checkBareSignals(program, signalCallees, filename, importedSignals = new Set, importedSignalMembers = new Map) {
3054
+ if (signalCallees.size === 0 && importedSignals.size === 0 && importedSignalMembers.size === 0)
3055
+ return;
3056
+ const reported = new Set;
3057
+ walkWithSignals(program, signalCallees, importedSignals, importedSignalMembers, (node, lookup) => {
3058
+ for (const expr of [...jsxReads(node), ...codeTests(node)]) {
3059
+ const found = bareSignal(expr, lookup);
3060
+ if (found === undefined || reported.has(found.start))
3061
+ continue;
3062
+ reported.add(found.start);
3063
+ guarded(found.start, () => {
3064
+ throw mistake(`${found.name} without .value`, filename, `write ${found.name}.value`);
3065
+ });
3066
+ }
3067
+ const copied = destructuredSignal(node, lookup);
3068
+ if (copied !== undefined)
3069
+ guarded(node.start, () => {
3070
+ throw mistake(`{ value } = ${copied}`, filename, `read ${copied}.value where it is used, a copied value never updates`);
3071
+ });
3072
+ });
3073
+ }
3074
+
3075
+ // packages/prunelle/src/compiler/analyze.ts
3076
+ var REACTIVE_IMPORTS = new Set(["signal", "computed", "effect", "onMount", "onCleanup", "selector", "store", "useAction"]);
3077
+ var STATE_PRIMITIVES = new Set(["signal", "computed", "selector", "store"]);
3078
+ var PRUNELLE_SOURCES = new Set(["prunelle"]);
3079
+ var PRUNELLE_SSR_SOURCES = new Set(["prunelle", "prunelle/internal/ssr"]);
3080
+ var PRUNELLE_SERVER_SOURCES = new Set(["prunelle/server"]);
3081
+ var RENDER_CONTEXT_IMPORTS = new Set(["Head", "Region", "Suspense", "ConsentGate", "createContext", "provideContext", "useContext", "useId"]);
3082
+ var SERVER_ONLY_TAGS = new Set(["Head", "Region", "Suspense", "ConsentGate"]);
3083
+ function exportedName(node) {
3084
+ return node.type === "Identifier" ? node.name : node.value;
3085
+ }
3086
+ function loadDeclarations(program) {
3087
+ const SERVER_ROUTE_EXPORTS = new Set(["load", "clientData"]);
3088
+ const localNames = new Set;
3089
+ const found = [];
3090
+ const collect = (stmt, names) => {
3091
+ if (stmt === null)
3092
+ return;
3093
+ if (stmt.type === "FunctionDeclaration" && stmt.id !== null && names.has(stmt.id.name)) {
3094
+ found.push(stmt);
3095
+ } else if (stmt.type === "VariableDeclaration") {
3096
+ for (const d of stmt.declarations) {
3097
+ if (d.id.type === "Identifier" && names.has(d.id.name) && d.init !== null)
3098
+ found.push(d.init);
3099
+ }
3100
+ }
3101
+ };
3102
+ for (const stmt of program.body) {
3103
+ if (stmt.type !== "ExportNamedDeclaration" || stmt.source !== null)
3104
+ continue;
3105
+ if (stmt.declaration !== null)
3106
+ collect(stmt.declaration, SERVER_ROUTE_EXPORTS);
3107
+ for (const spec of stmt.specifiers) {
3108
+ const exp = exportedName(spec.exported);
3109
+ if (exp !== undefined && SERVER_ROUTE_EXPORTS.has(exp) && spec.local.type === "Identifier")
3110
+ localNames.add(spec.local.name);
3111
+ }
3112
+ }
3113
+ if (localNames.size > 0) {
3114
+ for (const stmt of program.body)
3115
+ collect(stmt, localNames);
3116
+ }
3117
+ return found;
3118
+ }
3119
+ var ENTITY_HINT_RE = /&(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/i;
3120
+ function decodeAttributeEntities(program) {
3121
+ walk(program, (node) => {
3122
+ if (node.type !== "JSXAttribute" || node.value?.type !== "Literal" || typeof node.value.value !== "string")
3123
+ return;
3124
+ if (node.name.type === "JSXIdentifier" && node.name.name === "innerHTML")
3125
+ return;
3126
+ node.value.value = decodeHtmlEntities(node.value.value);
3127
+ });
3128
+ }
3129
+ function parseTsx(filename, code) {
3130
+ const lang = /\.[cm]?ts$/i.test(filename) ? "ts" : "tsx";
3131
+ const result = import_oxc_parser7.parseSync(filename, code, { lang, sourceType: "module" });
3132
+ if (result.errors.length > 0) {
3133
+ const first = result.errors[0];
3134
+ const label = first.labels?.[0];
3135
+ const offset = label?.start ?? 0;
3136
+ const loc = formatLoc(filename, code, offset);
3137
+ const frame = formatCodeFrame(code, offset, label?.end);
3138
+ const header = formatDiagnostic(loc, `prunelle compiler: syntax error: ${first.message}`);
3139
+ throw new Error(frame ? `${header}
3140
+ ${frame}` : header);
3141
+ }
3142
+ if (ENTITY_HINT_RE.test(code))
3143
+ decodeAttributeEntities(result.program);
3144
+ return result.program;
3145
+ }
3146
+ function asyncInteractiveError(filename, reason, start) {
3147
+ const err = new PrunelleMistake(`prunelle compiler: async route component in ${filename} cannot use browser interactivity (${reason}). Move interactive state/handlers into a non-async component and render it from the async page.`);
3148
+ err.start = start;
3149
+ return err;
3150
+ }
3151
+ function isAsyncFunction(node) {
3152
+ if (node === null || node === undefined)
3153
+ return false;
3154
+ const inner = unwrapTsExpr(node);
3155
+ return (inner.type === "FunctionDeclaration" || inner.type === "FunctionExpression" || inner.type === "ArrowFunctionExpression") && inner.async === true;
3156
+ }
3157
+ function actionVariable(program, call) {
3158
+ let name;
3159
+ walk(program, (node) => {
3160
+ if (node.type === "VariableDeclarator" && node.init === call && node.id.type === "Identifier")
3161
+ name = node.id.name;
3162
+ return name === undefined ? undefined : false;
3163
+ });
3164
+ return name;
3165
+ }
3166
+ function hydrateMode(value) {
3167
+ return staticStringValue(value?.type === "JSXExpressionContainer" ? value.expression : value) ?? "*";
3168
+ }
3169
+ function isActionCall(node, actionLocalName, serverNamespaces) {
3170
+ if (node.type !== "CallExpression")
3171
+ return false;
3172
+ const name = calleeName(node.callee);
3173
+ return actionLocalName !== undefined && name === actionLocalName || name.endsWith(".action") && serverNamespaces.has(name.slice(0, -".action".length));
3174
+ }
3175
+ function scanImports(program, filename) {
3176
+ const scan = { imports: [], reactiveLocals: new Map, stateCallees: new Set, signalCallees: new Set, effectCallees: new Set, serverOnlyLocals: new Map, prunelleNamespaces: new Set, serverNamespaces: new Set, actionLocalName: undefined, usesRenderContext: false };
3177
+ for (const stmt of program.body) {
3178
+ if (stmt.type === "ExportAllDeclaration" || stmt.type === "ExportNamedDeclaration" && stmt.source !== null)
3179
+ guarded(stmt.source.start, () => assertNoKayImport(stmt.source.value, filename));
3180
+ if (stmt.type !== "ImportDeclaration")
3181
+ continue;
3182
+ guarded(stmt.source.start, () => assertNoKayImport(stmt.source.value, filename));
3183
+ if (stmt.importKind === "type")
3184
+ continue;
3185
+ const source = stmt.source.value;
3186
+ const specifiers = [];
3187
+ for (const spec of stmt.specifiers) {
3188
+ if (spec.type === "ImportSpecifier") {
3189
+ const imported = spec.importKind === "type" ? undefined : exportedName(spec.imported);
3190
+ if (imported === undefined)
3191
+ continue;
3192
+ specifiers.push({ local: spec.local.name, imported });
3193
+ scanPrunelleImport(scan, source, imported, spec.local.name, filename, spec.start);
3194
+ } else if (spec.type === "ImportDefaultSpecifier") {
3195
+ specifiers.push({ local: spec.local.name, imported: "default" });
3196
+ } else {
3197
+ specifiers.push({ local: spec.local.name, imported: "*" });
3198
+ if (PRUNELLE_SOURCES.has(source))
3199
+ scan.prunelleNamespaces.add(spec.local.name);
3200
+ if (PRUNELLE_SERVER_SOURCES.has(source))
3201
+ scan.serverNamespaces.add(spec.local.name);
3202
+ }
3203
+ }
3204
+ scan.imports.push({ source, specifiers, start: stmt.start, end: stmt.end });
3205
+ }
3206
+ return scan;
3207
+ }
3208
+ function scanPrunelleImport(scan, source, imported, local, filename, start) {
3209
+ if (PRUNELLE_SOURCES.has(source)) {
3210
+ if (REACTIVE_IMPORTS.has(imported))
3211
+ scan.reactiveLocals.set(local, `uses ${imported}`);
3212
+ if (imported === "island")
3213
+ guarded(start, () => {
3214
+ throw islandRemoved(filename, start);
3215
+ });
3216
+ if (STATE_PRIMITIVES.has(imported))
3217
+ scan.stateCallees.add(local);
3218
+ if (imported === "signal" || imported === "computed")
3219
+ scan.signalCallees.add(local);
3220
+ if (imported === "effect")
3221
+ scan.effectCallees.add(local);
3222
+ if (SERVER_ONLY_TAGS.has(imported))
3223
+ scan.serverOnlyLocals.set(local, imported);
3224
+ }
3225
+ if (PRUNELLE_SSR_SOURCES.has(source) && RENDER_CONTEXT_IMPORTS.has(imported))
3226
+ scan.usesRenderContext = true;
3227
+ if (PRUNELLE_SERVER_SOURCES.has(source) && imported === "action")
3228
+ scan.actionLocalName = local;
3229
+ }
3230
+ function scanDeclarations(program, filename, imports) {
3231
+ const scan = { 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: [] };
3232
+ const collectInits = (decl) => {
3233
+ for (const d of decl.declarations) {
3234
+ if (d.id.type === "Identifier" && d.init !== null)
3235
+ scan.localInits.set(d.id.name, d.init);
3236
+ }
3237
+ };
3238
+ const addExport = (exported, local) => {
3239
+ scan.exportedNames.push(exported);
3240
+ if (local !== undefined)
3241
+ scan.exportLocals.set(exported, local);
3242
+ if (exported === "load")
3243
+ scan.hasLoadExport = true;
3244
+ if (exported === "paths")
3245
+ scan.hasPaths = true;
3246
+ };
3247
+ for (const stmt of program.body) {
3248
+ if (stmt.type === "VariableDeclaration") {
3249
+ collectInits(stmt);
3250
+ } else if (stmt.type === "FunctionDeclaration") {
3251
+ if (stmt.async === true && stmt.id !== null)
3252
+ scan.asyncLocals.add(stmt.id.name);
3253
+ } else if (stmt.type === "ExportAllDeclaration") {
3254
+ if (stmt.exportKind !== "type")
3255
+ scan.reexports.push({ exported: "*", local: "*", source: stmt.source.value, start: stmt.start });
3256
+ } else if (stmt.type === "ExportDefaultDeclaration") {
3257
+ const decl = unwrapTsExpr(stmt.declaration);
3258
+ const named = decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration" ? decl.id?.name : undefined;
3259
+ addExport("default", decl.type === "Identifier" ? decl.name : named ?? "default");
3260
+ if (isAsyncFunction(decl))
3261
+ scan.hasAsyncDefault = true;
3262
+ else if (decl.type === "Identifier")
3263
+ scan.defaultLocal = decl.name;
3264
+ else
3265
+ scan.localInits.set("default", decl);
3266
+ } else if (stmt.type === "ExportNamedDeclaration" && stmt.exportKind !== "type") {
3267
+ for (const spec of stmt.specifiers) {
3268
+ const exported = spec.exportKind === "type" ? undefined : exportedName(spec.exported);
3269
+ const local = exportedName(spec.local);
3270
+ if (exported === undefined || local === undefined)
3271
+ continue;
3272
+ addExport(exported, stmt.source === null ? local : undefined);
3273
+ if (stmt.source !== null)
3274
+ scan.reexports.push({ exported, local, source: stmt.source.value, start: stmt.start });
3275
+ else if (exported === "default")
3276
+ scan.defaultLocal = local;
3277
+ }
3278
+ if (stmt.declaration !== null)
3279
+ scanExportedDeclaration(scan, stmt.declaration, filename, imports, collectInits, addExport);
3280
+ }
3281
+ }
3282
+ const hydrateLocal = scan.defaultHydrate === undefined ? scan.exportLocals.get("hydrate") : undefined;
3283
+ if (hydrateLocal !== undefined)
3284
+ scan.defaultHydrate = checkExportHydrate(scan.localInits.get(hydrateLocal), filename);
3285
+ return scan;
3286
+ }
3287
+ function scanExportedDeclaration(scan, decl, filename, imports, collectInits, addExport) {
3288
+ if (decl.type === "FunctionDeclaration" && decl.id !== null) {
3289
+ if (decl.async === true)
3290
+ scan.asyncLocals.add(decl.id.name);
3291
+ addExport(decl.id.name, decl.id.name);
3292
+ } else if (decl.type === "ClassDeclaration" && decl.id !== null) {
3293
+ addExport(decl.id.name, decl.id.name);
3294
+ } else if (decl.type === "VariableDeclaration") {
3295
+ collectInits(decl);
3296
+ for (const d of decl.declarations) {
3297
+ if (d.id.type !== "Identifier")
3298
+ continue;
3299
+ const name = d.id.name;
3300
+ addExport(name, name);
3301
+ if (name === "prerender" && d.init?.type === "Literal") {
3302
+ if (d.init.value === true)
3303
+ scan.hasPrerender = true;
3304
+ else if (d.init.value === false)
3305
+ scan.prerenderFalse = true;
3306
+ }
3307
+ if (name === "hydrate" && d.init !== null)
3308
+ scan.defaultHydrate = checkExportHydrate(d.init, filename);
3309
+ if (d.init !== null && isActionCall(d.init, imports.actionLocalName, imports.serverNamespaces)) {
3310
+ scan.exportedActions.push(name);
3311
+ scan.registeredActions.add(d.init);
3312
+ }
3313
+ }
3314
+ }
3315
+ }
3316
+ function bindingUnits(program) {
3317
+ const units = [];
3318
+ const add = (node) => {
3319
+ if (node.type.startsWith("TS"))
3320
+ return;
3321
+ if ((node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && node.id !== null) {
3322
+ units.push({ name: node.id.name, node });
3323
+ } else if (node.type === "VariableDeclaration") {
3324
+ for (const d of node.declarations)
3325
+ units.push({ name: d.id.type === "Identifier" ? d.id.name : "", node: d });
3326
+ } else {
3327
+ units.push({ name: "", node });
3328
+ }
3329
+ };
3330
+ for (const stmt of program.body) {
3331
+ if (stmt.type === "ExportNamedDeclaration") {
3332
+ if (stmt.declaration !== null)
3333
+ add(stmt.declaration);
3334
+ } else if (stmt.type === "ExportDefaultDeclaration") {
3335
+ const decl = unwrapTsExpr(stmt.declaration);
3336
+ if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id !== null)
3337
+ add(decl);
3338
+ else if (decl.type !== "Identifier")
3339
+ units.push({ name: "default", node: decl });
3340
+ } else if (stmt.type !== "ImportDeclaration") {
3341
+ add(stmt);
3342
+ }
3343
+ }
3344
+ return units;
3345
+ }
3346
+ var TS_EXPR_WRAPPERS3 = new Set(["TSAsExpression", "TSNonNullExpression", "TSSatisfiesExpression", "TSTypeAssertion", "TSInstantiationExpression"]);
3347
+ function scanBody(program, filename, code, imports, decls, warnings, loadCode) {
3348
+ const body = { hasJsx: false, usesRenderContext: imports.usesRenderContext, deferredIslandTags: new Set, hydrateModes: new Set, jsxTags: new Set, dynamicImports: [], bindings: [] };
3349
+ const units = bindingUnits(program);
3350
+ const tracked = new Set(units.map((u) => u.name));
3351
+ for (const imp of imports.imports) {
3352
+ for (const spec of imp.specifiers)
3353
+ tracked.add(spec.local);
3354
+ }
3355
+ const checkActions = imports.actionLocalName !== undefined || imports.serverNamespaces.size > 0;
3356
+ const isEffect = (callee) => imports.effectCallees.has(callee) || callee.endsWith(".effect") && imports.prunelleNamespaces.has(callee.slice(0, -".effect".length));
3357
+ const ref = (binding, name, offset) => {
3358
+ if (tracked.has(name) && !binding.refs.has(name))
3359
+ binding.refs.set(name, offset);
3360
+ };
3361
+ const addMember = (binding, name, member) => {
3362
+ if (!tracked.has(name))
3363
+ return;
3364
+ const set = binding.memberRefs.get(name) ?? new Set;
3365
+ set.add(member);
3366
+ binding.memberRefs.set(name, set);
3367
+ };
3368
+ const resolveTag = (tag) => resolvePrunelleTag(tag, imports.imports);
3369
+ for (const unit of units) {
3370
+ const binding = { name: unit.name, start: unit.node.start, end: unit.node.end, fact: undefined, refs: new Map, valueRefs: new Map, memberRefs: new Map, tags: new Set, serverOnlyTag: undefined };
3371
+ body.bindings.push(binding);
3372
+ const freeIds = new Map;
3373
+ const memberObjStarts = new Set;
3374
+ walkScoped(unit.node, {
3375
+ onIdentifier(id) {
3376
+ freeIds.set(id.start, id.name);
3377
+ ref(binding, id.name, id.start);
3378
+ if (tracked.has(id.name) && !binding.valueRefs.has(id.name))
3379
+ binding.valueRefs.set(id.name, id.start);
3380
+ const reason = imports.reactiveLocals.get(id.name);
3381
+ if (reason !== undefined)
3382
+ binding.fact ??= { reason, offset: id.start };
3383
+ }
3384
+ });
3385
+ const isLoadUnit = loadCode.has(unit.node) || unit.node.type === "VariableDeclarator" && unit.node.init !== null && loadCode.has(unit.node.init);
3386
+ walk(unit.node, (node) => {
3387
+ if (node.type.startsWith("TS") && !TS_EXPR_WRAPPERS3.has(node.type))
3388
+ return false;
3389
+ if (isJsxNode(node))
3390
+ body.hasJsx = true;
3391
+ if (node.type === "JSXElement")
3392
+ checkMistakes(node, filename, code, warnings, resolveTag);
3393
+ checkHabits(node, isEffect, filename);
3394
+ if (checkActions && isActionCall(node, imports.actionLocalName, imports.serverNamespaces) && !decls.registeredActions.has(node))
3395
+ guarded(node.start, () => {
3396
+ throw mistake("action() not declared as export const", filename, `write export const ${actionVariable(program, node) ?? "name"} = ${imports.actionLocalName ?? "action"}(...) at the top level, only those get a URL`);
3397
+ });
3398
+ if (node.type === "ImportExpression" && !isLoadUnit) {
3399
+ const src = staticStringValue(node.source);
3400
+ if (src !== undefined)
3401
+ body.dynamicImports.push({ source: src, start: node.start });
3402
+ } else if (node.type === "JSXOpeningElement") {
3403
+ scanOpeningElement(node, binding, body, imports, filename);
3404
+ const root = jsxTagName(node.name).split(".")[0];
3405
+ if (isComponentTag(root))
3406
+ ref(binding, root, node.start);
3407
+ } else if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && freeIds.has(node.object.start) && node.property.type === "Identifier") {
3408
+ memberObjStarts.add(node.object.start);
3409
+ addMember(binding, node.object.name, node.property.name);
3410
+ scanPrunelleMember(node, binding, body, imports, filename);
3411
+ }
3412
+ });
3413
+ for (const [start, name] of freeIds) {
3414
+ if (!memberObjStarts.has(start))
3415
+ addMember(binding, name, "*");
3416
+ }
3417
+ }
3418
+ return body;
3419
+ }
3420
+ function scanOpeningElement(node, binding, body, imports, filename) {
3421
+ const tag = jsxTagName(node.name);
3422
+ const isComponent = isComponentTag(tag);
3423
+ if (isComponent) {
3424
+ body.jsxTags.add(tag);
3425
+ binding.tags.add(tag);
3426
+ binding.serverOnlyTag ??= imports.serverOnlyLocals.get(tag);
3427
+ const [ns, member] = tag.split(".");
3428
+ if (member !== undefined && imports.prunelleNamespaces.has(ns) && RENDER_CONTEXT_IMPORTS.has(member)) {
3429
+ body.usesRenderContext = true;
3430
+ if (SERVER_ONLY_TAGS.has(member))
3431
+ binding.serverOnlyTag ??= member;
3432
+ }
3433
+ }
3434
+ for (const attr of node.attributes) {
3435
+ if (attr.type !== "JSXAttribute" || attr.name.type !== "JSXIdentifier")
3436
+ continue;
3437
+ const attrName = attr.name.name;
3438
+ if (isComponent && attrName === "$hydrate") {
3439
+ const mode = hydrateMode(attr.value);
3440
+ guarded(attr.start, () => checkHydrateMode(mode, `$hydrate="${mode}"`, filename));
3441
+ body.hydrateModes.add(mode);
3442
+ if (mode !== "load")
3443
+ body.deferredIslandTags.add(tag);
3444
+ }
3445
+ if (!isComponent && tag !== "" && (EVENT_ATTR.test(attrName) || attrName === "ref"))
3446
+ binding.fact ??= { reason: `uses ${attrName}`, offset: attr.start };
3447
+ }
3448
+ }
3449
+ function scanPrunelleMember(node, binding, body, imports, filename) {
3450
+ if (node.computed || node.object.type !== "Identifier" || !imports.prunelleNamespaces.has(node.object.name) || node.property.type !== "Identifier")
3451
+ return;
3452
+ const member = node.property.name;
3453
+ const callee = `${node.object.name}.${member}`;
3454
+ if (member === "island")
3455
+ guarded(node.start, () => {
3456
+ throw islandRemoved(filename, node.start);
3457
+ });
3458
+ if (REACTIVE_IMPORTS.has(member))
3459
+ binding.fact ??= { reason: `calls ${callee}`, offset: node.start };
3460
+ if (STATE_PRIMITIVES.has(member))
3461
+ imports.stateCallees.add(callee);
3462
+ if (member === "signal" || member === "computed")
3463
+ imports.signalCallees.add(callee);
3464
+ if (RENDER_CONTEXT_IMPORTS.has(member))
3465
+ body.usesRenderContext = true;
3466
+ }
3467
+ function containsStateInit(init, callees, containers) {
3468
+ if (init === undefined)
3469
+ return false;
3470
+ const inner = unwrapTsExpr(init);
3471
+ if (inner.type === "CallExpression")
3472
+ return callees.has(calleeName(inner.callee));
3473
+ if (!containers)
3474
+ return false;
3475
+ if (inner.type === "ObjectExpression")
3476
+ return inner.properties.some((p) => p.type === "Property" && containsStateInit(p.value, callees, true));
3477
+ return inner.type === "ArrayExpression" && inner.elements.some((el) => el !== null && el.type !== "SpreadElement" && containsStateInit(el, callees, true));
3478
+ }
3479
+ function stateExportsOf(decls, callees, containers) {
3480
+ return [...decls.exportLocals].filter(([, local]) => containsStateInit(decls.localInits.get(local), callees, containers)).map(([exported]) => exported);
3481
+ }
3482
+ function analyzeModule(filename, code, program = parseTsx(filename, code)) {
3483
+ const imports = scanImports(program, filename);
3484
+ const decls = scanDeclarations(program, filename, imports);
3485
+ const warnings = [];
3486
+ const loadNodes = loadDeclarations(program);
3487
+ const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes));
3488
+ checkBareSignals(program, imports.signalCallees, filename);
3489
+ if (body.hasJsx) {
3490
+ checkCompliance(program, filename, code, warnings, (tag) => resolvePrunelleTag(tag, imports.imports));
3491
+ checkBrowserGlobals(program, code, filename, warnings);
3492
+ }
3493
+ for (const [name, init] of decls.localInits) {
3494
+ if (isAsyncFunction(init))
3495
+ decls.asyncLocals.add(name);
3496
+ }
3497
+ const hasAsyncDefault = decls.hasAsyncDefault || decls.defaultLocal !== undefined && decls.asyncLocals.has(decls.defaultLocal);
3498
+ const interactivity = resolveInteractivity(body.bindings, decls.exportLocals);
3499
+ const page = interactivity.exports.get("default");
3500
+ if (hasAsyncDefault && page?.interactive === true)
3501
+ guarded(page.offset ?? 0, () => {
3502
+ throw asyncInteractiveError(filename, page.reason, page.offset);
3503
+ });
3504
+ if (interactivity.serverOnly !== undefined)
3505
+ guarded(interactivity.serverOnly.offset, () => {
3506
+ throw serverOnlyTagError(filename, interactivity.serverOnly);
3507
+ });
3508
+ const cacheExport = parseCacheExport(program);
3509
+ return {
3510
+ filename,
3511
+ program,
3512
+ warnings,
3513
+ ...interactivity,
3514
+ hasAsyncDefault,
3515
+ hasLoadExport: decls.hasLoadExport || loadNodes.length > 0,
3516
+ hasJsx: body.hasJsx,
3517
+ jsxNodes: body.hasJsx ? computeJsxNodes(program) : new WeakSet,
3518
+ hasPrerender: decls.hasPrerender,
3519
+ prerenderFalse: decls.prerenderFalse,
3520
+ ...cacheExport.spec !== undefined ? { cache: cacheExport.spec } : {},
3521
+ hasPaths: decls.hasPaths,
3522
+ usesRenderContext: body.usesRenderContext,
3523
+ defaultHydrate: decls.defaultHydrate,
3524
+ deferredIslandTags: body.deferredIslandTags,
3525
+ hydrateModes: body.hydrateModes,
3526
+ jsxTags: body.jsxTags,
3527
+ asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get("default") ?? "default"]) : decls.asyncLocals,
3528
+ stateExports: stateExportsOf(decls, imports.stateCallees, true),
3529
+ signalExports: stateExportsOf(decls, imports.signalCallees, false),
3530
+ defaultDataKeys: page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined,
3531
+ exportedActions: decls.exportedActions,
3532
+ imports: imports.imports,
3533
+ dynamicImports: body.dynamicImports,
3534
+ reexports: decls.reexports,
3535
+ exportedNames: decls.exportedNames,
3536
+ bindings: body.bindings,
3537
+ exportLocals: decls.exportLocals,
3538
+ nodeEnvReads: findNodeEnvReads(program, code)
3539
+ };
3540
+ }
3541
+
3542
+ // packages/prunelle/src/ts-plugin/fixes.ts
3543
+ var PRUNELLE_CODE = {
3544
+ ERROR: 98001,
3545
+ WARNING: 98002,
3546
+ BARE_SIGNAL: 98101,
3547
+ LOWERCASE_EVENT: 98102,
3548
+ RENAMED_EVENT: 98103,
3549
+ NAMESPACED_EVENT: 98104,
3550
+ CLIENT_DIRECTIVE: 98105,
3551
+ SET_HTML: 98106,
3552
+ STRIP_NAMESPACE: 98107,
3553
+ CAMEL_ARIA: 98108,
3554
+ CAMEL_SVG: 98109,
3555
+ REACT_DEFAULT: 98110,
3556
+ BOOLEAN_FALSE_STRING: 98111,
3557
+ DANGEROUSLY_SET_HTML: 98112,
3558
+ INNER_HTML_OBJECT: 98113,
3559
+ HANDLER_MUTATION: 98114,
3560
+ DIRECTIVE: 98115,
3561
+ NON_BUBBLING_FOCUS: 98116,
3562
+ TEXT_INPUT_ONCHANGE: 98117,
3563
+ KAY_IMPORT: 98118
3564
+ };
3565
+ var PRUNELLE_FIXABLE_CODES = [
3566
+ PRUNELLE_CODE.BARE_SIGNAL,
3567
+ PRUNELLE_CODE.LOWERCASE_EVENT,
3568
+ PRUNELLE_CODE.RENAMED_EVENT,
3569
+ PRUNELLE_CODE.NAMESPACED_EVENT,
3570
+ PRUNELLE_CODE.CLIENT_DIRECTIVE,
3571
+ PRUNELLE_CODE.SET_HTML,
3572
+ PRUNELLE_CODE.STRIP_NAMESPACE,
3573
+ PRUNELLE_CODE.CAMEL_ARIA,
3574
+ PRUNELLE_CODE.CAMEL_SVG,
3575
+ PRUNELLE_CODE.REACT_DEFAULT,
3576
+ PRUNELLE_CODE.BOOLEAN_FALSE_STRING,
3577
+ PRUNELLE_CODE.DANGEROUSLY_SET_HTML,
3578
+ PRUNELLE_CODE.INNER_HTML_OBJECT,
3579
+ PRUNELLE_CODE.HANDLER_MUTATION,
3580
+ PRUNELLE_CODE.DIRECTIVE,
3581
+ PRUNELLE_CODE.NON_BUBBLING_FOCUS,
3582
+ PRUNELLE_CODE.TEXT_INPUT_ONCHANGE,
3583
+ PRUNELLE_CODE.KAY_IMPORT
3584
+ ];
3585
+ var CLIENT_HYDRATE_MAP = {
3586
+ load: "load",
3587
+ visible: "visible",
3588
+ idle: "idle",
3589
+ only: "client"
3590
+ };
3591
+ var WRITE_PROP_RE = /^write ([a-zA-Z0-9_:-]+)=\{\.\.\.\}/;
3592
+ var WRITE_IMPORT_RE = /^write '([^']+)'/;
3593
+ var BUBBLING_FOCUS_RE = /focus does not bubble, write (onFocus(?:In|Out))=\{\.\.\.\}/;
3594
+ function findNode(nodes, type) {
3595
+ for (const node of nodes) {
3596
+ if (node.type === type)
3597
+ return node;
3598
+ }
3599
+ return;
3600
+ }
3601
+ function spanOf(start, end) {
3602
+ return { start, length: Math.max(1, end - start) };
3603
+ }
3604
+ function attrRenameFix(code, attr, fromName, toName, fixName) {
3605
+ const span = spanOf(attr.name.start, attr.name.end);
3606
+ return {
3607
+ code,
3608
+ diagSpan: span,
3609
+ fix: { fixName, description: `Change '${fromName}' to '${toName}'`, span, newText: toName }
3610
+ };
3611
+ }
3612
+ function extractHtmlObjectExpr(value, source) {
3613
+ if (value?.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression")
3614
+ return;
3615
+ const obj = unwrapParens(value.expression);
3616
+ if (obj.type !== "ObjectExpression")
3617
+ return;
3618
+ const prop = obj.properties.find((p) => p.type === "Property" && (p.key.type === "Identifier" && p.key.name === "__html" || p.key.type === "Literal" && p.key.value === "__html"));
3619
+ return prop?.type === "Property" ? source.slice(prop.value.start, prop.value.end) : undefined;
3620
+ }
3621
+ function staticLiteralString(value) {
3622
+ if (value?.type === "Literal" && typeof value.value === "string")
3623
+ return value.value;
3624
+ if (value?.type === "JSXExpressionContainer" && value.expression.type !== "JSXEmptyExpression") {
3625
+ const inner = unwrapTsExpr(value.expression);
3626
+ if (inner.type === "Literal" && typeof inner.value === "string")
3627
+ return inner.value;
3628
+ }
3629
+ return;
3630
+ }
3631
+ function directiveDeleteSpan(code, start, end) {
3632
+ let delStart = start;
3633
+ let lineStart = start;
3634
+ while (lineStart > 0 && code.charCodeAt(lineStart - 1) !== 10 && code.charCodeAt(lineStart - 1) !== 13)
3635
+ lineStart--;
3636
+ if (/^[ \t]*$/.test(code.slice(lineStart, start)))
3637
+ delStart = lineStart;
3638
+ let delEnd = end;
3639
+ while (delEnd < code.length && (code.charCodeAt(delEnd) === 32 || code.charCodeAt(delEnd) === 9))
3640
+ delEnd++;
3641
+ if (code.charCodeAt(delEnd) === 13 && code.charCodeAt(delEnd + 1) === 10)
3642
+ delEnd += 2;
3643
+ else if (code.charCodeAt(delEnd) === 10)
3644
+ delEnd += 1;
3645
+ return { start: delStart, length: delEnd - delStart };
3646
+ }
3647
+ function classifyNamespacedAttrFix(attr, what, fixText) {
3648
+ if (attr.name.type !== "JSXNamespacedName")
3649
+ return;
3650
+ const ns = attr.name.namespace.name;
3651
+ const local = attr.name.name.name;
3652
+ if (ns === "on") {
3653
+ const match = WRITE_PROP_RE.exec(fixText);
3654
+ return match !== null ? attrRenameFix(PRUNELLE_CODE.NAMESPACED_EVENT, attr, what, match[1], "prunelle-namespaced-event") : undefined;
3655
+ }
3656
+ if (ns === "client") {
3657
+ let mode = CLIENT_HYDRATE_MAP[local];
3658
+ if (mode === undefined && local === "media") {
3659
+ const query = staticLiteralString(attr.value);
3660
+ if (query !== undefined && query.trim() !== "")
3661
+ mode = `media(${query})`;
3662
+ }
3663
+ if (mode === undefined)
3664
+ return;
3665
+ const span = spanOf(attr.start, attr.end);
3666
+ const newText = `$hydrate="${mode}"`;
3667
+ return {
3668
+ code: PRUNELLE_CODE.CLIENT_DIRECTIVE,
3669
+ diagSpan: span,
3670
+ fix: { fixName: "prunelle-client-directive", description: `Replace '${what}' with '${newText}'`, span, newText }
3671
+ };
3672
+ }
3673
+ if (what === "set:html")
3674
+ return attrRenameFix(PRUNELLE_CODE.SET_HTML, attr, "set:html", "innerHTML", "prunelle-set-html");
3675
+ if (ns === "prop" || ns === "attr" || ns === "bool")
3676
+ return attrRenameFix(PRUNELLE_CODE.STRIP_NAMESPACE, attr, what, local, "prunelle-strip-namespace");
3677
+ return;
3678
+ }
3679
+ function classifyInnerHtmlFix(attr, what, code) {
3680
+ const isDangerous = what === "dangerouslySetInnerHTML";
3681
+ if (!isDangerous && what !== "innerHTML={{ __html }}")
3682
+ return;
3683
+ const expr = extractHtmlObjectExpr(attr.value, code);
3684
+ if (expr === undefined)
3685
+ return;
3686
+ const span = spanOf(attr.start, attr.end);
3687
+ const newText = `innerHTML={${expr}}`;
3688
+ return {
3689
+ code: isDangerous ? PRUNELLE_CODE.DANGEROUSLY_SET_HTML : PRUNELLE_CODE.INNER_HTML_OBJECT,
3690
+ diagSpan: span,
3691
+ fix: {
3692
+ fixName: isDangerous ? "prunelle-dangerously-set-html" : "prunelle-inner-html-object",
3693
+ description: `Replace with '${newText}'`,
3694
+ span,
3695
+ newText
3696
+ }
3697
+ };
3698
+ }
3699
+ function classifyJsxAttrMistake(attr, what, fixText, code) {
3700
+ if (attr.name.type === "JSXNamespacedName")
3701
+ return classifyNamespacedAttrFix(attr, what, fixText);
3702
+ const attrName = attr.name.name;
3703
+ const htmlFix = classifyInnerHtmlFix(attr, what, code);
3704
+ if (htmlFix !== undefined)
3705
+ return htmlFix;
3706
+ if (fixText.includes("prunelle binds camelCase event props only")) {
3707
+ const match = WRITE_PROP_RE.exec(fixText);
3708
+ return match !== null ? attrRenameFix(PRUNELLE_CODE.LOWERCASE_EVENT, attr, attrName, match[1], "prunelle-lowercase-event") : undefined;
3709
+ }
3710
+ if (fixText.includes("ARIA attributes use kebab-case")) {
3711
+ const match = WRITE_PROP_RE.exec(fixText);
3712
+ return match !== null ? attrRenameFix(PRUNELLE_CODE.CAMEL_ARIA, attr, attrName, match[1], "prunelle-kebab-aria") : undefined;
3713
+ }
3714
+ if (fixText.includes("SVG attributes are case-sensitive") || what === "xlinkHref") {
3715
+ const target = what === "xlinkHref" ? "xlink:href" : WRITE_PROP_RE.exec(fixText)?.[1];
3716
+ return target !== undefined ? attrRenameFix(PRUNELLE_CODE.CAMEL_SVG, attr, attrName, target, "prunelle-kebab-svg") : undefined;
3717
+ }
3718
+ if (what === "defaultValue" || what === "defaultChecked") {
3719
+ const target = what === "defaultValue" ? "value" : "checked";
3720
+ return attrRenameFix(PRUNELLE_CODE.REACT_DEFAULT, attr, attrName, target, "prunelle-react-default");
3721
+ }
3722
+ if (fixText.includes("any string turns it on")) {
3723
+ const span = spanOf(attr.start, attr.end);
3724
+ const newText = `${attrName}={false}`;
3725
+ return {
3726
+ code: PRUNELLE_CODE.BOOLEAN_FALSE_STRING,
3727
+ diagSpan: span,
3728
+ fix: { fixName: "prunelle-boolean-false", description: `Change '${what}' to '${newText}'`, span, newText }
3729
+ };
3730
+ }
3731
+ if (what.includes(" runs ") && what.endsWith(" at render") && attr.value?.type === "JSXExpressionContainer" && attr.value.expression.type !== "JSXEmptyExpression") {
3732
+ const inner = unwrapParens(attr.value.expression);
3733
+ const exprSrc = code.slice(inner.start, inner.end);
3734
+ const newText = `() => ${exprSrc}`;
3735
+ return {
3736
+ code: PRUNELLE_CODE.HANDLER_MUTATION,
3737
+ diagSpan: spanOf(attr.start, attr.end),
3738
+ fix: {
3739
+ fixName: "prunelle-wrap-handler",
3740
+ description: `Wrap handler in '${newText}'`,
3741
+ span: spanOf(attr.value.expression.start, attr.value.expression.end),
3742
+ newText
3743
+ }
3744
+ };
3745
+ }
3746
+ const focusMatch = BUBBLING_FOCUS_RE.exec(fixText);
3747
+ if (focusMatch !== null)
3748
+ return attrRenameFix(PRUNELLE_CODE.NON_BUBBLING_FOCUS, attr, attrName, focusMatch[1], "prunelle-bubbling-focus");
3749
+ if (what === attrName && attrName.startsWith("on")) {
3750
+ const match = WRITE_PROP_RE.exec(fixText);
3751
+ if (match !== null && match[1].startsWith("on"))
3752
+ return attrRenameFix(PRUNELLE_CODE.RENAMED_EVENT, attr, attrName, match[1], "prunelle-renamed-event");
3753
+ }
3754
+ return;
3755
+ }
3756
+ function parseMistakeParts(message, fileName) {
3757
+ const prefix = "prunelle compiler: ";
3758
+ if (!message.startsWith(prefix))
3759
+ return;
3760
+ const marker = ` in ${fileName}: `;
3761
+ const idx = message.indexOf(marker, prefix.length);
3762
+ if (idx === -1)
3763
+ return;
3764
+ const what = message.slice(prefix.length, idx);
3765
+ const rawFix = message.slice(idx + marker.length);
3766
+ const fixText = rawFix.endsWith(".") ? rawFix.slice(0, -1) : rawFix;
3767
+ return { what, fixText };
3768
+ }
3769
+ function classifyMistakeFix(message, fileName, nodesAtStart, code) {
3770
+ const parts = parseMistakeParts(message, fileName);
3771
+ if (parts === undefined)
3772
+ return;
3773
+ const { what, fixText } = parts;
3774
+ if (what.endsWith(" without .value")) {
3775
+ const name = what.slice(0, -" without .value".length);
3776
+ const node = name.includes(".") ? findNode(nodesAtStart, "MemberExpression") : findNode(nodesAtStart, "Identifier");
3777
+ if (node === undefined)
3778
+ return;
3779
+ const span = spanOf(node.start, node.end);
3780
+ const exprText = code.slice(node.start, node.end);
3781
+ return {
3782
+ code: PRUNELLE_CODE.BARE_SIGNAL,
3783
+ diagSpan: span,
3784
+ fix: { fixName: "prunelle-add-signal-value", description: `Add '.value' to '${name}'`, span, newText: `${exprText}.value` }
3785
+ };
3786
+ }
3787
+ if (what === "'use client'" || what === "'use server'") {
3788
+ const stmt = findNode(nodesAtStart, "ExpressionStatement");
3789
+ if (stmt === undefined)
3790
+ return;
3791
+ return {
3792
+ code: PRUNELLE_CODE.DIRECTIVE,
3793
+ diagSpan: spanOf(stmt.start, stmt.end),
3794
+ fix: {
3795
+ fixName: "prunelle-remove-directive",
3796
+ description: `Remove ${what} directive`,
3797
+ span: directiveDeleteSpan(code, stmt.start, stmt.end),
3798
+ newText: ""
3799
+ }
3800
+ };
3801
+ }
3802
+ if (what.startsWith("import from '@kayjs/")) {
3803
+ const lit = findNode(nodesAtStart, "Literal");
3804
+ const match = WRITE_IMPORT_RE.exec(fixText);
3805
+ if (lit === undefined || match === null)
3806
+ return;
3807
+ const quote = code[lit.start] === '"' ? '"' : "'";
3808
+ const replacement = match[1];
3809
+ const span = spanOf(lit.start, lit.end);
3810
+ return {
3811
+ code: PRUNELLE_CODE.KAY_IMPORT,
3812
+ diagSpan: span,
3813
+ fix: {
3814
+ fixName: "prunelle-rewrite-kay-import",
3815
+ description: `Replace import with '${replacement}'`,
3816
+ span,
3817
+ newText: `${quote}${replacement}${quote}`
3818
+ }
3819
+ };
3820
+ }
3821
+ const attr = findNode(nodesAtStart, "JSXAttribute");
3822
+ if (attr !== undefined)
3823
+ return classifyJsxAttrMistake(attr, what, fixText, code);
3824
+ return;
3825
+ }
3826
+ function classifyWarningFix(message, nodesAtStart) {
3827
+ if (message.includes("fires when the field loses focus, not per keystroke; write onInput={...}")) {
3828
+ const attr = findNode(nodesAtStart, "JSXAttribute");
3829
+ if (attr !== undefined)
3830
+ return attrRenameFix(PRUNELLE_CODE.TEXT_INPUT_ONCHANGE, attr, "onChange", "onInput", "prunelle-text-input-oninput");
3831
+ }
3832
+ return;
3833
+ }
3834
+ function toCodeFixAction(fileName, fix) {
3835
+ return {
3836
+ fixName: fix.fixName,
3837
+ description: fix.description,
3838
+ changes: [{
3839
+ fileName,
3840
+ textChanges: [{
3841
+ span: { start: fix.span.start, length: fix.span.length },
3842
+ newText: fix.newText
3843
+ }]
3844
+ }]
3845
+ };
3846
+ }
3847
+
3848
+ // packages/prunelle/src/ts-plugin/diagnostics.ts
3849
+ var PRUNELLE_DIAG_SOURCE = "prunelle";
3850
+ var TS_EXT_RE = /\.[cm]?tsx?$/i;
3851
+ var DTS_EXT_RE = /\.d\.[cm]?ts$/i;
3852
+ var SIGNAL_HINT_RE = /\b(?:signal|computed)\b/;
3853
+ var EMPTY_SET = new Set;
3854
+ var REL_EXTS = ["", ".ts", ".tsx", "/index.ts", "/index.tsx"];
3855
+ var TOKEN_RE = /^[A-Za-z_$][\w$-]*(?::[A-Za-z_$][\w$-]*)?|^'[^'\r\n]*'|^"[^"\r\n]*"|^<[A-Za-z_$][\w$.-]*/;
3856
+ var configCache = new Map;
3857
+ function isCheckableFile(fileName) {
3858
+ return TS_EXT_RE.test(fileName) && !DTS_EXT_RE.test(fileName) && !isInNodeModules(fileName);
3859
+ }
3860
+ function propKeyName2(node) {
3861
+ if (node.type === "Identifier")
3862
+ return node.name;
3863
+ if (node.type === "Literal" && typeof node.value === "string")
3864
+ return node.value;
3865
+ return;
3866
+ }
3867
+ function staticString(node) {
3868
+ const inner = unwrapTsExpr(node);
3869
+ if (inner.type === "Literal" && typeof inner.value === "string")
3870
+ return inner.value;
3871
+ return;
3872
+ }
3873
+ function extractConfigObject(program) {
3874
+ for (const stmt of program.body) {
3875
+ if (stmt.type !== "ExportDefaultDeclaration")
3876
+ continue;
3877
+ const decl = unwrapTsExpr(stmt.declaration);
3878
+ if (decl.type === "ObjectExpression")
3879
+ return decl;
3880
+ if (decl.type === "CallExpression" && decl.arguments[0] !== undefined) {
3881
+ const arg = unwrapTsExpr(decl.arguments[0]);
3882
+ if (arg.type === "ObjectExpression")
3883
+ return arg;
3884
+ }
3885
+ }
3886
+ return;
3887
+ }
3888
+ function parseStaticCompliance(node) {
3889
+ const obj = unwrapTsExpr(node);
3890
+ if (obj.type !== "ObjectExpression")
3891
+ return;
3892
+ const out = {};
3893
+ for (const prop of obj.properties) {
3894
+ if (prop.type !== "Property")
3895
+ continue;
3896
+ const key = propKeyName2(prop.key);
3897
+ const val = unwrapTsExpr(prop.value);
3898
+ if (key === "publicBody" && val.type === "Literal" && typeof val.value === "boolean") {
3899
+ out.publicBody = val.value;
3900
+ } else if (key === "legalNotice" && val.type === "Literal" && (val.value === false || typeof val.value === "string")) {
3901
+ out.legalNotice = val.value;
3902
+ } else if (key === "ignore" && val.type === "ArrayExpression") {
3903
+ const rules = [];
3904
+ for (const el of val.elements) {
3905
+ if (el !== null && el.type !== "SpreadElement") {
3906
+ const s = staticString(el);
3907
+ if (s !== undefined)
3908
+ rules.push(s);
3909
+ }
3910
+ }
3911
+ out.ignore = rules;
3912
+ }
3913
+ }
3914
+ return out;
3915
+ }
3916
+ function readStaticProjectConfig(projectRoot) {
3917
+ if (projectRoot === undefined || projectRoot === "")
3918
+ return {};
3919
+ const cfgPath = import_node_path2.join(projectRoot, "prunelle.config.ts");
3920
+ if (!import_node_fs.existsSync(cfgPath))
3921
+ return {};
3922
+ let mtimeMs;
3923
+ try {
3924
+ mtimeMs = import_node_fs.statSync(cfgPath).mtimeMs;
3925
+ } catch {
3926
+ return {};
3927
+ }
3928
+ const cached = configCache.get(cfgPath);
3929
+ if (cached !== undefined && cached.mtimeMs === mtimeMs)
3930
+ return { site: cached.site, compliance: cached.compliance };
3931
+ let site;
3932
+ let compliance;
3933
+ try {
3934
+ const code = import_node_fs.readFileSync(cfgPath, "utf8");
3935
+ const parsed = import_oxc_parser8.parseSync(cfgPath, code, { lang: "ts", sourceType: "module" });
3936
+ const obj = parsed.errors.length === 0 ? extractConfigObject(parsed.program) : undefined;
3937
+ if (obj !== undefined) {
3938
+ for (const prop of obj.properties) {
3939
+ if (prop.type !== "Property")
3940
+ continue;
3941
+ const key = propKeyName2(prop.key);
3942
+ if (key === "site")
3943
+ site = staticString(prop.value);
3944
+ else if (key === "compliance")
3945
+ compliance = parseStaticCompliance(prop.value);
3946
+ }
3947
+ }
3948
+ } catch {
3949
+ return {};
3950
+ }
3951
+ configCache.set(cfgPath, { mtimeMs, site, compliance });
3952
+ return { site, compliance };
3953
+ }
3954
+ function indexNodesAtOffsets(program, offsets) {
3955
+ const byOffset = new Map;
3956
+ if (offsets.size === 0)
3957
+ return byOffset;
3958
+ walk(program, (node) => {
3959
+ if (!offsets.has(node.start))
3960
+ return;
3961
+ let list = byOffset.get(node.start);
3962
+ if (list === undefined) {
3963
+ list = [];
3964
+ byOffset.set(node.start, list);
3965
+ }
3966
+ list.push(node);
3967
+ });
3968
+ return byOffset;
3969
+ }
3970
+ function clampSingleLine(code, start, end) {
3971
+ const safeStart = Math.max(0, Math.min(start, code.length));
3972
+ const safeEnd = Math.max(safeStart, Math.min(end, code.length));
3973
+ const nl = code.indexOf(`
3974
+ `, safeStart);
3975
+ const effectiveEnd = nl !== -1 && nl < safeEnd ? nl : safeEnd;
3976
+ return { start: safeStart, length: Math.max(1, effectiveEnd - safeStart) };
3977
+ }
3978
+ function spanFromNodes(nodes, code, start) {
3979
+ for (const node of nodes) {
3980
+ if (node.type === "JSXAttribute")
3981
+ return clampSingleLine(code, node.start, node.end);
3982
+ if (node.type === "JSXElement") {
3983
+ const opening = node.openingElement;
3984
+ const hasNewline = code.slice(opening.start, opening.end).includes(`
3985
+ `);
3986
+ return clampSingleLine(code, opening.start, hasNewline ? opening.name.end : opening.end);
3987
+ }
3988
+ if (node.type === "JSXOpeningElement") {
3989
+ const hasNewline = code.slice(node.start, node.end).includes(`
3990
+ `);
3991
+ return clampSingleLine(code, node.start, hasNewline ? node.name.end : node.end);
3992
+ }
3993
+ if (node.type === "ImportSpecifier" || node.type === "ExpressionStatement" || node.type === "Literal" || node.type === "MemberExpression" || node.type === "Identifier" || node.type === "CallExpression" || node.type === "VariableDeclarator")
3994
+ return clampSingleLine(code, node.start, node.end);
3995
+ if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression")
3996
+ return clampSingleLine(code, node.start, node.end);
3997
+ }
3998
+ const safeStart = Math.max(0, Math.min(start, Math.max(0, code.length - 1)));
3999
+ const match = TOKEN_RE.exec(code.slice(safeStart));
4000
+ const length = match !== null ? match[0].length : Math.min(1, Math.max(0, code.length - safeStart));
4001
+ return { start: safeStart, length: Math.max(1, length) };
4002
+ }
4003
+ function normalizeDisplayPath(fileName, projectRoot) {
4004
+ if (projectRoot === undefined || projectRoot === "")
4005
+ return fileName;
4006
+ const rel = relPosix(projectRoot, fileName);
4007
+ return rel !== "" ? rel : fileName;
4008
+ }
4009
+ function mergeCompliance(base, override) {
4010
+ if (base === undefined)
4011
+ return override;
4012
+ if (override === undefined)
4013
+ return base;
4014
+ return {
4015
+ ignore: override.ignore ?? base.ignore,
4016
+ publicBody: override.publicBody ?? base.publicBody,
4017
+ legalNotice: override.legalNotice ?? base.legalNotice
4018
+ };
4019
+ }
4020
+ function resolveRelativeSource(fromFile, specifier, readFile) {
4021
+ const base = import_node_path2.resolve(import_node_path2.dirname(fromFile), specifier);
4022
+ const stripped = base.replace(/\.[cm]?js$/i, "");
4023
+ for (const ext of REL_EXTS) {
4024
+ const candidate = `${stripped}${ext}`;
4025
+ if (!TS_EXT_RE.test(candidate))
4026
+ continue;
4027
+ const code = readFile(candidate);
4028
+ if (code !== undefined)
4029
+ return { path: candidate, code };
4030
+ }
4031
+ return;
4032
+ }
4033
+ function collectImportedSignalMistakes(fileName, program, imports, readFile) {
4034
+ if (readFile === undefined)
4035
+ return [];
4036
+ const importedSignals = new Set;
4037
+ const importedSignalMembers = new Map;
4038
+ for (const imp of imports) {
4039
+ if (!imp.source.startsWith("./") && !imp.source.startsWith("../"))
4040
+ continue;
4041
+ const resolved = resolveRelativeSource(fileName, imp.source, readFile);
4042
+ if (resolved === undefined || !SIGNAL_HINT_RE.test(resolved.code))
4043
+ continue;
4044
+ let depProgram;
4045
+ try {
4046
+ depProgram = parseTsx(resolved.path, resolved.code);
4047
+ } catch {
4048
+ continue;
4049
+ }
4050
+ const { value: dep } = collectMistakes(() => analyzeModule(resolved.path, resolved.code, depProgram));
4051
+ if (dep === undefined || dep.signalExports.length === 0)
4052
+ continue;
4053
+ const exported = new Set(dep.signalExports);
4054
+ for (const spec of imp.specifiers) {
4055
+ if (spec.imported === "*") {
4056
+ importedSignalMembers.set(spec.local, exported);
4057
+ } else if (exported.has(spec.imported)) {
4058
+ importedSignals.add(spec.local);
4059
+ }
4060
+ }
4061
+ }
4062
+ if (importedSignals.size === 0 && importedSignalMembers.size === 0)
4063
+ return [];
4064
+ return collectMistakes(() => checkBareSignals(program, EMPTY_SET, fileName, importedSignals, importedSignalMembers)).mistakes;
4065
+ }
4066
+ function collectPrunelleDiagnostics(fileName, code, options = {}) {
4067
+ if (!isCheckableFile(fileName))
4068
+ return [];
4069
+ let program;
4070
+ try {
4071
+ program = parseTsx(fileName, code);
4072
+ } catch {
4073
+ return [];
4074
+ }
4075
+ const { value, mistakes, error } = collectMistakes(() => analyzeModule(fileName, code, program));
4076
+ const allMistakes = [...mistakes];
4077
+ if (error instanceof PrunelleMistake)
4078
+ allMistakes.push(error);
4079
+ if (value !== undefined)
4080
+ allMistakes.push(...collectImportedSignalMistakes(fileName, program, value.imports, options.readFile));
4081
+ const staticCfg = options.compliance !== undefined && options.site !== undefined ? {} : readStaticProjectConfig(options.projectRoot);
4082
+ const compliance = mergeCompliance(staticCfg.compliance, options.compliance);
4083
+ const site = options.site ?? staticCfg.site;
4084
+ const activeWarnings = (value?.warnings ?? []).filter((w) => shouldEmitWarning(w, compliance, site));
4085
+ if (allMistakes.length === 0 && activeWarnings.length === 0)
4086
+ return [];
4087
+ const offsets = new Set;
4088
+ for (const m of allMistakes)
4089
+ offsets.add(m.start ?? 0);
4090
+ for (const w of activeWarnings)
4091
+ offsets.add(w.start);
4092
+ const nodesByOffset = indexNodesAtOffsets(program, offsets);
4093
+ const displayFile = normalizeDisplayPath(fileName, options.projectRoot);
4094
+ const items = [];
4095
+ for (const m of allMistakes) {
4096
+ const start = m.start ?? 0;
4097
+ const nodes = nodesByOffset.get(start) ?? [];
4098
+ const classified = classifyMistakeFix(m.message, fileName, nodes, code);
4099
+ const span = classified?.diagSpan ?? spanFromNodes(nodes, code, start);
4100
+ items.push({
4101
+ code: classified?.code ?? PRUNELLE_CODE.ERROR,
4102
+ category: "error",
4103
+ start: span.start,
4104
+ length: span.length,
4105
+ message: m.message.replaceAll(fileName, displayFile),
4106
+ ...classified !== undefined ? { fix: classified.fix } : {}
4107
+ });
4108
+ }
4109
+ for (const w of activeWarnings) {
4110
+ const nodes = nodesByOffset.get(w.start) ?? [];
4111
+ const classified = classifyWarningFix(w.message, nodes);
4112
+ const span = classified?.diagSpan ?? spanFromNodes(nodes, code, w.start);
4113
+ items.push({
4114
+ code: classified?.code ?? PRUNELLE_CODE.WARNING,
4115
+ category: "warning",
4116
+ start: span.start,
4117
+ length: span.length,
4118
+ message: w.message.replaceAll(fileName, displayFile),
4119
+ ...classified !== undefined ? { fix: classified.fix } : {}
4120
+ });
4121
+ }
4122
+ return items;
4123
+ }
4124
+ function toTsDiagnostic(tsLib, item, sourceFile) {
4125
+ return {
4126
+ file: sourceFile,
4127
+ start: item.start,
4128
+ length: item.length,
4129
+ messageText: item.message,
4130
+ category: item.category === "warning" ? tsLib.DiagnosticCategory.Warning : tsLib.DiagnosticCategory.Error,
4131
+ code: item.code,
4132
+ source: PRUNELLE_DIAG_SOURCE
4133
+ };
4134
+ }
4135
+
4136
+ // packages/prunelle/src/ts-plugin/index.ts
4137
+ var MAX_CACHE_ENTRIES = 200;
4138
+ function readPluginConfig(raw) {
4139
+ if (raw === null || typeof raw !== "object")
4140
+ return {};
4141
+ const rec = raw;
4142
+ const site = typeof rec.site === "string" ? rec.site : undefined;
4143
+ const compliance = rec.compliance !== null && typeof rec.compliance === "object" ? rec.compliance : undefined;
4144
+ return { site, compliance };
4145
+ }
4146
+ function registerSupportedCodeFixes(tsLib) {
4147
+ if (typeof tsLib.getSupportedCodeFixes !== "function")
4148
+ return;
4149
+ try {
4150
+ const supported = tsLib.getSupportedCodeFixes();
4151
+ if (!Array.isArray(supported) || Object.isFrozen(supported))
4152
+ return;
4153
+ const existing = new Set(supported);
4154
+ for (const code of PRUNELLE_FIXABLE_CODES) {
4155
+ const str = String(code);
4156
+ if (!existing.has(str))
4157
+ supported.push(str);
4158
+ }
4159
+ } catch {
4160
+ return;
4161
+ }
4162
+ }
4163
+ function readFileSource(prior, host, fileName) {
4164
+ const sourceFile = prior.getProgram()?.getSourceFile(fileName);
4165
+ if (sourceFile !== undefined)
4166
+ return { sourceFile, text: sourceFile.text };
4167
+ const snapshot = host.getScriptSnapshot(fileName);
4168
+ if (snapshot !== undefined)
4169
+ return { sourceFile: undefined, text: snapshot.getText(0, snapshot.getLength()) };
4170
+ return { sourceFile: undefined, text: undefined };
4171
+ }
4172
+ function getPrunelleDiagnostics(tsLib, fileName, code, options = {}, sourceFile) {
4173
+ return collectPrunelleDiagnostics(fileName, code, options).map((item) => toTsDiagnostic(tsLib, item, sourceFile));
4174
+ }
4175
+ function getPrunelleCodeFixes(fileName, code, start, end, errorCodes, options = {}) {
4176
+ const items = collectPrunelleDiagnostics(fileName, code, options);
4177
+ return selectCodeFixes(fileName, items, start, end, errorCodes);
4178
+ }
4179
+ function selectCodeFixes(fileName, items, start, end, errorCodes) {
4180
+ const out = [];
4181
+ for (const item of items) {
4182
+ if (item.fix === undefined)
4183
+ continue;
4184
+ if (errorCodes.length > 0 && !errorCodes.includes(item.code))
4185
+ continue;
4186
+ const itemEnd = item.start + item.length;
4187
+ if (item.start <= end && start <= itemEnd)
4188
+ out.push(toCodeFixAction(fileName, item.fix));
4189
+ }
4190
+ return out;
4191
+ }
4192
+ function createPrunellePlugin(tsLib, info) {
4193
+ const prior = info.languageService;
4194
+ const log = (msg) => {
4195
+ info.project?.projectService?.logger?.info(`[prunelle/ts-plugin] ${msg}`);
4196
+ };
4197
+ registerSupportedCodeFixes(tsLib);
4198
+ const cache = new Map;
4199
+ const pluginCfg = readPluginConfig(info.config);
4200
+ const readFile = (path) => readFileSource(prior, info.languageServiceHost, path).text;
4201
+ const getOptions = () => ({
4202
+ projectRoot: typeof info.project?.getCurrentDirectory === "function" ? info.project.getCurrentDirectory() : undefined,
4203
+ compliance: pluginCfg.compliance,
4204
+ site: pluginCfg.site,
4205
+ readFile
4206
+ });
4207
+ const getItems = (fileName) => {
4208
+ if (!isCheckableFile(fileName))
4209
+ return { sourceFile: undefined, items: [] };
4210
+ const { sourceFile, text } = readFileSource(prior, info.languageServiceHost, fileName);
4211
+ if (text === undefined)
4212
+ return { sourceFile, items: [] };
4213
+ const projectVersion = typeof info.languageServiceHost.getProjectVersion === "function" ? info.languageServiceHost.getProjectVersion() : "";
4214
+ const cached = cache.get(fileName);
4215
+ if (cached !== undefined && cached.text === text && cached.projectVersion === projectVersion)
4216
+ return { sourceFile, items: cached.items };
4217
+ try {
4218
+ const items = collectPrunelleDiagnostics(fileName, text, getOptions());
4219
+ if (cache.size >= MAX_CACHE_ENTRIES) {
4220
+ const oldest = cache.keys().next().value;
4221
+ if (oldest !== undefined)
4222
+ cache.delete(oldest);
4223
+ }
4224
+ cache.set(fileName, { text, projectVersion, items });
4225
+ return { sourceFile, items };
4226
+ } catch (err) {
4227
+ log(`analysis failed for ${fileName}: ${err instanceof Error ? err.message : String(err)}`);
4228
+ return { sourceFile, items: [] };
4229
+ }
4230
+ };
4231
+ const proxy = Object.create(null);
4232
+ for (const key of Object.keys(prior)) {
4233
+ const member = prior[key];
4234
+ if (typeof member === "function") {
4235
+ proxy[key] = (...args) => member.apply(prior, args);
4236
+ }
4237
+ }
4238
+ proxy.getSemanticDiagnostics = (fileName) => {
4239
+ const base = prior.getSemanticDiagnostics(fileName);
4240
+ const { sourceFile, items } = getItems(fileName);
4241
+ if (items.length === 0)
4242
+ return base;
4243
+ return [...base, ...items.map((item) => toTsDiagnostic(tsLib, item, sourceFile))];
4244
+ };
4245
+ proxy.getCodeFixesAtPosition = (fileName, start, end, errorCodes, formatOptions, preferences) => {
4246
+ const base = prior.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
4247
+ const { items } = getItems(fileName);
4248
+ if (items.length === 0)
4249
+ return base;
4250
+ const prunelleFixes = selectCodeFixes(fileName, items, start, end, errorCodes);
4251
+ return prunelleFixes.length === 0 ? base : [...base, ...prunelleFixes];
4252
+ };
4253
+ return proxy;
4254
+ }
4255
+ function init(modules) {
4256
+ const tsLib = modules.typescript;
4257
+ return {
4258
+ create(info) {
4259
+ return createPrunellePlugin(tsLib, info);
4260
+ }
4261
+ };
4262
+ }
4263
+ var ts_plugin_default = init;
4264
+
4265
+
4266
+ ;(function () {
4267
+ const exported = module.exports;
4268
+ if (exported && typeof exported.default === 'function') {
4269
+ const factory = exported.default;
4270
+ for (const key of Object.keys(exported)) {
4271
+ if (key !== 'default' && !(key in factory))
4272
+ factory[key] = exported[key];
4273
+ }
4274
+ factory.default = factory;
4275
+ module.exports = factory;
4276
+ }
4277
+ })();