|
| 1 | +import type { Context } from './plugins/context.ts'; |
| 2 | +import type { CreateOnceRule, Rule } from './plugins/load.ts'; |
| 3 | + |
| 4 | +const { defineProperty, getPrototypeOf, setPrototypeOf } = Object; |
| 5 | + |
| 6 | +const dummyOptions: unknown[] = [], |
| 7 | + dummyReport = () => {}; |
| 8 | + |
| 9 | +// Define a rule. |
| 10 | +// If rule has `createOnce` method, add an ESLint-compatible `create` method which delegates to `createOnce`. |
| 11 | +export function defineRule(rule: Rule): Rule { |
| 12 | + if (!('createOnce' in rule)) return rule; |
| 13 | + if ('create' in rule) throw new Error('Rules must define only `create` or `createOnce` methods, not both'); |
| 14 | + |
| 15 | + // Run `createOnce` with empty context object. |
| 16 | + // Really, `context` should be an instance of `Context`, which would throw error on accessing e.g. `id` |
| 17 | + // in body of `createOnce`. But any such bugs should have been caught when testing the rule in Oxlint, |
| 18 | + // so should be OK to take this shortcut. |
| 19 | + const context = Object.create(null, { |
| 20 | + id: { value: '', enumerable: true, configurable: true }, |
| 21 | + options: { value: dummyOptions, enumerable: true, configurable: true }, |
| 22 | + report: { value: dummyReport, enumerable: true, configurable: true }, |
| 23 | + }); |
| 24 | + |
| 25 | + const { before: beforeHook, after: afterHook, ...visitor } = rule.createOnce(context as Context); |
| 26 | + |
| 27 | + // Add `after` hook to `Program:exit` visit fn |
| 28 | + if (afterHook !== null) { |
| 29 | + const programExit = visitor['Program:exit']; |
| 30 | + visitor['Program:exit'] = programExit |
| 31 | + ? (node) => { |
| 32 | + programExit(node); |
| 33 | + afterHook(); |
| 34 | + } |
| 35 | + : (_node) => afterHook(); |
| 36 | + } |
| 37 | + |
| 38 | + // Create `create` function |
| 39 | + rule.create = (eslintContext) => { |
| 40 | + // Copy properties from ESLint's context object to `context`. |
| 41 | + // ESLint's context object is an object of form `{ id, options, report }`, with all other properties |
| 42 | + // and methods on another object which is its prototype. |
| 43 | + defineProperty(context, 'id', { value: eslintContext.id }); |
| 44 | + defineProperty(context, 'options', { value: eslintContext.options }); |
| 45 | + defineProperty(context, 'report', { value: eslintContext.report }); |
| 46 | + setPrototypeOf(context, getPrototypeOf(eslintContext)); |
| 47 | + |
| 48 | + // If `before` hook returns `false`, skip rest of traversal by returning an empty object as visitor |
| 49 | + if (beforeHook !== null) { |
| 50 | + const shouldRun = beforeHook(); |
| 51 | + if (shouldRun === false) return {}; |
| 52 | + } |
| 53 | + |
| 54 | + // Return same visitor each time |
| 55 | + return visitor; |
| 56 | + }; |
| 57 | + |
| 58 | + return rule; |
| 59 | +} |
0 commit comments