massive update, probably broken
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / @humanwhocodes / config-array / README.md
1 # Config Array
2
3 by [Nicholas C. Zakas](https://humanwhocodes.com)
4
5 If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
6
7 ## Description
8
9 A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename. 
10
11 ## Background
12
13 In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born.
14
15 The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
16
17 ```js
18 export default [
19
20     // match all JSON files
21     {
22         name: "JSON Handler",
23         files: ["**/*.json"],
24         handler: jsonHandler
25     },
26
27     // match only package.json
28     {
29         name: "package.json Handler",
30         files: ["package.json"],
31         handler: packageJsonHandler
32     }
33 ];
34 ```
35
36 In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
37
38 ## Installation
39
40 You can install the package using npm or Yarn:
41
42 ```bash
43 npm install @humanwhocodes/config-array --save
44
45 # or
46
47 yarn add @humanwhocodes/config-array
48 ```
49
50 ## Usage
51
52 First, import the `ConfigArray` constructor:
53
54 ```js
55 import { ConfigArray } from "@humanwhocodes/config-array";
56
57 // or using CommonJS
58
59 const { ConfigArray } = require("@humanwhocodes/config-array");
60 ```
61
62 When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
63
64 ```js
65 const configFilename = path.resolve(process.cwd(), "my.config.js");
66 const { default: rawConfigs } = await import(configFilename);
67 const configs = new ConfigArray(rawConfigs, {
68     
69     // the path to match filenames from
70     basePath: process.cwd(),
71
72     // additional items in each config
73     schema: mySchema
74 });
75 ```
76
77 This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directoy in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
78
79 ### Specifying a Schema
80
81 The `schema` option is required for you to use additional properties in config objects. The schema is object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
82
83 ```js
84 const configFilename = path.resolve(process.cwd(), "my.config.js");
85 const { default: rawConfigs } = await import(configFilename);
86
87 const mySchema = {
88
89     // define the handler key in configs
90     handler: {
91         required: true,
92         merge(a, b) {
93             if (!b) return a;
94             if (!a) return b;
95         },
96         validate(value) {
97             if (typeof value !== "function") {
98                 throw new TypeError("Function expected.");
99             }
100         }
101     }
102 };
103
104 const configs = new ConfigArray(rawConfigs, {
105     
106     // the path to match filenames from
107     basePath: process.cwd(),
108
109     // additional items in each config
110     schema: mySchema
111 });
112 ```
113
114 ### Config Arrays
115
116 Config arrays can be multidimensional, so it's possible for a config array to contain another config array, such as:
117
118 ```js
119 export default [
120     
121     // JS config
122     {
123         files: ["**/*.js"],
124         handler: jsHandler
125     },
126
127     // JSON configs
128     [
129
130         // match all JSON files
131         {
132             name: "JSON Handler",
133             files: ["**/*.json"],
134             handler: jsonHandler
135         },
136
137         // match only package.json
138         {
139             name: "package.json Handler",
140             files: ["package.json"],
141             handler: packageJsonHandler
142         }
143     ],
144
145     // filename must match function
146     {
147         files: [ filePath => filePath.endsWith(".md") ],
148         handler: markdownHandler
149     },
150
151     // filename must match all patterns in subarray
152     {
153         files: [ ["*.test.*", "*.js"] ],
154         handler: jsTestHandler
155     },
156
157     // filename must not match patterns beginning with !
158     {
159         name: "Non-JS files",
160         files: ["!*.js"],
161         settings: {
162             js: false
163         }
164     }
165 ];
166 ```
167
168 In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
169
170 If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
171
172 If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
173
174 If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically getting a `settings.js` property set to `false`.
175
176 ### Config Functions
177
178 Config arrays can also include config functions. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
179
180 ```js
181 export default [
182     
183     // JS config
184     {
185         files: ["**/*.js"],
186         handler: jsHandler
187     },
188
189     // JSON configs
190     function (context) {
191         return [
192
193             // match all JSON files
194             {
195                 name: context.name + " JSON Handler",
196                 files: ["**/*.json"],
197                 handler: jsonHandler
198             },
199
200             // match only package.json
201             {
202                 name: context.name + " package.json Handler",
203                 files: ["package.json"],
204                 handler: packageJsonHandler
205             }
206         ];
207     }
208 ];
209 ```
210
211 When a config array is normalized, each function is executed and replaced in the config array with the return value.
212
213 **Note:** Config functions cannot be async. This will be added in a future version.
214
215 ### Normalizing Config Arrays
216
217 Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
218
219 To normalize a config array, call the `normalize()` method and pass in a context object:
220
221 ```js
222 await configs.normalize({
223     name: "MyApp"
224 });
225 ```
226
227 The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
228
229 **Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
230
231 ### Getting Config for a File
232
233 To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
234
235 ```js
236 // pass in absolute filename
237 const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json"));
238 ```
239
240 The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
241
242 A few things to keep in mind:
243
244 * You must pass in the absolute filename to get a config for.
245 * The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
246 * The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
247
248 ## Acknowledgements
249
250 The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
251
252 * Teddy Katz (@not-an-aardvark)
253 * Toru Nagashima (@mysticatea)
254 * Kai Cataldo (@kaicataldo)
255
256 ## License
257
258 Apache 2.0