@murky-web/oxlint-plugin-solid 1.2.0 → 1.4.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.
@@ -1,6 +1,87 @@
1
1
  import { getStringIfConstant } from "@eslint-community/eslint-utils";
2
2
 
3
3
  import { getSourceCode } from "../compat.mjs";
4
+ import { appendImports, insertImports } from "../utils.mjs";
5
+ const SOLID_SOURCE = "solid-js";
6
+ const isSolidValueImport = (node) =>
7
+ node.type === "ImportDeclaration" &&
8
+ node.importKind !== "type" &&
9
+ node.source.value === SOLID_SOURCE;
10
+ // The specifiers that import `name` by value from "solid-js" (`merge`,
11
+ // `merge as solidMerge`, ...).
12
+ const findSolidImportSpecifiers = (program, name) => {
13
+ const found = [];
14
+ for (const node of program.body) {
15
+ if (!isSolidValueImport(node)) {
16
+ continue;
17
+ }
18
+ for (const specifier of node.specifiers) {
19
+ if (
20
+ specifier.type === "ImportSpecifier" &&
21
+ specifier.importKind !== "type" &&
22
+ (specifier.imported.name ?? specifier.imported.value) === name
23
+ ) {
24
+ found.push(specifier);
25
+ }
26
+ }
27
+ }
28
+ return found;
29
+ };
30
+ // The variable `name` resolves to when read from `scope`: the nearest
31
+ // binding up the scope chain, or null. Variables for which `ignore` is true
32
+ // are skipped, as if they were not there.
33
+ const lookupVariable = (scope, name, ignore = () => false) => {
34
+ for (let current = scope; current; current = current.upper) {
35
+ const variable = current.set.get(name);
36
+ if (variable && !ignore(variable)) {
37
+ return variable;
38
+ }
39
+ }
40
+ return null;
41
+ };
42
+ // `solid` + the name with a capital: `merge` gives `solidMerge`.
43
+ const aliasFor = (name, attempt) =>
44
+ `solid${name[0].toUpperCase()}${name.slice(1)}${attempt > 1 ? attempt : ""}`;
45
+ const importSpecifierText = ({ imported, local }) =>
46
+ imported === local ? imported : `${imported} as ${local}`;
47
+ // The names this rule writes into fixed code: `merge`, `omit` and their
48
+ // aliases (`solidMerge`, `solidOmit2`, ...). The `solid-js` import a name
49
+ // stands for, as an imported/local pair, or null for any other name.
50
+ const GENERATED_NAME = /^(?:(merge|omit)|solid(Merge|Omit)\d*)$/u;
51
+ const generatedImport = (name) => {
52
+ const match = GENERATED_NAME.exec(name);
53
+ return match === null
54
+ ? null
55
+ : { imported: (match[1] ?? match[2]).toLowerCase(), local: name };
56
+ };
57
+ // Whether `call` is a call the fixes of this rule write, with `callee` as its
58
+ // callee: `merge({ ... }, _props)`, `omit(props, "a", "b")` or the same with an
59
+ // alias (`solidMerge2`). Anything else is somebody else's `merge`/`omit`.
60
+ const isGeneratedCall = (call, callee) => {
61
+ if (call?.type !== "CallExpression" || call.callee !== callee) {
62
+ return false;
63
+ }
64
+ const imported = generatedImport(callee.name)?.imported;
65
+ const [first, ...others] = call.arguments;
66
+ if (imported === "merge") {
67
+ return (
68
+ first?.type === "ObjectExpression" &&
69
+ others.length === 1 &&
70
+ others[0].type === "Identifier"
71
+ );
72
+ }
73
+ return (
74
+ imported === "omit" &&
75
+ first?.type === "Identifier" &&
76
+ others.length > 0 &&
77
+ others.every(
78
+ (key) =>
79
+ key.type === "Literal" &&
80
+ (typeof key.value === "string" ||
81
+ typeof key.value === "number"),
82
+ )
83
+ );
84
+ };
4
85
  const getName = (node) => {
5
86
  switch (node.type) {
6
87
  case "Literal":
@@ -43,12 +124,17 @@ export default {
43
124
  messages: {
44
125
  noDestructure:
45
126
  "Destructuring component props breaks Solid's reactivity; use property access instead.",
127
+ missingImport:
128
+ "`{{name}}` is used without an import from solid-js.",
46
129
  // noWriteToProps: "Component props are readonly, writing to props is not supported.",
47
130
  },
48
131
  },
49
132
  defaultOptions: [],
50
133
  create(context) {
51
134
  const functionStack = [];
135
+ // Destructuring components found so far, as `{ func, props }`.
136
+ const components = [];
137
+ let sawJSX = false;
52
138
  const currentFunction = () => functionStack[functionStack.length - 1];
53
139
  const onFunctionEnter = () => {
54
140
  functionStack.push({ hasJSX: false });
@@ -64,46 +150,128 @@ export default {
64
150
  // Props are destructured in the function params, not the body. We actually don't
65
151
  // need to handle the case where props are destructured in the body, because that
66
152
  // will be a violation of "solid/reactivity".
67
- context.report({
68
- node: props,
69
- messageId: "noDestructure",
70
- fix: (fixer) => fixDestructure(node, props, fixer),
71
- });
153
+ // Reported at `Program:exit`, once every component of the
154
+ // file is known (see `reportAll`).
155
+ components.push({ func: node, props });
72
156
  }
73
157
  }
74
158
  // Pop on exit
75
159
  functionStack.pop();
76
160
  };
77
- function* fixDestructure(func, props, fixer) {
78
- const propsName = "props";
161
+ // Everything about the rewrite of one component that does not need
162
+ // the fixer: the new parameter, the line for the body, and the
163
+ // `solid-js` names that line calls (`imports`, as imported/local pairs
164
+ // that the file does not import yet).
165
+ //
166
+ // `fixable` is false when a rewrite would change what the code does:
167
+ // a nested pattern (`{ user: { name } }`) leaves `name` without a
168
+ // binding, a computed key that is not a literal (`{ [key]: label }`)
169
+ // cannot be named in `omit(props, ...)`, and a write to a destructured
170
+ // name (`count += 1`) or a read of one in the pattern itself (a
171
+ // default that uses an earlier prop) has no `props.x` form. Those
172
+ // components are reported without a fix.
173
+ const planFix = (func, props) => {
79
174
  const properties = props.properties;
80
175
  const propertyInfo = [];
81
176
  let rest = null;
177
+ let fixable = true;
82
178
  for (const property of properties) {
83
179
  if (property.type === "RestElement") {
84
180
  rest = property;
85
181
  } else {
86
182
  const info = getPropertyInfo(property);
87
- if (info === null) {
183
+ if (
184
+ info === null ||
185
+ (info.computed && info.real.type !== "Literal")
186
+ ) {
187
+ fixable = false;
88
188
  continue;
89
189
  }
90
190
  propertyInfo.push(info);
91
191
  }
92
192
  }
193
+ const sourceCode = getSourceCode(context);
194
+ const program = sourceCode.ast;
195
+ const scopeManager = sourceCode.scopeManager;
196
+ const callScope = scopeManager?.acquire(func) ?? null;
197
+ // The bindings of the destructured props: the fix removes them.
198
+ const removedByFix = (variable) =>
199
+ propertyInfo.some((info) => info.var === variable.name) &&
200
+ variable.defs.every(
201
+ (def) =>
202
+ def.name?.range !== undefined &&
203
+ def.name.range[0] >= props.range[0] &&
204
+ def.name.range[1] <= props.range[1],
205
+ );
206
+ if (fixable && callScope) {
207
+ fixable = propertyInfo.every((info) => {
208
+ const variable = callScope.set.get(info.var);
209
+ return (
210
+ variable === undefined ||
211
+ variable.references.every((reference) => {
212
+ const isInPattern =
213
+ reference.identifier.range[0] >=
214
+ props.range[0] &&
215
+ reference.identifier.range[1] <= props.range[1];
216
+ if (isInPattern) {
217
+ // The binding itself, nothing else.
218
+ return variable.defs.some(
219
+ (def) => def.name === reference.identifier,
220
+ );
221
+ }
222
+ return reference.isReadOnly();
223
+ })
224
+ );
225
+ });
226
+ }
227
+ if (!fixable) {
228
+ return { fixable, func, props, imports: [] };
229
+ }
230
+ // The scopes of the reads that the fix rewrites to `props.x`.
231
+ // They can sit inside functions of their own (`items.map((props)
232
+ // => ... title ...)`), where a binding of the name would be read
233
+ // instead of the parameter.
234
+ const rewrittenScopes = [];
235
+ for (const info of propertyInfo) {
236
+ for (const reference of callScope?.set.get(info.var)
237
+ ?.references ?? []) {
238
+ if (reference.isReadOnly() && !reference.init) {
239
+ rewrittenScopes.push(reference.from);
240
+ }
241
+ }
242
+ }
243
+ // The names the fix declares: the parameter and, when defaults
244
+ // are merged, the object next to it. Free means nothing visible
245
+ // from `func` or from any rewritten read has the name, and
246
+ // nothing in `func` reads an undeclared global of that name, or
247
+ // the new binding would capture the reads of the outer one
248
+ // (`props` of an outer component read in an inner one), or a
249
+ // rewritten read would find another binding first.
250
+ const isDeclaredOutside = (name) =>
251
+ lookupVariable(callScope, name, removedByFix) !== null ||
252
+ rewrittenScopes.some(
253
+ (scope) =>
254
+ lookupVariable(scope, name, removedByFix) !== null,
255
+ ) ||
256
+ (scopeManager?.globalScope?.through ?? []).some(
257
+ ({ identifier }) =>
258
+ identifier.name === name &&
259
+ identifier.range[0] >= func.range[0] &&
260
+ identifier.range[1] <= func.range[1],
261
+ );
93
262
  const hasDefaults = propertyInfo.some((info) => info.init);
94
- // Replace destructured props with a `props` identifier. Only the
95
- // defaults case needs a second binding, because `merge` produces a
96
- // new object; `omit` returns just the rest, so the parameter itself
97
- // still carries the named props.
98
- const origProps = hasDefaults ? "_" + propsName : propsName;
99
- if (props.typeAnnotation) {
100
- // in `{ prop1, prop2 }: Props`, leave `: Props` alone
101
- const range = [props.range[0], props.typeAnnotation.range[0]];
102
- yield fixer.replaceTextRange(range, origProps);
103
- } else {
104
- yield fixer.replaceText(props, origProps);
263
+ let propsName = "props";
264
+ for (let attempt = 2; ; attempt += 1) {
265
+ const origName = hasDefaults ? `_${propsName}` : propsName;
266
+ if (
267
+ !isDeclaredOutside(propsName) &&
268
+ !isDeclaredOutside(origName)
269
+ ) {
270
+ break;
271
+ }
272
+ propsName = `props${attempt}`;
105
273
  }
106
- const sourceCode = getSourceCode(context);
274
+ const origProps = hasDefaults ? "_" + propsName : propsName;
107
275
  const defaultsObjectString = () =>
108
276
  propertyInfo
109
277
  .filter((info) => info.init)
@@ -125,15 +293,112 @@ export default {
125
293
  const restName = () =>
126
294
  (rest.argument.type === "Identifier" && rest.argument.name) ||
127
295
  "rest";
296
+ // The name to call `merge`/`omit` by in the body of `func`:
297
+ // the local name of an existing `solid-js` import, otherwise the
298
+ // plain name if nothing else is called that, otherwise a free
299
+ // alias (`solidMerge`, `solidMerge2`, ...). Both of the last two
300
+ // are imported by the carrying fix.
301
+ // A name the import would clash with: a binding in the module
302
+ // scope (import, const, function, class, ...), one on the way from
303
+ // the body of `func` up to it. An unresolved read of the name
304
+ // does not count: it is a dangling call of an earlier fix, which
305
+ // the import settles (see `reportAll`).
306
+ const isTaken = (name) =>
307
+ lookupVariable(callScope, name, removedByFix) !== null ||
308
+ program.body.some(
309
+ (node) =>
310
+ node.type === "ImportDeclaration" &&
311
+ node.specifiers.some(
312
+ (specifier) => specifier.local.name === name,
313
+ ),
314
+ );
315
+ const imports = [];
316
+ const solidCallName = (name) => {
317
+ for (const specifier of findSolidImportSpecifiers(
318
+ program,
319
+ name,
320
+ )) {
321
+ const variable = lookupVariable(
322
+ callScope,
323
+ specifier.local.name,
324
+ removedByFix,
325
+ );
326
+ // Unless a nearer binding shadows the import here.
327
+ if (
328
+ variable === null ||
329
+ variable.defs.some((def) => def.node === specifier)
330
+ ) {
331
+ return specifier.local.name;
332
+ }
333
+ }
334
+ let local = name;
335
+ for (let attempt = 1; isTaken(local); attempt += 1) {
336
+ local = aliasFor(name, attempt);
337
+ }
338
+ if (!imports.some((entry) => entry.local === local)) {
339
+ imports.push({ imported: name, local });
340
+ }
341
+ return local;
342
+ };
128
343
  let lineToInsert = "";
129
344
  if (hasDefaults && rest) {
130
345
  // Merge the defaults, then take the rest off the merged object.
131
- lineToInsert = ` const ${propsName} = merge({ ${defaultsObjectString()} }, ${origProps});\n const ${restName()} = omit(${propsName}, ${omitArgs()});\n`;
346
+ lineToInsert = ` const ${propsName} = ${solidCallName("merge")}({ ${defaultsObjectString()} }, ${origProps});\n const ${restName()} = ${solidCallName("omit")}(${propsName}, ${omitArgs()});\n`;
132
347
  } else if (hasDefaults) {
133
- lineToInsert = ` const ${propsName} = merge({ ${defaultsObjectString()} }, ${origProps});\n`;
348
+ lineToInsert = ` const ${propsName} = ${solidCallName("merge")}({ ${defaultsObjectString()} }, ${origProps});\n`;
134
349
  } else if (rest) {
135
350
  // `props` already carries the named props; only the rest is new.
136
- lineToInsert = ` const ${restName()} = omit(${origProps}, ${omitArgs()});\n`;
351
+ lineToInsert = ` const ${restName()} = ${solidCallName("omit")}(${origProps}, ${omitArgs()});\n`;
352
+ }
353
+ return {
354
+ fixable,
355
+ func,
356
+ props,
357
+ propsName,
358
+ propertyInfo,
359
+ origProps,
360
+ lineToInsert,
361
+ imports,
362
+ };
363
+ };
364
+ // The import edit: the names go into the file's `solid-js` value
365
+ // import, or into a new one if it has none.
366
+ const importFix = (fixer, imports) => {
367
+ const sourceCode = getSourceCode(context);
368
+ const program = sourceCode.ast;
369
+ const names = imports.map(importSpecifierText);
370
+ const declaration = program.body.find(isSolidValueImport);
371
+ return declaration
372
+ ? appendImports(fixer, sourceCode, declaration, names)
373
+ : insertImports(fixer, sourceCode, SOLID_SOURCE, names);
374
+ };
375
+ // `carriedImports` are the names to import, for the one component of
376
+ // the file whose fix also adds the import (see `reportAll`).
377
+ function* fixDestructure(plan, carriedImports, fixer) {
378
+ const {
379
+ func,
380
+ props,
381
+ propsName,
382
+ propertyInfo,
383
+ origProps,
384
+ lineToInsert,
385
+ } = plan;
386
+ const sourceCode = getSourceCode(context);
387
+ // Replace destructured props with a `props` identifier. Only the
388
+ // defaults case needs a second binding (`_props`), because
389
+ // `merge` produces a new object.
390
+ if (props.typeAnnotation) {
391
+ // in `{ prop1, prop2 }: Props`, leave `: Props` alone
392
+ const range = [props.range[0], props.typeAnnotation.range[0]];
393
+ yield fixer.replaceTextRange(range, origProps);
394
+ } else {
395
+ yield fixer.replaceText(props, origProps);
396
+ }
397
+ if (carriedImports.length > 0) {
398
+ const fix = importFix(fixer, carriedImports);
399
+ if (fix) {
400
+ yield fix;
401
+ }
137
402
  }
138
403
  if (lineToInsert) {
139
404
  const body = func.body;
@@ -181,9 +446,18 @@ export default {
181
446
  !info.computed
182
447
  ? `.${info.real.name}`
183
448
  : `[${sourceCode.getText(info.real)}]`;
449
+ // `{ title }` is `{ title: title }`: the key stays,
450
+ // only the value becomes the property access.
451
+ const parent = reference.identifier.parent;
452
+ const isShorthand =
453
+ parent?.type === "Property" &&
454
+ parent.shorthand === true &&
455
+ parent.parent?.type === "ObjectExpression";
184
456
  yield fixer.replaceText(
185
457
  reference.identifier,
186
- `${propsName}${access}`,
458
+ isShorthand
459
+ ? `${reference.identifier.name}: ${propsName}${access}`
460
+ : `${propsName}${access}`,
187
461
  );
188
462
  }
189
463
  }
@@ -191,7 +465,100 @@ export default {
191
465
  }
192
466
  }
193
467
  }
468
+ // oxlint merges the edits of one fix into a single replacement that
469
+ // runs from its first to its last edit, and skips a fix that overlaps
470
+ // one it already applied (a run is one pass). An import edit at the
471
+ // top of the file in every component's fix would make all of them
472
+ // overlap, so one run would fix one component. Instead the fix of the
473
+ // first component in the file (the carrier) holds the import, for the
474
+ // names of all components; the others only rewrite themselves. Every
475
+ // fix then starts after the end of the one before.
476
+ //
477
+ // The catch: if the carrier's fix is dropped (another rule's fix
478
+ // overlaps it), the others call names that are not imported yet. A
479
+ // later run heals that: calls of `merge`, `omit` and their aliases in
480
+ // the shape this rule writes, that no binding resolves ("dangling"),
481
+ // get their own report, whose fix only adds those names. The carrier
482
+ // leaves the dangling names out. Its import edit and that fix start
483
+ // at the same position, so when both are in one run oxlint applies
484
+ // the missingImport fix and drops the carrier's fix; the next run
485
+ // appends the carrier's names to the import. Every run then makes
486
+ // progress and the file ends with valid code.
487
+ const reportAll = () => {
488
+ const sourceCode = getSourceCode(context);
489
+ const plans = [...components]
490
+ .sort((a, b) => a.props.range[0] - b.props.range[0])
491
+ .map(({ func, props }) => planFix(func, props));
492
+ // Only in a Solid file: JSX or an import from solid-js. Any other
493
+ // module may call its own global `merge`.
494
+ const isSolidFile =
495
+ sawJSX ||
496
+ sourceCode.ast.body.some(
497
+ (node) =>
498
+ node.type === "ImportDeclaration" &&
499
+ node.source.value === SOLID_SOURCE,
500
+ );
501
+ const callees = (
502
+ sourceCode.scopeManager?.globalScope?.through ?? []
503
+ )
504
+ .filter(
505
+ ({ identifier }) =>
506
+ isSolidFile &&
507
+ isGeneratedCall(identifier.parent, identifier),
508
+ )
509
+ .sort((a, b) => a.identifier.range[0] - b.identifier.range[0]);
510
+ const danglingImports = [];
511
+ const plannedImports = [];
512
+ const addImport = (list, entry) => {
513
+ if (!list.some((known) => known.local === entry.local)) {
514
+ list.push(entry);
515
+ }
516
+ };
517
+ callees.forEach(({ identifier }) =>
518
+ addImport(danglingImports, generatedImport(identifier.name)),
519
+ );
520
+ plans.forEach((plan) =>
521
+ plan.imports
522
+ .filter(
523
+ (entry) =>
524
+ !danglingImports.some(
525
+ (known) => known.local === entry.local,
526
+ ),
527
+ )
528
+ .forEach((entry) => addImport(plannedImports, entry)),
529
+ );
530
+ if (callees.length > 0) {
531
+ const [{ identifier }] = callees;
532
+ context.report({
533
+ node: identifier,
534
+ messageId: "missingImport",
535
+ data: { name: identifier.name },
536
+ fix: (fixer) => importFix(fixer, danglingImports),
537
+ });
538
+ }
539
+ const [carrier] = plans.filter((plan) => plan.fixable);
540
+ plans.forEach((plan) => {
541
+ if (!plan.fixable) {
542
+ context.report({
543
+ node: plan.props,
544
+ messageId: "noDestructure",
545
+ });
546
+ return;
547
+ }
548
+ context.report({
549
+ node: plan.props,
550
+ messageId: "noDestructure",
551
+ fix: (fixer) =>
552
+ fixDestructure(
553
+ plan,
554
+ plan === carrier ? plannedImports : [],
555
+ fixer,
556
+ ),
557
+ });
558
+ });
559
+ };
194
560
  return {
561
+ "Program:exit": reportAll,
195
562
  FunctionDeclaration: onFunctionEnter,
196
563
  FunctionExpression: onFunctionEnter,
197
564
  ArrowFunctionExpression: onFunctionEnter,
@@ -199,11 +566,13 @@ export default {
199
566
  "FunctionExpression:exit": onFunctionExit,
200
567
  "ArrowFunctionExpression:exit": onFunctionExit,
201
568
  JSXElement() {
569
+ sawJSX = true;
202
570
  if (functionStack.length) {
203
571
  currentFunction().hasJSX = true;
204
572
  }
205
573
  },
206
574
  JSXFragment() {
575
+ sawJSX = true;
207
576
  if (functionStack.length) {
208
577
  currentFunction().hasJSX = true;
209
578
  }
@@ -70,7 +70,9 @@ export default {
70
70
  },
71
71
  CallExpression(node) {
72
72
  if (node.callee.type === "Identifier") {
73
- if (matchImport(["merge", "mergeProps"], node.callee.name)) {
73
+ if (
74
+ matchImport(["merge", "mergeProps"], node.callee.name)
75
+ ) {
74
76
  node.arguments
75
77
  .filter((arg) => {
76
78
  if (arg.type === "SpreadElement") return true;