|
12 | 12 | */ |
13 | 13 |
|
14 | 14 | /** |
15 | | - * @typedef {{ line: number; column: number; offset: number; }} Location |
16 | | - * |
| 15 | + * @typedef {{ line: number; column: number; offset: number }} Location |
17 | 16 | * |
18 | 17 | * @typedef {PrettierOptions & { |
19 | 18 | * onDiskFilepath: string; |
|
30 | 29 | * ) => string} PrettierFormat |
31 | 30 | * |
32 | 31 | * |
33 | | - * @typedef {Parameters<Exclude<ESLint.Plugin['rules'], undefined>[string]['create']>[0]} RuleContext |
| 32 | + * @typedef {Parameters< |
| 33 | + * Exclude<ESLint.Plugin['rules'], undefined>[string]['create'] |
| 34 | + * >[0]} RuleContext |
34 | 35 | */ |
35 | 36 |
|
36 | 37 | 'use strict'; |
@@ -97,15 +98,38 @@ function reportDifference(context, difference) { |
97 | 98 | // with the `sourceCode` property. |
98 | 99 | // TODO: Only use property when our eslint peerDependency is >=8.40.0. |
99 | 100 | const sourceCode = context.sourceCode ?? context.getSourceCode(); |
100 | | - if (!('text' in sourceCode)) { |
101 | | - throw new Error('prettier/prettier: non-textual source code is unsupported'); |
102 | | - } |
103 | 101 |
|
104 | | - const lineIndexes = [...sourceCode.text.matchAll(/\n/g)].map(match => match.index); |
105 | | - // first line in the file starts at byte offset 0 |
106 | | - lineIndexes.unshift(0); |
107 | | - const [start, end] = range.map(index => |
108 | | - getLocFromOffset(lineIndexes, index) |
| 102 | + const lazy = { |
| 103 | + /** |
| 104 | + * Lazily computes the line indices for `sourceCode`. |
| 105 | + * |
| 106 | + * @returns {number[]} |
| 107 | + */ |
| 108 | + get lineIndexes() { |
| 109 | + // @ts-ignore |
| 110 | + delete this.lineIndexes; |
| 111 | + |
| 112 | + if (!('text' in sourceCode)) { |
| 113 | + throw new Error( |
| 114 | + 'prettier/prettier: non-textual source code is unsupported', |
| 115 | + ); |
| 116 | + } |
| 117 | + |
| 118 | + // @ts-ignore |
| 119 | + this.lineIndexes = [...sourceCode.text.matchAll(/\n/g)].map( |
| 120 | + match => match.index, |
| 121 | + ); |
| 122 | + // first line in the file starts at byte offset 0 |
| 123 | + this.lineIndexes.unshift(0); |
| 124 | + return this.lineIndexes; |
| 125 | + }, |
| 126 | + }; |
| 127 | + |
| 128 | + const [start, end] = range.map( |
| 129 | + index => |
| 130 | + // @ts-ignore |
| 131 | + sourceCode.getLocFromIndex?.(index) ?? |
| 132 | + getLocFromOffset(lazy.lineIndexes, index), |
109 | 133 | ); |
110 | 134 |
|
111 | 135 | context.report({ |
@@ -284,7 +308,7 @@ const eslintPluginPrettier = { |
284 | 308 |
|
285 | 309 | for (const difference of differences) { |
286 | 310 | reportDifference( |
287 | | - /** @type {Rule.RuleContext} */(context), |
| 311 | + /** @type {Rule.RuleContext} */ (context), |
288 | 312 | difference, |
289 | 313 | ); |
290 | 314 | } |
|
0 commit comments