|
| 1 | +import type { AST } from "svelte-eslint-parser" |
| 2 | +import type * as ESTree from "estree" |
| 3 | +import { createRule } from "../utils" |
| 4 | +import { isKitPageComponent } from "../utils/svelte-kit" |
| 5 | + |
| 6 | +const EXPECTED_PROP_NAMES = ["data", "errors"] |
| 7 | + |
| 8 | +export default createRule("valid-prop-names-in-kit-pages", { |
| 9 | + meta: { |
| 10 | + docs: { |
| 11 | + description: |
| 12 | + "disallow props other than data or errors in Svelte Kit page components.", |
| 13 | + category: "Possible Errors", |
| 14 | + // TODO Switch to recommended in the major version. |
| 15 | + recommended: false, |
| 16 | + }, |
| 17 | + schema: [], |
| 18 | + messages: { |
| 19 | + unexpected: |
| 20 | + "disallow props other than data or errors in Svelte Kit page components.", |
| 21 | + }, |
| 22 | + type: "problem", |
| 23 | + }, |
| 24 | + create(context) { |
| 25 | + if (!isKitPageComponent(context)) return {} |
| 26 | + let isScript = false |
| 27 | + return { |
| 28 | + // <script> |
| 29 | + "Program > SvelteScriptElement > SvelteStartTag": ( |
| 30 | + node: AST.SvelteStartTag, |
| 31 | + ) => { |
| 32 | + // except for <script context="module"> |
| 33 | + isScript = !node.attributes.some( |
| 34 | + (a) => |
| 35 | + a.type === "SvelteAttribute" && |
| 36 | + a.key.name === "context" && |
| 37 | + a.value.some( |
| 38 | + (v) => v.type === "SvelteLiteral" && v.value === "module", |
| 39 | + ), |
| 40 | + ) |
| 41 | + }, |
| 42 | + |
| 43 | + // </script> |
| 44 | + "Program > SvelteScriptElement:exit": () => { |
| 45 | + isScript = false |
| 46 | + }, |
| 47 | + |
| 48 | + "ExportNamedDeclaration > VariableDeclaration > VariableDeclarator": ( |
| 49 | + node: ESTree.VariableDeclarator, |
| 50 | + ) => { |
| 51 | + if (!isScript) return |
| 52 | + |
| 53 | + // export let foo |
| 54 | + if (node.id.type === "Identifier") { |
| 55 | + if (!EXPECTED_PROP_NAMES.includes(node.id.name)) { |
| 56 | + context.report({ |
| 57 | + node, |
| 58 | + loc: node.loc!, |
| 59 | + messageId: "unexpected", |
| 60 | + }) |
| 61 | + } |
| 62 | + return |
| 63 | + } |
| 64 | + |
| 65 | + // export let { xxx, yyy } = zzz |
| 66 | + if (node.id.type !== "ObjectPattern") return |
| 67 | + for (const p of node.id.properties) { |
| 68 | + if ( |
| 69 | + p.type === "Property" && |
| 70 | + p.value.type === "Identifier" && |
| 71 | + !EXPECTED_PROP_NAMES.includes(p.value.name) |
| 72 | + ) { |
| 73 | + context.report({ |
| 74 | + node: p.value, |
| 75 | + loc: p.value.loc!, |
| 76 | + messageId: "unexpected", |
| 77 | + }) |
| 78 | + } |
| 79 | + } |
| 80 | + }, |
| 81 | + } |
| 82 | + }, |
| 83 | +}) |
0 commit comments