Socket
Socket
Sign inDemoInstall

strip-comments

Package Overview
Dependencies
Maintainers
1
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

strip-comments - npm Package Compare versions

Comparing version 0.4.4 to 1.0.0

217

index.js
/*!
* strip-comments <https://github.com/jonschlinkert/strip-comments>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Released under the MIT license.
* Copyright (c) 2014-2016, 2018, Jon Schlinkert.
* Released under the MIT License.
*/

@@ -10,25 +10,22 @@

var extend = require('extend-shallow');
var extract = require('extract-comments');
const assign = Object.assign;
const extract = require('babel-extract-comments');
/**
* Strip all code comments from the given `input`,
* including these that are ignored.
* Pass `opts.safe: true` to keep them.
* Strip all code comments from the given `input`, including protected
* comments that start with `!`, unless disabled by setting `options.keepProtected`
* to true.
*
* **Example**
*
* ```js
* var str = strip('foo; // this is a comment\n /* me too *\/');
* const str = strip('const foo = "bar";// this is a comment\n /* me too *\/');
* console.log(str);
* // => 'foo; \n '
* // => 'const foo = "bar";'
* ```
*
* @name strip
* @param {String} `<input>` string from which to strip comments
* @param {Object} `opts` optional options, passed to [extract-comments][extract-comments]
* @option {Boolean} [opts] `line` if `false` strip only block comments, default `true`
* @option {Boolean} [opts] `block` if `false` strip only line comments, default `true`
* @option {Boolean} [opts] `safe` pass `true` to keep ignored comments (e.g. `/*!` and `//!`)
* @option {Boolean} [opts] `preserveNewlines` if `true` preserve newlines after comments are stripped
* @param {String} `input` string from which to strip comments
* @param {Object} `options` optional options, passed to [extract-comments][extract-comments]
* @option {Boolean} [options] `line` if `false` strip only block comments, default `true`
* @option {Boolean} [options] `block` if `false` strip only line comments, default `true`
* @option {Boolean} [options] `keepProtected` Keep ignored comments (e.g. `/*!` and `//!`)
* @option {Boolean} [options] `preserveNewlines` Preserve newlines after comments are stripped
* @return {String} modified input

@@ -38,6 +35,5 @@ * @api public

exports = module.exports = function stripAllComments(input, opts) {
opts = extend({block: true, line: true}, opts);
return stripComments(input, opts);
};
function strip(input, options) {
return stripComments(input, assign({ block: true, line: true }, options));
}

@@ -47,21 +43,11 @@ /**

*
* **Example**
*
* ```js
* var output = strip('foo; // this is a comment\n /* me too *\/', { line: false });
* console.log(output);
* // => 'foo; // this is a comment\n '
* const strip = require('..');
* const str = strip.block('const foo = "bar";// this is a comment\n /* me too *\/');
* console.log(str);
* // => 'const foo = "bar";// this is a comment'
* ```
*
* **Example**
*
* ```js
* var output = strip.block('foo; // this is a comment\n /* me too *\/');
* console.log(output);
* // => 'foo; // this is a comment\n '
* ```
*
* @name .block
* @param {String} `<input>` string from which to strip comments
* @param {Object} `[opts]` pass `opts.safe: true` to keep ignored comments (e.g. `/*!`)
* @param {String} `input` string from which to strip comments
* @param {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`)
* @return {String} modified string

@@ -71,5 +57,4 @@ * @api public

exports.block = function stripBlockComments(input, opts) {
opts = extend({block: true}, opts);
return stripComments(input, opts);
strip.block = function(input, options) {
return stripComments(input, assign({ block: true }, options));
};

@@ -80,21 +65,10 @@

*
* **Example**
*
* ```js
* var output = strip('foo; // this is a comment\n /* me too *\/', { block: false });
* console.log(output);
* // => 'foo; \n /* me too *\/'
* const str = strip.line('const foo = "bar";// this is a comment\n /* me too *\/');
* console.log(str);
* // => 'const foo = "bar";\n/* me too *\/'
* ```
*
* **Example**
*
* ```js
* var output = strip.line('foo; // this is a comment\n /* me too *\/');
* console.log(output);
* // => 'foo; \n /* me too *\/'
* ```
*
* @name .line
* @param {String} `<input>` string from which to strip comments
* @param {Object} `[opts]` pass `opts.safe: true` to keep ignored comments (e.g. `//!`)
* @param {String} `input` string from which to strip comments
* @param {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`)
* @return {String} modified string

@@ -104,34 +78,18 @@ * @api public

exports.line = function stripLineComments(input, opts) {
opts = extend({line: true}, opts);
return stripComments(input, opts);
strip.line = function(input, options) {
return stripComments(input, assign({ line: true }, options));
};
/**
* Strip the first comment from the given `input`.
* If `opts.safe: true` is passed, will strip the first that is not ignored.
* Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true,
* the first non-protected comment will be stripped.
*
* **Example**
*
* ```js
* var str = '//! first comment\nfoo; // this is a comment';
* var output = strip(str, {
* first: true
* });
* const output = strip.first(input, { keepProtected: true });
* console.log(output);
* // => '\nfoo; // this is a comment'
* ```
*
* **Example**
*
* ```js
* var str = '//! first comment\nfoo; // this is a comment';
* var output = strip.first(str, { safe: true });
* console.log(output);
* // => '//! first comment\nfoo; '
* ```
*
* @name .first
* @param {String} `<input>`
* @param {Object} `[opts]` pass `opts.safe: true` to keep comments with `!`
* @param {String} `input`
* @param {Object} `options` pass `opts.keepProtected: true` to keep comments with `!`
* @return {String}

@@ -141,4 +99,4 @@ * @api public

exports.first = function stripFirstComment(input, opts) {
opts = extend({block: true, line: true, first: true}, opts);
strip.first = function(input, options) {
const opts = assign({ block: true, line: true, first: true }, options);
return stripComments(input, opts);

@@ -148,28 +106,38 @@ };

/**
* Private function for stripping comments.
*
* @param {String} `<input>`
* @param {Object} `[opts]`
* @return {String}
* @api private
* Strip comments
*/
function stripComments(input, opts) {
function stripComments(input, options, tried) {
if (typeof input !== 'string') {
throw new TypeError('expected a string');
}
// strip all by default, including `ingored` comments.
opts = extend({
block: false,
line: false,
safe: false,
first: false
}, opts);
const defaults = { block: false, line: false, safe: false, first: false };
const opts = assign({}, defaults, options);
tried = tried || 0;
// compatibility with `extract-comments`
opts.keepProtected = opts.safe;
if (typeof opts.keepProtected !== 'boolean') {
opts.keepProtected = opts.safe;
}
var comments = extract(input, opts);
var len = comments.length;
var i = 0;
try {
const comments = extract(input, opts);
let pos = { start: 0, end: 0, removed: 0 };
while (i < len) {
var comment = comments[i++];
input = discard(input, comment, opts);
for (const comment of comments) {
if (typeof opts.filter === 'function' && opts.filter(comment, opts) === false) {
continue;
}
input = remove(input, comment, opts, pos);
if (opts.first === true && !isProtected(comment, opts)) {
break;
}
}
} catch (err) {
if (options.verbose) {
throw err;
}
}

@@ -180,26 +148,37 @@ return input;

/**
* Remove a comment from the given string.
*
* @param {String} `str`
* @param {Object} `comment`
* @param {Object} `opts`
* @return {String}
* Remove a single comment from the given string.
*/
function discard(str, comment, opts) {
var ch = comment.value.charAt(0);
if (opts && opts.safe === true && ch === '!') {
function remove(str, comment, options, pos) {
let nl = '';
if (isProtected(comment, options)) {
return str;
}
var nl = '';
if (opts && opts.preserveNewlines) {
nl = comment.raw.replace(/[^\r\n]/g, '');
if (options && options.preserveNewlines) {
nl = comment.value.replace(/[^\r\n]/g, '');
}
if (comment.type === 'line') {
str = str.replace('//' + comment.raw, nl);
if (comment.type === 'CommentLine' && options.line === true) {
const before = str.slice(0, comment.start - pos.removed);
const after = str.slice(comment.end - pos.removed);
pos.removed += comment.end - comment.start - nl.length;
return before + nl + after;
}
if (comment.type === 'block') {
str = str.replace('/*' + comment.raw + '*/', nl);
if (comment.type === 'CommentBlock' && options.block === true) {
const before = str.slice(0, comment.start - pos.removed);
const after = str.slice(comment.end - pos.removed);
pos.removed += comment.end - comment.start - nl.length;
return before + nl + after;
}
return str;
}
function isProtected(comment, options) {
return options && options.keepProtected === true && /^\*?!/.test(comment.value);
}
module.exports = strip;
{
"name": "strip-comments",
"description": "Strip comments from code. Removes line comments, block comments, the first comment only, or all comments. Optionally leave protected comments unharmed.",
"version": "0.4.4",
"version": "1.0.0",
"homepage": "https://github.com/jonschlinkert/strip-comments",

@@ -15,4 +15,5 @@ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",

],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
"node": ">=4"
},

@@ -23,20 +24,17 @@ "scripts": {

"dependencies": {
"extend-shallow": "^2.0.1",
"extract-comments": "^0.10.1"
"babel-extract-comments": "^1.0.0"
},
"devDependencies": {
"gulp-format-md": "^0.1.5",
"mocha": "*"
"gulp-format-md": "^1.0.0",
"mocha": "^3.5.3"
},
"keywords": [
"block",
"block comment",
"code comment",
"comment",
"comments",
"expressions",
"javascript",
"line",
"protected",
"re",
"regex",
"regexp",
"regular",
"line comment",
"remove",

@@ -47,2 +45,3 @@ "strip"

"toc": true,
"layout": "default",
"tasks": [

@@ -54,14 +53,18 @@ "readme"

],
"helpers": [
"./examples/support/helpers.js"
],
"related": {
"list": [
"babel-extract-comments",
"code-context",
"esprima-extract-comments",
"extract-comments",
"js-comments",
"parse-code-context",
"parse-comments",
"snapdragon"
"parse-comments"
]
},
"lint": {
"reflinks": true
}
}
}

@@ -1,6 +0,6 @@

# strip-comments [![NPM version](https://img.shields.io/npm/v/strip-comments.svg)](https://www.npmjs.com/package/strip-comments) [![Build Status](https://img.shields.io/travis/jonschlinkert/strip-comments.svg)](https://travis-ci.org/jonschlinkert/strip-comments)
# strip-comments [![NPM version](https://img.shields.io/npm/v/strip-comments.svg?style=flat)](https://www.npmjs.com/package/strip-comments) [![NPM monthly downloads](https://img.shields.io/npm/dm/strip-comments.svg?style=flat)](https://npmjs.org/package/strip-comments) [![NPM total downloads](https://img.shields.io/npm/dt/strip-comments.svg?style=flat)](https://npmjs.org/package/strip-comments) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/strip-comments.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/strip-comments)
> Strip comments from code. Removes line comments, block comments, the first comment only, or all comments. Optionally leave protected comments unharmed.
## Table Of Contents
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.

@@ -10,7 +10,3 @@ - [Install](#install)

- [API](#api)
- [Related projects](#related-projects)
- [Running tests](#running-tests)
- [Contributing](#contributing)
- [Author](#author)
- [License](#license)
- [About](#about)

@@ -24,3 +20,3 @@ _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_

```sh
$ npm i strip-comments --save
$ npm install --save strip-comments
```

@@ -30,41 +26,41 @@

For more use-cases see the [tests](./test/test.js)
By default all comments are stripped.
```js
var strip = require('strip-comments');
console.log(strip('Hey! // foo'));
//=> 'Hey !';
const strip = require('strip-comments');
const str = strip('const foo = "bar";// this is a comment\n /* me too *\/');
console.log(str);
// => 'const foo = "bar";\n'
```
For more use-cases see the [tests](./test/test.js)
## API
### [strip](index.js#L37)
### [strip](index.js#L34)
Strip all code comments from the given `input`, including these that are ignored. Pass `opts.safe: true` to keep them.
Strip all code comments from the given `input`, including protected comments that start with `!`, unless disabled by setting `options.keepProtected` to true.
**Params**
*
`<input>` **{String}**: string from which to strip comments
* `input` **{String}**: string from which to strip comments
* `options` **{Object}**: optional options, passed to [extract-comments](https://github.com/jonschlinkert/extract-comments)
* `returns` **{String}**: modified input
*
`opts` **{Object}**: optional options, passed to [extract-comments][extract-comments]
**Options**
- `line` **{Boolean}**: if `false` strip only block comments, default `true`
- `block` **{Boolean}**: if `false` strip only line comments, default `true`
- `safe` **{Boolean}**: pass `true` to keep ignored comments (e.g. `/*!` and `//!`)
- `preserveNewlines` **{Boolean}**: if `true` preserve newlines after comments are stripped
- `keepProtected` **{Boolean}**: Keep ignored comments (e.g. `/*!`, `/**!` and `//!`)
- `preserveNewlines` **{Boolean}**: Preserve newlines after comments are stripped
*
`returns` **{String}**: modified input
**Example**
```js
var str = strip('foo; // this is a comment\n /* me too *\/');
const str = strip('const foo = "bar";// this is a comment\n /* me too */');
console.log(str);
// => 'foo; \n '
// => 'const foo = "bar";'
```
### [.block](index.js#L68)
### [.block](index.js#L54)

@@ -75,22 +71,17 @@ Strip only block comments.

* `<input>` **{String}**: string from which to strip comments
* `[opts]` **{Object}**: pass `opts.safe: true` to keep ignored comments (e.g. `/*!`)
* `input` **{String}**: string from which to strip comments
* `options` **{Object}**: pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`)
* `returns` **{String}**: modified string
**Examples**
**Example**
```js
var output = strip('foo; // this is a comment\n /* me too *\/', { line: false });
console.log(output);
// => 'foo; // this is a comment\n '
const strip = require('..');
const str = strip.block('const foo = "bar";// this is a comment\n /* me too */');
console.log(str);
// => 'const foo = "bar";// this is a comment'
```
```js
var output = strip.block('foo; // this is a comment\n /* me too *\/');
console.log(output);
// => 'foo; // this is a comment\n '
```
### [.line](index.js#L73)
### [.line](index.js#L99)
Strip only line comments.

@@ -100,84 +91,100 @@

* `<input>` **{String}**: string from which to strip comments
* `[opts]` **{Object}**: pass `opts.safe: true` to keep ignored comments (e.g. `//!`)
* `input` **{String}**: string from which to strip comments
* `options` **{Object}**: pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`)
* `returns` **{String}**: modified string
**Examples**
**Example**
```js
var output = strip('foo; // this is a comment\n /* me too *\/', { block: false });
console.log(output);
// => 'foo; \n /* me too *\/'
const str = strip.line('const foo = "bar";// this is a comment\n /* me too */');
console.log(str);
// => 'const foo = "bar";\n/* me too */'
```
```js
var output = strip.line('foo; // this is a comment\n /* me too *\/');
console.log(output);
// => 'foo; \n /* me too *\/'
```
### [.first](index.js#L93)
### [.first](index.js#L135)
Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true, the first non-protected comment will be stripped.
Strip the first comment from the given `input`. If `opts.safe: true` is passed, will strip the first that is not ignored.
**Params**
* `<input>` **{String}**
* `[opts]` **{Object}**: pass `opts.safe: true` to keep comments with `!`
* `input` **{String}**
* `options` **{Object}**: pass `opts.keepProtected: true` to keep comments with `!`
* `returns` **{String}**
**Examples**
**Example**
```js
var str = '//! first comment\nfoo; // this is a comment';
var output = strip(str, {
first: true
});
const output = strip.first(input, { keepProtected: true });
console.log(output);
// => '\nfoo; // this is a comment'
// => '//! first comment\nfoo; '
```
```js
var str = '//! first comment\nfoo; // this is a comment';
var output = strip.first(str, { safe: true });
console.log(output);
// => '//! first comment\nfoo; '
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
## Related projects
</details>
* [code-context](https://www.npmjs.com/package/code-context): Parse a string of javascript to determine the context for functions, variables and comments based… [more](https://www.npmjs.com/package/code-context) | [homepage](https://github.com/jonschlinkert/code-context)
* [esprima-extract-comments](https://www.npmjs.com/package/esprima-extract-comments): Extract code comments from string or from a glob of files using esprima. | [homepage](https://github.com/jonschlinkert/esprima-extract-comments)
* [extract-comments](https://www.npmjs.com/package/extract-comments): Uses esprima to extract line and block comments from a string of JavaScript. Also optionally… [more](https://www.npmjs.com/package/extract-comments) | [homepage](https://github.com/jonschlinkert/extract-comments)
* [js-comments](https://www.npmjs.com/package/js-comments): Parse JavaScript code comments and generate API documentation. | [homepage](https://github.com/jonschlinkert/js-comments)
* [parse-code-context](https://www.npmjs.com/package/parse-code-context): Parse code context in a single line of javascript, for functions, variable declarations, methods, prototype… [more](https://www.npmjs.com/package/parse-code-context) | [homepage](https://github.com/jonschlinkert/parse-code-context)
* [parse-comments](https://www.npmjs.com/package/parse-comments): Parse code comments from JavaScript or any language that uses the same format. | [homepage](https://github.com/jonschlinkert/parse-comments)
* [snapdragon](https://www.npmjs.com/package/snapdragon): snapdragon is an extremely pluggable, powerful and easy-to-use parser-renderer factory. | [homepage](https://github.com/jonschlinkert/snapdragon)
<details>
<summary><strong>Building docs</strong></summary>
## Running tests
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
Install dev dependencies:
To generate the readme, run the following command:
```sh
$ npm i -d && npm test
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
## Contributing
</details>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/strip-comments/issues/new).
### Related projects
## Author
You might also be interested in these projects:
* [babel-extract-comments](https://www.npmjs.com/package/babel-extract-comments): Uses babel (babylon) to extract JavaScript code comments from a JavaScript string or file. | [homepage](https://github.com/jonschlinkert/babel-extract-comments "Uses babel (babylon) to extract JavaScript code comments from a JavaScript string or file.")
* [code-context](https://www.npmjs.com/package/code-context): Parse a string of javascript to determine the context for functions, variables and comments based… [more](https://github.com/jonschlinkert/code-context) | [homepage](https://github.com/jonschlinkert/code-context "Parse a string of javascript to determine the context for functions, variables and comments based on the code that follows.")
* [extract-comments](https://www.npmjs.com/package/extract-comments): Uses esprima to extract line and block comments from a string of JavaScript. Also optionally… [more](https://github.com/jonschlinkert/extract-comments) | [homepage](https://github.com/jonschlinkert/extract-comments "Uses esprima to extract line and block comments from a string of JavaScript. Also optionally parses code context (the next line of code after a comment).")
* [parse-code-context](https://www.npmjs.com/package/parse-code-context): Parse code context in a single line of javascript, for functions, variable declarations, methods, prototype… [more](https://github.com/jonschlinkert/parse-code-context) | [homepage](https://github.com/jonschlinkert/parse-code-context "Parse code context in a single line of javascript, for functions, variable declarations, methods, prototype properties, prototype methods etc.")
* [parse-comments](https://www.npmjs.com/package/parse-comments): Parse code comments from JavaScript or any language that uses the same format. | [homepage](https://github.com/jonschlinkert/parse-comments "Parse code comments from JavaScript or any language that uses the same format.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 59 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [charlike-old](https://github.com/charlike-old) |
| 2 | [mk-pmb](https://github.com/mk-pmb) |
| 1 | [kgryte](https://github.com/kgryte) |
| 1 | [epicoxymoron](https://github.com/epicoxymoron) |
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
## License
### License
Copyright © 2014-2016 [Jon Schlinkert](https://github.com/jonschlinkert)
Released under the [MIT license](https://github.com/jonschlinkert/strip-comments/blob/master/LICENSE).
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on February 14, 2016._
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on March 24, 2018._

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc