---
title: "Visitors"
description: "Visit script and template nodes, skip files with a prefilter, and the order Doctor runs file Rules in."
canonical_url: "https://vite-doctor.onmax.me/extending/visitors"
---
# Visitors

> Visit script and template nodes, skip files with a prefilter, and the order Doctor runs file Rules in.

`create(ctx)` returns visitors keyed by ESTree node type, the same shape ESLint and oxlint use. Doctor walks each file's script once and calls a visitor only for nodes of its type. Add `:exit` to run after the node's children.

## Script nodes

This Rule reports every `createClient()` call after the first one in a module, with `ACME0002` registered next to `ACME0001`:

```ts [doctor/extension.ts]
import { createRule, type ScriptAstNodeOf } from "vite-doctor/extension";

export const singleClient = createRule({
  meta: {
    id: "acme/single-client",
    title: "Create one Acme client per module",
    category: "correctness",
    severity: "warn",
    prefilter: { calls: ["createClient"] },
  },
  create(ctx) {
    const clients: ScriptAstNodeOf<"CallExpression">[] = [];
    return {
      CallExpression(node) {
        if (node.callee.type === "Identifier" && node.callee.name === "createClient") {
          clients.push(node);
        }
      },
      "Program:exit"() {
        for (const node of clients.slice(1)) {
          ctx.report(
            acmeDiagnostics.diagnostics.ACME0002({
              why: "Each client opens its own connection pool.",
              fix: "Reuse the first client in this module.",
            }),
            { range: ctx.range(node) },
          );
        }
      },
    };
  },
});
```

Each visitor's `node` is typed for its key: `CallExpression(node)` receives a `CallExpression`. Script ASTs come from [oxc-parser](https://oxc.rs/docs/guide/usage/parser), so node types match its ESTree output, TypeScript and JSX nodes included. To type a helper, use `ScriptAstNodeOf<"CallExpression">` or the `ScriptAstNode` union from `vite-doctor/extension`. Vue SFC Rules can also use the `SFC` hook and template visitors.

## Template nodes

For Vue SFCs, return a `template` object with visitors keyed by node kind: `root`, `element`, `attribute`, `directive`, `text`, `interpolation`, and `comment`. Doctor walks the `<template>` AST that `@vue/compiler-sfc` builds when it parses the SFC, so template visitors add no parse of their own. This Rule reports `<AcmeImage>` elements without alt text and `:src` bindings to plain `http:` URLs, with `ACME0003` and `ACME0004` registered for `acme/image`:

```ts [doctor/extension.ts]
export const acmeImage = createRule({
  meta: {
    id: "acme/image",
    title: "Use accessible, secure Acme images",
    category: "a11y",
    severity: "warn",
  },
  create(ctx) {
    return {
      template: {
        element(node) {
          if (node.tag !== "AcmeImage") return;
          if (
            ctx.helpers.hasVueAttribute(node, "alt") ||
            ctx.helpers.hasVueDirective(node, "bind", "alt")
          )
            return;
          ctx.report(
            acmeDiagnostics.diagnostics.ACME0003({
              why: "Screen readers announce an image without alt text by its file name.",
              fix: 'Add alt text, or alt="" for a decorative image.',
            }),
            { range: ctx.range(node) },
          );
        },
        directive(node, element) {
          if (element.tag !== "AcmeImage" || node.name !== "bind" || node.arg?.content !== "src")
            return;
          const expression = node.exp && ctx.helpers.parseTemplateExpression(node.exp);
          if (expression?.type !== "Literal" || !String(expression.value).startsWith("http:"))
            return;
          ctx.report(
            acmeDiagnostics.diagnostics.ACME0004({
              why: "An http: image on an https: page is mixed content that browsers upgrade or block.",
              fix: "Serve the image over https:.",
            }),
            { range: ctx.range(expression) },
          );
        },
      },
    };
  },
});
```

Nodes are the compiler-dom nodes Vue's compiler produces, typed as `TemplateElementNode`, `TemplateDirectiveNode`, and so on in `vite-doctor/extension`:

- Each visitor receives the node and its parent. `attribute` and `directive` receive their element; other kinds receive their parent element or the template root.
- An element's attributes and directives are visited in source order before its children. `"element:exit"` and the other `:exit` keys run after a node's props and children, so a Rule can track ancestors with a counter or stack.
- `element.tag` is the tag as written, such as `button`, `NuxtLink`, or `router-view`. `element.props` holds static attributes (`type: 6`) and directives (`type: 7`).
- Directive shorthands are normalized: `:href`, `@click`, and `#default` have `name` `bind`, `on`, and `slot`, with a static argument in `arg.content`. `rawName` keeps the name as written.
- A static attribute value is `attribute.value?.content`. Directive values and interpolations are strings in `exp.content`. `ctx.helpers.parseTemplateExpression(exp)` parses one with oxc on first use and shares the result with every Rule. It returns `null` for a whole `v-for` (parse `forParseResult.source`), `v-slot` parameters, and `v-on` handlers with several statements.
- Template nodes and parsed expressions carry SFC offsets, so `ctx.range(node)` points at the source. `ctx.file.templateAst` is the root, for Rules that need the whole template in `create(ctx)`.

Template visitors don't run on `<template src>` or on templates with a non-HTML `lang`, such as Pug.

## Prefilter

`meta.prefilter` skips a Rule on files that cannot produce its Diagnostics; Doctor doesn't call `create(ctx)` for them. A Rule runs on a file when any listed signal is present:

| Field | Matches |
| --- | --- |
| `calls` | Call expressions by callee name, such as `useFetch` or `Math.random`. `new` expressions don't count. |
| `imports` | Static `import` declarations by exact source, such as `acme/legacy`. |
| `names` | Names the file text could spell, including through escape sequences. Use it for aliases and reads. |

List every signal the Rule reports from. If a Rule also reports from `create(ctx)`, `SFC`, or template visitors, or follows aliases such as `const load = createClient`, a `calls` prefilter can hide real Diagnostics. Use `names` or leave the prefilter out.

## Execution order

File Rules run one file at a time. For each file, Doctor:

1. skips Rules whose `meta.prefilter` cannot match;
2. awaits every remaining Rule's `create(ctx)` in enabled-rule order, then every `SFC` hook in that order;
3. walks the script once, depth first. Entering a node, it calls each Rule's visitor for that type in Rule order; after the node's children, it calls the `:exit` visitors the same way;
4. walks the template with the same enter and exit order, using each Rule's `template` visitors.

All callbacks for one file finish before the next file's `create()`. Diagnostics appear in Rule order, then file order.

Rule Packs that coordinate through shared module state or `ctx.cache` must not assume an earlier Rule has finished its callbacks when their `create()` runs. Use caches for reusable facts, not to sequence Rules.

## The AST is read-only

Doctor links script parents before any visitor runs. Treat SFC, script, and template ASTs as read-only. Both traversals are snapshotted before callbacks, so replacing or removing children doesn't cancel their queued visits, and inserted children are not visited. The single-visitor runner works the same way. Doctor guarantees no behavior for AST mutations across Rules, so keep analysis state outside the AST.

## Unknown hooks

Doctor checks every visitor a Rule's `create()` returns, including when its hooks differ between files. A hook Doctor never calls stops the run with `DOC0034`, naming the Rule and the hook:

- a removed hook such as `ScriptNode` or `TemplateNode`;
- a misspelled node type such as `CallExpresion`, with the closest hook suggested;
- a `template` key that isn't a template node kind;
- a lifecycle hook on a file Rule, or a node visitor on a workspace or manifest Rule.

Script hooks are the node types in oxc-parser's visitor keys, so a type that never appears as a child of another node, such as `Hashbang`, is rejected too.

### Migrate from `ScriptNode` and `TemplateNode`

Move a `ScriptNode` body into visitors for the node types it checked: `ScriptNode(node) { if (node.type !== "CallExpression") return; ... }` becomes `CallExpression(node) { ... }`.

`TemplateNode` went away with the vue-eslint-parser node shapes it received:

| Before | After |
| --- | --- |
| `node.type === "VElement"` | `template: { element(node) {} }` |
| `rawName` | `tag` |
| `startTag.attributes` | `props` |
| a directive's `key.name.name`, `key.argument.name` | `name`, `arg.content` |
| a static `value.value` | `value.content` |
| `value.expression` | `ctx.helpers.parseTemplateExpression(exp)` |
| `parent` chains | `element` and `"element:exit"` visitors |


## Sitemap

See the full [sitemap](https://vite-doctor.onmax.me/sitemap.md) for all pages.
