Minty U

Add OCR Module

Showing 334 changed files with 4832 additions and 0 deletions
../jpeg-autorotate/src/cli.js
\ No newline at end of file
../opencollective-postinstall/index.js
\ No newline at end of file
This diff is collapsed. Click to expand it.
tidelift: "npm/balanced-match"
patreon: juliangruber
(MIT)
Copyright (c) 2013 Julian Gruber <julian@juliangruber.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.
# balanced-match
Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)
## Example
Get the first matching pair of braces:
```js
var balanced = require('balanced-match');
console.log(balanced('{', '}', 'pre{in{nested}}post'));
console.log(balanced('{', '}', 'pre{first}between{second}post'));
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'));
```
The matches are:
```bash
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
end: 9,
pre: 'pre',
body: 'first',
post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
```
## API
### var m = balanced(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
object with those keys:
* **start** the index of the first match of `a`
* **end** the index of the matching `b`
* **pre** the preamble, `a` and `b` not included
* **body** the match, `a` and `b` not included
* **post** the postscript, `a` and `b` not included
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
### var r = balanced.range(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
array with indexes: `[ <a index>, <b index> ]`.
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install balanced-match
```
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
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.
'use strict';
module.exports = balanced;
function balanced(a, b, str) {
if (a instanceof RegExp) a = maybeMatch(a, str);
if (b instanceof RegExp) b = maybeMatch(b, str);
var r = range(a, b, str);
return r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + a.length, r[1]),
post: str.slice(r[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m = str.match(reg);
return m ? m[0] : null;
}
balanced.range = range;
function range(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i = ai;
if (ai >= 0 && bi > 0) {
if(a===b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i == ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length == 1) {
result = [ begs.pop(), bi ];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [ left, right ];
}
}
return result;
}
{
"name": "balanced-match",
"description": "Match balanced character pairs, like \"{\" and \"}\"",
"version": "1.0.2",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/balanced-match.git"
},
"homepage": "https://github.com/juliangruber/balanced-match",
"main": "index.js",
"scripts": {
"test": "tape test/test.js",
"bench": "matcha test/bench.js"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [
"match",
"regexp",
"test",
"balanced",
"parse"
],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}
MIT License
Copyright © 2011 Sebastian Tschan, https://blueimp.net
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.
This diff is collapsed. Click to expand it.
/* global module, require */
module.exports = require('./load-image')
require('./load-image-scale')
require('./load-image-meta')
require('./load-image-fetch')
require('./load-image-exif')
require('./load-image-exif-map')
require('./load-image-iptc')
require('./load-image-iptc-map')
require('./load-image-orientation')
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/*
* JavaScript Load Image Fetch
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2017, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(require('./load-image'))
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
if (typeof fetch !== 'undefined' && typeof Request !== 'undefined') {
loadImage.fetchBlob = function (url, callback, options) {
fetch(new Request(url, options))
.then(function (response) {
return response.blob()
})
.then(callback)
.catch(function (err) {
callback(null, err)
})
}
} else if (
// Check for XHR2 support:
typeof XMLHttpRequest !== 'undefined' &&
typeof ProgressEvent !== 'undefined'
) {
loadImage.fetchBlob = function (url, callback, options) {
// eslint-disable-next-line no-param-reassign
options = options || {}
var req = new XMLHttpRequest()
req.open(options.method || 'GET', url)
if (options.headers) {
Object.keys(options.headers).forEach(function (key) {
req.setRequestHeader(key, options.headers[key])
})
}
req.withCredentials = options.credentials === 'include'
req.responseType = 'blob'
req.onload = function () {
callback(req.response)
}
req.onerror = req.onabort = req.ontimeout = function (err) {
callback(null, err)
}
req.send(options.body)
}
}
})
/*
* JavaScript Load Image IPTC Map
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2013, Sebastian Tschan
* Copyright 2018, Dave Bevan
*
* IPTC tags mapping based on
* https://iptc.org/standards/photo-metadata
* https://exiftool.org/TagNames/IPTC.html
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image', './load-image-iptc'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(require('./load-image'), require('./load-image-iptc'))
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
var IptcMapProto = loadImage.IptcMap.prototype
IptcMapProto.tags = {
0: 'ApplicationRecordVersion',
3: 'ObjectTypeReference',
4: 'ObjectAttributeReference',
5: 'ObjectName',
7: 'EditStatus',
8: 'EditorialUpdate',
10: 'Urgency',
12: 'SubjectReference',
15: 'Category',
20: 'SupplementalCategories',
22: 'FixtureIdentifier',
25: 'Keywords',
26: 'ContentLocationCode',
27: 'ContentLocationName',
30: 'ReleaseDate',
35: 'ReleaseTime',
37: 'ExpirationDate',
38: 'ExpirationTime',
40: 'SpecialInstructions',
42: 'ActionAdvised',
45: 'ReferenceService',
47: 'ReferenceDate',
50: 'ReferenceNumber',
55: 'DateCreated',
60: 'TimeCreated',
62: 'DigitalCreationDate',
63: 'DigitalCreationTime',
65: 'OriginatingProgram',
70: 'ProgramVersion',
75: 'ObjectCycle',
80: 'Byline',
85: 'BylineTitle',
90: 'City',
92: 'Sublocation',
95: 'State',
100: 'CountryCode',
101: 'Country',
103: 'OriginalTransmissionReference',
105: 'Headline',
110: 'Credit',
115: 'Source',
116: 'CopyrightNotice',
118: 'Contact',
120: 'Caption',
121: 'LocalCaption',
122: 'Writer',
125: 'RasterizedCaption',
130: 'ImageType',
131: 'ImageOrientation',
135: 'LanguageIdentifier',
150: 'AudioType',
151: 'AudioSamplingRate',
152: 'AudioSamplingResolution',
153: 'AudioDuration',
154: 'AudioOutcue',
184: 'JobID',
185: 'MasterDocumentID',
186: 'ShortDocumentID',
187: 'UniqueDocumentID',
188: 'OwnerID',
200: 'ObjectPreviewFileFormat',
201: 'ObjectPreviewFileVersion',
202: 'ObjectPreviewData',
221: 'Prefs',
225: 'ClassifyState',
228: 'SimilarityIndex',
230: 'DocumentNotes',
231: 'DocumentHistory',
232: 'ExifCameraInfo',
255: 'CatalogSets'
}
IptcMapProto.stringValues = {
10: {
0: '0 (reserved)',
1: '1 (most urgent)',
2: '2',
3: '3',
4: '4',
5: '5 (normal urgency)',
6: '6',
7: '7',
8: '8 (least urgent)',
9: '9 (user-defined priority)'
},
75: {
a: 'Morning',
b: 'Both Morning and Evening',
p: 'Evening'
},
131: {
L: 'Landscape',
P: 'Portrait',
S: 'Square'
}
}
IptcMapProto.getText = function (id) {
var value = this.get(id)
var tagCode = this.map[id]
var stringValue = this.stringValues[tagCode]
if (stringValue) return stringValue[value]
return String(value)
}
IptcMapProto.getAll = function () {
var map = {}
var prop
var name
for (prop in this) {
if (Object.prototype.hasOwnProperty.call(this, prop)) {
name = this.tags[prop]
if (name) map[name] = this.getText(name)
}
}
return map
}
IptcMapProto.getName = function (tagCode) {
return this.tags[tagCode]
}
// Extend the map of tag names to tag codes:
;(function () {
var tags = IptcMapProto.tags
var map = IptcMapProto.map || {}
var prop
// Map the tag names to tags:
for (prop in tags) {
if (Object.prototype.hasOwnProperty.call(tags, prop)) {
map[tags[prop]] = Number(prop)
}
}
})()
})
/*
* JavaScript Load Image IPTC Parser
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2013, Sebastian Tschan
* Copyright 2018, Dave Bevan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require, DataView */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image', './load-image-meta'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(require('./load-image'), require('./load-image-meta'))
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
/**
* IPTC tag map
*
* @name IptcMap
* @class
*/
function IptcMap() {}
IptcMap.prototype.map = {
ObjectName: 5
}
IptcMap.prototype.types = {
0: 'Uint16', // ApplicationRecordVersion
200: 'Uint16', // ObjectPreviewFileFormat
201: 'Uint16', // ObjectPreviewFileVersion
202: 'binary' // ObjectPreviewData
}
/**
* Retrieves IPTC tag value
*
* @param {number|string} id IPTC tag code or name
* @returns {object} IPTC tag value
*/
IptcMap.prototype.get = function (id) {
return this[id] || this[this.map[id]]
}
/**
* Retrieves string for the given DataView and range
*
* @param {DataView} dataView Data view interface
* @param {number} offset Offset start
* @param {number} length Offset length
* @returns {string} String value
*/
function getStringValue(dataView, offset, length) {
var outstr = ''
var end = offset + length
for (var n = offset; n < end; n += 1) {
outstr += String.fromCharCode(dataView.getUint8(n))
}
return outstr
}
/**
* Retrieves tag value for the given DataView and range
*
* @param {number} tagCode Private IFD tag code
* @param {IptcMap} map IPTC tag map
* @param {DataView} dataView Data view interface
* @param {number} offset Range start
* @param {number} length Range length
* @returns {object} Tag value
*/
function getTagValue(tagCode, map, dataView, offset, length) {
if (map.types[tagCode] === 'binary') {
return new Blob([dataView.buffer.slice(offset, offset + length)])
}
if (map.types[tagCode] === 'Uint16') {
return dataView.getUint16(offset)
}
return getStringValue(dataView, offset, length)
}
/**
* Combines IPTC value with existing ones.
*
* @param {object} value Existing IPTC field value
* @param {object} newValue New IPTC field value
* @returns {object} Resulting IPTC field value
*/
function combineTagValues(value, newValue) {
if (value === undefined) return newValue
if (value instanceof Array) {
value.push(newValue)
return value
}
return [value, newValue]
}
/**
* Parses IPTC tags.
*
* @param {DataView} dataView Data view interface
* @param {number} segmentOffset Segment offset
* @param {number} segmentLength Segment length
* @param {object} data Data export object
* @param {object} includeTags Map of tags to include
* @param {object} excludeTags Map of tags to exclude
*/
function parseIptcTags(
dataView,
segmentOffset,
segmentLength,
data,
includeTags,
excludeTags
) {
var value, tagSize, tagCode
var segmentEnd = segmentOffset + segmentLength
var offset = segmentOffset
while (offset < segmentEnd) {
if (
dataView.getUint8(offset) === 0x1c && // tag marker
dataView.getUint8(offset + 1) === 0x02 // record number, only handles v2
) {
tagCode = dataView.getUint8(offset + 2)
if (
(!includeTags || includeTags[tagCode]) &&
(!excludeTags || !excludeTags[tagCode])
) {
tagSize = dataView.getInt16(offset + 3)
value = getTagValue(tagCode, data.iptc, dataView, offset + 5, tagSize)
data.iptc[tagCode] = combineTagValues(data.iptc[tagCode], value)
if (data.iptcOffsets) {
data.iptcOffsets[tagCode] = offset
}
}
}
offset += 1
}
}
/**
* Tests if field segment starts at offset.
*
* @param {DataView} dataView Data view interface
* @param {number} offset Segment offset
* @returns {boolean} True if '8BIM<EOT><EOT>' exists at offset
*/
function isSegmentStart(dataView, offset) {
return (
dataView.getUint32(offset) === 0x3842494d && // Photoshop segment start
dataView.getUint16(offset + 4) === 0x0404 // IPTC segment start
)
}
/**
* Returns header length.
*
* @param {DataView} dataView Data view interface
* @param {number} offset Segment offset
* @returns {number} Header length
*/
function getHeaderLength(dataView, offset) {
var length = dataView.getUint8(offset + 7)
if (length % 2 !== 0) length += 1
// Check for pre photoshop 6 format
if (length === 0) {
// Always 4
length = 4
}
return length
}
loadImage.parseIptcData = function (dataView, offset, length, data, options) {
if (options.disableIptc) {
return
}
var markerLength = offset + length
while (offset + 8 < markerLength) {
if (isSegmentStart(dataView, offset)) {
var headerLength = getHeaderLength(dataView, offset)
var segmentOffset = offset + 8 + headerLength
if (segmentOffset > markerLength) {
// eslint-disable-next-line no-console
console.log('Invalid IPTC data: Invalid segment offset.')
break
}
var segmentLength = dataView.getUint16(offset + 6 + headerLength)
if (offset + segmentLength > markerLength) {
// eslint-disable-next-line no-console
console.log('Invalid IPTC data: Invalid segment size.')
break
}
// Create the iptc object to store the tags:
data.iptc = new IptcMap()
if (!options.disableIptcOffsets) {
data.iptcOffsets = new IptcMap()
}
parseIptcTags(
dataView,
segmentOffset,
segmentLength,
data,
options.includeIptcTags,
options.excludeIptcTags || { 202: true } // ObjectPreviewData
)
return
}
// eslint-disable-next-line no-param-reassign
offset += 1
}
}
// Registers this IPTC parser for the APP13 JPEG meta data segment:
loadImage.metaDataParsers.jpeg[0xffed].push(loadImage.parseIptcData)
loadImage.IptcMap = IptcMap
// Adds the following properties to the parseMetaData callback data:
// - iptc: The iptc tags, parsed by the parseIptcData method
// Adds the following options to the parseMetaData method:
// - disableIptc: Disables IPTC parsing when true.
// - disableIptcOffsets: Disables storing IPTC tag offsets when true.
// - includeIptcTags: A map of IPTC tags to include for parsing.
// - excludeIptcTags: A map of IPTC tags to exclude from parsing.
})
/*
* JavaScript Load Image Meta
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Image meta data handling implementation
* based on the help and contribution of
* Achim Stöhr.
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require, DataView, Uint8Array */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(require('./load-image'))
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
var hasblobSlice =
typeof Blob !== 'undefined' &&
(Blob.prototype.slice ||
Blob.prototype.webkitSlice ||
Blob.prototype.mozSlice)
loadImage.blobSlice =
hasblobSlice &&
function () {
var slice = this.slice || this.webkitSlice || this.mozSlice
return slice.apply(this, arguments)
}
loadImage.metaDataParsers = {
jpeg: {
0xffe1: [], // APP1 marker
0xffed: [] // APP13 marker
}
}
// Parses image meta data and calls the callback with an object argument
// with the following properties:
// * imageHead: The complete image head as ArrayBuffer (Uint8Array for IE10)
// The options argument accepts an object and supports the following
// properties:
// * maxMetaDataSize: Defines the maximum number of bytes to parse.
// * disableImageHead: Disables creating the imageHead property.
loadImage.parseMetaData = function (file, callback, options, data) {
// eslint-disable-next-line no-param-reassign
options = options || {}
// eslint-disable-next-line no-param-reassign
data = data || {}
var that = this
// 256 KiB should contain all EXIF/ICC/IPTC segments:
var maxMetaDataSize = options.maxMetaDataSize || 262144
var noMetaData = !(
typeof DataView !== 'undefined' &&
file &&
file.size >= 12 &&
file.type === 'image/jpeg' &&
loadImage.blobSlice
)
if (
noMetaData ||
!loadImage.readFile(
loadImage.blobSlice.call(file, 0, maxMetaDataSize),
function (e) {
if (e.target.error) {
// FileReader error
// eslint-disable-next-line no-console
console.log(e.target.error)
callback(data)
return
}
// Note on endianness:
// Since the marker and length bytes in JPEG files are always
// stored in big endian order, we can leave the endian parameter
// of the DataView methods undefined, defaulting to big endian.
var buffer = e.target.result
var dataView = new DataView(buffer)
var offset = 2
var maxOffset = dataView.byteLength - 4
var headLength = offset
var markerBytes
var markerLength
var parsers
var i
// Check for the JPEG marker (0xffd8):
if (dataView.getUint16(0) === 0xffd8) {
while (offset < maxOffset) {
markerBytes = dataView.getUint16(offset)
// Search for APPn (0xffeN) and COM (0xfffe) markers,
// which contain application-specific meta-data like
// Exif, ICC and IPTC data and text comments:
if (
(markerBytes >= 0xffe0 && markerBytes <= 0xffef) ||
markerBytes === 0xfffe
) {
// The marker bytes (2) are always followed by
// the length bytes (2), indicating the length of the
// marker segment, which includes the length bytes,
// but not the marker bytes, so we add 2:
markerLength = dataView.getUint16(offset + 2) + 2
if (offset + markerLength > dataView.byteLength) {
// eslint-disable-next-line no-console
console.log('Invalid meta data: Invalid segment size.')
break
}
parsers = loadImage.metaDataParsers.jpeg[markerBytes]
if (parsers && !options.disableMetaDataParsers) {
for (i = 0; i < parsers.length; i += 1) {
parsers[i].call(
that,
dataView,
offset,
markerLength,
data,
options
)
}
}
offset += markerLength
headLength = offset
} else {
// Not an APPn or COM marker, probably safe to
// assume that this is the end of the meta data
break
}
}
// Meta length must be longer than JPEG marker (2)
// plus APPn marker (2), followed by length bytes (2):
if (!options.disableImageHead && headLength > 6) {
if (buffer.slice) {
data.imageHead = buffer.slice(0, headLength)
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
data.imageHead = new Uint8Array(buffer).subarray(0, headLength)
}
}
} else {
// eslint-disable-next-line no-console
console.log('Invalid JPEG file: Missing JPEG marker.')
}
callback(data)
},
'readAsArrayBuffer'
)
) {
callback(data)
}
}
// Replaces the image head of a JPEG blob with the given one.
// Calls the callback with the new Blob:
loadImage.replaceHead = function (blob, head, callback) {
loadImage.parseMetaData(
blob,
function (data) {
callback(
new Blob(
[head, loadImage.blobSlice.call(blob, data.imageHead.byteLength)],
{ type: 'image/jpeg' }
)
)
},
{ maxMetaDataSize: 256, disableMetaDataParsers: true }
)
}
var originalTransform = loadImage.transform
loadImage.transform = function (img, options, callback, file, data) {
if (loadImage.hasMetaOption(options)) {
loadImage.parseMetaData(
file,
function (data) {
originalTransform.call(loadImage, img, options, callback, file, data)
},
options,
data
)
} else {
originalTransform.apply(loadImage, arguments)
}
}
})
/*
* JavaScript Load Image Orientation
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image', './load-image-scale', './load-image-meta'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(
require('./load-image'),
require('./load-image-scale'),
require('./load-image-meta')
)
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
var originalHasCanvasOption = loadImage.hasCanvasOption
var originalHasMetaOption = loadImage.hasMetaOption
var originalTransformCoordinates = loadImage.transformCoordinates
var originalGetTransformedOptions = loadImage.getTransformedOptions
;(function () {
// black 2x1 JPEG, with the following meta information set:
// - EXIF Orientation: 6 (Rotated 90° CCW)
var testImageURL =
'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' +
'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' +
'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' +
'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/x' +
'ABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAA' +
'AAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q=='
var img = document.createElement('img')
img.onload = function () {
// Check if browser supports automatic image orientation:
loadImage.orientation = img.width === 1 && img.height === 2
}
img.src = testImageURL
})()
// Determines if the target image should be a canvas element:
loadImage.hasCanvasOption = function (options) {
return (
(!!options.orientation === true && !loadImage.orientation) ||
(options.orientation > 1 && options.orientation < 9) ||
originalHasCanvasOption.call(loadImage, options)
)
}
// Determines if meta data should be loaded automatically:
loadImage.hasMetaOption = function (options) {
return (
(options && options.orientation === true && !loadImage.orientation) ||
originalHasMetaOption.call(loadImage, options)
)
}
// Transform image orientation based on
// the given EXIF orientation option:
loadImage.transformCoordinates = function (canvas, options) {
originalTransformCoordinates.call(loadImage, canvas, options)
var ctx = canvas.getContext('2d')
var width = canvas.width
var height = canvas.height
var styleWidth = canvas.style.width
var styleHeight = canvas.style.height
var orientation = options.orientation
if (!(orientation > 1 && orientation < 9)) {
return
}
if (orientation > 4) {
canvas.width = height
canvas.height = width
canvas.style.width = styleHeight
canvas.style.height = styleWidth
}
switch (orientation) {
case 2:
// horizontal flip
ctx.translate(width, 0)
ctx.scale(-1, 1)
break
case 3:
// 180° rotate left
ctx.translate(width, height)
ctx.rotate(Math.PI)
break
case 4:
// vertical flip
ctx.translate(0, height)
ctx.scale(1, -1)
break
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI)
ctx.scale(1, -1)
break
case 6:
// 90° rotate right
ctx.rotate(0.5 * Math.PI)
ctx.translate(0, -height)
break
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI)
ctx.translate(width, -height)
ctx.scale(-1, 1)
break
case 8:
// 90° rotate left
ctx.rotate(-0.5 * Math.PI)
ctx.translate(-width, 0)
break
}
}
// Transforms coordinate and dimension options
// based on the given orientation option:
loadImage.getTransformedOptions = function (img, opts, data) {
var options = originalGetTransformedOptions.call(loadImage, img, opts)
var orientation = options.orientation
var newOptions
var i
if (orientation === true) {
if (loadImage.orientation) {
// Browser supports automatic image orientation
return options
}
orientation = data && data.exif && data.exif.get('Orientation')
}
if (!(orientation > 1 && orientation < 9)) {
return options
}
newOptions = {}
for (i in options) {
if (Object.prototype.hasOwnProperty.call(options, i)) {
newOptions[i] = options[i]
}
}
newOptions.orientation = orientation
switch (orientation) {
case 2:
// horizontal flip
newOptions.left = options.right
newOptions.right = options.left
break
case 3:
// 180° rotate left
newOptions.left = options.right
newOptions.top = options.bottom
newOptions.right = options.left
newOptions.bottom = options.top
break
case 4:
// vertical flip
newOptions.top = options.bottom
newOptions.bottom = options.top
break
case 5:
// vertical flip + 90 rotate right
newOptions.left = options.top
newOptions.top = options.left
newOptions.right = options.bottom
newOptions.bottom = options.right
break
case 6:
// 90° rotate right
newOptions.left = options.top
newOptions.top = options.right
newOptions.right = options.bottom
newOptions.bottom = options.left
break
case 7:
// horizontal flip + 90 rotate right
newOptions.left = options.bottom
newOptions.top = options.right
newOptions.right = options.top
newOptions.bottom = options.left
break
case 8:
// 90° rotate left
newOptions.left = options.bottom
newOptions.top = options.left
newOptions.right = options.top
newOptions.bottom = options.right
break
}
if (newOptions.orientation > 4) {
newOptions.maxWidth = options.maxHeight
newOptions.maxHeight = options.maxWidth
newOptions.minWidth = options.minHeight
newOptions.minHeight = options.minWidth
newOptions.sourceWidth = options.sourceHeight
newOptions.sourceHeight = options.sourceWidth
}
return newOptions
}
})
/*
* JavaScript Load Image Scaling
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, module, require */
;(function (factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['./load-image'], factory)
} else if (typeof module === 'object' && module.exports) {
factory(require('./load-image'))
} else {
// Browser globals:
factory(window.loadImage)
}
})(function (loadImage) {
'use strict'
var originalTransform = loadImage.transform
loadImage.transform = function (img, options, callback, file, data) {
originalTransform.call(
loadImage,
loadImage.scale(img, options, data),
options,
callback,
file,
data
)
}
// Transform image coordinates, allows to override e.g.
// the canvas orientation based on the orientation option,
// gets canvas, options passed as arguments:
loadImage.transformCoordinates = function () {}
// Returns transformed options, allows to override e.g.
// maxWidth, maxHeight and crop options based on the aspectRatio.
// gets img, options passed as arguments:
loadImage.getTransformedOptions = function (img, options) {
var aspectRatio = options.aspectRatio
var newOptions
var i
var width
var height
if (!aspectRatio) {
return options
}
newOptions = {}
for (i in options) {
if (Object.prototype.hasOwnProperty.call(options, i)) {
newOptions[i] = options[i]
}
}
newOptions.crop = true
width = img.naturalWidth || img.width
height = img.naturalHeight || img.height
if (width / height > aspectRatio) {
newOptions.maxWidth = height * aspectRatio
newOptions.maxHeight = height
} else {
newOptions.maxWidth = width
newOptions.maxHeight = width / aspectRatio
}
return newOptions
}
// Canvas render method, allows to implement a different rendering algorithm:
loadImage.renderImageToCanvas = function (
canvas,
img,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
destX,
destY,
destWidth,
destHeight,
options
) {
var ctx = canvas.getContext('2d')
if (options.imageSmoothingEnabled === false) {
ctx.imageSmoothingEnabled = false
} else if (options.imageSmoothingQuality) {
ctx.imageSmoothingQuality = options.imageSmoothingQuality
}
ctx.drawImage(
img,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
destX,
destY,
destWidth,
destHeight
)
return canvas
}
// Determines if the target image should be a canvas element:
loadImage.hasCanvasOption = function (options) {
return options.canvas || options.crop || !!options.aspectRatio
}
// Scales and/or crops the given image (img or canvas HTML element)
// using the given options.
// Returns a canvas object if the browser supports canvas
// and the hasCanvasOption method returns true or a canvas
// object is passed as image, else the scaled image:
loadImage.scale = function (img, options, data) {
// eslint-disable-next-line no-param-reassign
options = options || {}
var canvas = document.createElement('canvas')
var useCanvas =
img.getContext ||
(loadImage.hasCanvasOption(options) && canvas.getContext)
var width = img.naturalWidth || img.width
var height = img.naturalHeight || img.height
var destWidth = width
var destHeight = height
var maxWidth
var maxHeight
var minWidth
var minHeight
var sourceWidth
var sourceHeight
var sourceX
var sourceY
var pixelRatio
var downsamplingRatio
var tmp
/**
* Scales up image dimensions
*/
function scaleUp() {
var scale = Math.max(
(minWidth || destWidth) / destWidth,
(minHeight || destHeight) / destHeight
)
if (scale > 1) {
destWidth *= scale
destHeight *= scale
}
}
/**
* Scales down image dimensions
*/
function scaleDown() {
var scale = Math.min(
(maxWidth || destWidth) / destWidth,
(maxHeight || destHeight) / destHeight
)
if (scale < 1) {
destWidth *= scale
destHeight *= scale
}
}
if (useCanvas) {
// eslint-disable-next-line no-param-reassign
options = loadImage.getTransformedOptions(img, options, data)
sourceX = options.left || 0
sourceY = options.top || 0
if (options.sourceWidth) {
sourceWidth = options.sourceWidth
if (options.right !== undefined && options.left === undefined) {
sourceX = width - sourceWidth - options.right
}
} else {
sourceWidth = width - sourceX - (options.right || 0)
}
if (options.sourceHeight) {
sourceHeight = options.sourceHeight
if (options.bottom !== undefined && options.top === undefined) {
sourceY = height - sourceHeight - options.bottom
}
} else {
sourceHeight = height - sourceY - (options.bottom || 0)
}
destWidth = sourceWidth
destHeight = sourceHeight
}
maxWidth = options.maxWidth
maxHeight = options.maxHeight
minWidth = options.minWidth
minHeight = options.minHeight
if (useCanvas && maxWidth && maxHeight && options.crop) {
destWidth = maxWidth
destHeight = maxHeight
tmp = sourceWidth / sourceHeight - maxWidth / maxHeight
if (tmp < 0) {
sourceHeight = (maxHeight * sourceWidth) / maxWidth
if (options.top === undefined && options.bottom === undefined) {
sourceY = (height - sourceHeight) / 2
}
} else if (tmp > 0) {
sourceWidth = (maxWidth * sourceHeight) / maxHeight
if (options.left === undefined && options.right === undefined) {
sourceX = (width - sourceWidth) / 2
}
}
} else {
if (options.contain || options.cover) {
minWidth = maxWidth = maxWidth || minWidth
minHeight = maxHeight = maxHeight || minHeight
}
if (options.cover) {
scaleDown()
scaleUp()
} else {
scaleUp()
scaleDown()
}
}
if (useCanvas) {
pixelRatio = options.pixelRatio
if (pixelRatio > 1) {
canvas.style.width = destWidth + 'px'
canvas.style.height = destHeight + 'px'
destWidth *= pixelRatio
destHeight *= pixelRatio
canvas.getContext('2d').scale(pixelRatio, pixelRatio)
}
downsamplingRatio = options.downsamplingRatio
if (
downsamplingRatio > 0 &&
downsamplingRatio < 1 &&
destWidth < sourceWidth &&
destHeight < sourceHeight
) {
while (sourceWidth * downsamplingRatio > destWidth) {
canvas.width = sourceWidth * downsamplingRatio
canvas.height = sourceHeight * downsamplingRatio
loadImage.renderImageToCanvas(
canvas,
img,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
0,
0,
canvas.width,
canvas.height,
options
)
sourceX = 0
sourceY = 0
sourceWidth = canvas.width
sourceHeight = canvas.height
// eslint-disable-next-line no-param-reassign
img = document.createElement('canvas')
img.width = sourceWidth
img.height = sourceHeight
loadImage.renderImageToCanvas(
img,
canvas,
0,
0,
sourceWidth,
sourceHeight,
0,
0,
sourceWidth,
sourceHeight,
options
)
}
}
canvas.width = destWidth
canvas.height = destHeight
loadImage.transformCoordinates(canvas, options)
return loadImage.renderImageToCanvas(
canvas,
img,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
0,
0,
destWidth,
destHeight,
options
)
}
img.width = destWidth
img.height = destHeight
return img
}
})
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
/*
* JavaScript Load Image
* https://github.com/blueimp/JavaScript-Load-Image
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* global define, webkitURL, module */
;(function ($) {
'use strict'
/**
* Loads an image for a given File object.
* Invokes the callback with an img or optional canvas element
* (if supported by the browser) as parameter:.
*
* @param {File|Blob|string} file File or Blob object or image URL
* @param {Function} [callback] Image load event callback
* @param {object} [options] Options object
* @returns {HTMLImageElement|HTMLCanvasElement|FileReader} image object
*/
function loadImage(file, callback, options) {
var img = document.createElement('img')
var url
/**
* Callback for the fetchBlob call.
*
* @param {Blob} blob Blob object
* @param {Error} err Error object
*/
function fetchBlobCallback(blob, err) {
if (err) console.log(err) // eslint-disable-line no-console
if (blob && loadImage.isInstanceOf('Blob', blob)) {
// eslint-disable-next-line no-param-reassign
file = blob
url = loadImage.createObjectURL(file)
} else {
url = file
if (options && options.crossOrigin) {
img.crossOrigin = options.crossOrigin
}
}
img.src = url
}
img.onerror = function (event) {
return loadImage.onerror(img, event, file, url, callback, options)
}
img.onload = function (event) {
return loadImage.onload(img, event, file, url, callback, options)
}
if (typeof file === 'string') {
if (loadImage.hasMetaOption(options)) {
loadImage.fetchBlob(file, fetchBlobCallback, options)
} else {
fetchBlobCallback()
}
return img
} else if (
loadImage.isInstanceOf('Blob', file) ||
// Files are also Blob instances, but some browsers
// (Firefox 3.6) support the File API but not Blobs:
loadImage.isInstanceOf('File', file)
) {
url = loadImage.createObjectURL(file)
if (url) {
img.src = url
return img
}
return loadImage.readFile(file, function (e) {
var target = e.target
if (target && target.result) {
img.src = target.result
} else if (callback) {
callback(e)
}
})
}
}
// The check for URL.revokeObjectURL fixes an issue with Opera 12,
// which provides URL.createObjectURL but doesn't properly implement it:
var urlAPI =
($.createObjectURL && $) ||
($.URL && URL.revokeObjectURL && URL) ||
($.webkitURL && webkitURL)
/**
* Helper function to revoke an object URL
*
* @param {string} url Blob Object URL
* @param {object} [options] Options object
*/
function revokeHelper(url, options) {
if (url && url.slice(0, 5) === 'blob:' && !(options && options.noRevoke)) {
loadImage.revokeObjectURL(url)
}
}
// Determines if meta data should be loaded automatically.
// Requires the load image meta extension to load meta data.
loadImage.hasMetaOption = function (options) {
return options && options.meta
}
// If the callback given to this function returns a blob, it is used as image
// source instead of the original url and overrides the file argument used in
// the onload and onerror event callbacks:
loadImage.fetchBlob = function (url, callback) {
callback()
}
loadImage.isInstanceOf = function (type, obj) {
// Cross-frame instanceof check
return Object.prototype.toString.call(obj) === '[object ' + type + ']'
}
loadImage.transform = function (img, options, callback, file, data) {
callback(img, data)
}
loadImage.onerror = function (img, event, file, url, callback, options) {
revokeHelper(url, options)
if (callback) {
callback.call(img, event)
}
}
loadImage.onload = function (img, event, file, url, callback, options) {
revokeHelper(url, options)
if (callback) {
loadImage.transform(img, options, callback, file, {
originalWidth: img.naturalWidth || img.width,
originalHeight: img.naturalHeight || img.height
})
}
}
loadImage.createObjectURL = function (file) {
return urlAPI ? urlAPI.createObjectURL(file) : false
}
loadImage.revokeObjectURL = function (url) {
return urlAPI ? urlAPI.revokeObjectURL(url) : false
}
// Loads a given File object via FileReader interface,
// invokes the callback with the event object (load or error).
// The result can be read via event.target.result:
loadImage.readFile = function (file, callback, method) {
if ($.FileReader) {
var fileReader = new FileReader()
fileReader.onload = fileReader.onerror = callback
// eslint-disable-next-line no-param-reassign
method = method || 'readAsDataURL'
if (fileReader[method]) {
fileReader[method](file)
return fileReader
}
}
return false
}
if (typeof define === 'function' && define.amd) {
define(function () {
return loadImage
})
} else if (typeof module === 'object' && module.exports) {
module.exports = loadImage
} else {
$.loadImage = loadImage
}
})((typeof window !== 'undefined' && window) || this)
{
"name": "blueimp-load-image",
"version": "3.0.0",
"title": "JavaScript Load Image",
"description": "JavaScript Load Image is a library to load images provided as File or Blob objects or via URL. It returns an optionally scaled and/or cropped HTML img or canvas element. It also provides methods to parse image meta data to extract IPTC and Exif tags as well as embedded thumbnail images and to restore the complete image header after resizing.",
"keywords": [
"javascript",
"load",
"loading",
"image",
"file",
"blob",
"url",
"scale",
"crop",
"img",
"canvas",
"meta",
"exif",
"iptc",
"thumbnail",
"resizing"
],
"homepage": "https://github.com/blueimp/JavaScript-Load-Image",
"author": {
"name": "Sebastian Tschan",
"url": "https://blueimp.net"
},
"repository": {
"type": "git",
"url": "git://github.com/blueimp/JavaScript-Load-Image.git"
},
"license": "MIT",
"devDependencies": {
"eslint": "6",
"eslint-config-blueimp": "1",
"eslint-config-prettier": "6",
"eslint-plugin-jsdoc": "22",
"eslint-plugin-prettier": "3",
"prettier": "2",
"uglify-js": "3"
},
"eslintConfig": {
"extends": [
"blueimp",
"plugin:jsdoc/recommended",
"plugin:prettier/recommended"
],
"env": {
"browser": true
}
},
"eslintIgnore": [
"js/*.min.js",
"js/vendor",
"test/vendor"
],
"prettier": {
"arrowParens": "avoid",
"proseWrap": "always",
"semi": false,
"singleQuote": true,
"trailingComma": "none"
},
"scripts": {
"lint": "eslint .",
"unit": "docker-compose run --rm mocha",
"test": "npm run lint && npm run unit",
"posttest": "docker-compose down -v",
"build": "cd js && uglifyjs load-image.js load-image-scale.js load-image-meta.js load-image-fetch.js load-image-orientation.js load-image-exif.js load-image-exif-map.js load-image-iptc.js load-image-iptc-map.js -c -m -o load-image.all.min.js --source-map url=load-image.all.min.js.map",
"preversion": "npm test",
"version": "npm run build && git add -A js",
"postversion": "git push --tags origin master master:gh-pages && npm publish"
},
"files": [
"js/*.js",
"js/*.js.map"
],
"main": "js/index.js"
}
node_modules
.idea
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2014 @丝刀口
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.
bmp-js
======
A pure javascript Bmp encoder and decoder for node.js
Supports all bits decoding(1,4,8,16,24,32) and encoding with 24bit.
##Install
$ npm install bmp-js
How to use?
---
###Decode BMP
```js
var bmp = require("bmp-js");
var bmpBuffer = fs.readFileSync('bit24.bmp');
var bmpData = bmp.decode(bmpBuffer);
```
`bmpData` has all properties includes:
1. fileSize,reserved,offset
2. headerSize,width,height,planes,bitPP,compress,rawSize,hr,vr,colors,importantColors
3. palette
4. data-------byte array order by ABGR ABGR ABGR,4 bytes per pixel
###Encode RGB
```js
var bmp = require("bmp-js");
//bmpData={data:Buffer,width:Number,height:Height}
var rawData = bmp.encode(bmpData);//default no compression,write rawData to .bmp file
```
License
---
U can use on free with [MIT License](https://github.com/shaozilee/bmp-js/blob/master/LICENSE)
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
/**
* @author shaozilee
*
* support 1bit 4bit 8bit 24bit decode
* encode with 24bit
*
*/
var encode = require('./lib/encoder'),
decode = require('./lib/decoder');
module.exports = {
encode: encode,
decode: decode
};
This diff is collapsed. Click to expand it.
/**
* @author shaozilee
*
* BMP format encoder,encode 24bit BMP
* Not support quality compression
*
*/
function BmpEncoder(imgData){
this.buffer = imgData.data;
this.width = imgData.width;
this.height = imgData.height;
this.extraBytes = this.width%4;
this.rgbSize = this.height*(3*this.width+this.extraBytes);
this.headerInfoSize = 40;
this.data = [];
/******************header***********************/
this.flag = "BM";
this.reserved = 0;
this.offset = 54;
this.fileSize = this.rgbSize+this.offset;
this.planes = 1;
this.bitPP = 24;
this.compress = 0;
this.hr = 0;
this.vr = 0;
this.colors = 0;
this.importantColors = 0;
}
BmpEncoder.prototype.encode = function() {
var tempBuffer = new Buffer(this.offset+this.rgbSize);
this.pos = 0;
tempBuffer.write(this.flag,this.pos,2);this.pos+=2;
tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4;
tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4;
tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2;
tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2;
tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4;
tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4;
var i=0;
var rowBytes = 3*this.width+this.extraBytes;
for (var y = 0; y <this.height; y++){
for (var x = 0; x < this.width; x++){
var p = this.pos+y*rowBytes+x*3;
i++;//a
tempBuffer[p]= this.buffer[i++];//b
tempBuffer[p+1] = this.buffer[i++];//g
tempBuffer[p+2] = this.buffer[i++];//r
}
if(this.extraBytes>0){
var fillOffset = this.pos+y*rowBytes+this.width*3;
tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes);
}
}
return tempBuffer;
};
module.exports = function(imgData, quality) {
if (typeof quality === 'undefined') quality = 100;
var encoder = new BmpEncoder(imgData);
var data = encoder.encode();
return {
data: data,
width: imgData.width,
height: imgData.height
};
};
{
"name": "bmp-js",
"version": "0.1.0",
"description": "A pure javascript BMP encoder and decoder",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/shaozilee/bmp-js"
},
"keywords": [
"bmp",
"1bit",
"4bit",
"8bit",
"16bit",
"24bit",
"32bit",
"encoder",
"decoder",
"image",
"javascript",
"js"
],
"author": {
"name": "shaozilee",
"email": "shaozilee@gmail.com"
},
"license": "MIT",
"dependencies": {},
"devDependencies": {
}
}
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
var fs = require("fs");
var coder = require("../index.js");
var bmps = ["./bit1", "./bit4", "./bit4_RLE", "./bit8", "./bit8_RLE", "./bit16_565", "./bit16_a444", "./bit16_a555", "./bit16_x444", "./bit16_x555", "./bit24", "./bit32", "./bit32_alpha"];
console.log("test bmp decoding and encoding...");
for(var b=0; b<bmps.length;b++){
var src =bmps[b];
console.log("----------------"+src+".bmp");
var bufferData = fs.readFileSync(src+".bmp");
var decoder = coder.decode(bufferData);
console.log("width:",decoder.width);
console.log("height",decoder.height);
console.log("fileSize:",decoder.fileSize);
//encode with 24bit
var encodeData = coder.encode(decoder);
fs.writeFileSync(src+"_out.bmp", encodeData.data);
}
console.log("test bmp success!");
MIT License
Copyright (c) 2013 Julian Gruber <julian@juliangruber.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.
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
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.
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "1.1.11",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"gentest": "bash test/generate.sh",
"bench": "matcha test/perf/bench.js"
},
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}
MIT License
Original Library
- Copyright (c) Marak Squires
Additional Functionality
- 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.
# colors.js
[![Build Status](https://travis-ci.org/Marak/colors.js.svg?branch=master)](https://travis-ci.org/Marak/colors.js)
[![version](https://img.shields.io/npm/v/colors.svg)](https://www.npmjs.org/package/colors)
[![dependencies](https://david-dm.org/Marak/colors.js.svg)](https://david-dm.org/Marak/colors.js)
[![devDependencies](https://david-dm.org/Marak/colors.js/dev-status.svg)](https://david-dm.org/Marak/colors.js#info=devDependencies)
Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback, and check the `develop` branch for the latest bleeding-edge updates.
## get color and style in your node.js console
![Demo](https://raw.githubusercontent.com/Marak/colors.js/master/screenshots/colors.png)
## Installation
npm install colors
## colors and styles!
### text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
- grey
### bright text colors
- brightRed
- brightGreen
- brightYellow
- brightBlue
- brightMagenta
- brightCyan
- brightWhite
### background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
- bgGray
- bgGrey
### bright background colors
- bgBrightRed
- bgBrightGreen
- bgBrightYellow
- bgBrightBlue
- bgBrightMagenta
- bgBrightCyan
- bgBrightWhite
### styles
- reset
- bold
- dim
- italic
- underline
- inverse
- hidden
- strikethrough
### extras
- rainbow
- zebra
- america
- trap
- random
## Usage
By popular demand, `colors` now ships with two types of usages!
The super nifty way
```js
var colors = require('colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
```
or a slightly less nifty way which doesn't extend `String.prototype`
```js
var colors = require('colors/safe');
console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass
```
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
## Enabling/Disabling Colors
The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag:
```bash
node myapp.js --no-color
node myapp.js --color=false
node myapp.js --color
node myapp.js --color=true
node myapp.js --color=always
FORCE_COLOR=1 node myapp.js
```
Or in code:
```javascript
var colors = require('colors');
colors.enable();
colors.disable();
```
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
```js
var name = 'Marak';
console.log(colors.green('Hello %s'), name);
// outputs -> 'Hello Marak'
```
## Custom themes
### Using standard API
```js
var colors = require('colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Using string safe API
```js
var colors = require('colors/safe');
// set single property
var error = colors.red;
error('this is red');
// set theme
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
```
### Combining Colors
```javascript
var colors = require('colors');
colors.setTheme({
custom: ['red', 'underline']
});
console.log('test'.custom);
```
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*
var colors = require('../lib/index');
console.log('First some yellow text'.yellow);
console.log('Underline that text'.yellow.underline);
console.log('Make it bold and red'.red.bold);
console.log(('Double Raindows All Day Long').rainbow);
console.log('Drop the bass'.trap);
console.log('DROP THE RAINBOW BASS'.trap.rainbow);
// styles not widely supported
console.log('Chains are also cool.'.bold.italic.underline.red);
// styles not widely supported
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse
+ ' styles! '.yellow.bold);
console.log('Zebras are so fun!'.zebra);
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log('This is ' + 'not'.strikethrough + ' fun.');
console.log('Background color attack!'.black.bgWhite);
console.log('Use random styles on everything!'.random);
console.log('America, Heck Yeah!'.america);
console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen);
console.log('Setting themes is useful');
//
// Custom themes
//
console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
try {
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
} catch (err) {
console.log(err);
}
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
// console.log("Don't summon".zalgo)
var colors = require('../safe');
console.log(colors.yellow('First some yellow text'));
console.log(colors.yellow.underline('Underline that text'));
console.log(colors.red.bold('Make it bold and red'));
console.log(colors.rainbow('Double Raindows All Day Long'));
console.log(colors.trap('Drop the bass'));
console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS')));
// styles not widely supported
console.log(colors.bold.italic.underline.red('Chains are also cool.'));
// styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' '
+ colors.inverse('inverse') + colors.yellow.bold(' styles! '));
console.log(colors.zebra('Zebras are so fun!'));
console.log('This is ' + colors.strikethrough('not') + ' fun.');
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'));
console.log(colors.america('America, Heck Yeah!'));
console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!'));
console.log('Setting themes is useful');
//
// Custom themes
//
// console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'blue',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs blue text
console.log(colors.input('this is an input'));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs grey text
console.log(colors.input('this is an input'));
// console.log(colors.zalgo("Don't summon him"))
// Type definitions for Colors.js 1.2
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/Marak/colors.js
export interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
yellow: Color;
blue: Color;
magenta: Color;
cyan: Color;
white: Color;
gray: Color;
grey: Color;
bgBlack: Color;
bgRed: Color;
bgGreen: Color;
bgYellow: Color;
bgBlue: Color;
bgMagenta: Color;
bgCyan: Color;
bgWhite: Color;
reset: Color;
bold: Color;
dim: Color;
italic: Color;
underline: Color;
inverse: Color;
hidden: Color;
strikethrough: Color;
rainbow: Color;
zebra: Color;
america: Color;
trap: Color;
random: Color;
zalgo: Color;
}
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export let enabled: boolean;
export const strip: Color;
export const stripColors: Color;
export const black: Color;
export const red: Color;
export const green: Color;
export const yellow: Color;
export const blue: Color;
export const magenta: Color;
export const cyan: Color;
export const white: Color;
export const gray: Color;
export const grey: Color;
export const bgBlack: Color;
export const bgRed: Color;
export const bgGreen: Color;
export const bgYellow: Color;
export const bgBlue: Color;
export const bgMagenta: Color;
export const bgCyan: Color;
export const bgWhite: Color;
export const reset: Color;
export const bold: Color;
export const dim: Color;
export const italic: Color;
export const underline: Color;
export const inverse: Color;
export const hidden: Color;
export const strikethrough: Color;
export const rainbow: Color;
export const zebra: Color;
export const america: Color;
export const trap: Color;
export const random: Color;
export const zalgo: Color;
declare global {
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
yellow: string;
blue: string;
magenta: string;
cyan: string;
white: string;
gray: string;
grey: string;
bgBlack: string;
bgRed: string;
bgGreen: string;
bgYellow: string;
bgBlue: string;
bgMagenta: string;
bgCyan: string;
bgWhite: string;
reset: string;
// @ts-ignore
bold: string;
dim: string;
italic: string;
underline: string;
inverse: string;
hidden: string;
strikethrough: string;
rainbow: string;
zebra: string;
america: string;
trap: string;
random: string;
zalgo: string;
}
}
/*
The MIT License (MIT)
Original Library
- Copyright (c) Marak Squires
Additional functionality
- 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.
*/
var colors = {};
module['exports'] = colors;
colors.themes = {};
var util = require('util');
var ansiStyles = colors.styles = require('./styles');
var defineProps = Object.defineProperties;
var newLineRegex = new RegExp(/[\r\n]+/g);
colors.supportsColor = require('./system/supports-colors').supportsColor;
if (typeof colors.enabled === 'undefined') {
colors.enabled = colors.supportsColor() !== false;
}
colors.enable = function() {
colors.enabled = true;
};
colors.disable = function() {
colors.enabled = false;
};
colors.stripColors = colors.strip = function(str) {
return ('' + str).replace(/\x1B\[\d+m/g, '');
};
// eslint-disable-next-line no-unused-vars
var stylize = colors.stylize = function stylize(str, style) {
if (!colors.enabled) {
return str+'';
}
var styleMap = ansiStyles[style];
// Stylize should work for non-ANSI styles, too
if(!styleMap && style in colors){
// Style maps like trap operate as functions on strings;
// they don't have properties like open or close.
return colors[style](str);
}
return styleMap.open + str + styleMap.close;
};
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function(str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto;
return builder;
}
var styles = (function() {
var ret = {};
ansiStyles.grey = ansiStyles.gray;
Object.keys(ansiStyles).forEach(function(key) {
ansiStyles[key].closeRe =
new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function() {
return build(this._styles.concat(key));
},
};
});
return ret;
})();
var proto = defineProps(function colors() {}, styles);
function applyStyle() {
var args = Array.prototype.slice.call(arguments);
var str = args.map(function(arg) {
// Use weak equality check so we can colorize null/undefined in safe mode
if (arg != null && arg.constructor === String) {
return arg;
} else {
return util.inspect(arg);
}
}).join(' ');
if (!colors.enabled || !str) {
return str;
}
var newLinesPresent = str.indexOf('\n') != -1;
var nestedStyles = this._styles;
var i = nestedStyles.length;
while (i--) {
var code = ansiStyles[nestedStyles[i]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
if (newLinesPresent) {
str = str.replace(newLineRegex, function(match) {
return code.close + match + code.open;
});
}
}
return str;
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
}
for (var style in theme) {
(function(style) {
colors[style] = function(str) {
if (typeof theme[style] === 'object') {
var out = str;
for (var i in theme[style]) {
out = colors[theme[style][i]](out);
}
return out;
}
return colors[theme[style]](str);
};
})(style);
}
};
function init() {
var ret = {};
Object.keys(styles).forEach(function(name) {
ret[name] = {
get: function() {
return build([name]);
},
};
});
return ret;
}
var sequencer = function sequencer(map, str) {
var exploded = str.split('');
exploded = exploded.map(map);
return exploded.join('');
};
// custom formatter methods
colors.trap = require('./custom/trap');
colors.zalgo = require('./custom/zalgo');
// maps
colors.maps = {};
colors.maps.america = require('./maps/america')(colors);
colors.maps.zebra = require('./maps/zebra')(colors);
colors.maps.rainbow = require('./maps/rainbow')(colors);
colors.maps.random = require('./maps/random')(colors);
for (var map in colors.maps) {
(function(map) {
colors[map] = function(str) {
return sequencer(colors.maps[map], str);
};
})(map);
}
defineProps(colors, init());
module['exports'] = function runTheTrap(text, options) {
var result = '';
text = text || 'Run the trap, drop the bass';
text = text.split('');
var trap = {
a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
c: ['\u00a9', '\u023b', '\u03fe'],
d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
'\u0a6c'],
f: ['\u04fa'],
g: ['\u0262'],
h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
i: ['\u0f0f'],
j: ['\u0134'],
k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
l: ['\u0139'],
m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
'\u06dd', '\u0e4f'],
p: ['\u01f7', '\u048e'],
q: ['\u09cd'],
r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
t: ['\u0141', '\u0166', '\u0373'],
u: ['\u01b1', '\u054d'],
v: ['\u05d8'],
w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
y: ['\u00a5', '\u04b0', '\u04cb'],
z: ['\u01b5', '\u0240'],
};
text.forEach(function(c) {
c = c.toLowerCase();
var chars = trap[c] || [' '];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c] !== 'undefined') {
result += trap[c][rand];
} else {
result += c;
}
});
return result;
};
// please no
module['exports'] = function zalgo(text, options) {
text = text || ' he is here ';
var soul = {
'up': [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚',
],
'down': [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣',
],
'mid': [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉',
],
};
var all = [].concat(soul.up, soul.down, soul.mid);
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function isChar(character) {
var bool = false;
all.filter(function(i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '';
var counts;
var l;
options = options || {};
options['up'] =
typeof options['up'] !== 'undefined' ? options['up'] : true;
options['mid'] =
typeof options['mid'] !== 'undefined' ? options['mid'] : true;
options['down'] =
typeof options['down'] !== 'undefined' ? options['down'] : true;
options['size'] =
typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
text = text.split('');
for (l in text) {
if (isChar(l)) {
continue;
}
result = result + text[l];
counts = {'up': 0, 'down': 0, 'mid': 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.mid = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.mid = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ['up', 'mid', 'down'];
for (var d in arr) {
var index = arr[d];
for (var i = 0; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
// don't summon him
return heComes(text, options);
};
var colors = require('./colors');
module['exports'] = function() {
//
// Extends prototype of native string object to allow for "foo".red syntax
//
var addProperty = function(color, func) {
String.prototype.__defineGetter__(color, func);
};
addProperty('strip', function() {
return colors.strip(this);
});
addProperty('stripColors', function() {
return colors.strip(this);
});
addProperty('trap', function() {
return colors.trap(this);
});
addProperty('zalgo', function() {
return colors.zalgo(this);
});
addProperty('zebra', function() {
return colors.zebra(this);
});
addProperty('rainbow', function() {
return colors.rainbow(this);
});
addProperty('random', function() {
return colors.random(this);
});
addProperty('america', function() {
return colors.america(this);
});
//
// Iterate through all default styles and colors
//
var x = Object.keys(colors.styles);
x.forEach(function(style) {
addProperty(style, function() {
return colors.stylize(this, style);
});
});
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__',
'__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString',
'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length',
'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice',
'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase',
'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight',
];
Object.keys(theme).forEach(function(prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta +
' is probably something you don\'t want to override. ' +
'Ignoring style name');
} else {
if (typeof(theme[prop]) === 'string') {
colors[prop] = colors[theme[prop]];
addProperty(prop, function() {
return colors[prop](this);
});
} else {
var themePropApplicator = function(str) {
var ret = str || this;
for (var t = 0; t < theme[prop].length; t++) {
ret = colors[theme[prop][t]](ret);
}
return ret;
};
addProperty(prop, themePropApplicator);
colors[prop] = function(str) {
return themePropApplicator(str);
};
}
}
});
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
} else {
applyTheme(theme);
}
};
};
var colors = require('./colors');
module['exports'] = colors;
// Remark: By default, colors will add style properties to String.prototype.
//
// If you don't wish to extend String.prototype, you can do this instead and
// native String will not be touched:
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
require('./extendStringPrototype')();
module['exports'] = function(colors) {
return function(letter, i, exploded) {
if (letter === ' ') return letter;
switch (i%3) {
case 0: return colors.red(letter);
case 1: return colors.white(letter);
case 2: return colors.blue(letter);
}
};
};
module['exports'] = function(colors) {
// RoY G BiV
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
return function(letter, i, exploded) {
if (letter === ' ') {
return letter;
} else {
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
}
};
};
module['exports'] = function(colors) {
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
return function(letter, i, exploded) {
return letter === ' ' ? letter :
colors[
available[Math.round(Math.random() * (available.length - 2))]
](letter);
};
};
module['exports'] = function(colors) {
return function(letter, i, exploded) {
return i % 2 === 0 ? letter : colors.inverse(letter);
};
};
/*
The MIT License (MIT)
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.
*/
var styles = {};
module['exports'] = styles;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
brightRed: [91, 39],
brightGreen: [92, 39],
brightYellow: [93, 39],
brightBlue: [94, 39],
brightMagenta: [95, 39],
brightCyan: [96, 39],
brightWhite: [97, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49],
};
Object.keys(codes).forEach(function(key) {
var val = codes[key];
var style = styles[key] = [];
style.open = '\u001b[' + val[0] + 'm';
style.close = '\u001b[' + val[1] + 'm';
});
/*
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.
*/
'use strict';
module.exports = function(flag, argv) {
argv = argv || process.argv;
var terminatorPos = argv.indexOf('--');
var prefix = /^-{1,2}/.test(flag) ? '' : '--';
var pos = argv.indexOf(prefix + flag);
return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
};
/*
The MIT License (MIT)
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.
*/
'use strict';
var os = require('os');
var hasFlag = require('./has-flag.js');
var env = process.env;
var forceColor = void 0;
if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
forceColor = false;
} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
|| hasFlag('color=always')) {
forceColor = true;
}
if ('FORCE_COLOR' in env) {
forceColor = env.FORCE_COLOR.length === 0
|| parseInt(env.FORCE_COLOR, 10) !== 0;
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level: level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}
function supportsColor(stream) {
if (forceColor === false) {
return 0;
}
if (hasFlag('color=16m') || hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (stream && !stream.isTTY && forceColor !== true) {
return 0;
}
var min = forceColor ? 1 : 0;
if (process.platform === 'win32') {
// Node.js 7.5.0 is the first version of Node.js to include a patch to
// libuv that enables 256 color output on Windows. Anything earlier and it
// won't work. However, here we target Node.js 8 at minimum as it is an LTS
// release, and Node.js 7 is not. Windows 10 build 10586 is the first
// Windows release that supports 256 colors. Windows 10 build 14931 is the
// first release that supports 16m/TrueColor.
var osRelease = os.release().split('.');
if (Number(process.versions.node.split('.')[0]) >= 8
&& Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
return sign in env;
}) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
);
}
if ('TERM_PROGRAM' in env) {
var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Hyper':
return 3;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
if (env.TERM === 'dumb') {
return min;
}
return min;
}
function getSupportLevel(stream) {
var level = supportsColor(stream);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel(process.stdout),
stderr: getSupportLevel(process.stderr),
};
{
"name": "colors",
"description": "get colors in your node.js console",
"version": "1.4.0",
"author": "Marak Squires",
"contributors": [
{
"name": "DABH",
"url": "https://github.com/DABH"
}
],
"homepage": "https://github.com/Marak/colors.js",
"bugs": "https://github.com/Marak/colors.js/issues",
"keywords": [
"ansi",
"terminal",
"colors"
],
"repository": {
"type": "git",
"url": "http://github.com/Marak/colors.js.git"
},
"license": "MIT",
"scripts": {
"lint": "eslint . --fix",
"test": "node tests/basic-test.js && node tests/safe-test.js"
},
"engines": {
"node": ">=0.1.90"
},
"main": "lib/index.js",
"files": [
"examples",
"lib",
"LICENSE",
"safe.js",
"themes",
"index.d.ts",
"safe.d.ts"
],
"devDependencies": {
"eslint": "^5.2.0",
"eslint-config-google": "^0.11.0"
}
}
// Type definitions for Colors.js 1.2
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/Marak/colors.js
export const enabled: boolean;
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export function strip(str: string): string;
export function stripColors(str: string): string;
export function black(str: string): string;
export function red(str: string): string;
export function green(str: string): string;
export function yellow(str: string): string;
export function blue(str: string): string;
export function magenta(str: string): string;
export function cyan(str: string): string;
export function white(str: string): string;
export function gray(str: string): string;
export function grey(str: string): string;
export function bgBlack(str: string): string;
export function bgRed(str: string): string;
export function bgGreen(str: string): string;
export function bgYellow(str: string): string;
export function bgBlue(str: string): string;
export function bgMagenta(str: string): string;
export function bgCyan(str: string): string;
export function bgWhite(str: string): string;
export function reset(str: string): string;
export function bold(str: string): string;
export function dim(str: string): string;
export function italic(str: string): string;
export function underline(str: string): string;
export function inverse(str: string): string;
export function hidden(str: string): string;
export function strikethrough(str: string): string;
export function rainbow(str: string): string;
export function zebra(str: string): string;
export function america(str: string): string;
export function trap(str: string): string;
export function random(str: string): string;
export function zalgo(str: string): string;
//
// Remark: Requiring this file will use the "safe" colors API,
// which will not touch String.prototype.
//
// var colors = require('colors/safe');
// colors.red("foo")
//
//
var colors = require('./lib/colors');
module['exports'] = colors;
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
};
language: node_js
node_js:
- 0.4
- 0.6
This software is released under the MIT license:
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.
concat-map
==========
Concatenative mapdashery.
[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map)
[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map)
example
=======
``` js
var concatMap = require('concat-map');
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ys = concatMap(xs, function (x) {
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
console.dir(ys);
```
***
```
[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]
```
methods
=======
``` js
var concatMap = require('concat-map')
```
concatMap(xs, fn)
-----------------
Return an array of concatenated elements by calling `fn(x, i)` for each element
`x` and each index `i` in the array `xs`.
When `fn(x, i)` returns an array, its result will be concatenated with the
result array. If `fn(x, i)` returns anything else, that value will be pushed
onto the end of the result array.
install
=======
With [npm](http://npmjs.org) do:
```
npm install concat-map
```
license
=======
MIT
notes
=====
This module was written while sitting high above the ground in a tree.
var concatMap = require('../');
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ys = concatMap(xs, function (x) {
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
console.dir(ys);
module.exports = function (xs, fn) {
var res = [];
for (var i = 0; i < xs.length; i++) {
var x = fn(xs[i], i);
if (isArray(x)) res.push.apply(res, x);
else res.push(x);
}
return res;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
{
"name" : "concat-map",
"description" : "concatenative mapdashery",
"version" : "0.0.1",
"repository" : {
"type" : "git",
"url" : "git://github.com/substack/node-concat-map.git"
},
"main" : "index.js",
"keywords" : [
"concat",
"concatMap",
"map",
"functional",
"higher-order"
],
"directories" : {
"example" : "example",
"test" : "test"
},
"scripts" : {
"test" : "tape test/*.js"
},
"devDependencies" : {
"tape" : "~2.4.0"
},
"license" : "MIT",
"author" : {
"name" : "James Halliday",
"email" : "mail@substack.net",
"url" : "http://substack.net"
},
"testling" : {
"files" : "test/*.js",
"browsers" : {
"ie" : [ 6, 7, 8, 9 ],
"ff" : [ 3.5, 10, 15.0 ],
"chrome" : [ 10, 22 ],
"safari" : [ 5.1 ],
"opera" : [ 12 ]
}
}
}
var concatMap = require('../');
var test = require('tape');
test('empty or not', function (t) {
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ixes = [];
var ys = concatMap(xs, function (x, ix) {
ixes.push(ix);
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]);
t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]);
t.end();
});
test('always something', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function (x) {
return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ];
});
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
t.end();
});
test('scalars', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function (x) {
return x === 'b' ? [ 'B', 'B', 'B' ] : x;
});
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
t.end();
});
test('undefs', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function () {});
t.same(ys, [ undefined, undefined, undefined, undefined ]);
t.end();
});
/// <reference types="node"/>
import {Readable as ReadableStream} from 'stream';
declare namespace fileType {
type FileType =
| 'jpg'
| 'png'
| 'apng'
| 'gif'
| 'webp'
| 'flif'
| 'cr2'
| 'orf'
| 'arw'
| 'dng'
| 'nef'
| 'rw2'
| 'raf'
| 'tif'
| 'bmp'
| 'jxr'
| 'psd'
| 'zip'
| 'tar'
| 'rar'
| 'gz'
| 'bz2'
| '7z'
| 'dmg'
| 'mp4'
| 'mid'
| 'mkv'
| 'webm'
| 'mov'
| 'avi'
| 'wmv'
| 'mpg'
| 'mp2'
| 'mp3'
| 'm4a'
| 'ogg'
| 'opus'
| 'flac'
| 'wav'
| 'qcp'
| 'amr'
| 'pdf'
| 'epub'
| 'mobi'
| 'exe'
| 'swf'
| 'rtf'
| 'woff'
| 'woff2'
| 'eot'
| 'ttf'
| 'otf'
| 'ico'
| 'flv'
| 'ps'
| 'xz'
| 'sqlite'
| 'nes'
| 'crx'
| 'xpi'
| 'cab'
| 'deb'
| 'ar'
| 'rpm'
| 'Z'
| 'lz'
| 'msi'
| 'mxf'
| 'mts'
| 'wasm'
| 'blend'
| 'bpg'
| 'docx'
| 'pptx'
| 'xlsx'
| '3gp'
| '3g2'
| 'jp2'
| 'jpm'
| 'jpx'
| 'mj2'
| 'aif'
| 'odt'
| 'ods'
| 'odp'
| 'xml'
| 'heic'
| 'cur'
| 'ktx'
| 'ape'
| 'wv'
| 'asf'
| 'wma'
| 'dcm'
| 'mpc'
| 'ics'
| 'glb'
| 'pcap'
| 'dsf'
| 'lnk'
| 'alias'
| 'voc'
| 'ac3'
| 'm4b'
| 'm4p'
| 'm4v'
| 'f4a'
| 'f4b'
| 'f4p'
| 'f4v'
| 'mie'
| 'ogv'
| 'ogm'
| 'oga'
| 'spx'
| 'ogx'
| 'arrow'
| 'shp';
type MimeType =
| 'image/jpeg'
| 'image/png'
| 'image/gif'
| 'image/webp'
| 'image/flif'
| 'image/x-canon-cr2'
| 'image/tiff'
| 'image/bmp'
| 'image/vnd.ms-photo'
| 'image/vnd.adobe.photoshop'
| 'application/epub+zip'
| 'application/x-xpinstall'
| 'application/vnd.oasis.opendocument.text'
| 'application/vnd.oasis.opendocument.spreadsheet'
| 'application/vnd.oasis.opendocument.presentation'
| 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
| 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
| 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
| 'application/zip'
| 'application/x-tar'
| 'application/x-rar-compressed'
| 'application/gzip'
| 'application/x-bzip2'
| 'application/x-7z-compressed'
| 'application/x-apple-diskimage'
| 'video/mp4'
| 'audio/midi'
| 'video/x-matroska'
| 'video/webm'
| 'video/quicktime'
| 'video/vnd.avi'
| 'audio/vnd.wave'
| 'audio/qcelp'
| 'audio/x-ms-wma'
| 'video/x-ms-asf'
| 'application/vnd.ms-asf'
| 'video/mpeg'
| 'video/3gpp'
| 'audio/mpeg'
| 'audio/mp4' // RFC 4337
| 'audio/opus'
| 'video/ogg'
| 'audio/ogg'
| 'application/ogg'
| 'audio/x-flac'
| 'audio/ape'
| 'audio/wavpack'
| 'audio/amr'
| 'application/pdf'
| 'application/x-msdownload'
| 'application/x-shockwave-flash'
| 'application/rtf'
| 'application/wasm'
| 'font/woff'
| 'font/woff2'
| 'application/vnd.ms-fontobject'
| 'font/ttf'
| 'font/otf'
| 'image/x-icon'
| 'video/x-flv'
| 'application/postscript'
| 'application/x-xz'
| 'application/x-sqlite3'
| 'application/x-nintendo-nes-rom'
| 'application/x-google-chrome-extension'
| 'application/vnd.ms-cab-compressed'
| 'application/x-deb'
| 'application/x-unix-archive'
| 'application/x-rpm'
| 'application/x-compress'
| 'application/x-lzip'
| 'application/x-msi'
| 'application/x-mie'
| 'application/x-apache-arrow'
| 'application/mxf'
| 'video/mp2t'
| 'application/x-blender'
| 'image/bpg'
| 'image/jp2'
| 'image/jpx'
| 'image/jpm'
| 'image/mj2'
| 'audio/aiff'
| 'application/xml'
| 'application/x-mobipocket-ebook'
| 'image/heif'
| 'image/heif-sequence'
| 'image/heic'
| 'image/heic-sequence'
| 'image/ktx'
| 'application/dicom'
| 'audio/x-musepack'
| 'text/calendar'
| 'model/gltf-binary'
| 'application/vnd.tcpdump.pcap'
| 'audio/x-dsf' // Non-standard
| 'application/x.ms.shortcut' // Invented by us
| 'application/x.apple.alias' // Invented by us
| 'audio/x-voc'
| 'audio/vnd.dolby.dd-raw'
| 'audio/x-m4a'
| 'image/apng'
| 'image/x-olympus-orf'
| 'image/x-sony-arw'
| 'image/x-adobe-dng'
| 'image/x-nikon-nef'
| 'image/x-panasonic-rw2'
| 'image/x-fujifilm-raf'
| 'video/x-m4v'
| 'video/3gpp2'
| 'application/x-esri-shape';
interface FileTypeResult {
/**
One of the supported [file types](https://github.com/sindresorhus/file-type#supported-file-types).
*/
ext: FileType;
/**
The detected [MIME type](https://en.wikipedia.org/wiki/Internet_media_type).
*/
mime: MimeType;
}
type ReadableStreamWithFileType = ReadableStream & {
readonly fileType?: FileTypeResult;
};
}
declare const fileType: {
/**
Detect the file type of a `Buffer`/`Uint8Array`/`ArrayBuffer`. The file type is detected by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer.
@param buffer - It only needs the first `.minimumBytes` bytes. The exception is detection of `docx`, `pptx`, and `xlsx` which potentially requires reading the whole file.
@returns The detected file type and MIME type or `undefined` when there was no match.
@example
```
import readChunk = require('read-chunk');
import fileType = require('file-type');
const buffer = readChunk.sync('unicorn.png', 0, fileType.minimumBytes);
fileType(buffer);
//=> {ext: 'png', mime: 'image/png'}
// Or from a remote location:
import * as http from 'http';
const url = 'https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif';
http.get(url, response => {
response.on('readable', () => {
const chunk = response.read(fileType.minimumBytes);
response.destroy();
console.log(fileType(chunk));
//=> {ext: 'gif', mime: 'image/gif'}
});
});
```
*/
(buffer: Buffer | Uint8Array | ArrayBuffer): fileType.FileTypeResult | undefined;
/**
The minimum amount of bytes needed to detect a file type. Currently, it's 4100 bytes, but it can change, so don't hard-code it.
*/
readonly minimumBytes: number;
/**
Supported file extensions.
*/
readonly extensions: readonly fileType.FileType[];
/**
Supported MIME types.
*/
readonly mimeTypes: readonly fileType.MimeType[];
/**
Detect the file type of a readable stream.
@param readableStream - A readable stream containing a file to examine, see: [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable).
@returns A `Promise` which resolves to the original readable stream argument, but with an added `fileType` property, which is an object like the one returned from `fileType()`.
@example
```
import * as fs from 'fs';
import * as crypto from 'crypto';
import fileType = require('file-type');
(async () => {
const read = fs.createReadStream('encrypted.enc');
const decipher = crypto.createDecipheriv(alg, key, iv);
const stream = await fileType.stream(read.pipe(decipher));
console.log(stream.fileType);
//=> {ext: 'mov', mime: 'video/quicktime'}
const write = fs.createWriteStream(`decrypted.${stream.fileType.ext}`);
stream.pipe(write);
})();
```
*/
readonly stream: (
readableStream: ReadableStream
) => Promise<fileType.ReadableStreamWithFileType>;
};
export = fileType;
This diff is collapsed. Click to expand it.
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.
{
"name": "file-type",
"version": "12.4.2",
"description": "Detect the file type of a Buffer/Uint8Array/ArrayBuffer",
"license": "MIT",
"repository": "sindresorhus/file-type",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts",
"supported.js",
"util.js"
],
"keywords": [
"mime",
"file",
"type",
"archive",
"image",
"img",
"pic",
"picture",
"flash",
"photo",
"video",
"detect",
"check",
"is",
"exif",
"exe",
"binary",
"buffer",
"uint8array",
"jpg",
"png",
"apng",
"gif",
"webp",
"flif",
"cr2",
"orf",
"arw",
"dng",
"nef",
"rw2",
"raf",
"tif",
"bmp",
"jxr",
"psd",
"zip",
"tar",
"rar",
"gz",
"bz2",
"7z",
"dmg",
"mp4",
"mid",
"mkv",
"webm",
"mov",
"avi",
"mpg",
"mp2",
"mp3",
"m4a",
"ogg",
"opus",
"flac",
"wav",
"amr",
"pdf",
"epub",
"mobi",
"swf",
"rtf",
"woff",
"woff2",
"eot",
"ttf",
"otf",
"ico",
"flv",
"ps",
"xz",
"sqlite",
"xpi",
"cab",
"deb",
"ar",
"rpm",
"Z",
"lz",
"msi",
"mxf",
"mts",
"wasm",
"webassembly",
"blend",
"bpg",
"docx",
"pptx",
"xlsx",
"3gp",
"jp2",
"jpm",
"jpx",
"mj2",
"aif",
"odt",
"ods",
"odp",
"xml",
"heic",
"wma",
"ics",
"glb",
"pcap",
"dsf",
"lnk",
"alias",
"voc",
"ac3",
"3g2",
"m4b",
"m4p",
"m4v",
"f4a",
"f4b",
"f4p",
"f4v",
"mie",
"qcp",
"wmv",
"asf",
"ogv",
"ogm",
"oga",
"spx",
"ogx",
"ape",
"wv",
"cur",
"nes",
"crx",
"ktx",
"dcm",
"mpc",
"arrow",
"shp"
],
"devDependencies": {
"@types/node": "^12.7.2",
"ava": "^2.3.0",
"noop-stream": "^0.1.0",
"pify": "^4.0.1",
"read-chunk": "^3.2.0",
"tsd": "^0.7.1",
"xo": "^0.24.0"
}
}
This diff is collapsed. Click to expand it.
'use strict';
module.exports = {
extensions: [
'jpg',
'png',
'apng',
'gif',
'webp',
'flif',
'cr2',
'orf',
'arw',
'dng',
'nef',
'rw2',
'raf',
'tif',
'bmp',
'jxr',
'psd',
'zip',
'tar',
'rar',
'gz',
'bz2',
'7z',
'dmg',
'mp4',
'mid',
'mkv',
'webm',
'mov',
'avi',
'mpg',
'mp2',
'mp3',
'm4a',
'oga',
'ogg',
'ogv',
'opus',
'flac',
'wav',
'spx',
'amr',
'pdf',
'epub',
'exe',
'swf',
'rtf',
'wasm',
'woff',
'woff2',
'eot',
'ttf',
'otf',
'ico',
'flv',
'ps',
'xz',
'sqlite',
'nes',
'crx',
'xpi',
'cab',
'deb',
'ar',
'rpm',
'Z',
'lz',
'msi',
'mxf',
'mts',
'blend',
'bpg',
'docx',
'pptx',
'xlsx',
'3gp',
'3g2',
'jp2',
'jpm',
'jpx',
'mj2',
'aif',
'qcp',
'odt',
'ods',
'odp',
'xml',
'mobi',
'heic',
'cur',
'ktx',
'ape',
'wv',
'wmv',
'wma',
'dcm',
'ics',
'glb',
'pcap',
'dsf',
'lnk',
'alias',
'voc',
'ac3',
'm4v',
'm4p',
'm4b',
'f4v',
'f4p',
'f4b',
'f4a',
'mie',
'asf',
'ogm',
'ogx',
'mpc',
'arrow',
'shp'
],
mimeTypes: [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/flif',
'image/x-canon-cr2',
'image/tiff',
'image/bmp',
'image/vnd.ms-photo',
'image/vnd.adobe.photoshop',
'application/epub+zip',
'application/x-xpinstall',
'application/vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/x-tar',
'application/x-rar-compressed',
'application/gzip',
'application/x-bzip2',
'application/x-7z-compressed',
'application/x-apple-diskimage',
'application/x-apache-arrow',
'video/mp4',
'audio/midi',
'video/x-matroska',
'video/webm',
'video/quicktime',
'video/vnd.avi',
'audio/vnd.wave',
'audio/qcelp',
'audio/x-ms-wma',
'video/x-ms-asf',
'application/vnd.ms-asf',
'video/mpeg',
'video/3gpp',
'audio/mpeg',
'audio/mp4', // RFC 4337
'audio/opus',
'video/ogg',
'audio/ogg',
'application/ogg',
'audio/x-flac',
'audio/ape',
'audio/wavpack',
'audio/amr',
'application/pdf',
'application/x-msdownload',
'application/x-shockwave-flash',
'application/rtf',
'application/wasm',
'font/woff',
'font/woff2',
'application/vnd.ms-fontobject',
'font/ttf',
'font/otf',
'image/x-icon',
'video/x-flv',
'application/postscript',
'application/x-xz',
'application/x-sqlite3',
'application/x-nintendo-nes-rom',
'application/x-google-chrome-extension',
'application/vnd.ms-cab-compressed',
'application/x-deb',
'application/x-unix-archive',
'application/x-rpm',
'application/x-compress',
'application/x-lzip',
'application/x-msi',
'application/x-mie',
'application/mxf',
'video/mp2t',
'application/x-blender',
'image/bpg',
'image/jp2',
'image/jpx',
'image/jpm',
'image/mj2',
'audio/aiff',
'application/xml',
'application/x-mobipocket-ebook',
'image/heif',
'image/heif-sequence',
'image/heic',
'image/heic-sequence',
'image/ktx',
'application/dicom',
'audio/x-musepack',
'text/calendar',
'model/gltf-binary',
'application/vnd.tcpdump.pcap',
'audio/x-dsf', // Non-standard
'application/x.ms.shortcut', // Invented by us
'application/x.apple.alias', // Invented by us
'audio/x-voc',
'audio/vnd.dolby.dd-raw',
'audio/x-m4a',
'image/apng',
'image/x-olympus-orf',
'image/x-sony-arw',
'image/x-adobe-dng',
'image/x-nikon-nef',
'image/x-panasonic-rw2',
'image/x-fujifilm-raf',
'video/x-m4v',
'video/3gpp2',
'application/x-esri-shape'
]
};
'use strict';
exports.stringToBytes = string => [...string].map(character => character.charCodeAt(0));
const uint8ArrayUtf8ByteString = (array, start, end) => {
return String.fromCharCode(...array.slice(start, end));
};
exports.readUInt64LE = (buffer, offset = 0) => {
let n = buffer[offset];
let mul = 1;
let i = 0;
while (++i < 8) {
mul *= 0x100;
n += buffer[offset + i] * mul;
}
return n;
};
exports.tarHeaderChecksumMatches = buffer => { // Does not check if checksum field characters are valid
if (buffer.length < 512) { // `tar` header size, cannot compute checksum without it
return false;
}
const MASK_8TH_BIT = 0x80;
let sum = 256; // Intitalize sum, with 256 as sum of 8 spaces in checksum field
let signedBitSum = 0; // Initialize signed bit sum
for (let i = 0; i < 148; i++) {
const byte = buffer[i];
sum += byte;
signedBitSum += byte & MASK_8TH_BIT; // Add signed bit to signed bit sum
}
// Skip checksum field
for (let i = 156; i < 512; i++) {
const byte = buffer[i];
sum += byte;
signedBitSum += byte & MASK_8TH_BIT; // Add signed bit to signed bit sum
}
const readSum = parseInt(uint8ArrayUtf8ByteString(buffer, 148, 154), 8); // Read sum in header
// Some implementations compute checksum incorrectly using signed bytes
return (
// Checksum in header equals the sum we calculated
readSum === sum ||
// Checksum in header equals sum we calculated plus signed-to-unsigned delta
readSum === (sum - (signedBitSum << 1))
);
};
exports.multiByteIndexOf = (buffer, bytesToSearch, startAt = 0) => {
// `Buffer#indexOf()` can search for multiple bytes
if (Buffer && Buffer.isBuffer(buffer)) {
return buffer.indexOf(Buffer.from(bytesToSearch), startAt);
}
const nextBytesMatch = (buffer, bytes, startIndex) => {
for (let i = 1; i < bytes.length; i++) {
if (bytes[i] !== buffer[startIndex + i]) {
return false;
}
}
return true;
};
// `Uint8Array#indexOf()` can search for only a single byte
let index = buffer.indexOf(bytesToSearch[0], startAt);
while (index >= 0) {
if (nextBytesMatch(buffer, bytesToSearch, index)) {
return index;
}
index = buffer.indexOf(bytesToSearch[0], index + 1);
}
return -1;
};
exports.uint8ArrayUtf8ByteString = uint8ArrayUtf8ByteString;
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.