Initial commit

This commit is contained in:
Spencer Pincott
2024-07-15 22:20:13 -04:00
commit 97737ca1ae
16618 changed files with 934131 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
# CHANGELOG
The changelog is automatically updated using [semantic-release](https://github.com/semantic-release/semantic-release).
You can see it on the [releases page](../../releases).

20
themes/keepit/node_modules/babel-plugin-macros/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2017 Kent C. Dodds
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,426 @@
<p align="center">
<a href="https://codefund.io/properties/448/visit-sponsor">
<img src="https://codefund.io/properties/448/sponsor" />
</a>
</p>
<div align="center">
<h1>babel-plugin-macros 🎣</h1>
Allows you to build simple compile-time libraries
</div>
<hr />
[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![version][version-badge]][package]
[![downloads][downloads-badge]][npmchart]
[![MIT License][license-badge]][license]
[![All Contributors](https://img.shields.io/badge/all_contributors-22-orange.svg?style=flat-square)](#contributors)
[![PRs Welcome][prs-badge]][prs]
[![Donate][donate-badge]][donate]
[![Code of Conduct][coc-badge]][coc]
[![Watch on GitHub][github-watch-badge]][github-watch]
[![Star on GitHub][github-star-badge]][github-star]
[![Tweet][twitter-badge]][twitter]
## The problem
Check out <a href="https://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros" rel="nofollow">this guest post</a> on the Babel.js blog for a complete write up on the problem, motivation, and solution.
Currently, each babel plugin in the babel ecosystem requires that you configure
it individually. This is fine for things like language features, but can be
frustrating overhead for libraries that allow for compile-time code
transformation as an optimization.
## This solution
babel-plugin-macros defines a standard interface for libraries that want to use
compile-time code transformation without requiring the user to add a babel
plugin to their build system (other than `babel-plugin-macros`, which is ideally
already in place).
<details>
<summary>Expand for more details on the motivation</summary>
For instance, many css-in-js libraries have a css tagged template string
function:
```js
const styles = css`
.red {
color: red;
}
`
```
The function compiles your css into (for example) an object with generated class
names for each of the classes you defined in your css:
```js
console.log(styles) // { red: "1f-d34j8rn43y587t" }
```
This class name can be generated at runtime (in the browser), but this has some
disadvantages:
- There is cpu usage/time overhead; the client needs to run the code to generate
these classes every time the page loads
- There is code bundle size overhead; the client needs to receive a CSS parser
in order to generate these class names, and shipping this makes the amount of
js the client needs to parse larger.
To help solve those issues, many css-in-js libraries write their own babel
plugin that generates the class names at compile-time instead of runtime:
```js
// Before running through babel:
const styles = css`
.red {
color: red;
}
`
// After running through babel, with the library-specific plugin:
const styles = {red: '1f-d34j8rn43y587t'}
```
If the css-in-js library supported babel-plugin-macros instead, then they
wouldn't need their own babel plugin to compile these out; they could instead
rely on babel-plugin-macros to do it for them. So if a user already had
`babel-plugin-macros` installed and configured with babel, then they wouldn't
need to change their babel configuration to get the compile-time benefits of the
library. This would be most useful if the boilerplate they were using came with
`babel-plugin-macros` out of the box, which is true for
[`create-react-app`][cra].
Although css-in-js is the most common example, there are lots of other things
you could use `babel-plugin-macros` for, like:
- Compiling GraphQL fragments into objects so that the client doesn't need a
GraphQL parser
- Eval-ing out code at compile time that will be baked into the runtime code,
for instance to get a list of directories in the filesystem (see
[preval][preval])
</details>
## Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Installation](#installation)
- [Usage](#usage)
- [User docs](#user-docs)
- [Author docs](#author-docs)
- [Caveats](#caveats)
- [FAQ](#faq)
- [How do I find available macros?](#how-do-i-find-available-macros)
- [What's the difference between babel plugins and macros?](#whats-the-difference-between-babel-plugins-and-macros)
- [In what order are macros executed?](#in-what-order-are-macros-executed)
- [Does it work with function calls only?](#does-it-work-with-function-calls-only)
- [How about implicit optimizations at compile time?](#how-about-implicit-optimizations-at-compile-time)
- [Should macros be dependencies or devDependencies?](#should-macros-be-dependencies-or-devdependencies)
- [Inspiration](#inspiration)
- [Other Solutions](#other-solutions)
- [Contributors](#contributors)
- [LICENSE](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
This module is distributed via [npm][npm] which is bundled with [node][node] and
should be installed as one of your project's `devDependencies`:
```
npm install --save-dev babel-plugin-macros
```
## Usage
> You may like to watch
> [this YouTube video](https://www.youtube.com/watch?v=1queadQ0048&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u)
> to get an idea of what macros is and how it can be used.
### User docs
Are you trying to use `babel-plugin-macros`? Go to
[`other/docs/user.md`](other/docs/user.md).
### Author docs
Are you trying to make your own macros that works with `babel-plugin-macros`? Go to
[`other/docs/author.md`](other/docs/author.md).
(you should probably read the user docs too).
### Caveats
#### Babel cache problem
> **Note:** This issue is not present when used in Create React App.
Most of the time you'll probably be using this with the babel cache enabled in webpack to rebuild faster. If your macro function is **not pure** which gets different output with same code (e.g., IO side effects) it will cause recompile mechanism fail. Unfortunately you'll also experience this problem while developing your macro as well. If there's not a change to the source code that's being transpiled, then babel will use the cache rather than running your macro again.
For now, to force recompile the code you can simply add a cache busting comment in the file:
```diff
import macro from 'non-pure.macro';
-// Do some changes of your code or
+// add a cache busting comment to force recompile.
macro('parameters');
```
This problem is still being worked on and is not unique to `babel-plugin-macros`. For more details and workarounds, please check related issues below:
- babel-plugin-preval: [How to force recompile? #19](https://github.com/kentcdodds/babel-plugin-preval/issues/19)
- graphql.macro: [Recompile problem (babel cache) #6](https://github.com/evenchange4/graphql.macro/issues/6)
## FAQ
### How do I find available macros?
You can write your own without publishing them to `npm`, but if you'd like to
see existing macros you can add to your project, then take a look at the
[Awesome babel macros](https://github.com/jgierer12/awesome-babel-macros) repository.
Please add any you don't see listed!
### What's the difference between babel plugins and macros?
Let's use
[`babel-plugin-console`](https://www.npmjs.com/package/babel-plugin-console) as
an example.
If we used `babel-plugin-console`, it would look like this:
1. Add `babel-plugin-console` to `.babelrc`
2. Use it in a code:
```js
function add100(a) {
const oneHundred = 100
console.scope('Add 100 to another number')
return add(a, oneHundred)
}
function add(a, b) {
return a + b
}
```
When that code is run, the `scope` function does some pretty nifty things:
**Browser:**
![Browser console scoping add100](https://github.com/mattphillips/babel-plugin-console/raw/53536cba919d5be49d4f66d957769c07ca7a4207/assets/add100-chrome.gif)
**Node:**
<img alt="Node console scoping add100" src="https://github.com/mattphillips/babel-plugin-console/raw/53536cba919d5be49d4f66d957769c07ca7a4207/assets/add100-node.png" width="372">
Instead, let's use the macro it's shipped with like this:
1. Add `babel-plugin-macros` to `.babelrc` (only once for all macros)
2. Use it in a code:
```js
import scope from 'babel-plugin-console/scope.macro'
function add100(a) {
const oneHundred = 100
scope('Add 100 to another number')
return add(a, oneHundred)
}
function add(a, b) {
return a + b
}
```
The result is exactly the same, but this approach has a few advantages:
**Advantages:**
- requires only one entry in `.babelrc` for all macros used in project. Add that
once and you can use all the macros you want
- toolkits (like [create-react-app][cra]) may already support
`babel-plugin-macros`, so no configuration is needed at all
- it's explicit. With `console.scope` people may be fooled that it's just a
normal `console` API when there's really a babel transpilation going on. When
you import `scope`, it's obvious that it's macro and does something with the
code at compile time. Some ESLint rules may also have issues with plugins that
look for "global" variables
- macros are safer and easier to write, because they receive exactly the AST
node to process
- If you misconfigure `babel-plugin-console` you wont find out until you run the
code. If you misconfigure `babel-plugin-macros` you'll get a compile-time
error.
**Drawbacks:**
- Cannot (should not) be used for implicit transpilations (like syntax plugins)
- Explicitness is more verbose. Which some people might consider a drawback...
### In what order are macros executed?
This is another advantage of `babel-plugin-macros` over regular plugins. The
user of the macro is in control of the ordering! The order of execution is the
same order as imported. The order of execution is clear, explicit and in full
control of the user:
```js
import preval from 'preval.macro'
import idx from 'idx.macro'
// preval macro is evaluated first, then idx
```
This differs from the current situation with babel plugins where it's
prohibitively difficult to control the order plugins run in a particular file.
### Does it work with function calls only?
No! Any AST node type is supported.
It can be tagged template literal:
```js
import eval from 'eval.macro'
const val = eval`7 * 6`
```
A function:
```js
import eval from 'eval.macro'
const val = eval('7 * 6')
```
JSX Element:
```js
import Eval from 'eval.macro'
const val = <Eval>7 * 6</Eval>
```
Really, anything...
See the [testing snapshot](src/__tests__/__snapshots__/index.js.snap) for more examples.
### How about implicit optimizations at compile time?
All examples above were _explicit_ - a macro was imported and then evaluated
with a specific AST node.
Completely different story are _implicit_ babel plugins, like
[transform-react-constant-elements](https://babeljs.io/docs/plugins/transform-react-constant-elements/),
which process whole AST tree.
Explicit is often a better pattern than implicit because it requires others to
understand how things are globally configured. This is in this spirit are
`babel-plugin-macros` designed. However, some things _do_ need to be implicit,
and those kinds of babel plugins can't be turned into macros.
### Should macros be dependencies or devDependencies?
Macros are processed at build-time and not required at runtime. They should be devDependencies.
## Inspiration
- [threepointone/babel-plugin-macros](https://github.com/threepointone/babel-plugin-macros)
- [facebookincubator/create-react-app#2730][cra-issue]
Thank you to [@phpnode](https://github.com/phpnode) for donating the npm package
`babel-plugin-macros`.
## Other Solutions
- [sweetjs](http://sweetjs.org/)
## Contributors
Thanks goes to these people ([emoji key][emojis]):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://kentcdodds.com"><img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;" alt="Kent C. Dodds"/><br /><sub><b>Kent C. Dodds</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds" title="Code">💻</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds" title="Documentation">📖</a> <a href="#infra-kentcdodds" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=kentcdodds" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/threepointone"><img src="https://avatars1.githubusercontent.com/u/18808?v=3" width="100px;" alt="Sunil Pai"/><br /><sub><b>Sunil Pai</b></sub></a><br /><a href="#ideas-threepointone" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="http://suchipi.com"><img src="https://avatars0.githubusercontent.com/u/1341513?v=4" width="100px;" alt="Lily Scott"/><br /><sub><b>Lily Scott</b></sub></a><br /><a href="#question-suchipi" title="Answering Questions">💬</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=suchipi" title="Documentation">📖</a></td>
<td align="center"><a href="http://twitter.com/dralletje"><img src="https://avatars1.githubusercontent.com/u/767261?v=4" width="100px;" alt="Michiel Dral"/><br /><sub><b>Michiel Dral</b></sub></a><br /><a href="#ideas-dralletje" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://github.com/tkh44"><img src="https://avatars2.githubusercontent.com/u/662750?v=4" width="100px;" alt="Kye Hohenberger"/><br /><sub><b>Kye Hohenberger</b></sub></a><br /><a href="#ideas-tkh44" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://hamil.town"><img src="https://avatars1.githubusercontent.com/u/11481355?v=4" width="100px;" alt="Mitchell Hamilton"/><br /><sub><b>Mitchell Hamilton</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=mitchellhamilton" title="Code">💻</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=mitchellhamilton" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/wKovacs64"><img src="https://avatars1.githubusercontent.com/u/1288694?v=4" width="100px;" alt="Justin Hall"/><br /><sub><b>Justin Hall</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=wKovacs64" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/PiereDome"><img src="https://avatars3.githubusercontent.com/u/1903016?v=4" width="100px;" alt="Brian Pedersen"/><br /><sub><b>Brian Pedersen</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=PiereDome" title="Code">💻</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=PiereDome" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/apalm"><img src="https://avatars3.githubusercontent.com/u/4495237?v=4" width="100px;" alt="Andrew Palm"/><br /><sub><b>Andrew Palm</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=apalm" title="Code">💻</a></td>
<td align="center"><a href="https://michaelhsu.tw/"><img src="https://avatars1.githubusercontent.com/u/1527371?v=4" width="100px;" alt="Michael Hsu"/><br /><sub><b>Michael Hsu</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=evenchange4" title="Documentation">📖</a> <a href="#plugin-evenchange4" title="Plugin/utility libraries">🔌</a></td>
<td align="center"><a href="https://github.com/citycide"><img src="https://avatars2.githubusercontent.com/u/16605186?v=4" width="100px;" alt="Bo Lingen"/><br /><sub><b>Bo Lingen</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=citycide" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/tylerthehaas"><img src="https://avatars1.githubusercontent.com/u/11150235?v=4" width="100px;" alt="Tyler Haas"/><br /><sub><b>Tyler Haas</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=tylerthehaas" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/FWeinb"><img src="https://avatars0.githubusercontent.com/u/1250430?v=4" width="100px;" alt="FWeinb"/><br /><sub><b>FWeinb</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=FWeinb" title="Code">💻</a></td>
<td align="center"><a href="http://www.tomasehrlich.cz"><img src="https://avatars2.githubusercontent.com/u/827862?v=4" width="100px;" alt="Tomáš Ehrlich"/><br /><sub><b>Tomáš Ehrlich</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/issues?q=author%3Atricoder42" title="Bug reports">🐛</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=tricoder42" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/jgierer12"><img src="https://avatars0.githubusercontent.com/u/4331946?v=4" width="100px;" alt="Jonas Gierer"/><br /><sub><b>Jonas Gierer</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=jgierer12" title="Documentation">📖</a></td>
<td align="center"><a href="http://loicpadier.com"><img src="https://avatars2.githubusercontent.com/u/4009640?v=4" width="100px;" alt="Loïc Padier"/><br /><sub><b>Loïc Padier</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=lPadier" title="Code">💻</a></td>
<td align="center"><a href="https://www.pshrmn.com"><img src="https://avatars0.githubusercontent.com/u/1127037?v=4" width="100px;" alt="Paul Sherman"/><br /><sub><b>Paul Sherman</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=pshrmn" title="Code">💻</a></td>
<td align="center"><a href="http://burningpotato.com"><img src="https://avatars1.githubusercontent.com/u/540777?v=4" width="100px;" alt="Conrad Buck"/><br /><sub><b>Conrad Buck</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=conartist6" title="Code">💻</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=conartist6" title="Tests">⚠️</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=conartist6" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/InvictusMB"><img src="https://avatars3.githubusercontent.com/u/3091209?v=4" width="100px;" alt="InvictusMB"/><br /><sub><b>InvictusMB</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=InvictusMB" title="Tests">⚠️</a></td>
<td align="center"><a href="https://codefund.io"><img src="https://avatars2.githubusercontent.com/u/12481?v=4" width="100px;" alt="Eric Berry"/><br /><sub><b>Eric Berry</b></sub></a><br /><a href="#fundingFinding-coderberry" title="Funding Finding">🔍</a></td>
<td align="center"><a href="http://futagoza.github.io/"><img src="https://avatars1.githubusercontent.com/u/1943570?v=4" width="100px;" alt="Futago-za Ryuu"/><br /><sub><b>Futago-za Ryuu</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=futagoza" title="Code">💻</a> <a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=futagoza" title="Tests">⚠️</a></td>
</tr>
<tr>
<td align="center"><a href="https://luc.im"><img src="https://avatars3.githubusercontent.com/u/6616955?v=4" width="100px;" alt="Luc"/><br /><sub><b>Luc</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=lucleray" title="Code">💻</a></td>
<td align="center"><a href="http://wintercounter.me"><img src="https://avatars2.githubusercontent.com/u/963776?v=4" width="100px;" alt="Victor Vincent"/><br /><sub><b>Victor Vincent</b></sub></a><br /><a href="https://github.com/kentcdodds/babel-plugin-macros/commits?author=wintercounter" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors][all-contributors] specification.
Contributions of any kind welcome!
## LICENSE
MIT
[npm]: https://www.npmjs.com/
[node]: https://nodejs.org
[build-badge]: https://img.shields.io/travis/kentcdodds/babel-plugin-macros.svg?style=flat-square
[build]: https://travis-ci.org/kentcdodds/babel-plugin-macros
[coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/babel-plugin-macros.svg?style=flat-square
[coverage]: https://codecov.io/github/kentcdodds/babel-plugin-macros
[version-badge]: https://img.shields.io/npm/v/babel-plugin-macros.svg?style=flat-square
[package]: https://www.npmjs.com/package/babel-plugin-macros
[downloads-badge]: https://img.shields.io/npm/dm/babel-plugin-macros.svg?style=flat-square
[npmchart]: http://npmcharts.com/compare/babel-plugin-macros
[license-badge]: https://img.shields.io/npm/l/babel-plugin-macros.svg?style=flat-square
[license]: LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[donate-badge]: https://img.shields.io/badge/$-support-green.svg?style=flat-square
[donate]: http://kcd.im/donate
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: other/CODE_OF_CONDUCT.md
[github-watch-badge]: https://img.shields.io/github/watchers/kentcdodds/babel-plugin-macros.svg?style=social
[github-watch]: https://github.com/kentcdodds/babel-plugin-macros/watchers
[github-star-badge]: https://img.shields.io/github/stars/kentcdodds/babel-plugin-macros.svg?style=social
[github-star]: https://github.com/kentcdodds/babel-plugin-macros/stargazers
[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20babel-plugin-macros!%20https://github.com/kentcdodds/babel-plugin-macros%20%F0%9F%91%8D
[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/kentcdodds/babel-plugin-macros.svg?style=social
[emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
[all-contributors]: https://github.com/kentcdodds/all-contributors
[preval]: https://github.com/kentcdodds/babel-plugin-preval
[cra]: https://github.com/facebookincubator/create-react-app
[cra-issue]: https://github.com/facebookincubator/create-react-app/issues/2730

View File

@@ -0,0 +1,353 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
const p = require('path');
const resolve = require('resolve'); // const printAST = require('ast-pretty-print')
const macrosRegex = /[./]macro(\.js)?$/;
const testMacrosRegex = v => macrosRegex.test(v); // https://stackoverflow.com/a/32749533/971592
class MacroError extends Error {
constructor(message) {
super(message);
this.name = 'MacroError';
/* istanbul ignore else */
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else if (!this.stack) {
this.stack = new Error(message).stack;
}
}
}
let _configExplorer = null;
function getConfigExporer() {
return _configExplorer = _configExplorer || // Lazy load cosmiconfig since it is a relatively large bundle
require('cosmiconfig').cosmiconfigSync('babel-plugin-macros', {
searchPlaces: ['package.json', '.babel-plugin-macrosrc', '.babel-plugin-macrosrc.json', '.babel-plugin-macrosrc.yaml', '.babel-plugin-macrosrc.yml', '.babel-plugin-macrosrc.js', 'babel-plugin-macros.config.js'],
packageProp: 'babelMacros'
});
}
function createMacro(macro, options = {}) {
if (options.configName === 'options') {
throw new Error(`You cannot use the configName "options". It is reserved for babel-plugin-macros.`);
}
macroWrapper.isBabelMacro = true;
macroWrapper.options = options;
return macroWrapper;
function macroWrapper(args) {
const {
source,
isBabelMacrosCall
} = args;
if (!isBabelMacrosCall) {
throw new MacroError(`The macro you imported from "${source}" is being executed outside the context of compilation with babel-plugin-macros. ` + `This indicates that you don't have the babel plugin "babel-plugin-macros" configured correctly. ` + `Please see the documentation for how to configure babel-plugin-macros properly: ` + 'https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md');
}
return macro(args);
}
}
function nodeResolvePath(source, basedir) {
return resolve.sync(source, {
basedir,
// This is here to support the package being globally installed
// read more: https://github.com/kentcdodds/babel-plugin-macros/pull/138
paths: [p.resolve(__dirname, '../../')]
});
}
function macrosPlugin(babel, _ref = {}) {
let {
require: _require = require,
resolvePath = nodeResolvePath,
isMacrosName = testMacrosRegex
} = _ref,
options = (0, _objectWithoutPropertiesLoose2.default)(_ref, ["require", "resolvePath", "isMacrosName"]);
function interopRequire(path) {
// eslint-disable-next-line import/no-dynamic-require
const o = _require(path);
return o && o.__esModule && o.default ? o.default : o;
}
return {
name: 'macros',
visitor: {
Program(progPath, state) {
progPath.traverse({
ImportDeclaration(path) {
const isMacros = looksLike(path, {
node: {
source: {
value: v => isMacrosName(v)
}
}
});
if (!isMacros) {
return;
}
const imports = path.node.specifiers.map(s => ({
localName: s.local.name,
importedName: s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
}));
const source = path.node.source.value;
const result = applyMacros({
path,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
});
if (!result || !result.keepImports) {
path.remove();
}
},
VariableDeclaration(path) {
const isMacros = child => looksLike(child, {
node: {
init: {
callee: {
type: 'Identifier',
name: 'require'
},
arguments: args => args.length === 1 && isMacrosName(args[0].value)
}
}
});
path.get('declarations').filter(isMacros).forEach(child => {
const imports = child.node.id.name ? [{
localName: child.node.id.name,
importedName: 'default'
}] : child.node.id.properties.map(property => ({
localName: property.value.name,
importedName: property.key.name
}));
const call = child.get('init');
const source = call.node.arguments[0].value;
const result = applyMacros({
path: call,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
});
if (!result || !result.keepImports) {
child.remove();
}
});
}
});
}
}
};
} // eslint-disable-next-line complexity
function applyMacros({
path,
imports,
source,
state,
babel,
interopRequire,
resolvePath,
options
}) {
/* istanbul ignore next (pretty much only useful for astexplorer I think) */
const {
file: {
opts: {
filename = ''
}
}
} = state;
let hasReferences = false;
const referencePathsByImportName = imports.reduce((byName, {
importedName,
localName
}) => {
const binding = path.scope.getBinding(localName);
byName[importedName] = binding.referencePaths;
hasReferences = hasReferences || Boolean(byName[importedName].length);
return byName;
}, {});
const isRelative = source.indexOf('.') === 0;
const requirePath = resolvePath(source, p.dirname(getFullFilename(filename)));
const macro = interopRequire(requirePath);
if (!macro.isBabelMacro) {
throw new Error(`The macro imported from "${source}" must be wrapped in "createMacro" ` + `which you can get from "babel-plugin-macros". ` + `Please refer to the documentation to see how to do this properly: https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/author.md#writing-a-macro`);
}
const config = getConfig(macro, filename, source, options);
let result;
try {
/**
* Other plugins that run before babel-plugin-macros might use path.replace, where a path is
* put into its own replacement. Apparently babel does not update the scope after such
* an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
* visitor - this makes the problem go away.
*
* See: https://github.com/kentcdodds/import-all.macro/issues/7
*/
state.file.scope.path.traverse({
Identifier() {}
});
result = macro({
references: referencePathsByImportName,
source,
state,
babel,
config,
isBabelMacrosCall: true
});
} catch (error) {
if (error.name === 'MacroError') {
throw error;
}
error.message = `${source}: ${error.message}`;
if (!isRelative) {
error.message = `${error.message} Learn more: https://www.npmjs.com/package/${source.replace( // remove everything after package name
// @org/package/macro -> @org/package
// package/macro -> package
/^((?:@[^/]+\/)?[^/]+).*/, '$1')}`;
}
throw error;
}
return result;
}
function getConfigFromFile(configName, filename) {
try {
const loaded = getConfigExporer().search(filename);
if (loaded) {
return {
options: loaded.config[configName],
path: loaded.filepath
};
}
} catch (e) {
return {
error: e
};
}
return {};
}
function getConfigFromOptions(configName, options) {
if (options.hasOwnProperty(configName)) {
if (options[configName] && typeof options[configName] !== 'object') {
// eslint-disable-next-line no-console
console.error(`The macro plugin options' ${configName} property was not an object or null.`);
} else {
return {
options: options[configName]
};
}
}
return {};
}
function getConfig(macro, filename, source, options) {
const {
configName
} = macro.options;
if (configName) {
const fileConfig = getConfigFromFile(configName, filename);
const optionsConfig = getConfigFromOptions(configName, options);
if (optionsConfig.options === undefined && fileConfig.options === undefined && fileConfig.error !== undefined) {
// eslint-disable-next-line no-console
console.error(`There was an error trying to load the config "${configName}" ` + `for the macro imported from "${source}. ` + `Please see the error thrown for more information.`);
throw fileConfig.error;
}
if (fileConfig.options !== undefined && optionsConfig.options !== undefined && typeof fileConfig.options !== 'object') {
throw new Error(`${fileConfig.path} specified a ${configName} config of type ` + `${typeof optionsConfig.options}, but the the macros plugin's ` + `options.${configName} did contain an object. Both configs must ` + `contain objects for their options to be mergeable.`);
}
return (0, _extends2.default)({}, optionsConfig.options, {}, fileConfig.options);
}
return undefined;
}
/*
istanbul ignore next
because this is hard to test
and not worth it...
*/
function getFullFilename(filename) {
if (p.isAbsolute(filename)) {
return filename;
}
return p.join(process.cwd(), filename);
}
function looksLike(a, b) {
return a && b && Object.keys(b).every(bKey => {
const bVal = b[bKey];
const aVal = a[bKey];
if (typeof bVal === 'function') {
return bVal(aVal);
}
return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal);
});
}
function isPrimitive(val) {
// eslint-disable-next-line
return val == null || /^[sbn]/.test(typeof val);
}
module.exports = macrosPlugin;
Object.assign(module.exports, {
createMacro,
MacroError
});

View File

@@ -0,0 +1,196 @@
# Changelog
## 6.0.0
- **Breaking change:** The package now has named exports. See examples below.
- **Breaking change:** Separate async and sync APIs, accessible from different named exports. If you used `explorer.searchSync()` or `explorer.loadSync()`, you'll now create a sync explorer with `cosmiconfigSync()`, then use `explorerSync.search()` and `explorerSync.load()`.
```js
// OLD: cosmiconfig v5
import cosmiconfig from 'cosmiconfig';
const explorer = cosmiconfig('example');
const searchAsyncResult = await explorer.search();
const loadAsyncResult = await explorer.load('./file/to/load');
const searchSyncResult = explorer.searchSync();
const loadSyncResult = explorer.loadSync('./file/to/load');
// NEW: cosmiconfig v6
import { cosmiconfig, cosmiconfigSync } from 'cosmiconfig';
const explorer = cosmiconfig('example');
const searchAsyncResult = await explorer.search();
const loadAsyncResult = await explorer.load('./file/to/load');
const explorerSync = cosmiconfigSync('example');
const searchSyncResult = explorerSync.search();
const loadSyncResult = explorerSync.load('./file/to/load');
```
- **Breaking change:** Remove support for Node 4 and 6. Requires Node 8+.
- **Breaking change:** Use npm package [yaml](https://www.npmjs.com/package/yaml) to parse YAML instead of npm package [js-yaml](https://www.npmjs.com/package/js-yaml).
- **Breaking change:** Remove `cosmiconfig.loaders` and add named export `defaultLoaders` that exports the default loaders used for each extension.
```js
import { defaultLoaders } from 'cosmiconfig';
console.log(Object.entries(defaultLoaders))
// [
// [ '.js', [Function: loadJs] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: loadYaml] ]
// ]
```
- Migrate from Flowtype to Typescript.
- Lazy load all default loaders.
## 5.2.1
- Chore: Upgrade `js-yaml` to avoid npm audit warning.
## 5.2.0
- Added: `packageProp` values can be arrays of strings, to allow for property names that include periods. (This was possible before, but not documented or deliberately supported.)
- Chore: Replaced the `lodash.get` dependency with a locally defined function.
- Chore: Upgrade `js-yaml` to avoid npm audit warning.
## 5.1.0
- Added: `packageProp` values can include periods to describe paths to nested objects within `package.json`.
## 5.0.7
- Fixed: JS loader bypasses Node's `require` cache, fixing a bug where updates to `.js` config files would not load even when Cosmiconfig was told not to cache.
## 5.0.6
- Fixed: Better error message if the end user tries an extension Cosmiconfig is not configured to understand.
## 5.0.5
- Fixed: `load` and `loadSync` work with paths relative to `process.cwd()`.
## 5.0.4
- Fixed: `rc` files with `.js` extensions included in default `searchPlaces`.
## 5.0.3
- Docs: Minor corrections to documentation. *Released to update package documentation on npm*.
## 5.0.2
- Fixed: Allow `searchSync` and `loadSync` to load JS configuration files whose export is a Promise.
## 5.0.1
The API has been completely revamped to increase clarity and enable a very wide range of new usage. **Please read the readme for all the details.**
While the defaults remain just as useful as before — and you can still pass no options at all — now you can also do all kinds of wild and crazy things.
- The `loaders` option allows you specify custom functions to derive config objects from files. Your loader functions could parse ES2015 modules or TypeScript, JSON5, even INI or XML. Whatever suits you.
- The `searchPlaces` option allows you to specify exactly where cosmiconfig looks within each directory it searches.
- The combination of `loaders` and `searchPlaces` means that you should be able to load pretty much any kind of configuration file you want, from wherever you want it to look.
Additionally, the overloaded `load()` function has been split up into several clear and focused functions:
- `search()` now searches up the directory tree, and `load()` loads a configuration file that you don't need to search for.
- The `sync` option has been replaced with separate synchronous functions: `searchSync()` and `loadSync()`.
- `clearFileCache()` and `clearDirectoryCache()` have been renamed to `clearLoadCache()` and `clearSearchPath()` respectively.
More details:
- The default JS loader uses `require`, instead of `require-from-string`. So you *could* use `require` hooks to control the loading of JS files (e.g. pass them through esm or Babel). In most cases it is probably preferable to use a custom loader.
- The options `rc`, `js`, and `rcExtensions` have all been removed. You can accomplish the same and more with `searchPlaces`.
- The default `searchPlaces` include `rc` files with extensions, e.g. `.thingrc.json`, `.thingrc.yaml`, `.thingrc.yml`. This is the equivalent of switching the default value of the old `rcExtensions` option to `true`.
- The option `rcStrictJson` has been removed. To get the same effect, you can specify `noExt: cosmiconfig.loadJson` in your `loaders` object.
- `packageProp` no longer accepts `false`. If you don't want to look in `package.json`, write a `searchPlaces` array that does not include it.
- By default, empty files are ignored by `search()`. The new option `ignoreEmptySearchPlaces` allows you to load them, instead, in case you want to do something with empty files.
- The option `configPath` has been removed. Just pass your filepaths directory to `load()`.
- Removed the `format` option. Formats are now all handled via the file extensions specified in `loaders`.
(If you're wondering with happened to 5.0.0 ... it was a silly publishing mistake.)
## 4.0.0
- Licensing improvement: updated `parse-json` from `3.0.0` to `4.0.0`(see [sindresorhus/parse-json#12][parse-json-pr-12]).
- Changed: error message format for `JSON` parse errors(see [#101][pr-101]). If you were relying on the format of JSON-parsing error messages, this will be a breaking change for you.
- Changed: set default for `searchPath` as `process.cwd()` in `explorer.load`.
## 3.1.0
- Added: infer format based on filePath
## 3.0.1
- Fixed: memory leak due to bug in `require-from-string`.
- Added: for JSON files, append position to end of error message.
## 3.0.0
- Removed: support for loading config path using the `--config` flag. cosmiconfig will not parse command line arguments. Your application can parse command line arguments and pass them to cosmiconfig.
- Removed: `argv` config option.
- Removed: support for Node versions &lt; 4.
- Added: `sync` option.
- Fixed: Throw a clear error on getting empty config file.
- Fixed: when a `options.configPath` is `package.json`, return the package prop, not the entire JSON file.
## 2.2.2
- Fixed: `options.configPath` and `--config` flag are respected.
## 2.2.0, 2.2.1
- 2.2.0 included a number of improvements but somehow broke stylelint. The changes were reverted in 2.2.1, to be restored later.
## 2.1.3
- Licensing improvement: switched from `json-parse-helpfulerror` to `parse-json`.
## 2.1.2
- Fixed: bug where an `ENOENT` error would be thrown is `searchPath` referenced a non-existent file.
- Fixed: JSON parsing errors in Node v7.
## 2.1.1
- Fixed: swapped `graceful-fs` for regular `fs`, fixing a garbage collection problem.
## 2.1.0
- Added: Node 0.12 support.
## 2.0.2
- Fixed: Node version specified in `package.json`.
## 2.0.1
- Fixed: no more infinite loop in Windows.
## 2.0.0
- Changed: module now creates cosmiconfig instances with `load` methods (see README).
- Added: caching (enabled by the change above).
- Removed: support for Node versions &lt;4.
## 1.1.0
- Add `rcExtensions` option.
## 1.0.2
- Fix handling of `require()`'s within JS module configs.
## 1.0.1
- Switch Promise implementation to pinkie-promise.
## 1.0.0
- Initial release.
[parse-json-pr-12]: https://github.com/sindresorhus/parse-json/pull/12
[pr-101]: https://github.com/davidtheclark/cosmiconfig/pull/101

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 David Clark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,576 @@
# cosmiconfig
[![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/master.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/master.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/master)
[![codecov](https://codecov.io/gh/davidtheclark/cosmiconfig/branch/master/graph/badge.svg)](https://codecov.io/gh/davidtheclark/cosmiconfig)
Cosmiconfig searches for and loads configuration for your program.
It features smart defaults based on conventional expectations in the JavaScript ecosystem.
But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
- a `package.json` property
- a JSON or YAML, extensionless "rc file"
- an "rc file" with the extensions `.json`, `.yaml`, `.yml`, or `.js`.
- a `.config.js` CommonJS module
For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
- a `myapp` property in `package.json`
- a `.myapprc` file in JSON or YAML format
- a `.myapprc.json` file
- a `.myapprc.yaml`, `.myapprc.yml`, or `.myapprc.js` file
- a `myapp.config.js` file exporting a JS object
Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).
👀 **Looking for the v5 docs?**
v6 involves slight changes to Cosmiconfig's API, clarifying the difference between synchronous and asynchronous usage.
If you have trouble switching from v5 to v6, please file an issue.
If you are still using v5, those v5 docs are available [in the `5.x.x` tagged code](https://github.com/davidtheclark/cosmiconfig/tree/5.2.1).
## Table of contents
- [Installation](#installation)
- [Usage](#usage)
- [Result](#result)
- [Asynchronous API](#asynchronous-api)
- [cosmiconfig()](#cosmiconfig)
- [explorer.search()](#explorersearch)
- [explorer.load()](#explorerload)
- [explorer.clearLoadCache()](#explorerclearloadcache)
- [explorer.clearSearchCache()](#explorerclearsearchcache)
- [explorer.clearCaches()](#explorerclearcaches)
- [Synchronsous API](#synchronsous-api)
- [cosmiconfigSync()](#cosmiconfigsync)
- [explorerSync.search()](#explorersyncsearch)
- [explorerSync.load()](#explorersyncload)
- [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
- [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
- [explorerSync.clearCaches()](#explorersyncclearcaches)
- [cosmiconfigOptions](#cosmiconfigoptions)
- [searchPlaces](#searchplaces)
- [loaders](#loaders)
- [packageProp](#packageprop)
- [stopDir](#stopdir)
- [cache](#cache)
- [transform](#transform)
- [ignoreEmptySearchPlaces](#ignoreemptysearchplaces)
- [Caching](#caching)
- [Differences from rc](#differences-from-rc)
- [Contributing & Development](#contributing--development)
## Installation
```
npm install cosmiconfig
```
Tested in Node 8+.
## Usage
Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
```js
const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
// ...
const explorer = cosmiconfig(moduleName);
// Search for a configuration by walking up directories.
// See documentation for search, below.
explorer.search()
.then((result) => {
// result.config is the parsed configuration object.
// result.filepath is the path to the config file that was found.
// result.isEmpty is true if there was nothing to parse in the config file.
})
.catch((error) => {
// Do something constructive.
});
// Load a configuration directly when you know where it should be.
// The result object is the same as for search.
// See documentation for load, below.
explorer.load(pathToConfig).then(..);
// You can also search and load synchronously.
const explorerSync = cosmiconfigSync(moduleName);
const searchedFor = explorerSync.search();
const loaded = explorerSync.load(pathToConfig);
```
## Result
The result object you get from `search` or `load` has the following properties:
- **config:** The parsed configuration object. `undefined` if the file is empty.
- **filepath:** The path to the configuration file that was found.
- **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
## Asynchronous API
### cosmiconfig()
```js
const { cosmiconfig } = require('cosmiconfig');
const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
```
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
#### moduleName
Type: `string`. **Required.**
Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
If your [`searchPlaces`] value will include files, as it does by default (e.g. `${moduleName}rc`), your `moduleName` must consist of characters allowed in filenames. That means you should not copy scoped package names, such as `@my-org/my-package`, directly into `moduleName`.
**[`cosmiconfigOptions`] are documented below.**
You may not need them, and should first read about the functions you'll use.
### explorer.search()
```js
explorer.search([searchFrom]).then(result => {..})
```
Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
You can do the same thing synchronously with [`explorerSync.search()`].
Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
Here's how your default [`search()`] will work:
- Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
1. A `goldengrahams` property in a `package.json` file.
2. A `.goldengrahamsrc` file with JSON or YAML syntax.
3. A `.goldengrahamsrc.json` file.
4. A `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, or `.goldengrahamsrc.js` file.
5. A `goldengrahams.config.js` JS file exporting the object.
- If none of those searches reveal a configuration object, move up one directory level and try again.
So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
- If at any point a parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `null` is returned).
- If a configuration object is found *but is malformed* (causing a parsing error), the [`search()`] Promise rejects with that error (so you should `.catch()` it). (Or, with [`explorerSync.search()`], the error is thrown.)
**If you know exactly where your configuration file should be, you can use [`load()`], instead.**
**The search process is highly customizable.**
Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
#### searchFrom
Type: `string`.
Default: `process.cwd()`.
A filename.
[`search()`] will start its search here.
If the value is a directory, that's where the search starts.
If it's a file, the search starts in that file's directory.
### explorer.load()
```js
explorer.load(loadPath).then(result => {..})
```
Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded).
Use `load` if you already know where the configuration file is and you just need to load it.
```js
explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
```
If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
You can do the same thing synchronously with [`explorerSync.load()`].
### explorer.clearLoadCache()
Clears the cache used in [`load()`].
### explorer.clearSearchCache()
Clears the cache used in [`search()`].
### explorer.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## Synchronsous API
### cosmiconfigSync()
```js
const { cosmiconfigSync } = require('cosmiconfig');
const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
```
Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
See [`cosmiconfig()`].
### explorerSync.search()
```js
const result = explorerSync.search([searchFrom]);
```
Synchronous version of [`explorer.search()`].
Returns a [result] or `null`.
### explorerSync.load()
```js
const result = explorerSync.load(loadPath);
```
Synchronous version of [`explorer.load()`].
Returns a [result].
### explorerSync.clearLoadCache()
Clears the cache used in [`load()`].
### explorerSync.clearSearchCache()
Clears the cache used in [`search()`].
### explorerSync.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## cosmiconfigOptions
Type: `Object`.
Possible options are documented below.
### searchPlaces
Type: `Array<string>`.
Default: See below.
An array of places that [`search()`] will check in each directory as it moves up the directory tree.
Each place is relative to the directory being searched, and the places are checked in the specified order.
**Default `searchPlaces`:**
```js
[
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`${moduleName}.config.js`,
]
```
Create your own array to search more, fewer, or altogether different places.
Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
(Common extensions are covered by default loaders.)
Read more about [`loaders`] below.
`package.json` is a special value: When it is included in `searchPlaces`, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file.
That property is defined with the [`packageProp`] option, and defaults to your module name.
Examples, with a module named `porgy`:
```js
// Disallow extensions on rc files:
[
'package.json',
'.porgyrc',
'porgy.config.js'
]
// ESLint searches for configuration in these places:
[
'.eslintrc.js',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc',
'package.json'
]
// Babel looks in fewer places:
[
'package.json',
'.babelrc'
]
// Maybe you want to look for a wide variety of JS flavors:
[
'porgy.config.js',
'porgy.config.mjs',
'porgy.config.ts',
'porgy.config.coffee'
]
// ^^ You will need to designate custom loaders to tell
// Cosmiconfig how to handle these special JS flavors.
// Look within a .config/ subdirectory of every searched directory:
[
'package.json',
'.porgyrc',
'.config/.porgyrc',
'.porgyrc.json',
'.config/.porgyrc.json'
]
```
### loaders
Type: `Object`.
Default: See below.
An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
Cosmiconfig exposes its default loaders on a named export `defaultLoaders`.
**Default `loaders`:**
```js
const { defaultLoaders } = require('cosmiconfig');
console.log(Object.entries(defaultLoaders))
// [
// [ '.js', [Function: loadJs] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: loadYaml] ]
// ]
```
(YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML *or* JSON with only one parser.)
**If you provide a `loaders` object, your object will be *merged* with the defaults.**
So you can override one or two without having to override them all.
**Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.myapprc`.
**Values in `loaders`** are a loader function (described below) whose values are loader functions.
**The most common use case for custom loaders value is to load extensionless `rc` files as strict JSON**, instead of JSON *or* YAML (the default).
To accomplish that, provide the following `loaders` value:
```js
{
noExt: defaultLoaders['.json']
}
```
If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists.
**Third-party loaders:**
- [@endemolshinegroup/cosmiconfig-typescript-loader](https://github.com/EndemolShineGroup/cosmiconfig-typescript-loader)
**Use cases for custom loader function:**
- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
- Allow ES2015 modules from `.mjs` configuration files.
- Parse JS files with Babel before deriving the configuration.
**Custom loader functions** have the following signature:
```js
// Sync
(filepath: string, content: string) => Object | null
// Async
(filepath: string, content: string) => Object | null | Promise<Object | null>
```
Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
Do whatever you need to, and return either a configuration object or `null` (or, for async-only loaders, a Promise that resolves with one of those).
`null` indicates that no real configuration was found and the search should continue.
A few things to note:
- If you use a custom loader, be aware of whether it's sync or async: you cannot use async customer loaders with the sync API ([`cosmiconfigSync()`]).
- **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
Whether you use custom loaders or a `require` hook is up to you.
Examples:
```js
// Allow JSON5 syntax:
{
'.json': json5Loader
}
// Allow a special configuration syntax of your own creation:
{
'.special': specialLoader
}
// Allow many flavors of JS, using custom loaders:
{
'.mjs': esmLoader,
'.ts': typeScriptLoader,
'.coffee': coffeeScriptLoader
}
// Allow many flavors of JS but rely on require hooks:
{
'.mjs': defaultLoaders['.js'],
'.ts': defaultLoaders['.js'],
'.coffee': defaultLoaders['.js']
}
```
### packageProp
Type: `string | Array<string>`.
Default: `` `${moduleName}` ``.
Name of the property in `package.json` to look for.
Use a period-delimited string or an array of strings to describe a path to nested properties.
For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this:
```json
{
"configs": {
"myPackage": {..}
}
}
```
If nested property names within the path include periods, you need to use an array of strings. For example, the value `['configs', 'foo.bar', 'baz']` will get you the `"baz"` value in a `package.json` like this:
```json
{
"configs": {
"foo.bar": {
"baz": {..}
}
}
}
```
If a string includes period but corresponds to a top-level property name, it will not be interpreted as a period-delimited path. For example, the value `'one.two'` will get you the `"three"` value in a `package.json` like this:
```json
{
"one.two": "three",
"one": {
"two": "four"
}
}
```
### stopDir
Type: `string`.
Default: Absolute path to your home directory.
Directory where the search will stop.
### cache
Type: `boolean`.
Default: `true`.
If `false`, no caches will be used.
Read more about ["Caching"](#caching) below.
### transform
Type: `(Result) => Promise<Result> | Result`.
A function that transforms the parsed configuration. Receives the [result].
If using [`search()`] or [`load()`] \(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
If using `cosmiconfigSync`, [`search()`] or [`load()`], the function must be synchronous and return the transformed result.
The reason you might use this option — instead of simply applying your transform function some other way — is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded.
### ignoreEmptySearchPlaces
Type: `boolean`.
Default: `true`.
By default, if [`search()`] encounters an empty file (containing nothing but whitespace) in one of the [`searchPlaces`], it will ignore the empty file and move on.
If you'd like to load empty configuration files, instead, set this option to `false`.
Why might you want to load empty configuration files?
If you want to throw an error, or if an empty configuration file means something to your program.
## Caching
As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches.
To avoid or work around caching, you can do the following:
- Set the `cosmiconfig` option [`cache`] to `false`.
- Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
- Create separate instances of cosmiconfig (separate "explorers").
## Differences from [rc](https://github.com/dominictarr/rc)
[rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
- Built-in support for JSON, YAML, and CommonJS formats.
- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
- Options.
- Asynchronous by default (though can be run synchronously).
## Contributing & Development
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
And please do participate!
[result]: #result
[`load()`]: #explorerload
[`search()`]: #explorersearch
[`clearloadcache()`]: #explorerclearloadcache
[`clearsearchcache()`]: #explorerclearsearchcache
[`cosmiconfig()`]: #cosmiconfig
[`cosmiconfigSync()`]: #cosmiconfigsync
[`clearcaches()`]: #explorerclearcaches
[`packageprop`]: #packageprop
[`cache`]: #cache
[`stopdir`]: #stopdir
[`searchplaces`]: #searchplaces
[`loaders`]: #loaders
[`cosmiconfigoptions`]: #cosmiconfigoptions
[`explorerSync.search()`]: #explorersyncsearch
[`explorerSync.load()`]: #explorersyncload
[`explorer.search()`]: #explorersearch
[`explorer.load()`]: #explorerload

View File

@@ -0,0 +1,14 @@
import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptions } from './types';
declare class Explorer extends ExplorerBase<ExplorerOptions> {
constructor(options: ExplorerOptions);
search(searchFrom?: string): Promise<CosmiconfigResult>;
private searchFromDirectory;
private searchDirectory;
private loadSearchPlace;
private loadFileContent;
private createCosmiconfigResult;
load(filepath: string): Promise<CosmiconfigResult>;
}
export { Explorer };
//# sourceMappingURL=Explorer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Explorer.d.ts","sourceRoot":"","sources":["../src/Explorer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI9C,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAqB,MAAM,SAAS,CAAC;AAEhF,cAAM,QAAS,SAAQ,YAAY,CAAC,eAAe,CAAC;gBAC/B,OAAO,EAAE,eAAe;IAI9B,MAAM,CACjB,UAAU,GAAE,MAAsB,GACjC,OAAO,CAAC,iBAAiB,CAAC;YAOf,mBAAmB;YAuBnB,eAAe;YAaf,eAAe;YAYf,eAAe;YAef,uBAAuB;IAUxB,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;CAyBhE;AAED,OAAO,EAAE,QAAQ,EAAE,CAAC"}

View File

@@ -0,0 +1,141 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Explorer = void 0;
var _path = _interopRequireDefault(require("path"));
var _ExplorerBase = require("./ExplorerBase");
var _readFile = require("./readFile");
var _cacheWrapper = require("./cacheWrapper");
var _getDirectory = require("./getDirectory");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncIterator(iterable) { var method; if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator]; if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator]; if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); }
class Explorer extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
async search(searchFrom = process.cwd()) {
const startDirectory = await (0, _getDirectory.getDirectory)(searchFrom);
const result = await this.searchFromDirectory(startDirectory);
return result;
}
async searchFromDirectory(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = async () => {
const result = await this.searchDirectory(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectory(nextDir);
}
const transformResult = await this.config.transform(result);
return transformResult;
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapper)(this.searchCache, absoluteDir, run);
}
return run();
}
async searchDirectory(dir) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError;
try {
for (var _iterator = _asyncIterator(this.config.searchPlaces), _step, _value; _step = await _iterator.next(), _iteratorNormalCompletion = _step.done, _value = await _step.value, !_iteratorNormalCompletion; _iteratorNormalCompletion = true) {
const place = _value;
const placeResult = await this.loadSearchPlace(dir, place);
if (this.shouldSearchStopWithResult(placeResult) === true) {
return placeResult;
}
} // config not found
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
await _iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return null;
}
async loadSearchPlace(dir, place) {
const filepath = _path.default.join(dir, place);
const fileContents = await (0, _readFile.readFile)(filepath);
const result = await this.createCosmiconfigResult(filepath, fileContents);
return result;
}
async loadFileContent(filepath, content) {
if (content === null) {
return null;
}
if (content.trim() === '') {
return undefined;
}
const loader = this.getLoaderEntryForFile(filepath);
const loaderResult = await loader(filepath, content);
return loaderResult;
}
async createCosmiconfigResult(filepath, content) {
const fileContent = await this.loadFileContent(filepath, content);
const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
return result;
}
async load(filepath) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoad = async () => {
const fileContents = await (0, _readFile.readFile)(absoluteFilePath, {
throwNotFound: true
});
const result = await this.createCosmiconfigResult(absoluteFilePath, fileContents);
const transformResult = await this.config.transform(result);
return transformResult;
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapper)(this.loadCache, absoluteFilePath, runLoad);
}
return runLoad();
}
}
exports.Explorer = Explorer;
//# sourceMappingURL=Explorer.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import { CosmiconfigResult, ExplorerOptions, ExplorerOptionsSync, Cache, LoadedFileContent } from './types';
import { Loader } from './index';
declare class ExplorerBase<T extends ExplorerOptions | ExplorerOptionsSync> {
protected readonly loadCache?: Cache;
protected readonly searchCache?: Cache;
protected readonly config: T;
constructor(options: T);
clearLoadCache(): void;
clearSearchCache(): void;
clearCaches(): void;
private validateConfig;
protected shouldSearchStopWithResult(result: CosmiconfigResult): boolean;
protected nextDirectoryToSearch(currentDir: string, currentResult: CosmiconfigResult): string | null;
private loadPackageProp;
protected getLoaderEntryForFile(filepath: string): Loader;
protected loadedContentToCosmiconfigResult(filepath: string, loadedContent: LoadedFileContent): CosmiconfigResult;
protected validateFilePath(filepath: string): void;
}
declare function getExtensionDescription(filepath: string): string;
export { ExplorerBase, getExtensionDescription };
//# sourceMappingURL=ExplorerBase.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerBase.d.ts","sourceRoot":"","sources":["../src/ExplorerBase.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACnB,KAAK,EACL,iBAAiB,EAClB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,cAAM,YAAY,CAAC,CAAC,SAAS,eAAe,GAAG,mBAAmB;IAChE,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;IACrC,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC;IACvC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBAEV,OAAO,EAAE,CAAC;IAUtB,cAAc,IAAI,IAAI;IAMtB,gBAAgB,IAAI,IAAI;IAMxB,WAAW,IAAI,IAAI;IAK1B,OAAO,CAAC,cAAc;IAwBtB,SAAS,CAAC,0BAA0B,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO;IAMxE,SAAS,CAAC,qBAAqB,CAC7B,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,iBAAiB,GAC/B,MAAM,GAAG,IAAI;IAWhB,OAAO,CAAC,eAAe;IASvB,SAAS,CAAC,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;IAmBzD,SAAS,CAAC,gCAAgC,CACxC,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,iBAAiB,GAC/B,iBAAiB;IAUpB,SAAS,CAAC,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;CAKnD;AAMD,iBAAS,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGzD;AAED,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,CAAC"}

View File

@@ -0,0 +1,142 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getExtensionDescription = getExtensionDescription;
exports.ExplorerBase = void 0;
var _path = _interopRequireDefault(require("path"));
var _loaders = require("./loaders");
var _getPropertyByPath = require("./getPropertyByPath");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExplorerBase {
constructor(options) {
if (options.cache === true) {
this.loadCache = new Map();
this.searchCache = new Map();
}
this.config = options;
this.validateConfig();
}
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
}
}
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
}
}
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
validateConfig() {
const config = this.config;
config.searchPlaces.forEach(place => {
const loaderKey = _path.default.extname(place) || 'noExt';
const loader = config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
}
if (typeof loader !== 'function') {
throw new Error(`loader for ${getExtensionDescription(place)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
}
});
}
shouldSearchStopWithResult(result) {
if (result === null) return false;
if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
return true;
}
nextDirectoryToSearch(currentDir, currentResult) {
if (this.shouldSearchStopWithResult(currentResult)) {
return null;
}
const nextDir = nextDirUp(currentDir);
if (nextDir === currentDir || currentDir === this.config.stopDir) {
return null;
}
return nextDir;
}
loadPackageProp(filepath, content) {
const parsedContent = _loaders.loaders.loadJson(filepath, content);
const packagePropValue = (0, _getPropertyByPath.getPropertyByPath)(parsedContent, this.config.packageProp);
return packagePropValue || null;
}
getLoaderEntryForFile(filepath) {
if (_path.default.basename(filepath) === 'package.json') {
const loader = this.loadPackageProp.bind(this);
return loader;
}
const loaderKey = _path.default.extname(filepath) || 'noExt';
const loader = this.config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(filepath)}`);
}
return loader;
}
loadedContentToCosmiconfigResult(filepath, loadedContent) {
if (loadedContent === null) {
return null;
}
if (loadedContent === undefined) {
return {
filepath,
config: undefined,
isEmpty: true
};
}
return {
config: loadedContent,
filepath
};
}
validateFilePath(filepath) {
if (!filepath) {
throw new Error('load must pass a non-empty string');
}
}
}
exports.ExplorerBase = ExplorerBase;
function nextDirUp(dir) {
return _path.default.dirname(dir);
}
function getExtensionDescription(filepath) {
const ext = _path.default.extname(filepath);
return ext ? `extension "${ext}"` : 'files without extensions';
}
//# sourceMappingURL=ExplorerBase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptionsSync } from './types';
declare class ExplorerSync extends ExplorerBase<ExplorerOptionsSync> {
constructor(options: ExplorerOptionsSync);
searchSync(searchFrom?: string): CosmiconfigResult;
private searchFromDirectorySync;
private searchDirectorySync;
private loadSearchPlaceSync;
private loadFileContentSync;
private createCosmiconfigResultSync;
loadSync(filepath: string): CosmiconfigResult;
}
export { ExplorerSync };
//# sourceMappingURL=ExplorerSync.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerSync.d.ts","sourceRoot":"","sources":["../src/ExplorerSync.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI9C,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EAEpB,MAAM,SAAS,CAAC;AAEjB,cAAM,YAAa,SAAQ,YAAY,CAAC,mBAAmB,CAAC;gBACvC,OAAO,EAAE,mBAAmB;IAIxC,UAAU,CAAC,UAAU,GAAE,MAAsB,GAAG,iBAAiB;IAOxE,OAAO,CAAC,uBAAuB;IAuB/B,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,mBAAmB;IAgB3B,OAAO,CAAC,2BAA2B;IAU5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB;CAsBrD;AAED,OAAO,EAAE,YAAY,EAAE,CAAC"}

View File

@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ExplorerSync = void 0;
var _path = _interopRequireDefault(require("path"));
var _ExplorerBase = require("./ExplorerBase");
var _readFile = require("./readFile");
var _cacheWrapper = require("./cacheWrapper");
var _getDirectory = require("./getDirectory");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExplorerSync extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
searchSync(searchFrom = process.cwd()) {
const startDirectory = (0, _getDirectory.getDirectorySync)(searchFrom);
const result = this.searchFromDirectorySync(startDirectory);
return result;
}
searchFromDirectorySync(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = () => {
const result = this.searchDirectorySync(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectorySync(nextDir);
}
const transformResult = this.config.transform(result);
return transformResult;
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.searchCache, absoluteDir, run);
}
return run();
}
searchDirectorySync(dir) {
for (const place of this.config.searchPlaces) {
const placeResult = this.loadSearchPlaceSync(dir, place);
if (this.shouldSearchStopWithResult(placeResult) === true) {
return placeResult;
}
} // config not found
return null;
}
loadSearchPlaceSync(dir, place) {
const filepath = _path.default.join(dir, place);
const content = (0, _readFile.readFileSync)(filepath);
const result = this.createCosmiconfigResultSync(filepath, content);
return result;
}
loadFileContentSync(filepath, content) {
if (content === null) {
return null;
}
if (content.trim() === '') {
return undefined;
}
const loader = this.getLoaderEntryForFile(filepath);
const loaderResult = loader(filepath, content);
return loaderResult;
}
createCosmiconfigResultSync(filepath, content) {
const fileContent = this.loadFileContentSync(filepath, content);
const result = this.loadedContentToCosmiconfigResult(filepath, fileContent);
return result;
}
loadSync(filepath) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoadSync = () => {
const content = (0, _readFile.readFileSync)(absoluteFilePath, {
throwNotFound: true
});
const cosmiconfigResult = this.createCosmiconfigResultSync(absoluteFilePath, content);
const transformResult = this.config.transform(cosmiconfigResult);
return transformResult;
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.loadCache, absoluteFilePath, runLoadSync);
}
return runLoadSync();
}
}
exports.ExplorerSync = ExplorerSync;
//# sourceMappingURL=ExplorerSync.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import { Cache, CosmiconfigResult } from './types';
declare function cacheWrapper(cache: Cache, key: string, fn: () => Promise<CosmiconfigResult>): Promise<CosmiconfigResult>;
declare function cacheWrapperSync(cache: Cache, key: string, fn: () => CosmiconfigResult): CosmiconfigResult;
export { cacheWrapper, cacheWrapperSync };
//# sourceMappingURL=cacheWrapper.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cacheWrapper.d.ts","sourceRoot":"","sources":["../src/cacheWrapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEnD,iBAAe,YAAY,CACzB,KAAK,EAAE,KAAK,EACZ,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,MAAM,OAAO,CAAC,iBAAiB,CAAC,GACnC,OAAO,CAAC,iBAAiB,CAAC,CAS5B;AAED,iBAAS,gBAAgB,CACvB,KAAK,EAAE,KAAK,EACZ,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,MAAM,iBAAiB,GAC1B,iBAAiB,CASnB;AAED,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,CAAC"}

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cacheWrapper = cacheWrapper;
exports.cacheWrapperSync = cacheWrapperSync;
async function cacheWrapper(cache, key, fn) {
const cached = cache.get(key);
if (cached !== undefined) {
return cached;
}
const result = await fn();
cache.set(key, result);
return result;
}
function cacheWrapperSync(cache, key, fn) {
const cached = cache.get(key);
if (cached !== undefined) {
return cached;
}
const result = fn();
cache.set(key, result);
return result;
}
//# sourceMappingURL=cacheWrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/cacheWrapper.ts"],"names":["cacheWrapper","cache","key","fn","cached","get","undefined","result","set","cacheWrapperSync"],"mappings":";;;;;;;;AAEA,eAAeA,YAAf,CACEC,KADF,EAEEC,GAFF,EAGEC,EAHF,EAI8B;AAC5B,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAG,MAAMJ,EAAE,EAAvB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD;;AAED,SAASE,gBAAT,CACER,KADF,EAEEC,GAFF,EAGEC,EAHF,EAIqB;AACnB,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAGJ,EAAE,EAAjB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD","sourcesContent":["import { Cache, CosmiconfigResult } from './types';\n\nasync function cacheWrapper(\n cache: Cache,\n key: string,\n fn: () => Promise<CosmiconfigResult>,\n): Promise<CosmiconfigResult> {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = await fn();\n cache.set(key, result);\n return result;\n}\n\nfunction cacheWrapperSync(\n cache: Cache,\n key: string,\n fn: () => CosmiconfigResult,\n): CosmiconfigResult {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = fn();\n cache.set(key, result);\n return result;\n}\n\nexport { cacheWrapper, cacheWrapperSync };\n"],"file":"cacheWrapper.js"}

View File

@@ -0,0 +1,4 @@
declare function getDirectory(filepath: string): Promise<string>;
declare function getDirectorySync(filepath: string): string;
export { getDirectory, getDirectorySync };
//# sourceMappingURL=getDirectory.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getDirectory.d.ts","sourceRoot":"","sources":["../src/getDirectory.ts"],"names":[],"mappings":"AAGA,iBAAe,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAU7D;AAED,iBAAS,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAUlD;AAED,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,CAAC"}

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getDirectory = getDirectory;
exports.getDirectorySync = getDirectorySync;
var _path = _interopRequireDefault(require("path"));
var _pathType = require("path-type");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function getDirectory(filepath) {
const filePathIsDirectory = await (0, _pathType.isDirectory)(filepath);
if (filePathIsDirectory === true) {
return filepath;
}
const directory = _path.default.dirname(filepath);
return directory;
}
function getDirectorySync(filepath) {
const filePathIsDirectory = (0, _pathType.isDirectorySync)(filepath);
if (filePathIsDirectory === true) {
return filepath;
}
const directory = _path.default.dirname(filepath);
return directory;
}
//# sourceMappingURL=getDirectory.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/getDirectory.ts"],"names":["getDirectory","filepath","filePathIsDirectory","directory","path","dirname","getDirectorySync"],"mappings":";;;;;;;;AAAA;;AACA;;;;AAEA,eAAeA,YAAf,CAA4BC,QAA5B,EAA+D;AAC7D,QAAMC,mBAAmB,GAAG,MAAM,2BAAYD,QAAZ,CAAlC;;AAEA,MAAIC,mBAAmB,KAAK,IAA5B,EAAkC;AAChC,WAAOD,QAAP;AACD;;AAED,QAAME,SAAS,GAAGC,cAAKC,OAAL,CAAaJ,QAAb,CAAlB;;AAEA,SAAOE,SAAP;AACD;;AAED,SAASG,gBAAT,CAA0BL,QAA1B,EAAoD;AAClD,QAAMC,mBAAmB,GAAG,+BAAgBD,QAAhB,CAA5B;;AAEA,MAAIC,mBAAmB,KAAK,IAA5B,EAAkC;AAChC,WAAOD,QAAP;AACD;;AAED,QAAME,SAAS,GAAGC,cAAKC,OAAL,CAAaJ,QAAb,CAAlB;;AAEA,SAAOE,SAAP;AACD","sourcesContent":["import path from 'path';\nimport { isDirectory, isDirectorySync } from 'path-type';\n\nasync function getDirectory(filepath: string): Promise<string> {\n const filePathIsDirectory = await isDirectory(filepath);\n\n if (filePathIsDirectory === true) {\n return filepath;\n }\n\n const directory = path.dirname(filepath);\n\n return directory;\n}\n\nfunction getDirectorySync(filepath: string): string {\n const filePathIsDirectory = isDirectorySync(filepath);\n\n if (filePathIsDirectory === true) {\n return filepath;\n }\n\n const directory = path.dirname(filepath);\n\n return directory;\n}\n\nexport { getDirectory, getDirectorySync };\n"],"file":"getDirectory.js"}

View File

@@ -0,0 +1,5 @@
declare function getPropertyByPath(source: {
[key: string]: unknown;
}, path: string | Array<string>): unknown;
export { getPropertyByPath };
//# sourceMappingURL=getPropertyByPath.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getPropertyByPath.d.ts","sourceRoot":"","sources":["../src/getPropertyByPath.ts"],"names":[],"mappings":"AAKA,iBAAS,iBAAiB,CACxB,MAAM,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,EAClC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAC3B,OAAO,CAgBT;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"}

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPropertyByPath = getPropertyByPath;
// Resolves property names or property paths defined with period-delimited
// strings or arrays of strings. Property names that are found on the source
// object are used directly (even if they include a period).
// Nested property names that include periods, within a path, are only
// understood in array paths.
function getPropertyByPath(source, path) {
if (typeof path === 'string' && Object.prototype.hasOwnProperty.call(source, path)) {
return source[path];
}
const parsedPath = typeof path === 'string' ? path.split('.') : path; // eslint-disable-next-line @typescript-eslint/no-explicit-any
return parsedPath.reduce((previous, key) => {
if (previous === undefined) {
return previous;
}
return previous[key];
}, source);
}
//# sourceMappingURL=getPropertyByPath.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/getPropertyByPath.ts"],"names":["getPropertyByPath","source","path","Object","prototype","hasOwnProperty","call","parsedPath","split","reduce","previous","key","undefined"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,SAASA,iBAAT,CACEC,MADF,EAEEC,IAFF,EAGW;AACT,MACE,OAAOA,IAAP,KAAgB,QAAhB,IACAC,MAAM,CAACC,SAAP,CAAiBC,cAAjB,CAAgCC,IAAhC,CAAqCL,MAArC,EAA6CC,IAA7C,CAFF,EAGE;AACA,WAAOD,MAAM,CAACC,IAAD,CAAb;AACD;;AAED,QAAMK,UAAU,GAAG,OAAOL,IAAP,KAAgB,QAAhB,GAA2BA,IAAI,CAACM,KAAL,CAAW,GAAX,CAA3B,GAA6CN,IAAhE,CARS,CAST;;AACA,SAAOK,UAAU,CAACE,MAAX,CAAkB,CAACC,QAAD,EAAgBC,GAAhB,KAAiC;AACxD,QAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1B,aAAOF,QAAP;AACD;;AACD,WAAOA,QAAQ,CAACC,GAAD,CAAf;AACD,GALM,EAKJV,MALI,CAAP;AAMD","sourcesContent":["// Resolves property names or property paths defined with period-delimited\n// strings or arrays of strings. Property names that are found on the source\n// object are used directly (even if they include a period).\n// Nested property names that include periods, within a path, are only\n// understood in array paths.\nfunction getPropertyByPath(\n source: { [key: string]: unknown },\n path: string | Array<string>,\n): unknown {\n if (\n typeof path === 'string' &&\n Object.prototype.hasOwnProperty.call(source, path)\n ) {\n return source[path];\n }\n\n const parsedPath = typeof path === 'string' ? path.split('.') : path;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return parsedPath.reduce((previous: any, key): unknown => {\n if (previous === undefined) {\n return previous;\n }\n return previous[key];\n }, source);\n}\n\nexport { getPropertyByPath };\n"],"file":"getPropertyByPath.js"}

View File

@@ -0,0 +1,44 @@
import { Config, CosmiconfigResult, Loaders, LoadersSync } from './types';
declare type LoaderResult = Config | null;
export declare type Loader = ((filepath: string, content: string) => Promise<LoaderResult>) | LoaderSync;
export declare type LoaderSync = (filepath: string, content: string) => LoaderResult;
export declare type Transform = ((CosmiconfigResult: CosmiconfigResult) => Promise<CosmiconfigResult>) | TransformSync;
export declare type TransformSync = (CosmiconfigResult: CosmiconfigResult) => CosmiconfigResult;
interface OptionsBase {
packageProp?: string;
searchPlaces?: Array<string>;
ignoreEmptySearchPlaces?: boolean;
stopDir?: string;
cache?: boolean;
}
export interface Options extends OptionsBase {
loaders?: Loaders;
transform?: Transform;
}
export interface OptionsSync extends OptionsBase {
loaders?: LoadersSync;
transform?: TransformSync;
}
declare function cosmiconfig(moduleName: string, options?: Options): {
readonly search: (searchFrom?: string) => Promise<CosmiconfigResult>;
readonly load: (filepath: string) => Promise<CosmiconfigResult>;
readonly clearLoadCache: () => void;
readonly clearSearchCache: () => void;
readonly clearCaches: () => void;
};
declare function cosmiconfigSync(moduleName: string, options?: OptionsSync): {
readonly search: (searchFrom?: string) => CosmiconfigResult;
readonly load: (filepath: string) => CosmiconfigResult;
readonly clearLoadCache: () => void;
readonly clearSearchCache: () => void;
readonly clearCaches: () => void;
};
declare const defaultLoaders: Readonly<{
readonly '.js': LoaderSync;
readonly '.json': LoaderSync;
readonly '.yaml': LoaderSync;
readonly '.yml': LoaderSync;
readonly noExt: LoaderSync;
}>;
export { cosmiconfig, cosmiconfigSync, defaultLoaders };
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,MAAM,EACN,iBAAiB,EAGjB,OAAO,EACP,WAAW,EACZ,MAAM,SAAS,CAAC;AAEjB,aAAK,YAAY,GAAG,MAAM,GAAG,IAAI,CAAC;AAClC,oBAAY,MAAM,GACd,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,GAC9D,UAAU,CAAC;AACf,oBAAY,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,YAAY,CAAC;AAE7E,oBAAY,SAAS,GACjB,CAAC,CAAC,iBAAiB,EAAE,iBAAiB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC,GACtE,aAAa,CAAC;AAElB,oBAAY,aAAa,GAAG,CAC1B,iBAAiB,EAAE,iBAAiB,KACjC,iBAAiB,CAAC;AAEvB,UAAU,WAAW;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAED,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,SAAS,CAAC,EAAE,aAAa,CAAC;CAC3B;AAGD,iBAAS,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,OAAY;;;;;;EAe7D;AAGD,iBAAS,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB;;;;;;EAerE;AAGD,QAAA,MAAM,cAAc;;;;;;EAMT,CAAC;AAgDZ,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC"}

View File

@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cosmiconfig = cosmiconfig;
exports.cosmiconfigSync = cosmiconfigSync;
exports.defaultLoaders = void 0;
var _os = _interopRequireDefault(require("os"));
var _Explorer = require("./Explorer");
var _ExplorerSync = require("./ExplorerSync");
var _loaders = require("./loaders");
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function cosmiconfig(moduleName, options = {}) {
const normalizedOptions = normalizeOptions(moduleName, options);
const explorer = new _Explorer.Explorer(normalizedOptions);
return {
search: explorer.search.bind(explorer),
load: explorer.load.bind(explorer),
clearLoadCache: explorer.clearLoadCache.bind(explorer),
clearSearchCache: explorer.clearSearchCache.bind(explorer),
clearCaches: explorer.clearCaches.bind(explorer)
};
} // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function cosmiconfigSync(moduleName, options = {}) {
const normalizedOptions = normalizeOptions(moduleName, options);
const explorerSync = new _ExplorerSync.ExplorerSync(normalizedOptions);
return {
search: explorerSync.searchSync.bind(explorerSync),
load: explorerSync.loadSync.bind(explorerSync),
clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
clearCaches: explorerSync.clearCaches.bind(explorerSync)
};
} // do not allow mutation of default loaders. Make sure it is set inside options
const defaultLoaders = Object.freeze({
'.js': _loaders.loaders.loadJs,
'.json': _loaders.loaders.loadJson,
'.yaml': _loaders.loaders.loadYaml,
'.yml': _loaders.loaders.loadYaml,
noExt: _loaders.loaders.loadYaml
});
exports.defaultLoaders = defaultLoaders;
function normalizeOptions(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `${moduleName}.config.js`],
ignoreEmptySearchPlaces: true,
stopDir: _os.default.homedir(),
cache: true,
transform: identity,
loaders: defaultLoaders
};
const normalizedOptions = { ...defaults,
...options,
loaders: { ...defaults.loaders,
...options.loaders
}
};
return normalizedOptions;
}
const identity = function identity(x) {
return x;
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
import { LoadersSync } from './types';
declare const loaders: LoadersSync;
export { loaders };
//# sourceMappingURL=loaders.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"loaders.d.ts","sourceRoot":"","sources":["../src/loaders.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AA0CtC,QAAA,MAAM,OAAO,EAAE,WAA4C,CAAC;AAE5D,OAAO,EAAE,OAAO,EAAE,CAAC"}

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loaders = void 0;
/* eslint-disable @typescript-eslint/no-require-imports */
let importFresh;
const loadJs = function loadJs(filepath) {
if (importFresh === undefined) {
importFresh = require('import-fresh');
}
const result = importFresh(filepath);
return result;
};
let parseJson;
const loadJson = function loadJson(filepath, content) {
if (parseJson === undefined) {
parseJson = require('parse-json');
}
try {
const result = parseJson(content);
return result;
} catch (error) {
error.message = `JSON Error in ${filepath}:\n${error.message}`;
throw error;
}
};
let yaml;
const loadYaml = function loadYaml(filepath, content) {
if (yaml === undefined) {
yaml = require('yaml');
}
try {
const result = yaml.parse(content, {
prettyErrors: true
});
return result;
} catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
};
const loaders = {
loadJs,
loadJson,
loadYaml
};
exports.loaders = loaders;
//# sourceMappingURL=loaders.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/loaders.ts"],"names":["importFresh","loadJs","filepath","undefined","require","result","parseJson","loadJson","content","error","message","yaml","loadYaml","parse","prettyErrors","loaders"],"mappings":";;;;;;;AAAA;AAQA,IAAIA,WAAJ;;AACA,MAAMC,MAAkB,GAAG,SAASA,MAAT,CAAgBC,QAAhB,EAA0B;AACnD,MAAIF,WAAW,KAAKG,SAApB,EAA+B;AAC7BH,IAAAA,WAAW,GAAGI,OAAO,CAAC,cAAD,CAArB;AACD;;AAED,QAAMC,MAAM,GAAGL,WAAW,CAACE,QAAD,CAA1B;AACA,SAAOG,MAAP;AACD,CAPD;;AASA,IAAIC,SAAJ;;AACA,MAAMC,QAAoB,GAAG,SAASA,QAAT,CAAkBL,QAAlB,EAA4BM,OAA5B,EAAqC;AAChE,MAAIF,SAAS,KAAKH,SAAlB,EAA6B;AAC3BG,IAAAA,SAAS,GAAGF,OAAO,CAAC,YAAD,CAAnB;AACD;;AAED,MAAI;AACF,UAAMC,MAAM,GAAGC,SAAS,CAACE,OAAD,CAAxB;AACA,WAAOH,MAAP;AACD,GAHD,CAGE,OAAOI,KAAP,EAAc;AACdA,IAAAA,KAAK,CAACC,OAAN,GAAiB,iBAAgBR,QAAS,MAAKO,KAAK,CAACC,OAAQ,EAA7D;AACA,UAAMD,KAAN;AACD;AACF,CAZD;;AAcA,IAAIE,IAAJ;;AACA,MAAMC,QAAoB,GAAG,SAASA,QAAT,CAAkBV,QAAlB,EAA4BM,OAA5B,EAAqC;AAChE,MAAIG,IAAI,KAAKR,SAAb,EAAwB;AACtBQ,IAAAA,IAAI,GAAGP,OAAO,CAAC,MAAD,CAAd;AACD;;AAED,MAAI;AACF,UAAMC,MAAM,GAAGM,IAAI,CAACE,KAAL,CAAWL,OAAX,EAAoB;AAAEM,MAAAA,YAAY,EAAE;AAAhB,KAApB,CAAf;AACA,WAAOT,MAAP;AACD,GAHD,CAGE,OAAOI,KAAP,EAAc;AACdA,IAAAA,KAAK,CAACC,OAAN,GAAiB,iBAAgBR,QAAS,MAAKO,KAAK,CAACC,OAAQ,EAA7D;AACA,UAAMD,KAAN;AACD;AACF,CAZD;;AAcA,MAAMM,OAAoB,GAAG;AAAEd,EAAAA,MAAF;AAAUM,EAAAA,QAAV;AAAoBK,EAAAA;AAApB,CAA7B","sourcesContent":["/* eslint-disable @typescript-eslint/no-require-imports */\n\nimport parseJsonType from 'parse-json';\nimport yamlType from 'yaml';\nimport importFreshType from 'import-fresh';\nimport { LoaderSync } from './index';\nimport { LoadersSync } from './types';\n\nlet importFresh: typeof importFreshType;\nconst loadJs: LoaderSync = function loadJs(filepath) {\n if (importFresh === undefined) {\n importFresh = require('import-fresh');\n }\n\n const result = importFresh(filepath);\n return result;\n};\n\nlet parseJson: typeof parseJsonType;\nconst loadJson: LoaderSync = function loadJson(filepath, content) {\n if (parseJson === undefined) {\n parseJson = require('parse-json');\n }\n\n try {\n const result = parseJson(content);\n return result;\n } catch (error) {\n error.message = `JSON Error in ${filepath}:\\n${error.message}`;\n throw error;\n }\n};\n\nlet yaml: typeof yamlType;\nconst loadYaml: LoaderSync = function loadYaml(filepath, content) {\n if (yaml === undefined) {\n yaml = require('yaml');\n }\n\n try {\n const result = yaml.parse(content, { prettyErrors: true });\n return result;\n } catch (error) {\n error.message = `YAML Error in ${filepath}:\\n${error.message}`;\n throw error;\n }\n};\n\nconst loaders: LoadersSync = { loadJs, loadJson, loadYaml };\n\nexport { loaders };\n"],"file":"loaders.js"}

View File

@@ -0,0 +1,7 @@
interface Options {
throwNotFound?: boolean;
}
declare function readFile(filepath: string, options?: Options): Promise<string | null>;
declare function readFileSync(filepath: string, options?: Options): string | null;
export { readFile, readFileSync };
//# sourceMappingURL=readFile.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"readFile.d.ts","sourceRoot":"","sources":["../src/readFile.ts"],"names":[],"mappings":"AAkBA,UAAU,OAAO;IACf,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,iBAAe,QAAQ,CACrB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,OAAY,GACpB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAcxB;AAED,iBAAS,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAE,OAAY,GAAG,MAAM,GAAG,IAAI,CAc5E;AAED,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC"}

View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readFile = readFile;
exports.readFileSync = readFileSync;
var _fs = _interopRequireDefault(require("fs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function fsReadFileAsync(pathname, encoding) {
return new Promise((resolve, reject) => {
_fs.default.readFile(pathname, encoding, (error, contents) => {
if (error) {
reject(error);
return;
}
resolve(contents);
});
});
}
async function readFile(filepath, options = {}) {
const throwNotFound = options.throwNotFound === true;
try {
const content = await fsReadFileAsync(filepath, 'utf8');
return content;
} catch (error) {
if (throwNotFound === false && error.code === 'ENOENT') {
return null;
}
throw error;
}
}
function readFileSync(filepath, options = {}) {
const throwNotFound = options.throwNotFound === true;
try {
const content = _fs.default.readFileSync(filepath, 'utf8');
return content;
} catch (error) {
if (throwNotFound === false && error.code === 'ENOENT') {
return null;
}
throw error;
}
}
//# sourceMappingURL=readFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/readFile.ts"],"names":["fsReadFileAsync","pathname","encoding","Promise","resolve","reject","fs","readFile","error","contents","filepath","options","throwNotFound","content","code","readFileSync"],"mappings":";;;;;;;;AAAA;;;;AAEA,eAAeA,eAAf,CACEC,QADF,EAEEC,QAFF,EAGmB;AACjB,SAAO,IAAIC,OAAJ,CAAY,CAACC,OAAD,EAAUC,MAAV,KAA2B;AAC5CC,gBAAGC,QAAH,CAAYN,QAAZ,EAAsBC,QAAtB,EAAgC,CAACM,KAAD,EAAQC,QAAR,KAA2B;AACzD,UAAID,KAAJ,EAAW;AACTH,QAAAA,MAAM,CAACG,KAAD,CAAN;AACA;AACD;;AAEDJ,MAAAA,OAAO,CAACK,QAAD,CAAP;AACD,KAPD;AAQD,GATM,CAAP;AAUD;;AAMD,eAAeF,QAAf,CACEG,QADF,EAEEC,OAAgB,GAAG,EAFrB,EAG0B;AACxB,QAAMC,aAAa,GAAGD,OAAO,CAACC,aAAR,KAA0B,IAAhD;;AAEA,MAAI;AACF,UAAMC,OAAO,GAAG,MAAMb,eAAe,CAACU,QAAD,EAAW,MAAX,CAArC;AAEA,WAAOG,OAAP;AACD,GAJD,CAIE,OAAOL,KAAP,EAAc;AACd,QAAII,aAAa,KAAK,KAAlB,IAA2BJ,KAAK,CAACM,IAAN,KAAe,QAA9C,EAAwD;AACtD,aAAO,IAAP;AACD;;AAED,UAAMN,KAAN;AACD;AACF;;AAED,SAASO,YAAT,CAAsBL,QAAtB,EAAwCC,OAAgB,GAAG,EAA3D,EAA8E;AAC5E,QAAMC,aAAa,GAAGD,OAAO,CAACC,aAAR,KAA0B,IAAhD;;AAEA,MAAI;AACF,UAAMC,OAAO,GAAGP,YAAGS,YAAH,CAAgBL,QAAhB,EAA0B,MAA1B,CAAhB;;AAEA,WAAOG,OAAP;AACD,GAJD,CAIE,OAAOL,KAAP,EAAc;AACd,QAAII,aAAa,KAAK,KAAlB,IAA2BJ,KAAK,CAACM,IAAN,KAAe,QAA9C,EAAwD;AACtD,aAAO,IAAP;AACD;;AAED,UAAMN,KAAN;AACD;AACF","sourcesContent":["import fs from 'fs';\n\nasync function fsReadFileAsync(\n pathname: string,\n encoding: string,\n): Promise<string> {\n return new Promise((resolve, reject): void => {\n fs.readFile(pathname, encoding, (error, contents): void => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve(contents);\n });\n });\n}\n\ninterface Options {\n throwNotFound?: boolean;\n}\n\nasync function readFile(\n filepath: string,\n options: Options = {},\n): Promise<string | null> {\n const throwNotFound = options.throwNotFound === true;\n\n try {\n const content = await fsReadFileAsync(filepath, 'utf8');\n\n return content;\n } catch (error) {\n if (throwNotFound === false && error.code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n}\n\nfunction readFileSync(filepath: string, options: Options = {}): string | null {\n const throwNotFound = options.throwNotFound === true;\n\n try {\n const content = fs.readFileSync(filepath, 'utf8');\n\n return content;\n } catch (error) {\n if (throwNotFound === false && error.code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n}\n\nexport { readFile, readFileSync };\n"],"file":"readFile.js"}

View File

@@ -0,0 +1,20 @@
import { Loader, LoaderSync, Options, OptionsSync } from './index';
export declare type Config = any;
export declare type CosmiconfigResult = {
config: Config;
filepath: string;
isEmpty?: boolean;
} | null;
export interface ExplorerOptions extends Required<Options> {
}
export interface ExplorerOptionsSync extends Required<OptionsSync> {
}
export declare type Cache = Map<string, CosmiconfigResult>;
export declare type LoadedFileContent = Config | null | undefined;
export interface Loaders {
[key: string]: Loader;
}
export interface LoadersSync {
[key: string]: LoaderSync;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGnE,oBAAY,MAAM,GAAG,GAAG,CAAC;AAEzB,oBAAY,iBAAiB,GAAG;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,IAAI,CAAC;AAIT,MAAM,WAAW,eAAgB,SAAQ,QAAQ,CAAC,OAAO,CAAC;CAAG;AAC7D,MAAM,WAAW,mBAAoB,SAAQ,QAAQ,CAAC,WAAW,CAAC;CAAG;AAGrE,oBAAY,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AAMnD,oBAAY,iBAAiB,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AAE1D,MAAM,WAAW,OAAO;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,WAAW;IAC1B,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC;CAC3B"}

View File

@@ -0,0 +1,2 @@
"use strict";
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[],"file":"types.js"}

View File

@@ -0,0 +1,148 @@
{
"name": "cosmiconfig",
"version": "6.0.0",
"description": "Find and load configuration from a package.json property, rc file, or CommonJS module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"clean": "del-cli --dot=true \"./dist/**/*\"",
"build": "npm run clean && npm run build:compile && npm run build:types",
"build:compile": "cross-env NODE_ENV=production babel src -d dist --verbose --extensions .js,.ts --ignore \"**/**/*.test.js\",\"**/**/*.test.ts\" --source-maps",
"build:types": "cross-env NODE_ENV=production tsc --project tsconfig.types.json",
"dev": "npm run clean && npm run build:compile -- --watch",
"lint": "eslint --ext .js,.ts . && npm run lint:md",
"lint:fix": "eslint --ext .js,.ts . --fix",
"lint:md": "remark-preset-davidtheclark",
"format": "prettier \"**/*.{js,ts,json,yml,yaml}\" --write",
"format:md": "remark-preset-davidtheclark --format",
"format:check": "prettier \"**/*.{js,ts,json,yml,yaml}\" --check",
"typescript": "tsc",
"test": "jest --coverage",
"test:watch": "jest --watch",
"check:all": "npm run test && npm run typescript && npm run lint && npm run format:check",
"prepublishOnly": "npm run check:all && npm run build"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged && npm run typescript && npm run test",
"pre-push": "npm run check:all"
}
},
"lint-staged": {
"*.{js,ts}": [
"eslint --fix",
"prettier --write",
"git add"
],
"*.{json,yml,yaml}": [
"prettier --write",
"git add"
],
"*.md": [
"remark-preset-davidtheclark",
"remark-preset-davidtheclark --format",
"git add"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/davidtheclark/cosmiconfig.git"
},
"keywords": [
"load",
"configuration",
"config"
],
"author": "David Clark <david.dave.clark@gmail.com>",
"contributors": [
"Bogdan Chadkin <trysound@yandex.ru>",
"Suhas Karanth <sudo.suhas@gmail.com>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/davidtheclark/cosmiconfig/issues"
},
"homepage": "https://github.com/davidtheclark/cosmiconfig#readme",
"prettier": {
"trailingComma": "all",
"arrowParens": "always",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
},
"jest": {
"testEnvironment": "node",
"collectCoverageFrom": [
"src/**/*.{js,ts}"
],
"coverageReporters": [
"text",
"html",
"lcov"
],
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"resetModules": true,
"resetMocks": true,
"restoreMocks": true
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "8.9"
}
}
],
"@babel/preset-typescript"
]
},
"dependencies": {
"@types/parse-json": "^4.0.0",
"import-fresh": "^3.1.0",
"parse-json": "^5.0.0",
"path-type": "^4.0.0",
"yaml": "^1.7.2"
},
"devDependencies": {
"@babel/cli": "^7.6.4",
"@babel/core": "^7.6.4",
"@babel/preset-env": "^7.6.3",
"@babel/preset-typescript": "^7.6.0",
"@types/jest": "^24.0.19",
"@types/node": "^12.11.5",
"@typescript-eslint/eslint-plugin": "^2.5.0",
"@typescript-eslint/parser": "^2.5.0",
"cross-env": "^6.0.3",
"del": "^5.1.0",
"del-cli": "^3.0.0",
"eslint": "^6.5.1",
"eslint-config-davidtheclark-node": "^0.2.2",
"eslint-config-prettier": "^6.4.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jest": "^22.20.0",
"eslint-plugin-node": "^10.0.0",
"husky": "^3.0.9",
"jest": "^24.9.0",
"lint-staged": "^9.4.2",
"make-dir": "^3.0.0",
"parent-module": "^2.0.0",
"prettier": "^1.18.2",
"remark-preset-davidtheclark": "^0.10.0",
"typescript": "^3.6.4"
},
"engines": {
"node": ">=8"
}
}

View File

@@ -0,0 +1,70 @@
{
"name": "babel-plugin-macros",
"version": "2.8.0",
"description": "Allows you to build compile-time libraries",
"main": "dist/index.js",
"scripts": {
"add-contributor": "kcd-scripts contributors add",
"build": "kcd-scripts build",
"lint": "kcd-scripts lint",
"test": "kcd-scripts test",
"test:update": "npm test -- --updateSnapshot",
"validate": "kcd-scripts validate",
"setup": "npm install && npm run validate -s"
},
"husky": {
"hooks": {
"pre-commit": "kcd-scripts pre-commit"
}
},
"files": [
"dist"
],
"keywords": [
"babel-plugin",
"macros",
"macro",
"babel-macro",
"babel-plugin-macro",
"babel-macros",
"babel-plugin-macros"
],
"author": "Kent C. Dodds <kent@doddsfamily.us> (http://kentcdodds.com/)",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.7.2",
"cosmiconfig": "^6.0.0",
"resolve": "^1.12.0"
},
"devDependencies": {
"@babel/core": "^7.7.2",
"@babel/parser": "^7.7.3",
"@babel/types": "^7.7.2",
"ast-pretty-print": "^2.0.1",
"babel-plugin-tester": "^7.0.4",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"cpy": "^7.3.0",
"kcd-scripts": "^1.11.0"
},
"eslintConfig": {
"extends": "./node_modules/kcd-scripts/eslint.js"
},
"eslintIgnore": [
"node_modules",
"coverage",
"dist"
],
"babel": {
"presets": [
"./other/babel-config.js"
]
},
"repository": {
"type": "git",
"url": "https://github.com/kentcdodds/babel-plugin-macros.git"
},
"bugs": {
"url": "https://github.com/kentcdodds/babel-plugin-macros/issues"
},
"homepage": "https://github.com/kentcdodds/babel-plugin-macros#readme"
}