@murky-web/oxlint-plugin-solid 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +163 -18
  2. package/THIRD_PARTY_NOTICES.md +7 -4
  3. package/package.json +5 -2
  4. package/src/compat.mjs +3 -0
  5. package/src/index.mjs +26 -3
  6. package/src/rules/components_return_once.mjs +136 -89
  7. package/src/rules/event_handlers.mjs +55 -35
  8. package/src/rules/filename_matches_export.mjs +292 -0
  9. package/src/rules/function_size.mjs +189 -0
  10. package/src/rules/imports.mjs +24 -21
  11. package/src/rules/init_declarations.mjs +139 -0
  12. package/src/rules/jsx_no_duplicate_props.mjs +46 -18
  13. package/src/rules/jsx_no_script_url.mjs +7 -6
  14. package/src/rules/jsx_no_undef.mjs +35 -38
  15. package/src/rules/jsx_uses_vars.mjs +4 -4
  16. package/src/rules/no_array_handlers.mjs +38 -9
  17. package/src/rules/no_cleanup_in_effect_apply.mjs +154 -0
  18. package/src/rules/no_destructure.mjs +105 -35
  19. package/src/rules/no_innerhtml.mjs +64 -31
  20. package/src/rules/no_module_scope_reactive_primitive.mjs +73 -0
  21. package/src/rules/no_owned_primitives_in_ref.mjs +30 -9
  22. package/src/rules/no_proxy_apis.mjs +44 -15
  23. package/src/rules/no_react_deps.mjs +397 -41
  24. package/src/rules/no_react_specific_props.mjs +40 -11
  25. package/src/rules/no_server_import_in_client.mjs +9 -9
  26. package/src/rules/no_setter_in_effect.mjs +153 -30
  27. package/src/rules/no_single_arg_create_effect.mjs +55 -0
  28. package/src/rules/no_unassigned_vars.mjs +99 -0
  29. package/src/rules/no_unknown_namespaces.mjs +108 -29
  30. package/src/rules/no_untracked_effect_read.mjs +69 -32
  31. package/src/rules/no_write_in_pure_computation.mjs +273 -0
  32. package/src/rules/prefer_arrow_components.mjs +47 -21
  33. package/src/rules/prefer_class_object.mjs +52 -20
  34. package/src/rules/prefer_destructuring.mjs +164 -0
  35. package/src/rules/prefer_for.mjs +42 -12
  36. package/src/rules/prefer_ref_shorthand.mjs +142 -0
  37. package/src/rules/prefer_show.mjs +55 -24
  38. package/src/rules/reactive_async.mjs +64 -17
  39. package/src/rules/reactivity.mjs +1218 -350
  40. package/src/rules/self_closing_comp.mjs +23 -18
  41. package/src/rules/strict_void_return.mjs +50 -20
  42. package/src/rules/style_prop.mjs +53 -25
  43. package/src/rules/typed_merge_defaults.mjs +88 -0
  44. package/src/rules/validate_jsx_nesting.mjs +16 -16
  45. package/src/utils.mjs +65 -34
@@ -0,0 +1,154 @@
1
+ // `onCleanup` registers on the current owner. An effect function runs
2
+ // imperatively with no owner (NO_OWNER_CLEANUP: the cleanup never runs), and
3
+ // `onSettled` and `createTrackedEffect` callbacks forbid it
4
+ // (CLEANUP_IN_FORBIDDEN_SCOPE). All of them take a returned cleanup instead.
5
+ // Ref callbacks also throw CLEANUP_IN_FORBIDDEN_SCOPE; no-owned-primitives-in-ref
6
+ // reports those.
7
+ import { getSourceCode } from "../compat.mjs";
8
+ import { isFunctionNode, trackImports, walkOwnBody } from "../utils.mjs";
9
+
10
+ const EFFECTS = ["createEffect", "createRenderEffect"];
11
+ const FORBIDDEN = ["onSettled", "createTrackedEffect"];
12
+ const BUNDLE_KEYS = new Set(["effect", "error"]);
13
+
14
+ /** The call `fn` is passed to, and whether `fn` arrives as a bundle member. */
15
+ function callOf(fn) {
16
+ const { parent } = fn;
17
+ if (parent?.type === "CallExpression") {
18
+ return { call: parent, index: parent.arguments.indexOf(fn) };
19
+ }
20
+
21
+ // `createEffect(compute, { effect: (v) => …, error: (e) => … })`
22
+ if (
23
+ parent?.type === "Property" &&
24
+ parent.value === fn &&
25
+ !parent.computed &&
26
+ BUNDLE_KEYS.has(parent.key.name ?? parent.key.value) &&
27
+ parent.parent.parent?.type === "CallExpression"
28
+ ) {
29
+ const call = parent.parent.parent;
30
+
31
+ return {
32
+ bundle: true,
33
+ call,
34
+ index: call.arguments.indexOf(parent.parent)
35
+ };
36
+ }
37
+
38
+ return null;
39
+ }
40
+
41
+ /** True when `fn` itself returns something (nested functions aside). */
42
+ function hasReturn(fn) {
43
+ if (fn.body.type !== "BlockStatement") {
44
+ return true;
45
+ }
46
+ let found = false;
47
+ walkOwnBody(fn.body, (node) => {
48
+ found ||= node.type === "ReturnStatement";
49
+ });
50
+
51
+ return found;
52
+ }
53
+
54
+ export default {
55
+ meta: {
56
+ type: "problem",
57
+ docs: {
58
+ description:
59
+ "Disallow `onCleanup` in an effect function, an `onSettled` callback or a `createTrackedEffect` callback; return the cleanup instead.",
60
+ url: "https://github.com/MurkyTheMurloc/web_dev_tools/blob/main/docs/solid-2-effects.md"
61
+ },
62
+ hasSuggestions: true,
63
+ schema: [],
64
+ messages: {
65
+ cleanupInEffectFn:
66
+ "`{{name}}` is called in the effect function of `{{api}}`, which runs without an owner, so the cleanup never runs and whatever it releases leaks (Solid warns NO_OWNER_CLEANUP in dev). Fix: return the cleanup from the effect function, `return {{cleanup}};`; it runs before the next run and on disposal. Do not: move `{{name}}` into the compute function (a compute function only reads), wrap it in `runWithOwner`, or disable the rule.",
67
+ cleanupInForbiddenScope:
68
+ "`{{name}}` is called in the `{{api}}` callback, where Solid 2.0 forbids it and throws CLEANUP_IN_FORBIDDEN_SCOPE in dev. Fix: return the cleanup from the callback, `return {{cleanup}};`; it runs when the owner is disposed. Do not: wrap `{{name}}` in `runWithOwner` or a nested function, or disable the rule.",
69
+ returnCleanup: "Return the cleanup instead."
70
+ }
71
+ },
72
+ defaultOptions: [],
73
+ create(context) {
74
+ const { matchImport, handleImportDeclaration } = trackImports();
75
+ const sourceCode = getSourceCode(context);
76
+
77
+ return {
78
+ ImportDeclaration: handleImportDeclaration,
79
+ CallExpression(node) {
80
+ if (
81
+ node.callee.type !== "Identifier" ||
82
+ !matchImport("onCleanup", node.callee.name)
83
+ ) {
84
+ return;
85
+ }
86
+
87
+ let fn = node.parent;
88
+ while (fn && !isFunctionNode(fn)) {
89
+ fn = fn.parent;
90
+ }
91
+ const target = fn && callOf(fn);
92
+ if (
93
+ target?.call.callee.type !== "Identifier" ||
94
+ target.call.arguments.some(
95
+ (arg) => arg.type === "SpreadElement"
96
+ )
97
+ ) {
98
+ return;
99
+ }
100
+
101
+ const api = target.call.callee.name;
102
+ const isEffectFn =
103
+ matchImport(EFFECTS, api) && target.index === 1;
104
+ const isForbidden =
105
+ matchImport(FORBIDDEN, api) &&
106
+ target.index === 0 &&
107
+ !target.bundle;
108
+ if (!isEffectFn && !isForbidden) {
109
+ return;
110
+ }
111
+
112
+ const [argument] = node.arguments;
113
+ const cleanup = argument
114
+ ? sourceCode.getText(argument)
115
+ : "() => …";
116
+ const statement = node.parent;
117
+ // `onCleanup(fn)` as the last statement of a callback that
118
+ // returns nothing else becomes `return fn`.
119
+ const canFix =
120
+ argument &&
121
+ statement.type === "ExpressionStatement" &&
122
+ statement.parent === fn.body &&
123
+ fn.body.body.at(-1) === statement &&
124
+ !hasReturn(fn);
125
+
126
+ context.report({
127
+ data: {
128
+ api,
129
+ cleanup: cleanup.includes("\n")
130
+ ? "() => { … }"
131
+ : cleanup,
132
+ name: node.callee.name
133
+ },
134
+ messageId: isEffectFn
135
+ ? "cleanupInEffectFn"
136
+ : "cleanupInForbiddenScope",
137
+ node,
138
+ suggest: canFix
139
+ ? [
140
+ {
141
+ messageId: "returnCleanup",
142
+ fix: (fixer) =>
143
+ fixer.replaceText(
144
+ statement,
145
+ `return ${cleanup};`
146
+ )
147
+ }
148
+ ]
149
+ : []
150
+ });
151
+ }
152
+ };
153
+ }
154
+ };
@@ -77,8 +77,7 @@ const isGeneratedCall = (call, callee) => {
77
77
  others.every(
78
78
  (key) =>
79
79
  key.type === "Literal" &&
80
- (typeof key.value === "string" ||
81
- typeof key.value === "number"),
80
+ (typeof key.value === "string" || typeof key.value === "number")
82
81
  )
83
82
  );
84
83
  };
@@ -105,29 +104,92 @@ const getPropertyInfo = (prop) => {
105
104
  init:
106
105
  prop.value.type === "AssignmentPattern"
107
106
  ? prop.value.right
108
- : undefined,
107
+ : undefined
109
108
  };
110
109
  } else {
111
110
  return null;
112
111
  }
113
112
  };
113
+ const MAX_LISTED_READS = 4;
114
+ const MAX_SETUP_LENGTH = 160;
115
+ // The parts of the noDestructure message that name the code: the pattern as
116
+ // written, the parameter to take instead, the `props.x` reads, and the setup
117
+ // line for defaults and a rest. A fixable plan carries the exact line its fix
118
+ // inserts. Without a fix (a default that reads another prop, a computed key)
119
+ // the line cannot be written for the code, so the message names the helpers.
120
+ const describeDestructure = (sourceCode, plan) => {
121
+ const { props } = plan;
122
+ const end = props.typeAnnotation?.range[0] ?? props.range[1];
123
+ const written = sourceCode.text.slice(props.range[0], end).trim();
124
+ const properties = props.properties.filter(
125
+ (property) => property.type === "Property"
126
+ );
127
+ const rest = props.properties.find(
128
+ (property) => property.type === "RestElement"
129
+ );
130
+ const hasDefaults = properties.some(
131
+ (property) => property.value.type === "AssignmentPattern"
132
+ );
133
+ const propsName = plan.propsName ?? "props";
134
+ const param = plan.origProps ?? (hasDefaults ? "_props" : propsName);
135
+ const access = (property) =>
136
+ property.key.type === "Identifier" && !property.computed
137
+ ? `\`${propsName}.${property.key.name}\``
138
+ : `\`${propsName}[${sourceCode.getText(property.key)}]\``;
139
+ const listed = properties.slice(0, MAX_LISTED_READS).map(access);
140
+ if (properties.length > MAX_LISTED_READS) {
141
+ listed.push("…");
142
+ }
143
+ let reads = listed.join(", ");
144
+ if (listed.length === 0) {
145
+ // `({ ...rest })` is the whole props object under another name.
146
+ reads =
147
+ rest?.argument.type === "Identifier"
148
+ ? `\`${propsName}\` in place of \`${rest.argument.name}\``
149
+ : `\`${propsName}.<name>\``;
150
+ }
151
+ const setup = plan.fixable
152
+ ? (plan.lineToInsert ?? "")
153
+ .split("\n")
154
+ .map((line) => line.trim())
155
+ .filter(Boolean)
156
+ .join(" ")
157
+ : "";
158
+ const helpers = [
159
+ hasDefaults && `\`merge({ … }, ${param})\` for the defaults`,
160
+ rest && listed.length > 0 && `\`omit(${propsName}, …)\` for the rest`
161
+ ].filter(Boolean);
162
+ let setupText = "";
163
+ if (setup !== "" && setup.length <= MAX_SETUP_LENGTH && listed.length > 0) {
164
+ setupText = `, after \`${setup}\` as the first line of the body`;
165
+ } else if (helpers.length > 0) {
166
+ setupText = `, with ${helpers.join(" and ")}`;
167
+ }
168
+ return {
169
+ param,
170
+ pattern: written.includes("\n") ? "{ … }" : written,
171
+ reads,
172
+ setup: setupText
173
+ };
174
+ };
175
+
114
176
  export default {
115
177
  meta: {
116
178
  type: "problem",
117
179
  docs: {
118
180
  description:
119
181
  "Disallow destructuring props. In Solid, props must be used with property accesses (`props.foo`) to preserve reactivity. This rule only tracks destructuring in the parameter list.",
120
- url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/no-destructure.md",
182
+ url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/no-destructure.md"
121
183
  },
122
184
  fixable: "code",
123
185
  schema: [],
124
186
  messages: {
125
187
  noDestructure:
126
- "Destructuring component props breaks Solid's reactivity; use property access instead.",
188
+ "Destructuring `{{pattern}}` in the parameter list reads each prop once, so later changes from the parent never reach this component. Fix: take `{{param}}` as the parameter and read {{reads}} where each value is used{{setup}}. Do not: copy the props into locals in the body; that reads them once too.",
127
189
  missingImport:
128
- "`{{name}}` is used without an import from solid-js.",
190
+ '`{{name}}` is called but not imported, so the call throws a ReferenceError. Fix: `import { {{specifier}} } from "solid-js";`.'
129
191
  // noWriteToProps: "Component props are readonly, writing to props is not supported.",
130
- },
192
+ }
131
193
  },
132
194
  defaultOptions: [],
133
195
  create(context) {
@@ -201,7 +263,7 @@ export default {
201
263
  (def) =>
202
264
  def.name?.range !== undefined &&
203
265
  def.name.range[0] >= props.range[0] &&
204
- def.name.range[1] <= props.range[1],
266
+ def.name.range[1] <= props.range[1]
205
267
  );
206
268
  if (fixable && callScope) {
207
269
  fixable = propertyInfo.every((info) => {
@@ -216,7 +278,7 @@ export default {
216
278
  if (isInPattern) {
217
279
  // The binding itself, nothing else.
218
280
  return variable.defs.some(
219
- (def) => def.name === reference.identifier,
281
+ (def) => def.name === reference.identifier
220
282
  );
221
283
  }
222
284
  return reference.isReadOnly();
@@ -251,13 +313,13 @@ export default {
251
313
  lookupVariable(callScope, name, removedByFix) !== null ||
252
314
  rewrittenScopes.some(
253
315
  (scope) =>
254
- lookupVariable(scope, name, removedByFix) !== null,
316
+ lookupVariable(scope, name, removedByFix) !== null
255
317
  ) ||
256
318
  (scopeManager?.globalScope?.through ?? []).some(
257
319
  ({ identifier }) =>
258
320
  identifier.name === name &&
259
321
  identifier.range[0] >= func.range[0] &&
260
- identifier.range[1] <= func.range[1],
322
+ identifier.range[1] <= func.range[1]
261
323
  );
262
324
  const hasDefaults = propertyInfo.some((info) => info.init);
263
325
  let propsName = "props";
@@ -277,7 +339,7 @@ export default {
277
339
  .filter((info) => info.init)
278
340
  .map(
279
341
  (info) =>
280
- `${info.computed ? "[" : ""}${sourceCode.getText(info.real)}${info.computed ? "]" : ""}: ${sourceCode.getText(info.init)}`,
342
+ `${info.computed ? "[" : ""}${sourceCode.getText(info.real)}${info.computed ? "]" : ""}: ${sourceCode.getText(info.init)}`
281
343
  )
282
344
  .join(", ");
283
345
  // `omit(props, "a", "b")` takes the keys as varargs, where Solid
@@ -287,7 +349,7 @@ export default {
287
349
  .map((info) =>
288
350
  info.real.type === "Identifier"
289
351
  ? JSON.stringify(info.real.name)
290
- : sourceCode.getText(info.real),
352
+ : sourceCode.getText(info.real)
291
353
  )
292
354
  .join(", ");
293
355
  const restName = () =>
@@ -309,19 +371,19 @@ export default {
309
371
  (node) =>
310
372
  node.type === "ImportDeclaration" &&
311
373
  node.specifiers.some(
312
- (specifier) => specifier.local.name === name,
313
- ),
374
+ (specifier) => specifier.local.name === name
375
+ )
314
376
  );
315
377
  const imports = [];
316
378
  const solidCallName = (name) => {
317
379
  for (const specifier of findSolidImportSpecifiers(
318
380
  program,
319
- name,
381
+ name
320
382
  )) {
321
383
  const variable = lookupVariable(
322
384
  callScope,
323
385
  specifier.local.name,
324
- removedByFix,
386
+ removedByFix
325
387
  );
326
388
  // Unless a nearer binding shadows the import here.
327
389
  if (
@@ -358,7 +420,7 @@ export default {
358
420
  propertyInfo,
359
421
  origProps,
360
422
  lineToInsert,
361
- imports,
423
+ imports
362
424
  };
363
425
  };
364
426
  // The import edit: the names go into the file's `solid-js` value
@@ -381,7 +443,7 @@ export default {
381
443
  propsName,
382
444
  propertyInfo,
383
445
  origProps,
384
- lineToInsert,
446
+ lineToInsert
385
447
  } = plan;
386
448
  const sourceCode = getSourceCode(context);
387
449
  // Replace destructured props with a `props` identifier. Only the
@@ -407,7 +469,7 @@ export default {
407
469
  // Inject lines handling defaults/rest params before the first statement in the block.
408
470
  yield fixer.insertTextBefore(
409
471
  body.body[0],
410
- lineToInsert,
472
+ lineToInsert
411
473
  );
412
474
  }
413
475
  // with an empty block statement body, no need to inject code
@@ -425,7 +487,7 @@ export default {
425
487
  // Inject lines handling defaults/rest params
426
488
  yield fixer.insertTextBefore(
427
489
  body,
428
- `{\n${lineToInsert} return (`,
490
+ `{\n${lineToInsert} return (`
429
491
  );
430
492
  yield fixer.insertTextAfter(body, `);\n}`);
431
493
  }
@@ -435,7 +497,7 @@ export default {
435
497
  // iterate through destructured variables, associated with real node
436
498
  for (const [info, variable] of propertyInfo.map((info) => [
437
499
  info,
438
- scope.set.get(info.var),
500
+ scope.set.get(info.var)
439
501
  ])) {
440
502
  if (variable) {
441
503
  // replace all usages of the variable with props accesses
@@ -457,7 +519,7 @@ export default {
457
519
  reference.identifier,
458
520
  isShorthand
459
521
  ? `${reference.identifier.name}: ${propsName}${access}`
460
- : `${propsName}${access}`,
522
+ : `${propsName}${access}`
461
523
  );
462
524
  }
463
525
  }
@@ -496,7 +558,7 @@ export default {
496
558
  sourceCode.ast.body.some(
497
559
  (node) =>
498
560
  node.type === "ImportDeclaration" &&
499
- node.source.value === SOLID_SOURCE,
561
+ node.source.value === SOLID_SOURCE
500
562
  );
501
563
  const callees = (
502
564
  sourceCode.scopeManager?.globalScope?.through ?? []
@@ -504,7 +566,7 @@ export default {
504
566
  .filter(
505
567
  ({ identifier }) =>
506
568
  isSolidFile &&
507
- isGeneratedCall(identifier.parent, identifier),
569
+ isGeneratedCall(identifier.parent, identifier)
508
570
  )
509
571
  .sort((a, b) => a.identifier.range[0] - b.identifier.range[0]);
510
572
  const danglingImports = [];
@@ -515,45 +577,53 @@ export default {
515
577
  }
516
578
  };
517
579
  callees.forEach(({ identifier }) =>
518
- addImport(danglingImports, generatedImport(identifier.name)),
580
+ addImport(danglingImports, generatedImport(identifier.name))
519
581
  );
520
582
  plans.forEach((plan) =>
521
583
  plan.imports
522
584
  .filter(
523
585
  (entry) =>
524
586
  !danglingImports.some(
525
- (known) => known.local === entry.local,
526
- ),
587
+ (known) => known.local === entry.local
588
+ )
527
589
  )
528
- .forEach((entry) => addImport(plannedImports, entry)),
590
+ .forEach((entry) => addImport(plannedImports, entry))
529
591
  );
530
592
  if (callees.length > 0) {
531
593
  const [{ identifier }] = callees;
532
594
  context.report({
533
595
  node: identifier,
534
596
  messageId: "missingImport",
535
- data: { name: identifier.name },
536
- fix: (fixer) => importFix(fixer, danglingImports),
597
+ data: {
598
+ name: identifier.name,
599
+ specifier: importSpecifierText(
600
+ generatedImport(identifier.name)
601
+ )
602
+ },
603
+ fix: (fixer) => importFix(fixer, danglingImports)
537
604
  });
538
605
  }
539
606
  const [carrier] = plans.filter((plan) => plan.fixable);
540
607
  plans.forEach((plan) => {
608
+ const data = describeDestructure(sourceCode, plan);
541
609
  if (!plan.fixable) {
542
610
  context.report({
543
611
  node: plan.props,
544
612
  messageId: "noDestructure",
613
+ data
545
614
  });
546
615
  return;
547
616
  }
548
617
  context.report({
549
618
  node: plan.props,
550
619
  messageId: "noDestructure",
620
+ data,
551
621
  fix: (fixer) =>
552
622
  fixDestructure(
553
623
  plan,
554
624
  plan === carrier ? plannedImports : [],
555
- fixer,
556
- ),
625
+ fixer
626
+ )
557
627
  });
558
628
  });
559
629
  };
@@ -576,7 +646,7 @@ export default {
576
646
  if (functionStack.length) {
577
647
  currentFunction().hasJSX = true;
578
648
  }
579
- },
649
+ }
580
650
  };
581
- },
651
+ }
582
652
  };
@@ -1,14 +1,15 @@
1
1
  import { getStringIfConstant } from "@eslint-community/eslint-utils";
2
2
  import isHtml from "is-html";
3
3
 
4
- import { jsxPropName } from "../utils.mjs";
4
+ import { getSourceCode } from "../compat.mjs";
5
+ import { jsxPropName, messageCode } from "../utils.mjs";
5
6
  export default {
6
7
  meta: {
7
8
  type: "problem",
8
9
  docs: {
9
10
  description:
10
11
  "Disallow usage of the innerHTML attribute, which can often lead to security vulnerabilities.",
11
- url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/no-innerhtml.md",
12
+ url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/no-innerhtml.md"
12
13
  },
13
14
  fixable: "code",
14
15
  hasSuggestions: true,
@@ -20,28 +21,50 @@ export default {
20
21
  description:
21
22
  "if the innerHTML value is guaranteed to be a static HTML string (i.e. no user input), allow it",
22
23
  type: "boolean",
23
- default: true,
24
- },
24
+ default: true
25
+ }
25
26
  },
26
- additionalProperties: false,
27
- },
27
+ additionalProperties: false
28
+ }
28
29
  ],
29
30
  messages: {
30
31
  dangerous:
31
- "The innerHTML attribute is dangerous; passing unsanitized input can lead to security vulnerabilities.",
32
+ "`innerHTML={{{value}}}` parses the value as HTML, so input that reaches it can inject markup and run script (XSS). Fix: for text, render it as a child, `<{{element}}>{{{value}}}</{{element}}>`; for HTML, sanitize it before it reaches `innerHTML`.",
32
33
  conflict:
33
- "The innerHTML attribute should not be used on an element with child elements; they will be overwritten.",
34
+ "`<{{element}}>` has both `innerHTML` and children, and one replaces the other, so part of this markup never renders. Fix: keep one: drop the children, or drop `innerHTML` and write its markup as JSX.",
34
35
  notHtml:
35
- "The string passed to innerHTML does not appear to be valid HTML.",
36
- useInnerText:
37
- "For text content, using innerText is clearer and safer.",
36
+ "`innerHTML` gets `{{value}}`, which holds no HTML, so it is parsed as HTML for nothing and a later `<` or `&` in it turns into markup. Fix: `{{fix}}`.",
37
+ useInnerText: "Replace `innerHTML` with `innerText`.",
38
38
  dangerouslySetInnerHTML:
39
- "The dangerouslySetInnerHTML prop is not supported; use innerHTML instead.",
40
- },
39
+ "`dangerouslySetInnerHTML` is React's prop; Solid sets it as an unknown attribute and the HTML never renders. Fix: `{{fix}}`."
40
+ }
41
41
  },
42
42
  defaultOptions: [{ allowStatic: true }],
43
43
  create(context) {
44
44
  const allowStatic = Boolean(context.options[0]?.allowStatic ?? true);
45
+ const sourceCode = getSourceCode(context);
46
+ const elementName = (attribute) =>
47
+ sourceCode.getText(attribute.parent.name);
48
+ // `<div innerHTML={html} />`: the value as an expression.
49
+ const valueText = (attribute) =>
50
+ messageCode(
51
+ sourceCode.getText(
52
+ attribute.value?.type === "JSXExpressionContainer"
53
+ ? attribute.value.expression
54
+ : attribute.value
55
+ ),
56
+ "html"
57
+ );
58
+ const reportDangerous = (node) => {
59
+ context.report({
60
+ node,
61
+ messageId: "dangerous",
62
+ data: {
63
+ element: elementName(node),
64
+ value: node.value ? valueText(node) : "true"
65
+ }
66
+ });
67
+ };
45
68
  return {
46
69
  JSXAttribute(node) {
47
70
  if (jsxPropName(node) === "dangerouslySetInnerHTML") {
@@ -59,31 +82,36 @@ export default {
59
82
  context.report({
60
83
  node,
61
84
  messageId: "dangerouslySetInnerHTML",
85
+ data: {
86
+ fix: `innerHTML={${messageCode(sourceCode.getText(htmlProp.value), "html")}}`
87
+ },
62
88
  fix: (fixer) => {
63
89
  const propRange = node.range;
64
90
  const valueRange = htmlProp.value.range;
65
91
  return [
66
92
  fixer.replaceTextRange(
67
93
  [propRange[0], valueRange[0]],
68
- "innerHTML={",
94
+ "innerHTML={"
69
95
  ),
70
96
  fixer.replaceTextRange(
71
97
  [valueRange[1], propRange[1]],
72
- "}",
73
- ),
98
+ "}"
99
+ )
74
100
  ];
75
- },
101
+ }
76
102
  });
77
103
  } else {
78
104
  context.report({
79
105
  node,
80
106
  messageId: "dangerouslySetInnerHTML",
107
+ data: { fix: "innerHTML={html}" }
81
108
  });
82
109
  }
83
110
  } else {
84
111
  context.report({
85
112
  node,
86
113
  messageId: "dangerouslySetInnerHTML",
114
+ data: { fix: "innerHTML={html}" }
87
115
  });
88
116
  }
89
117
  return;
@@ -107,37 +135,42 @@ export default {
107
135
  context.report({
108
136
  node: node.parent.parent, // report error on JSXElement instead of JSXAttribute
109
137
  messageId: "conflict",
138
+ data: { element: elementName(node) }
110
139
  });
111
140
  }
112
141
  } else {
113
142
  context.report({
114
143
  node,
115
144
  messageId: "notHtml",
145
+ data: {
146
+ value: messageCode(
147
+ sourceCode.getText(node.value),
148
+ '"…"'
149
+ ),
150
+ fix: messageCode(
151
+ `innerText=${sourceCode.getText(node.value)}`,
152
+ "innerText={text}"
153
+ )
154
+ },
116
155
  suggest: [
117
156
  {
118
157
  fix: (fixer) =>
119
158
  fixer.replaceText(
120
159
  node.name,
121
- "innerText",
160
+ "innerText"
122
161
  ),
123
- messageId: "useInnerText",
124
- },
125
- ],
162
+ messageId: "useInnerText"
163
+ }
164
+ ]
126
165
  });
127
166
  }
128
167
  } else {
129
- context.report({
130
- node,
131
- messageId: "dangerous",
132
- });
168
+ reportDangerous(node);
133
169
  }
134
170
  } else {
135
- context.report({
136
- node,
137
- messageId: "dangerous",
138
- });
171
+ reportDangerous(node);
139
172
  }
140
- },
173
+ }
141
174
  };
142
- },
175
+ }
143
176
  };