progress on migrating to heex templates and font-icons

This commit is contained in:
Adam Piontek 2022-08-13 07:32:36 -04:00
parent d43daafdb7
commit 3eff955672
21793 changed files with 2161968 additions and 16895 deletions

424
assets_old/node_modules/postcss-loader/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,424 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [5.2.0](https://github.com/webpack-contrib/postcss-loader/compare/v5.1.0...v5.2.0) (2021-03-11)
### Features
* support `ecma` modules for the 'parser', 'stringifier' and 'syntax' options ([#519](https://github.com/webpack-contrib/postcss-loader/issues/519)) ([cc69754](https://github.com/webpack-contrib/postcss-loader/commit/cc69754383f6f9881ac5f02ec489eb89db2cfb0d))
## [5.1.0](https://github.com/webpack-contrib/postcss-loader/compare/v5.0.0...v5.1.0) (2021-03-05)
### Features
* added support for registering `context`, `build` and `missing` dependencies ([#518](https://github.com/webpack-contrib/postcss-loader/issues/518)) ([9ce4972](https://github.com/webpack-contrib/postcss-loader/commit/9ce4972c6740c8dd82463fff0934987695ccf7d2)), please read [docs](https://github.com/webpack-contrib/postcss-loader#add-dependencies-contextdependencies-builddependencies-missingdependencies)
## [5.0.0](https://github.com/webpack-contrib/postcss-loader/compare/v4.2.0...v5.0.0) (2021-02-02)
### ⚠ BREAKING CHANGES
* minimum supported `webpack` version is `5`
## [4.2.0](https://github.com/webpack-contrib/postcss-loader/compare/v4.1.0...v4.2.0) (2021-01-21)
### Features
* added the `implementation` option ([#511](https://github.com/webpack-contrib/postcss-loader/issues/511)) ([deac978](https://github.com/webpack-contrib/postcss-loader/commit/deac9787eed614b1c445f091a2b70736a6212812))
## [4.1.0](https://github.com/webpack-contrib/postcss-loader/compare/v4.0.4...v4.1.0) (2020-11-19)
### Features
* partial compatibility with `postcss-cli`, added `api.env` (alias for `api.mode`) and `api.options` (contains options from the `postcssOptions` options), please look at the [example](https://github.com/webpack-contrib/postcss-loader#examples-of-config-files) for more details ([#498](https://github.com/webpack-contrib/postcss-loader/issues/498)) ([84a9c46](https://github.com/webpack-contrib/postcss-loader/commit/84a9c46467086df0185519ceb93bf66893af4cf2))
### [4.0.4](https://github.com/webpack-contrib/postcss-loader/compare/v4.0.3...v4.0.4) (2020-10-09)
### Chore
* update `schema-utils`
## [4.0.3](https://github.com/webpack-contrib/postcss-loader/compare/v4.0.2...v4.0.3) (2020-10-02)
### Bug Fixes
* PostCSS 8 plugin loading ([e1b82fe](https://github.com/webpack-contrib/postcss-loader/commit/e1b82feb9cc27f55953b9237708800cb8c07724e))
* error and warning messages ([#485](https://github.com/webpack-contrib/postcss-loader/issues/485)) ([4b44e01](https://github.com/webpack-contrib/postcss-loader/commit/4b44e01a323aa9d2c0965e92c1796158cb36ce5a))
### [4.0.2](https://github.com/webpack-contrib/postcss-loader/compare/v4.0.1...v4.0.2) (2020-09-15)
### Bug Fixes
* compatibility with `postcss@8` ([#479](https://github.com/webpack-contrib/postcss-loader/issues/479)) ([218b0f8](https://github.com/webpack-contrib/postcss-loader/commit/218b0f8013acfafdabea9f561d4c3d074bd2eff3))
### [4.0.1](https://github.com/webpack-contrib/postcss-loader/compare/v4.0.0...v4.0.1) (2020-09-08)
### Bug Fixes
* source map generation with the `map` option for `postcss` ([#476](https://github.com/webpack-contrib/postcss-loader/issues/476)) ([6babeb1](https://github.com/webpack-contrib/postcss-loader/commit/6babeb1d64ca1e7d3d3651cb07881e1e291fa994))
## [4.0.0](https://github.com/webpack-contrib/postcss-loader/compare/v3.0.0...v4.0.0) (2020-09-07)
### ⚠ BREAKING CHANGES
* minimum supported `Node.js` version is `10.13`
* minimum supported `webpack` version is `4`
* `postcss` was moved to `peerDependencies`, you need to install `postcss`
* `PostCSS` (`plugins`/`syntax`/`parser`/`stringifier`) options was moved to the `postcssOptions` option, please look at [docs](https://github.com/webpack-contrib/postcss-loader#postcssoptions)
* `sourceMap` default value depends on the `compiler.devtool` option
* the `inline` value was removed for the `sourceMap` option, please use `{ map: { inline: true, annotation: false } }` to achieve this
* source maps contain absolute paths in `sources`
* loader output only CSS, so you need to use `css-loader`/`file-loader`/`raw-loader` to inject code inside bundle
* `exec` option was renamed to the `execute` option
* the `config` option doesn't support `Object` type anymore, `config.path` and `config.ctx` options were removed
* argument in the config for `Function` notation (previously `config.ctx`) was changed, now it contains `{ file, mode, webpackLoaderContext }`
* loader context in the config was renamed from `webpack` to `webpackLoaderContext`
### Features
* message API for emit assets ([#443](https://github.com/webpack-contrib/postcss-loader/issues/443)) ([e966ab9](https://github.com/webpack-contrib/postcss-loader/commit/e966ab965132ca812cb50e5eaf7df5fc2ad9c137))
* reuse AST from other loaders ([#468](https://github.com/webpack-contrib/postcss-loader/issues/468)) ([9b75888](https://github.com/webpack-contrib/postcss-loader/commit/9b75888dff4957f2ef1e94eca871e329354a9f6d))
* allows to use config and loader options together, options from the loader takes precedence over the config, the `plugins` option from the config and options are merged ([0eb5aaf](https://github.com/webpack-contrib/postcss-loader/commit/0eb5aaf3d49f6d5e570a3c3fdb6b201487e503c7))
* `postcssOptions` options can be `Function`
### Bug Fixes
* compatibility with webpack@5 ([#437](https://github.com/webpack-contrib/postcss-loader/issues/437)) ([ed50491](https://github.com/webpack-contrib/postcss-loader/commit/ed504910b70b4d8b4d77084c19ad92330676433e))
* `default` export for plugins ([#465](https://github.com/webpack-contrib/postcss-loader/issues/465)) ([3d32c35](https://github.com/webpack-contrib/postcss-loader/commit/3d32c35c5c911d6bd25dc0c4b5b3cd11408632d7))
* avoid mutations of loader options and config ([#470](https://github.com/webpack-contrib/postcss-loader/issues/470)) ([cad6f07](https://github.com/webpack-contrib/postcss-loader/commit/cad6f07c7f4923e8ef69ecb402b10bbd08d09530))
* respect the `map` option from loader options and config ([#458](https://github.com/webpack-contrib/postcss-loader/issues/458)) ([98441ff](https://github.com/webpack-contrib/postcss-loader/commit/98441ff87e51b58e9322d1bebb5eefc5ba417e24))
### Notes
* you don't need `ident` option for loader
* `Object` syntax for the `plugin` option is soft deprecated, please migrate on `Array` syntax (`plugins: ['postcss-preset-env', ['cssnano', options]]`)
<a name="3.0.0"></a>
# [3.0.0](https://github.com/postcss/postcss-loader/compare/v2.1.6...v3.0.0) (2018-08-08)
### Bug Fixes
* **index:** add ast version (`meta.ast`) ([f34954f](https://github.com/postcss/postcss-loader/commit/f34954f))
* **index:** emit `warnings` as an instance of `{Error}` ([8ac6fb5](https://github.com/postcss/postcss-loader/commit/8ac6fb5))
* **options:** improved `ValidationError` messages ([549ea08](https://github.com/postcss/postcss-loader/commit/549ea08))
### Chores
* **package:** update `postcss` v6.0.0...7.0.0 (`dependencies`) ([#375](https://github.com/postcss/postcss-loader/issues/375)) ([daa0da8](https://github.com/postcss/postcss-loader/commit/daa0da8))
### BREAKING CHANGES
* **package:** requires `node >= v6.0.0`
<a name="2.1.6"></a>
## [2.1.6](https://github.com/postcss/postcss-loader/compare/v2.1.5...v2.1.6) (2018-07-10)
### Bug Fixes
* **package:** config memory leak, updates `postcss-load-config` v1.2.0...2.0.0 (`dependencies`) ([0547b12](https://github.com/postcss/postcss-loader/commit/0547b12))
<a name="2.1.5"></a>
## [2.1.5](https://github.com/postcss/postcss-loader/compare/v2.1.4...v2.1.5) (2018-05-04)
### Bug Fixes
* **index:** remove `sourceMap` warning ([#361](https://github.com/postcss/postcss-loader/issues/361)) ([4416791](https://github.com/postcss/postcss-loader/commit/4416791))
<a name="2.1.4"></a>
## [2.1.4](https://github.com/postcss/postcss-loader/compare/v2.1.3...v2.1.4) (2018-04-16)
### Bug Fixes
* restore loader object in postcss config context ([#355](https://github.com/postcss/postcss-loader/issues/355)) ([2ff1735](https://github.com/postcss/postcss-loader/commit/2ff1735))
<a name="2.1.3"></a>
## [2.1.3](https://github.com/postcss/postcss-loader/compare/v2.1.2...v2.1.3) (2018-03-20)
### Bug Fixes
* **options:** revert additionalProperties changes to keep SemVer ([bd7fc38](https://github.com/postcss/postcss-loader/commit/bd7fc38))
<a name="2.1.2"></a>
## [2.1.2](https://github.com/postcss/postcss-loader/compare/v2.1.1...v2.1.2) (2018-03-17)
### Bug Fixes
* **options:** disallow additional properties and add `ident` to validation ([#346](https://github.com/postcss/postcss-loader/issues/346)) ([82ef553](https://github.com/postcss/postcss-loader/commit/82ef553))
<a name="2.1.1"></a>
## [2.1.1](https://github.com/postcss/postcss-loader/compare/v2.1.0...v2.1.1) (2018-02-26)
### Bug Fixes
* **index:** don't set `to` value (`options`) ([#339](https://github.com/postcss/postcss-loader/issues/339)) ([cdbb8b6](https://github.com/postcss/postcss-loader/commit/cdbb8b6))
<a name="2.1.0"></a>
# [2.1.0](https://github.com/postcss/postcss-loader/compare/v2.0.10...v2.1.0) (2018-02-02)
### Bug Fixes
* **index:** continue watching after dependency `{Error}` ([#332](https://github.com/postcss/postcss-loader/issues/332)) ([a8921cc](https://github.com/postcss/postcss-loader/commit/a8921cc))
### Features
* **index:** pass AST (`result.root`) && Messages (`result.messages`) as metadata to other loaders ([#322](https://github.com/postcss/postcss-loader/issues/322)) ([56232e7](https://github.com/postcss/postcss-loader/commit/56232e7))
<a name="2.0.10"></a>
## [2.0.10](https://github.com/postcss/postcss-loader/compare/v2.0.9...v2.0.10) (2018-01-03)
### Bug Fixes
* **index:** copy loader `options` before modifying ([#326](https://github.com/postcss/postcss-loader/issues/326)) ([61ff03c](https://github.com/postcss/postcss-loader/commit/61ff03c))
<a name="2.0.9"></a>
## [2.0.9](https://github.com/postcss/postcss-loader/compare/v2.0.8...v2.0.9) (2017-11-24)
### Bug Fixes
* **index:** filter `ident` (`options.ident`) ([#315](https://github.com/postcss/postcss-loader/issues/315)) ([3e1c7fa](https://github.com/postcss/postcss-loader/commit/3e1c7fa))
<a name="2.0.8"></a>
## [2.0.8](https://github.com/postcss/postcss-loader/compare/v2.0.6...v2.0.8) (2017-10-14)
### Bug Fixes
* **lib/options:** handle `{Object}` return (`options.plugins`) ([#301](https://github.com/postcss/postcss-loader/issues/301)) ([df010a7](https://github.com/postcss/postcss-loader/commit/df010a7))
* **schema:** allow to pass an `{Object}` (`options.syntax/options.stringifier`) ([#300](https://github.com/postcss/postcss-loader/issues/300)) ([58e9996](https://github.com/postcss/postcss-loader/commit/58e9996))
<a name="2.0.7"></a>
## [2.0.7](https://github.com/postcss/postcss-loader/compare/v2.0.6...v2.0.7) (2017-10-10)
### Bug Fixes
* sanitizing `from` and `to` options (`postcss.config.js`) ([#260](https://github.com/postcss/postcss-loader/issues/260)) ([753dea7](https://github.com/postcss/postcss-loader/commit/753dea7))
* **index:** runaway promise ([#269](https://github.com/postcss/postcss-loader/issues/269)) ([8df20ce](https://github.com/postcss/postcss-loader/commit/8df20ce))
<a name="2.0.6"></a>
## [2.0.6](https://github.com/postcss/postcss-loader/compare/v2.0.5...v2.0.6) (2017-06-14)
### Bug Fixes
* allow to pass an `{Object}` (`options.parser`) ([#257](https://github.com/postcss/postcss-loader/issues/257)) ([4974607](https://github.com/postcss/postcss-loader/commit/4974607))
* misspelling in warnings ([#237](https://github.com/postcss/postcss-loader/issues/237)) ([adcbb2e](https://github.com/postcss/postcss-loader/commit/adcbb2e))
* **index:** simplify config loading behaviour ([#259](https://github.com/postcss/postcss-loader/issues/259)) ([b313478](https://github.com/postcss/postcss-loader/commit/b313478))
<a name="2.0.5"></a>
## [2.0.5](https://github.com/postcss/postcss-loader/compare/v2.0.4...v2.0.5) (2017-05-10)
### Bug Fixes
* regression with `options.plugins` `{Function}` (`webpack.config.js`) (#229) ([dca52a9](https://github.com/postcss/postcss-loader/commit/dca52a9))
<a name="2.0.4"></a>
## [2.0.4](https://github.com/postcss/postcss-loader/compare/v2.0.3...v2.0.4) (2017-05-10)
### Bug Fixes
* **index:** `postcss.config.js` not resolved correctly (`options.config`) ([faaeee4](https://github.com/postcss/postcss-loader/commit/faaeee4))
* **index:** update validation schema, better warning message ([4f20c99](https://github.com/postcss/postcss-loader/commit/4f20c99))
<a name="2.0.3"></a>
## [2.0.3](https://github.com/postcss/postcss-loader/compare/v2.0.2...v2.0.3) (2017-05-09)
### Bug Fixes
* **index:** don't fail on 'sourceMap: false' && emit a warning instead, when previous map found (`options.sourceMap`) ([159b66a](https://github.com/postcss/postcss-loader/commit/159b66a))
<a name="2.0.2"></a>
## [2.0.2](https://github.com/postcss/postcss-loader/compare/v2.0.1...v2.0.2) (2017-05-09)
### Bug Fixes
* **index:** 'No PostCSS Config found' (`options.config`) (#215) ([e764761](https://github.com/postcss/postcss-loader/commit/e764761))
<a name="2.0.1"></a>
## [2.0.1](https://github.com/postcss/postcss-loader/compare/v2.0.0...v2.0.1) (2017-05-08)
### Bug Fixes
* **index:** 'Cannot create property `prev` on boolean `false`' (`options.sourceMap`) ([c4f0064](https://github.com/postcss/postcss-loader/commit/c4f0064))
<a name="2.0.0"></a>
# [2.0.0](https://github.com/postcss/postcss-loader/compare/1.2.2...v2.0.0) (2017-05-08)
### Features
* **index:** add ctx, ctx.file, ctx.options ([0dceb2c](https://github.com/postcss/postcss-loader/commit/0dceb2c))
* **index:** add options validation ([2b76df8](https://github.com/postcss/postcss-loader/commit/2b76df8))
## 1.3.3
* Remove `postcss-loader-before-processing` warning (by Michael Ciniawsky).
## 1.3.2
* Fix deprecated warning (by Xiaoyu Zhai).
## 1.3.1
* Fix conflict with CLI `--config` argument (by EGOIST).
## 1.3
* Allow object in syntax options, not only path for require (by Jeff Escalante).
## 1.2.2
* Watch `postcss.config.js` for changes (by Michael Ciniawsky).
## 1.2.1
* Fix relative `config` parameter resolving (by Simen Bekkhus).
## 1.2
* Add `config` parameter (by sainthkh).
## 1.1.1
* Fix `this` in options function (by Jeff Escalante).
## 1.1
* PostCSS common config could be placed to subdirs.
* Add webpack instance to PostCSS common config context.
## 1.0
* Add common PostCSS config support (by Mateusz Derks).
* Add Webpack 2 support with `plugins` query option (by Izaak Schroeder).
* Add `dependency` message support.
* Rewrite docs (by Michael Ciniawsky).
## 0.13
* Add `exec` parameter (by Neal Granger).
## 0.12
* Add CSS syntax highlight to syntax error code frame.
## 0.11.1
* Fix Promise API (by Daniel Haus).
## 0.11
* Add `postcss-loader-before-processing` webpack event (by Jan Nicklas).
## 0.10.1
* Better syntax error message (by Andrey Popp).
## 0.10.0
* Add `sourceMap` parameter to force inline maps (by 雪狼).
## 0.9.1
* Fix plugin in simple array config.
## 0.9
* Allow to pass syntax, parser or stringifier as function (by Jeff Escalante).
## 0.8.2
* Fix source map support (by Andrew Bradley).
## 0.8.1
* Fix resource path.
## 0.8
* Add postcss-js support (by Simon Degraeve).
## 0.7
* Added argument with webpack instance to plugins callback (by Maxime Thirouin).
## 0.6
* Use PostCSS 5.0.
* Remove `safe` parameter. Use Safe Parser.
* Add `syntax`, `parser` and `stringifier` parameters.
## 0.5.1
* Fix string source map support (by Jan Nicklas).
## 0.5.0
* Set plugins by function for hot reload support (by Stefano Brilli).
## 0.4.4
* Fix error on empty PostCSS config.
## 0.4.3
* Better check for `CssSyntaxError`.
## 0.4.2
* Fixed invalid sourcemap exception (by Richard Willis).
## 0.4.1
* Use only Promise API to catch PostCSS errors.
## 0.4
* Add PostCSS asynchronous API support.
* Fix source map support (by Richard Willis).
* Add warnings API support.
* Better output for CSS syntax errors.
## 0.3
* Use PostCSS 4.0.
## 0.2
* Use PostCSS 3.0.
## 0.1
* Initial release.

20
assets_old/node_modules/postcss-loader/LICENSE generated vendored Normal file
View file

@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
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.

1068
assets_old/node_modules/postcss-loader/README.md generated vendored Normal file

File diff suppressed because it is too large Load diff

44
assets_old/node_modules/postcss-loader/dist/Error.js generated vendored Normal file
View file

@ -0,0 +1,44 @@
"use strict";
/**
* **PostCSS Syntax Error**
*
* Loader wrapper for postcss syntax errors
*
* @class SyntaxError
* @extends Error
*
* @param {Object} err CssSyntaxError
*/
class SyntaxError extends Error {
constructor(error) {
super(error);
const {
line,
column,
reason,
plugin,
file
} = error;
this.name = "SyntaxError";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += file ? `${file} ` : "<css input> ";
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
this.stack = false;
}
}
module.exports = SyntaxError;

36
assets_old/node_modules/postcss-loader/dist/Warning.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
"use strict";
/**
* **PostCSS Plugin Warning**
*
* Loader wrapper for postcss plugin warnings (`root.messages`)
*
* @class Warning
* @extends Error
*
* @param {Object} warning PostCSS Warning
*/
class Warning extends Error {
constructor(warning) {
super(warning);
const {
text,
line,
column,
plugin
} = warning;
this.name = "Warning";
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += plugin ? `${plugin}: ` : "";
this.message += `${text}`;
this.stack = false;
}
}
module.exports = Warning;

3
assets_old/node_modules/postcss-loader/dist/cjs.js generated vendored Normal file
View file

@ -0,0 +1,3 @@
"use strict";
module.exports = require("./index").default;

148
assets_old/node_modules/postcss-loader/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _postcss = _interopRequireDefault(require("postcss"));
var _semver = require("semver");
var _package = _interopRequireDefault(require("postcss/package.json"));
var _Warning = _interopRequireDefault(require("./Warning"));
var _Error = _interopRequireDefault(require("./Error"));
var _options = _interopRequireDefault(require("./options.json"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* **PostCSS Loader**
*
* Loads && processes CSS with [PostCSS](https://github.com/postcss/postcss)
*
* @method loader
*
* @param {String} content Source
* @param {Object} sourceMap Source Map
* @param {Object} meta Meta
*
* @return {callback} callback Result
*/
async function loader(content, sourceMap, meta) {
const options = this.getOptions(_options.default);
const callback = this.async();
const configOption = typeof options.postcssOptions === "undefined" || typeof options.postcssOptions.config === "undefined" ? true : options.postcssOptions.config;
const postcssFactory = options.implementation || _postcss.default;
let loadedConfig;
if (configOption) {
try {
loadedConfig = await (0, _utils.loadConfig)(this, configOption, options.postcssOptions);
} catch (error) {
callback(error);
return;
}
}
const useSourceMap = typeof options.sourceMap !== "undefined" ? options.sourceMap : this.sourceMap;
const {
plugins,
processOptions
} = await (0, _utils.getPostcssOptions)(this, loadedConfig, options.postcssOptions);
if (useSourceMap) {
processOptions.map = {
inline: false,
annotation: false,
...processOptions.map
};
}
if (sourceMap && processOptions.map) {
processOptions.map.prev = (0, _utils.normalizeSourceMap)(sourceMap, this.context);
}
let root; // Reuse PostCSS AST from other loaders
if (meta && meta.ast && meta.ast.type === "postcss" && (0, _semver.satisfies)(meta.ast.version, `^${_package.default.version}`)) {
({
root
} = meta.ast);
}
if (!root && options.execute) {
// eslint-disable-next-line no-param-reassign
content = (0, _utils.exec)(content, this);
}
let result;
try {
result = await postcssFactory(plugins).process(root || content, processOptions);
} catch (error) {
if (error.file) {
this.addDependency(error.file);
}
if (error.name === "CssSyntaxError") {
callback(new _Error.default(error));
} else {
callback(error);
}
return;
}
for (const warning of result.warnings()) {
this.emitWarning(new _Warning.default(warning));
}
for (const message of result.messages) {
// eslint-disable-next-line default-case
switch (message.type) {
case "dependency":
this.addDependency(message.file);
break;
case "build-dependency":
this.addBuildDependency(message.file);
break;
case "missing-dependency":
this.addMissingDependency(message.file);
break;
case "context-dependency":
this.addContextDependency(message.file);
break;
case "asset":
if (message.content && message.file) {
this.emitFile(message.file, message.content, message.sourceMap, message.info);
}
}
} // eslint-disable-next-line no-undefined
let map = result.map ? result.map.toJSON() : undefined;
if (map && useSourceMap) {
map = (0, _utils.normalizeSourceMapAfterPostcss)(map, this.context);
}
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
callback(null, result.css, map, {
ast
});
}

View file

@ -0,0 +1,46 @@
{
"title": "PostCSS Loader options",
"type": "object",
"properties": {
"postcssOptions": {
"description": "Options to pass through to `Postcss`.",
"anyOf": [
{
"type": "object",
"additionalProperties": true,
"properties": {
"config": {
"description": "Allows to specify PostCSS Config Path (https://github.com/postcss/postcss-loader#config)",
"anyOf": [
{
"description": "Allows to specify the path to the configuration file",
"type": "string"
},
{
"description": "Enables/Disables autoloading config",
"type": "boolean"
}
]
}
}
},
{
"instanceof": "Function"
}
]
},
"execute": {
"description": "Enables/Disables PostCSS parser support in 'CSS-in-JS' (https://github.com/postcss/postcss-loader#execute)",
"type": "boolean"
},
"sourceMap": {
"description": "Enables/Disables generation of source maps (https://github.com/postcss/postcss-loader#sourcemap)",
"type": "boolean"
},
"implementation": {
"description": "The implementation of postcss to use, instead of the locally installed version (https://github.com/postcss/postcss-loader#implementation)",
"instanceof": "Function"
}
},
"additionalProperties": false
}

367
assets_old/node_modules/postcss-loader/dist/utils.js generated vendored Normal file
View file

@ -0,0 +1,367 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loadConfig = loadConfig;
exports.getPostcssOptions = getPostcssOptions;
exports.exec = exec;
exports.normalizeSourceMap = normalizeSourceMap;
exports.normalizeSourceMapAfterPostcss = normalizeSourceMapAfterPostcss;
var _path = _interopRequireDefault(require("path"));
var _module = _interopRequireDefault(require("module"));
var _full = require("klona/full");
var _cosmiconfig = require("cosmiconfig");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const parentModule = module;
const stat = (inputFileSystem, filePath) => new Promise((resolve, reject) => {
inputFileSystem.stat(filePath, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
function exec(code, loaderContext) {
const {
resource,
context
} = loaderContext;
const module = new _module.default(resource, parentModule); // eslint-disable-next-line no-underscore-dangle
module.paths = _module.default._nodeModulePaths(context);
module.filename = resource; // eslint-disable-next-line no-underscore-dangle
module._compile(code, resource);
return module.exports;
}
async function loadConfig(loaderContext, config, postcssOptions) {
const searchPath = typeof config === "string" ? _path.default.resolve(config) : _path.default.dirname(loaderContext.resourcePath);
let stats;
try {
stats = await stat(loaderContext.fs, searchPath);
} catch (errorIgnore) {
throw new Error(`No PostCSS config found in: ${searchPath}`);
}
const explorer = (0, _cosmiconfig.cosmiconfig)("postcss");
let result;
try {
if (stats.isFile()) {
result = await explorer.load(searchPath);
} else {
result = await explorer.search(searchPath);
}
} catch (error) {
throw error;
}
if (!result) {
return {};
}
loaderContext.addBuildDependency(result.filepath);
if (result.isEmpty) {
return result;
}
if (typeof result.config === "function") {
const api = {
mode: loaderContext.mode,
file: loaderContext.resourcePath,
// For complex use
webpackLoaderContext: loaderContext,
// Partial compatibility with `postcss-cli`
env: loaderContext.mode,
options: postcssOptions || {}
};
result.config = result.config(api);
}
result = (0, _full.klona)(result);
return result;
}
function loadPlugin(plugin, options, file) {
try {
if (!options || Object.keys(options).length === 0) {
// eslint-disable-next-line global-require, import/no-dynamic-require
const loadedPlugin = require(plugin);
if (loadedPlugin.default) {
return loadedPlugin.default;
}
return loadedPlugin;
} // eslint-disable-next-line global-require, import/no-dynamic-require
const loadedPlugin = require(plugin);
if (loadedPlugin.default) {
return loadedPlugin.default(options);
}
return loadedPlugin(options);
} catch (error) {
throw new Error(`Loading PostCSS "${plugin}" plugin failed: ${error.message}\n\n(@${file})`);
}
}
function pluginFactory() {
const listOfPlugins = new Map();
return plugins => {
if (typeof plugins === "undefined") {
return listOfPlugins;
}
if (Array.isArray(plugins)) {
for (const plugin of plugins) {
if (Array.isArray(plugin)) {
const [name, options] = plugin;
listOfPlugins.set(name, options);
} else if (plugin && typeof plugin === "function") {
listOfPlugins.set(plugin);
} else if (plugin && Object.keys(plugin).length === 1 && (typeof plugin[Object.keys(plugin)[0]] === "object" || typeof plugin[Object.keys(plugin)[0]] === "boolean") && plugin[Object.keys(plugin)[0]] !== null) {
const [name] = Object.keys(plugin);
const options = plugin[name];
if (options === false) {
listOfPlugins.delete(name);
} else {
listOfPlugins.set(name, options);
}
} else if (plugin) {
listOfPlugins.set(plugin);
}
}
} else {
const objectPlugins = Object.entries(plugins);
for (const [name, options] of objectPlugins) {
if (options === false) {
listOfPlugins.delete(name);
} else {
listOfPlugins.set(name, options);
}
}
}
return listOfPlugins;
};
}
async function load(module) {
let exports;
try {
// eslint-disable-next-line import/no-dynamic-require, global-require
exports = require(module);
return exports;
} catch (requireError) {
let importESM;
try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}
if (requireError.code === "ERR_REQUIRE_ESM" && importESM) {
exports = await importESM(module);
return exports.default;
}
throw requireError;
}
}
async function getPostcssOptions(loaderContext, loadedConfig = {}, postcssOptions = {}) {
const file = loaderContext.resourcePath;
let normalizedPostcssOptions = postcssOptions;
if (typeof normalizedPostcssOptions === "function") {
normalizedPostcssOptions = normalizedPostcssOptions(loaderContext);
}
let plugins = [];
try {
const factory = pluginFactory();
if (loadedConfig.config && loadedConfig.config.plugins) {
factory(loadedConfig.config.plugins);
}
factory(normalizedPostcssOptions.plugins);
plugins = [...factory()].map(item => {
const [plugin, options] = item;
if (typeof plugin === "string") {
return loadPlugin(plugin, options, file);
}
return plugin;
});
} catch (error) {
loaderContext.emitError(error);
}
const processOptionsFromConfig = loadedConfig.config || {};
if (processOptionsFromConfig.from) {
processOptionsFromConfig.from = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.from);
}
if (processOptionsFromConfig.to) {
processOptionsFromConfig.to = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.to);
} // No need them for processOptions
delete processOptionsFromConfig.plugins;
const processOptionsFromOptions = (0, _full.klona)(normalizedPostcssOptions);
if (processOptionsFromOptions.from) {
processOptionsFromOptions.from = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.from);
}
if (processOptionsFromOptions.to) {
processOptionsFromOptions.to = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.to);
} // No need them for processOptions
delete processOptionsFromOptions.config;
delete processOptionsFromOptions.plugins;
const processOptions = {
from: file,
to: file,
map: false,
...processOptionsFromConfig,
...processOptionsFromOptions
};
if (typeof processOptions.parser === "string") {
try {
processOptions.parser = await load(processOptions.parser);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.parser}" parser failed: ${error.message}\n\n(@${file})`));
}
}
if (typeof processOptions.stringifier === "string") {
try {
processOptions.stringifier = await load(processOptions.stringifier);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.stringifier}" stringifier failed: ${error.message}\n\n(@${file})`));
}
}
if (typeof processOptions.syntax === "string") {
try {
processOptions.syntax = await load(processOptions.syntax);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.syntax}" syntax failed: ${error.message}\n\n(@${file})`));
}
}
if (processOptions.map === true) {
// https://github.com/postcss/postcss/blob/master/docs/source-maps.md
processOptions.map = {
inline: true
};
}
return {
plugins,
processOptions
};
}
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourceContext) {
let newMap = map; // Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const {
sourceRoot
} = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
newMap.sources = newMap.sources.map(source => {
const sourceType = getURLType(source); // Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? _path.default.resolve(sourceRoot, _path.default.normalize(source)) : _path.default.normalize(source);
return _path.default.relative(resourceContext, absoluteSource);
}
return source;
});
}
return newMap;
}
function normalizeSourceMapAfterPostcss(map, resourceContext) {
const newMap = map; // result.map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete newMap.file; // eslint-disable-next-line no-param-reassign
newMap.sourceRoot = ""; // eslint-disable-next-line no-param-reassign
newMap.sources = newMap.sources.map(source => {
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source); // Do no touch `scheme-relative`, `path-absolute` and `absolute` types
if (sourceType === "path-relative") {
return _path.default.resolve(resourceContext, source);
}
return source;
});
return newMap;
}

View file

@ -0,0 +1 @@
../semver/bin/semver.js

View file

@ -0,0 +1,201 @@
# Changelog
## 7.0.0
- **Breaking change:** Add `${moduleName}rc.cjs` and `${moduleName}.config.cjs` to the default `searchPlaces`, to support users of `"type": "module"` in recent versions of Node.
- **Breaking change:** Drop support for Node 8. Now requires Node 10+.
## 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,572 @@
# 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`, `.js`, or `.cjs`
- a `.config.js` or `.config.cjs` 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`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, or `.myapprc.cjs` file
- a `myapp.config.js` or `myapp.config.cjs` CommonJS module exporting an 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).
## Table of contents
- [Installation](#installation)
- [Usage](#usage)
- [Result](#result)
- [Asynchronous API](#asynchronous-api)
- [cosmiconfig()](#cosmiconfig-1)
- [explorer.search()](#explorersearch)
- [explorer.load()](#explorerload)
- [explorer.clearLoadCache()](#explorerclearloadcache)
- [explorer.clearSearchCache()](#explorerclearsearchcache)
- [explorer.clearCaches()](#explorerclearcaches)
- [Synchronous API](#synchronous-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 10+.
## 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`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, or `.goldengrahamsrc.cjs` file.
4. A `goldengrahams.config.js` or `goldengrahams.config.cjs` CommonJS module 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()`].
## Synchronous 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}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
]
```
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))
// [
// [ '.cjs', [Function: loadJs] ],
// [ '.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,118 @@
"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 }; }
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) {
for await (const place of this.config.searchPlaces) {
const placeResult = await this.loadSearchPlace(dir, place);
if (this.shouldSearchStopWithResult(placeResult) === true) {
return placeResult;
}
} // config not found
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,45 @@
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 | Array<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 '.cjs': LoaderSync;
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":"AAKA,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,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACrC,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;;;;;;;EAOT,CAAC;AAkDZ,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC"}

View file

@ -0,0 +1,82 @@
"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 @typescript-eslint/explicit-module-boundary-types */
// 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({
'.cjs': _loaders.loaders.loadJs,
'.js': _loaders.loaders.loadJs,
'.json': _loaders.loaders.loadJson,
'.yaml': _loaders.loaders.loadYaml,
'.yml': _loaders.loaders.loadYaml,
noExt: _loaders.loaders.loadYaml
});
exports.defaultLoaders = defaultLoaders;
const identity = function identity(x) {
return x;
};
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}rc.cjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`],
ignoreEmptySearchPlaces: true,
stopDir: _os.default.homedir(),
cache: true,
transform: identity,
loaders: defaultLoaders
};
const normalizedOptions = { ...defaults,
...options,
loaders: { ...defaults.loaders,
...options.loaders
}
};
return normalizedOptions;
}
//# 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,145 @@
{
"name": "cosmiconfig",
"version": "7.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"
],
"*.{json,yml,yaml}": [
"prettier --write"
],
"*.md": [
"remark-preset-davidtheclark",
"remark-preset-davidtheclark --format"
]
},
"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": "10"
}
}
],
"@babel/preset-typescript"
]
},
"dependencies": {
"@types/parse-json": "^4.0.0",
"import-fresh": "^3.2.1",
"parse-json": "^5.0.0",
"path-type": "^4.0.0",
"yaml": "^1.10.0"
},
"devDependencies": {
"@babel/cli": "^7.10.4",
"@babel/core": "^7.10.4",
"@babel/preset-env": "^7.10.4",
"@babel/preset-typescript": "^7.10.4",
"@types/jest": "^26.0.4",
"@types/node": "^14.0.22",
"@typescript-eslint/eslint-plugin": "^3.6.0",
"@typescript-eslint/parser": "^3.6.0",
"cross-env": "^7.0.2",
"del": "^5.1.0",
"del-cli": "^3.0.1",
"eslint": "^7.4.0",
"eslint-config-davidtheclark-node": "^0.2.2",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^23.18.0",
"eslint-plugin-node": "^11.1.0",
"husky": "^4.2.5",
"jest": "^26.1.0",
"lint-staged": "^10.2.11",
"make-dir": "^3.1.0",
"parent-module": "^2.0.0",
"prettier": "^2.0.5",
"remark-preset-davidtheclark": "^0.12.0",
"typescript": "^3.9.6"
},
"engines": {
"node": ">=10"
}
}

View file

@ -0,0 +1,30 @@
/**
Import a module while bypassing the cache.
@example
```
// foo.js
let i = 0;
module.exports = () => ++i;
// index.js
import importFresh = require('import-fresh');
require('./foo')();
//=> 1
require('./foo')();
//=> 2
importFresh('./foo')();
//=> 1
importFresh('./foo')();
//=> 1
const foo = importFresh<typeof import('./foo')>('./foo');
```
*/
declare function importFresh<T>(moduleId: string): T;
export = importFresh;

View file

@ -0,0 +1,33 @@
'use strict';
const path = require('path');
const resolveFrom = require('resolve-from');
const parentModule = require('parent-module');
module.exports = moduleId => {
if (typeof moduleId !== 'string') {
throw new TypeError('Expected a string');
}
const parentPath = parentModule(__filename);
const cwd = parentPath ? path.dirname(parentPath) : __dirname;
const filePath = resolveFrom(cwd, moduleId);
const oldModule = require.cache[filePath];
// Delete itself from module parent
if (oldModule && oldModule.parent) {
let i = oldModule.parent.children.length;
while (i--) {
if (oldModule.parent.children[i].id === filePath) {
oldModule.parent.children.splice(i, 1);
}
}
}
delete require.cache[filePath]; // Delete module from cache
const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
};

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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,43 @@
{
"name": "import-fresh",
"version": "3.3.0",
"description": "Import a module while bypassing the cache",
"license": "MIT",
"repository": "sindresorhus/import-fresh",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=6"
},
"scripts": {
"test": "xo && ava && tsd",
"heapdump": "node heapdump.js"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"require",
"cache",
"uncache",
"uncached",
"module",
"fresh",
"bypass"
],
"dependencies": {
"parent-module": "^1.0.0",
"resolve-from": "^4.0.0"
},
"devDependencies": {
"ava": "^1.0.1",
"heapdump": "^0.3.12",
"tsd": "^0.7.3",
"xo": "^0.23.0"
}
}

View file

@ -0,0 +1,48 @@
# import-fresh
> Import a module while bypassing the [cache](https://nodejs.org/api/modules.html#modules_caching)
Useful for testing purposes when you need to freshly import a module.
## Install
```
$ npm install import-fresh
```
## Usage
```js
// foo.js
let i = 0;
module.exports = () => ++i;
```
```js
const importFresh = require('import-fresh');
require('./foo')();
//=> 1
require('./foo')();
//=> 2
importFresh('./foo')();
//=> 1
importFresh('./foo')();
//=> 1
```
## import-fresh for enterprise
Available as part of the Tidelift Subscription.
The maintainers of import-fresh and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-import-fresh?utm_source=npm-import-fresh&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [clear-module](https://github.com/sindresorhus/clear-module) - Clear a module from the import cache
- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path
- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory
- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import modules lazily

View file

@ -0,0 +1,54 @@
'use strict';
const errorEx = require('error-ex');
const fallback = require('json-parse-even-better-errors');
const {default: LinesAndColumns} = require('lines-and-columns');
const {codeFrameColumns} = require('@babel/code-frame');
const JSONError = errorEx('JSONError', {
fileName: errorEx.append('in %s'),
codeFrame: errorEx.append('\n\n%s\n')
});
const parseJson = (string, reviver, filename) => {
if (typeof reviver === 'string') {
filename = reviver;
reviver = null;
}
try {
try {
return JSON.parse(string, reviver);
} catch (error) {
fallback(string, reviver);
throw error;
}
} catch (error) {
error.message = error.message.replace(/\n/g, '');
const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/);
const jsonError = new JSONError(error);
if (filename) {
jsonError.fileName = filename;
}
if (indexMatch && indexMatch.length > 0) {
const lines = new LinesAndColumns(string);
const index = Number(indexMatch[1]);
const location = lines.locationForIndex(index);
const codeFrame = codeFrameColumns(
string,
{start: {line: location.line + 1, column: location.column + 1}},
{highlightCode: true}
);
jsonError.codeFrame = codeFrame;
}
throw jsonError;
}
};
parseJson.JSONError = JSONError;
module.exports = parseJson;

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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,45 @@
{
"name": "parse-json",
"version": "5.2.0",
"description": "Parse JSON with more helpful errors",
"license": "MIT",
"repository": "sindresorhus/parse-json",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && nyc ava"
},
"files": [
"index.js",
"vendor"
],
"keywords": [
"parse",
"json",
"graceful",
"error",
"message",
"humanize",
"friendly",
"helpful",
"string"
],
"dependencies": {
"@babel/code-frame": "^7.0.0",
"error-ex": "^1.3.1",
"json-parse-even-better-errors": "^2.3.0",
"lines-and-columns": "^1.1.6"
},
"devDependencies": {
"ava": "^1.4.1",
"nyc": "^14.1.1",
"xo": "^0.24.0"
}
}

View file

@ -0,0 +1,119 @@
# parse-json
> Parse JSON with more helpful errors
## Install
```
$ npm install parse-json
```
## Usage
```js
const parseJson = require('parse-json');
const json = '{\n\t"foo": true,\n}';
JSON.parse(json);
/*
undefined:3
}
^
SyntaxError: Unexpected token }
*/
parseJson(json);
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}'
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
parseJson(json, 'foo.json');
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
// You can also add the filename at a later point
try {
parseJson(json);
} catch (error) {
if (error instanceof parseJson.JSONError) {
error.fileName = 'foo.json';
}
throw error;
}
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
```
## API
### parseJson(string, reviver?, filename?)
Throws a `JSONError` when there is a parsing error.
#### string
Type: `string`
#### reviver
Type: `Function`
Prescribes how the value originally produced by parsing is transformed, before being returned. See [`JSON.parse` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter
) for more.
#### filename
Type: `string`
Filename displayed in the error message.
### parseJson.JSONError
Exposed for `instanceof` checking.
#### fileName
Type: `string`
The filename displayed in the error message.
#### codeFrame
Type: `string`
The printable section of the JSON which produces the error.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-parse-json?utm_source=npm-parse-json&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View file

@ -0,0 +1,47 @@
'use strict';
const path = require('path');
const Module = require('module');
const fs = require('fs');
const resolveFrom = (fromDir, moduleId, silent) => {
if (typeof fromDir !== 'string') {
throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
}
if (typeof moduleId !== 'string') {
throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
}
try {
fromDir = fs.realpathSync(fromDir);
} catch (err) {
if (err.code === 'ENOENT') {
fromDir = path.resolve(fromDir);
} else if (silent) {
return null;
} else {
throw err;
}
}
const fromFile = path.join(fromDir, 'noop.js');
const resolveFileName = () => Module._resolveFilename(moduleId, {
id: fromFile,
filename: fromFile,
paths: Module._nodeModulePaths(fromDir)
});
if (silent) {
try {
return resolveFileName();
} catch (err) {
return null;
}
}
return resolveFileName();
};
module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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,34 @@
{
"name": "resolve-from",
"version": "4.0.0",
"description": "Resolve the path of a module like `require.resolve()` but from a given path",
"license": "MIT",
"repository": "sindresorhus/resolve-from",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"require",
"resolve",
"path",
"module",
"from",
"like",
"import"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

View file

@ -0,0 +1,72 @@
# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from)
> Resolve the path of a module like [`require.resolve()`](https://nodejs.org/api/globals.html#globals_require_resolve) but from a given path
## Install
```
$ npm install resolve-from
```
## Usage
```js
const resolveFrom = require('resolve-from');
// There is a file at `./foo/bar.js`
resolveFrom('foo', './bar');
//=> '/Users/sindresorhus/dev/test/foo/bar.js'
```
## API
### resolveFrom(fromDir, moduleId)
Like `require()`, throws when the module can't be found.
### resolveFrom.silent(fromDir, moduleId)
Returns `null` instead of throwing when the module can't be found.
#### fromDir
Type: `string`
Directory to resolve from.
#### moduleId
Type: `string`
What you would use in `require()`.
## Tip
Create a partial using a bound function if you want to resolve from the same `fromDir` multiple times:
```js
const resolveFromFoo = resolveFrom.bind(null, 'foo');
resolveFromFoo('./bar');
resolveFromFoo('./baz');
```
## Related
- [resolve-cwd](https://github.com/sindresorhus/resolve-cwd) - Resolve the path of a module from the current working directory
- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path
- [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory
- [resolve-pkg](https://github.com/sindresorhus/resolve-pkg) - Resolve the path of a package regardless of it having an entry point
- [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily
- [resolve-global](https://github.com/sindresorhus/resolve-global) - Resolve the path of a globally installed module
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View file

@ -0,0 +1,111 @@
# changes log
## 7.3.0
* Add `subset(r1, r2)` method to determine if `r1` range is entirely
contained by `r2` range.
## 7.2.3
* Fix handling of `includePrelease` mode where version ranges like `1.0.0 -
2.0.0` would include `3.0.0-pre` and not `1.0.0-pre`.
## 7.2.2
* Fix bug where `2.0.0-pre` would be included in `^1.0.0` if
`includePrerelease` was set to true.
## 7.2.0
* Add `simplifyRange` method to attempt to generate a more human-readable
range expression that is equivalent to a supplied range, for a given set
of versions.
## 7.1.2
* Remove fancy lazy-loading logic, as it was causing problems for webpack
users.
## 7.1.0
* Add `require('semver/preload')` to load the entire module without using
lazy getter methods.
## 7.0.0
* Refactor module into separate files for better tree-shaking
* Drop support for very old node versions, use const/let, `=>` functions,
and classes.
## 6.3.0
* Expose the token enum on the exports
## 6.2.0
* Coerce numbers to strings when passed to semver.coerce()
* Add `rtl` option to coerce from right to left
## 6.1.3
* Handle X-ranges properly in includePrerelease mode
## 6.1.2
* Do not throw when testing invalid version strings
## 6.1.1
* Add options support for semver.coerce()
* Handle undefined version passed to Range.test
## 6.1.0
* Add semver.compareBuild function
* Support `*` in semver.intersects
## 6.0
* Fix `intersects` logic.
This is technically a bug fix, but since it is also a change to behavior
that may require users updating their code, it is marked as a major
version increment.
## 5.7
* Add `minVersion` method
## 5.6
* Move boolean `loose` param to an options object, with
backwards-compatibility protection.
* Add ability to opt out of special prerelease version handling with
the `includePrerelease` option flag.
## 5.5
* Add version coercion capabilities
## 5.4
* Add intersection checking
## 5.3
* Add `minSatisfying` method
## 5.2
* Add `prerelease(v)` that returns prerelease components
## 5.1
* Add Backus-Naur for ranges
* Remove excessively cute inspection methods
## 5.0
* Remove AMD/Browserified build artifacts
* Fix ltr and gtr when using the `*` range
* Fix for range `*` with a prerelease identifier

View file

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View file

@ -0,0 +1,566 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
You can also just load the module for the function that you care about, if
you'd like to minimize your footprint.
```js
// load the whole API at once in a single object
const semver = require('semver')
// or just load the bits you need
// all of them listed here, just pick and choose what you want
// classes
const SemVer = require('semver/classes/semver')
const Comparator = require('semver/classes/comparator')
const Range = require('semver/classes/range')
// functions for working with versions
const semverParse = require('semver/functions/parse')
const semverValid = require('semver/functions/valid')
const semverClean = require('semver/functions/clean')
const semverInc = require('semver/functions/inc')
const semverDiff = require('semver/functions/diff')
const semverMajor = require('semver/functions/major')
const semverMinor = require('semver/functions/minor')
const semverPatch = require('semver/functions/patch')
const semverPrerelease = require('semver/functions/prerelease')
const semverCompare = require('semver/functions/compare')
const semverRcompare = require('semver/functions/rcompare')
const semverCompareLoose = require('semver/functions/compare-loose')
const semverCompareBuild = require('semver/functions/compare-build')
const semverSort = require('semver/functions/sort')
const semverRsort = require('semver/functions/rsort')
// low-level comparators between versions
const semverGt = require('semver/functions/gt')
const semverLt = require('semver/functions/lt')
const semverEq = require('semver/functions/eq')
const semverNeq = require('semver/functions/neq')
const semverGte = require('semver/functions/gte')
const semverLte = require('semver/functions/lte')
const semverCmp = require('semver/functions/cmp')
const semverCoerce = require('semver/functions/coerce')
// working with ranges
const semverSatisfies = require('semver/functions/satisfies')
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
const semverMinSatisfying = require('semver/ranges/min-satisfying')
const semverToComparators = require('semver/ranges/to-comparators')
const semverMinVersion = require('semver/ranges/min-version')
const semverValidRange = require('semver/ranges/valid')
const semverOutside = require('semver/ranges/outside')
const semverGtr = require('semver/ranges/gtr')
const semverLtr = require('semver/ranges/ltr')
const semverIntersects = require('semver/ranges/intersects')
const simplifyRange = require('semver/ranges/simplify')
const rangeSubset = require('semver/ranges/subset')
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
## Ranges
A `version range` is a set of `comparators` which specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional, but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version. The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose for this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.
Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for the purpose of range
matching) by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
* `^0.0` := `>=0.0.0 <0.1.0-0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0-0`
* `^0.x` := `>=0.0.0 <1.0.0-0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose` Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease` Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, release)`: Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, or `prerelease`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, the `prerelease` will work the
same as `prepatch`. It increments the patch version, then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the exact same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can possibly match
the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect
* `simplifyRange(versions, range)`: Return a "simplified" range that
matches the same items in `versions` list as the range specified. Note
that it does *not* guarantee that it would match the same versions in all
cases, only for the set of versions provided. This is useful when
generating ranges by joining together multiple versions with `||`
programmatically, to provide the user with something a bit more
ergonomic. If the provided range is shorter in string-length than the
generated range, then that is returned.
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
entirely contained by the `superRange` range.
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so the version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided
version is not valid a null will be returned. This does not work for
ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `2.1.5`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
## Exported Modules
<!--
TODO: Make sure that all of these items are documented (classes aren't,
eg), and then pull the module name into the documentation for that specific
thing.
-->
You may pull in just the part of this semver utility that you need, if you
are sensitive to packing and tree-shaking concerns. The main
`require('semver')` export uses getter functions to lazily load the parts
of the API that are used.
The following modules are available:
* `require('semver')`
* `require('semver/classes')`
* `require('semver/classes/comparator')`
* `require('semver/classes/range')`
* `require('semver/classes/semver')`
* `require('semver/functions/clean')`
* `require('semver/functions/cmp')`
* `require('semver/functions/coerce')`
* `require('semver/functions/compare')`
* `require('semver/functions/compare-build')`
* `require('semver/functions/compare-loose')`
* `require('semver/functions/diff')`
* `require('semver/functions/eq')`
* `require('semver/functions/gt')`
* `require('semver/functions/gte')`
* `require('semver/functions/inc')`
* `require('semver/functions/lt')`
* `require('semver/functions/lte')`
* `require('semver/functions/major')`
* `require('semver/functions/minor')`
* `require('semver/functions/neq')`
* `require('semver/functions/parse')`
* `require('semver/functions/patch')`
* `require('semver/functions/prerelease')`
* `require('semver/functions/rcompare')`
* `require('semver/functions/rsort')`
* `require('semver/functions/satisfies')`
* `require('semver/functions/sort')`
* `require('semver/functions/valid')`
* `require('semver/ranges/gtr')`
* `require('semver/ranges/intersects')`
* `require('semver/ranges/ltr')`
* `require('semver/ranges/max-satisfying')`
* `require('semver/ranges/min-satisfying')`
* `require('semver/ranges/min-version')`
* `require('semver/ranges/outside')`
* `require('semver/ranges/to-comparators')`
* `require('semver/ranges/valid')`

View file

@ -0,0 +1,173 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
const argv = process.argv.slice(2)
let versions = []
const range = []
let inc = null
const version = require('../package.json').version
let loose = false
let includePrerelease = false
let coerce = false
let rtl = false
let identifier
const semver = require('../')
let reverse = false
const options = {}
const main = () => {
if (!argv.length) return help()
while (argv.length) {
let a = argv.shift()
const indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
a = a.slice(0, indexOfEqualSign)
argv.unshift(a.slice(indexOfEqualSign + 1))
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
const options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }
versions = versions.map((v) => {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter((v) => {
return semver.valid(v)
})
if (!versions.length) return fail()
if (inc && (versions.length !== 1 || range.length)) { return failInc() }
for (let i = 0, l = range.length; i < l; i++) {
versions = versions.filter((v) => {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) return fail()
}
return success(versions)
}
const failInc = () => {
console.error('--inc can only be used on a single version with no range')
fail()
}
const fail = () => process.exit(1)
const success = () => {
const compare = reverse ? 'rcompare' : 'compare'
versions.sort((a, b) => {
return semver[compare](a, b, options)
}).map((v) => {
return semver.clean(v, options)
}).map((v) => {
return inc ? semver.inc(v, inc, options, identifier) : v
}).forEach((v, i, _) => { console.log(v) })
}
const help = () => console.log(
`SemVer ${version}
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)
main()

View file

@ -0,0 +1,135 @@
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
const sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
const sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
const sameSemVer = this.semver.version === comp.semver.version
const differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
const oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<')
const oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>')
return (
sameDirectionIncreasing ||
sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan ||
oppositeDirectionsGreaterThan
)
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const {re, t} = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')

View file

@ -0,0 +1,5 @@
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js')
}

View file

@ -0,0 +1,510 @@
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range
.split(/\s*\|\|\s*/)
// map the range to a 2d array of comparators
.map(range => this.parseRange(range.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0)
this.set = [first]
else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.format()
}
format () {
this.range = this.set
.map((comps) => {
return comps.join(' ').trim()
})
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
range = range.trim()
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',')
const memoKey = `parseRange:${memoOpts}:${range}`
const cached = cache.get(memoKey)
if (cached)
return cached
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range, re[t.COMPARATORTRIM])
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// At this point, the range is completely trimmed and
// ready to be split into comparators.
const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
// in loose mode, throw out any that are not valid comparators
.filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
.map(comp => new Comparator(comp, this.options))
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const l = rangeList.length
const rangeMap = new Map()
for (const comp of rangeList) {
if (isNullSet(comp))
return [comp]
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has(''))
rangeMap.delete('')
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = require('lru-cache')
const cache = new LRU({ max: 1000 })
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = require('../internal/re')
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
const replaceTildes = (comp, options) =>
comp.trim().split(/\s+/).map((comp) => {
return replaceTilde(comp, options)
}).join(' ')
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
const replaceCarets = (comp, options) =>
comp.trim().split(/\s+/).map((comp) => {
return replaceCaret(comp, options)
}).join(' ')
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp.split(/\s+/).map((comp) => {
return replaceXRange(comp, options)
}).join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<')
pr = '-0'
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return (`${from} ${to}`).trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}

View file

@ -0,0 +1,287 @@
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier)
this.inc('pre', identifier)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier)
}
this.inc('pre', identifier)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.format()
this.raw = this.version
return this
}
}
module.exports = SemVer

View file

@ -0,0 +1,6 @@
const parse = require('./parse')
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean

View file

@ -0,0 +1,48 @@
const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a === b
case '!==':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp

View file

@ -0,0 +1,51 @@
const SemVer = require('../classes/semver')
const parse = require('./parse')
const {re, t} = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null)
return null
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce

View file

@ -0,0 +1,7 @@
const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose

View file

@ -0,0 +1,5 @@
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare

View file

@ -0,0 +1,23 @@
const parse = require('./parse')
const eq = require('./eq')
const diff = (version1, version2) => {
if (eq(version1, version2)) {
return null
} else {
const v1 = parse(version1)
const v2 = parse(version2)
const hasPre = v1.prerelease.length || v2.prerelease.length
const prefix = hasPre ? 'pre' : ''
const defaultResult = hasPre ? 'prerelease' : ''
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
module.exports = diff

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte

View file

@ -0,0 +1,15 @@
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier) => {
if (typeof (options) === 'string') {
identifier = options
options = undefined
}
try {
return new SemVer(version, options).inc(release, identifier).version
} catch (er) {
return null
}
}
module.exports = inc

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte

View file

@ -0,0 +1,3 @@
const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major

View file

@ -0,0 +1,3 @@
const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq

View file

@ -0,0 +1,33 @@
const {MAX_LENGTH} = require('../internal/constants')
const { re, t } = require('../internal/re')
const SemVer = require('../classes/semver')
const parseOptions = require('../internal/parse-options')
const parse = (version, options) => {
options = parseOptions(options)
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
const r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
module.exports = parse

View file

@ -0,0 +1,3 @@
const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch

View file

@ -0,0 +1,6 @@
const parse = require('./parse')
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease

View file

@ -0,0 +1,3 @@
const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare

View file

@ -0,0 +1,3 @@
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort

View file

@ -0,0 +1,10 @@
const Range = require('../classes/range')
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies

View file

@ -0,0 +1,3 @@
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort

View file

@ -0,0 +1,6 @@
const parse = require('./parse')
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid

View file

@ -0,0 +1,48 @@
// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
module.exports = {
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION,
SemVer: require('./classes/semver'),
compareIdentifiers: require('./internal/identifiers').compareIdentifiers,
rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers,
parse: require('./functions/parse'),
valid: require('./functions/valid'),
clean: require('./functions/clean'),
inc: require('./functions/inc'),
diff: require('./functions/diff'),
major: require('./functions/major'),
minor: require('./functions/minor'),
patch: require('./functions/patch'),
prerelease: require('./functions/prerelease'),
compare: require('./functions/compare'),
rcompare: require('./functions/rcompare'),
compareLoose: require('./functions/compare-loose'),
compareBuild: require('./functions/compare-build'),
sort: require('./functions/sort'),
rsort: require('./functions/rsort'),
gt: require('./functions/gt'),
lt: require('./functions/lt'),
eq: require('./functions/eq'),
neq: require('./functions/neq'),
gte: require('./functions/gte'),
lte: require('./functions/lte'),
cmp: require('./functions/cmp'),
coerce: require('./functions/coerce'),
Comparator: require('./classes/comparator'),
Range: require('./classes/range'),
satisfies: require('./functions/satisfies'),
toComparators: require('./ranges/to-comparators'),
maxSatisfying: require('./ranges/max-satisfying'),
minSatisfying: require('./ranges/min-satisfying'),
minVersion: require('./ranges/min-version'),
validRange: require('./ranges/valid'),
outside: require('./ranges/outside'),
gtr: require('./ranges/gtr'),
ltr: require('./ranges/ltr'),
intersects: require('./ranges/intersects'),
simplifyRange: require('./ranges/simplify'),
subset: require('./ranges/subset'),
}

Some files were not shown because too many files have changed in this diff Show more