김수민

commit

Showing 96 changed files with 4964 additions and 1 deletions
......@@ -2,7 +2,6 @@
<project version="4">
<component name="ChangeListManager">
<list default="true" id="5c08ae96-2f87-46c1-b81d-f30e494ce252" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/.gitignore" beforeDir="false" afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app.js" beforeDir="false" afterPath="$PROJECT_DIR$/app.js" afterDir="false" />
<change beforePath="$PROJECT_DIR$/package-lock.json" beforeDir="false" afterPath="$PROJECT_DIR$/package-lock.json" afterDir="false" />
......@@ -58,6 +57,7 @@
<workItem from="1573898557106" duration="89000" />
<workItem from="1573899005304" duration="7410000" />
<workItem from="1574071758382" duration="6285000" />
<workItem from="1574323490142" duration="7902000" />
</task>
<servers />
</component>
......
......@@ -105,10 +105,41 @@ function handleEvent(event) {
result.text = objBody.message.result.translatedText;
console.log(result.text);
//번역된 문장 보내기
let audio_options={
'Text': result.text,
'OutputFormat': 'mp3',
'VoiceId':'Seoyeon'
};
Polly.synthesizeSpeech(audio_options, (err, data) => {
console.log("check");
if (err) {
throw err;
} else if (data) {
if (data.AudioStream instanceof Buffer) {
fs.writeFile("./speech.mp3", data.AudioStream, function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
})
}
}
});
request.post(audio_options, function (error,response,body) {
if(!error && response.statusCode == 200){
for_audio_client.replyAudio(event.replyToken,{
originalContentUrl: 'https://panguin.ml/speech.mp3',
duration: 240000
}).then(resolve).catch(reject);
}
});
client.replyMessage(event.replyToken,result).then(resolve).catch(reject);
}
});
}
// 메시지의 언어가 영어 또는 한국어가 아닐 경우
else{
......
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../loose-envify/cli.js" "$@"
ret=$?
else
node "$basedir/../loose-envify/cli.js" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\loose-envify\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\loose-envify\cli.js" %*
)
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2017-present Yoctol (github.com/Yoctol/messaging-apis)
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.
# axios-error
> An axios error wrapper that aim to provide clear error message to the user
## Installation
```sh
npm i --save axios-error
```
or
```sh
yarn add axios-error
```
<br />
## Usage
```js
const AxiosError = require('axios-error');
// You can construct it from error throw by axios
const error = new AxiosError(errorThrowByAxios);
// Or with custom error message
const error = new AxiosError(message, errorThrowByAxios);
// Or construct it from axios config, axios request and axios response
const error = new AxiosError(message, { config, request, response });
```
Directly `console.log` on the error instance will return formatted message. If you'd like to get the axios `request`, `response`, or `config`, you can still get them via those keys on the error instance.
```js
console.log(error); // formatted error message
console.log(error.stack); // error stack trace
console.log(error.config); // axios request config
console.log(error.request); // HTTP request
console.log(error.response); // HTTP response
```
"use strict";var _util = _interopRequireDefault(require("util"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
function indent(str) {
return str.
split('\n').
map(s => s ? ` ${s}` : '').
join('\n');
}
function json(data) {
return JSON.stringify(data, null, 2);
}
module.exports = class AxiosError extends Error {
constructor(messageOrErr, _err = {}) {
let err;
if (messageOrErr instanceof Error) {
super(messageOrErr.message);
err = messageOrErr;
} else {
super(messageOrErr);
err = _err;
}
const { config, request, response } = err;
this.config = config;
this.request = request;
this.response = response;
if (response && response.status) {
this.status = response.status;
}
}
// TODO: remove inspect until we drop node < 6.6
inspect(...args) {
return this[_util.default.inspect.custom](...args);
}
[_util.default.inspect.custom]() {
let requestMessage = '';
if (this.config) {
let { data } = this.config;
try {
data = JSON.parse(data);
} catch (_) {} // eslint-disable-line
let requestData = '';
if (this.config.data) {
requestData = `
Request Data -
${indent(json(data))}`;
}
requestMessage = `
Request -
${this.config.method.toUpperCase()} ${this.config.url}
${requestData}`;
}
let responseMessage = '';
if (this.response) {
let responseData;
if (this.response.data) {
responseData = `
Response Data -
${indent(json(this.response.data))}`;
}
responseMessage = `
Response -
${this.response.status} ${this.response.statusText}
${responseData}`;
}
return `
${this.stack}
Error Message -
${this.message}
${requestMessage}
${responseMessage}
`;
}};
\ No newline at end of file
{
"_from": "axios-error@^0.8.1",
"_id": "axios-error@0.8.1",
"_inBundle": false,
"_integrity": "sha512-4YIf0FK2aO8HHVAQXvVFK2oPQSsOh3P1WQjkwQwO3oFjq4vO3S3YSyiRzyebBIR4NmcHaMJ6W5m0iHuisG7lTA==",
"_location": "/axios-error",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "axios-error@^0.8.1",
"name": "axios-error",
"escapedName": "axios-error",
"rawSpec": "^0.8.1",
"saveSpec": null,
"fetchSpec": "^0.8.1"
},
"_requiredBy": [
"/messaging-api-line"
],
"_resolved": "https://registry.npmjs.org/axios-error/-/axios-error-0.8.1.tgz",
"_shasum": "4d9c21370465c290d07192e7f3eacfff49c256ae",
"_spec": "axios-error@^0.8.1",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line",
"bugs": {
"url": "https://github.com/Yoctol/messaging-apis/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "An axios error wrapper that aim to provide clear error message to the user",
"devDependencies": {
"axios": "^0.19.0",
"axios-mock-adapter": "^1.17.0"
},
"engines": {
"node": ">=8"
},
"gitHead": "622f5664634c26e752e4e54bd32dbc773271390f",
"homepage": "https://github.com/Yoctol/messaging-apis#readme",
"keywords": [
"axios",
"error",
"http"
],
"license": "MIT",
"main": "lib/index.js",
"name": "axios-error",
"repository": {
"type": "git",
"url": "git+https://github.com/Yoctol/messaging-apis.git"
},
"version": "0.8.1"
}
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`should support error without axios data 1`] = `
"
Error: boom....
at Object.<anonymous> (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:16:19)
at Generator.throw (<anonymous>)
at step (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:336)
at /Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:535
at <anonymous>
Error Message -
custom error
"
`;
exports[`should work 1`] = `
"
Error: boom....
at Object.<anonymous> (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:16:19)
at Generator.throw (<anonymous>)
at step (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:336)
at /Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:535
at <anonymous>
Error Message -
boom....
Request -
POST /
Request Data -
{
\\"x\\": 1
}
Response -
400 Bad Request
Response Data -
{
\\"error_status\\": \\"boom....\\"
}
"
`;
exports[`should work with construct using error instance only 1`] = `
"
Error: boom....
at Object.<anonymous> (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:16:19)
at Generator.throw (<anonymous>)
at step (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:336)
at /Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:535
at <anonymous>
Error Message -
Request failed with status code 400
Request -
POST /
Request Data -
{
\\"x\\": 1
}
Response -
400 Bad Request
Response Data -
{
\\"error_status\\": \\"boom....\\"
}
"
`;
exports[`should work with undefined response 1`] = `
"
Error: boom....
at Object.<anonymous> (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:16:19)
at Generator.throw (<anonymous>)
at step (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:336)
at /Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:535
at <anonymous>
Error Message -
read ECONNRESET
Request -
POST /
Request Data -
{
\\"x\\": 1
}
"
`;
import util from 'util';
import MockAdapter from 'axios-mock-adapter';
import axios from 'axios';
import AxiosError from '..';
const mock = new MockAdapter(axios);
mock.onAny().reply(400, {
error_status: 'boom....',
});
const stack = `Error: boom....
at Object.<anonymous> (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:16:19)
at Generator.throw (<anonymous>)
at step (/Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:336)
at /Users/xxx/messaging-apis/packages/axios-error/src/__tests__/index.spec.js:4:535
at <anonymous>
`;
it('should work', async () => {
try {
await axios.post('/', { x: 1 });
} catch (err) {
// overwrite because axios-mock-adapter set it to undefined
err.response.statusText = 'Bad Request';
const error = new AxiosError(err.response.data.error_status, err);
// overwrite stack to test it
error.stack = stack;
expect(error[util.inspect.custom]()).toMatchSnapshot();
}
});
it('should set `.status` property', async () => {
try {
await axios.post('/', { x: 1 });
} catch (err) {
// overwrite because axios-mock-adapter set it to undefined
err.response.statusText = 'Bad Request';
const error = new AxiosError(err);
expect(error.status).toBe(400);
}
});
it('should work with construct using error instance only', async () => {
try {
await axios.post('/', { x: 1 });
} catch (err) {
// overwrite because axios-mock-adapter set it to undefined
err.response.statusText = 'Bad Request';
const error = new AxiosError(err);
// overwrite stack to test it
error.stack = stack;
expect(error[util.inspect.custom]()).toMatchSnapshot();
}
});
it('should work with undefined response', async () => {
try {
await axios.post('/', { x: 1 });
} catch (err) {
// overwrite to undefined
// https://github.com/Yoctol/bottender/issues/246
err.response = undefined;
const error = new AxiosError('read ECONNRESET', err);
// overwrite stack to test it
error.stack = stack;
expect(error[util.inspect.custom]()).toMatchSnapshot();
}
});
it('should support error without axios data', () => {
const error = new AxiosError('custom error');
error.stack = stack;
expect(error[util.inspect.custom]()).toMatchSnapshot();
});
import util from 'util';
function indent(str) {
return str
.split('\n')
.map(s => (s ? ` ${s}` : ''))
.join('\n');
}
function json(data) {
return JSON.stringify(data, null, 2);
}
module.exports = class AxiosError extends Error {
constructor(messageOrErr, _err = {}) {
let err;
if (messageOrErr instanceof Error) {
super(messageOrErr.message);
err = messageOrErr;
} else {
super(messageOrErr);
err = _err;
}
const { config, request, response } = err;
this.config = config;
this.request = request;
this.response = response;
if (response && response.status) {
this.status = response.status;
}
}
// TODO: remove inspect until we drop node < 6.6
inspect(...args) {
return this[util.inspect.custom](...args);
}
[util.inspect.custom]() {
let requestMessage = '';
if (this.config) {
let { data } = this.config;
try {
data = JSON.parse(data);
} catch (_) {} // eslint-disable-line
let requestData = '';
if (this.config.data) {
requestData = `
Request Data -
${indent(json(data))}`;
}
requestMessage = `
Request -
${this.config.method.toUpperCase()} ${this.config.url}
${requestData}`;
}
let responseMessage = '';
if (this.response) {
let responseData;
if (this.response.data) {
responseData = `
Response Data -
${indent(json(this.response.data))}`;
}
responseMessage = `
Response -
${this.response.status} ${this.response.statusText}
${responseData}`;
}
return `
${this.stack}
Error Message -
${this.message}
${requestMessage}
${responseMessage}
`;
}
};
/// <reference types="node"/>
declare namespace imageType {
type ImageType =
| 'jpg'
| 'png'
| 'gif'
| 'webp'
| 'flif'
| 'cr2'
| 'tif'
| 'bmp'
| 'jxr'
| 'psd'
| 'ico'
| 'bpg'
| 'jp2'
| 'jpm'
| 'jpx'
| 'heic'
| 'cur'
| 'dcm';
interface ImageTypeResult {
/**
One of the supported [file types](https://github.com/sindresorhus/image-type#supported-file-types).
*/
ext: ImageType;
/**
The detected [MIME type](https://en.wikipedia.org/wiki/Internet_media_type).
*/
mime: string;
}
}
declare const imageType: {
/**
Detect the image type of a `Buffer`/`Uint8Array`.
@param input - Input to examine to determine the file type. It only needs the first `.minimumBytes` bytes.
@example
```
import readChunk = require('read-chunk');
import imageType = require('image-type');
const buffer = readChunk.sync('unicorn.png', 0, 12);
imageType(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(imageType.minimumBytes);
response.destroy();
console.log(imageType(chunk));
//=> {ext: 'gif', mime: 'image/gif'}
});
});
```
*/
(input: Buffer | Uint8Array): imageType.ImageTypeResult | null;
/**
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;
// TODO: Remove this for the next major release
default: typeof imageType;
};
export = imageType;
'use strict';
const fileType = require('file-type');
const imageExts = new Set([
'jpg',
'png',
'gif',
'webp',
'flif',
'cr2',
'tif',
'bmp',
'jxr',
'psd',
'ico',
'bpg',
'jp2',
'jpm',
'jpx',
'heic',
'cur',
'dcm'
]);
const imageType = input => {
const ret = fileType(input);
return imageExts.has(ret && ret.ext) ? ret : null;
};
module.exports = imageType;
// TODO: Remove this for the next major release
module.exports.default = imageType;
Object.defineProperty(imageType, 'minimumBytes', {value: fileType.minimumBytes});
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.
/// <reference types="node"/>
import {Readable as ReadableStream} from 'stream';
declare namespace fileType {
type FileType =
| 'jpg'
| 'png'
| 'gif'
| 'webp'
| 'flif'
| 'cr2'
| 'tif'
| 'bmp'
| 'jxr'
| 'psd'
| 'zip'
| 'tar'
| 'rar'
| 'gz'
| 'bz2'
| '7z'
| 'dmg'
| 'mp4'
| 'm4v'
| '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'
| 'jp2'
| 'jpm'
| 'jpx'
| 'mj2'
| 'aif'
| 'odt'
| 'ods'
| 'odp'
| 'xml'
| 'heic'
| 'cur'
| 'ktx'
| 'ape'
| 'wv'
| 'asf'
| 'wma'
| 'wmv'
| 'dcm'
| 'mpc'
| 'ics'
| 'glb'
| 'pcap';
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: string;
}
type ReadableStreamWithFileType = ReadableStream & {
readonly fileType: FileTypeResult | null;
};
}
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 An object with the detected file type and MIME type or `null` 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 | null;
/**
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;
/**
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>;
// TODO: Remove this for the next major release
readonly default: typeof fileType;
};
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.
{
"_from": "file-type@^10.10.0",
"_id": "file-type@10.11.0",
"_inBundle": false,
"_integrity": "sha512-uzk64HRpUZyTGZtVuvrjP0FYxzQrBf4rojot6J65YMEbwBLB0CWm0CLojVpwpmFmxcE/lkvYICgfcGozbBq6rw==",
"_location": "/image-type/file-type",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "file-type@^10.10.0",
"name": "file-type",
"escapedName": "file-type",
"rawSpec": "^10.10.0",
"saveSpec": null,
"fetchSpec": "^10.10.0"
},
"_requiredBy": [
"/image-type"
],
"_resolved": "https://registry.npmjs.org/file-type/-/file-type-10.11.0.tgz",
"_shasum": "2961d09e4675b9fb9a3ee6b69e9cd23f43fd1890",
"_spec": "file-type@^10.10.0",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\image-type",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/file-type/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Detect the file type of a Buffer/Uint8Array/ArrayBuffer",
"devDependencies": {
"@types/node": "^11.12.2",
"ava": "^1.4.1",
"pify": "^4.0.1",
"read-chunk": "^3.2.0",
"tsd": "^0.7.1",
"xo": "^0.24.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/file-type#readme",
"keywords": [
"mime",
"file",
"type",
"archive",
"image",
"img",
"pic",
"picture",
"flash",
"photo",
"video",
"detect",
"check",
"is",
"exif",
"exe",
"binary",
"buffer",
"uint8array",
"jpg",
"png",
"gif",
"webp",
"flif",
"cr2",
"tif",
"bmp",
"jxr",
"psd",
"zip",
"tar",
"rar",
"gz",
"bz2",
"7z",
"dmg",
"mp4",
"m4v",
"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"
],
"license": "MIT",
"name": "file-type",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/file-type.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "10.11.0"
}
# file-type [![Build Status](https://travis-ci.org/sindresorhus/file-type.svg?branch=master)](https://travis-ci.org/sindresorhus/file-type)
> 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.
## Install
```
$ npm install file-type
```
<a href="https://www.patreon.com/sindresorhus">
<img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
</a>
## Usage
##### Node.js
```js
const readChunk = require('read-chunk');
const 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:
```js
const http = require('http');
const fileType = require('file-type');
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'}
});
});
```
Or from a stream:
```js
const fs = require('fs');
const crypto = require('crypto');
const 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);
})();
```
##### Browser
```js
const xhr = new XMLHttpRequest();
xhr.open('GET', 'unicorn.png');
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
fileType(new Uint8Array(this.response));
//=> {ext: 'png', mime: 'image/png'}
};
xhr.send();
```
## API
### fileType(input)
Returns an `Object` with:
- `ext` - One of the [supported file types](#supported-file-types)
- `mime` - The [MIME type](https://en.wikipedia.org/wiki/Internet_media_type)
Or `null` when there is no match.
#### input
Type: `Buffer | Uint8Array | ArrayBuffer`
It only needs the first `.minimumBytes` bytes. The exception is detection of `docx`, `pptx`, and `xlsx` which potentially requires reading the whole file.
### fileType.minimumBytes
Type: `number`
The minimum amount of bytes needed to detect a file type. Currently, it's 4100 bytes, but it can change, so don't hardcode it.
### fileType.stream(readableStream)
Detect the file type of a readable stream.
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()`.
*Note:* This method is only for Node.js.
#### readableStream
Type: [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable)
## Supported file types
- [`jpg`](https://en.wikipedia.org/wiki/JPEG)
- [`png`](https://en.wikipedia.org/wiki/Portable_Network_Graphics)
- [`gif`](https://en.wikipedia.org/wiki/GIF)
- [`webp`](https://en.wikipedia.org/wiki/WebP)
- [`flif`](https://en.wikipedia.org/wiki/Free_Lossless_Image_Format)
- [`cr2`](https://fileinfo.com/extension/cr2)
- [`tif`](https://en.wikipedia.org/wiki/Tagged_Image_File_Format)
- [`bmp`](https://en.wikipedia.org/wiki/BMP_file_format)
- [`jxr`](https://en.wikipedia.org/wiki/JPEG_XR)
- [`psd`](https://en.wikipedia.org/wiki/Adobe_Photoshop#File_format)
- [`zip`](https://en.wikipedia.org/wiki/Zip_(file_format))
- [`tar`](https://en.wikipedia.org/wiki/Tar_(computing)#File_format)
- [`rar`](https://en.wikipedia.org/wiki/RAR_(file_format))
- [`gz`](https://en.wikipedia.org/wiki/Gzip)
- [`bz2`](https://en.wikipedia.org/wiki/Bzip2)
- [`7z`](https://en.wikipedia.org/wiki/7z)
- [`dmg`](https://en.wikipedia.org/wiki/Apple_Disk_Image)
- [`mp4`](https://en.wikipedia.org/wiki/MPEG-4_Part_14#Filename_extensions)
- [`m4v`](https://en.wikipedia.org/wiki/M4V)
- [`mid`](https://en.wikipedia.org/wiki/MIDI)
- [`mkv`](https://en.wikipedia.org/wiki/Matroska)
- [`webm`](https://en.wikipedia.org/wiki/WebM)
- [`mov`](https://en.wikipedia.org/wiki/QuickTime_File_Format)
- [`avi`](https://en.wikipedia.org/wiki/Audio_Video_Interleave)
- [`wmv`](https://en.wikipedia.org/wiki/Windows_Media_Video)
- [`mpg`](https://en.wikipedia.org/wiki/MPEG-1)
- [`mp2`](https://en.wikipedia.org/wiki/MPEG-1_Audio_Layer_II)
- [`mp3`](https://en.wikipedia.org/wiki/MP3)
- [`m4a`](https://en.wikipedia.org/wiki/MPEG-4_Part_14#.MP4_versus_.M4A)
- [`ogg`](https://en.wikipedia.org/wiki/Ogg)
- [`opus`](https://en.wikipedia.org/wiki/Opus_(audio_format))
- [`flac`](https://en.wikipedia.org/wiki/FLAC)
- [`wav`](https://en.wikipedia.org/wiki/WAV)
- [`qcp`](https://en.wikipedia.org/wiki/QCP)
- [`amr`](https://en.wikipedia.org/wiki/Adaptive_Multi-Rate_audio_codec)
- [`pdf`](https://en.wikipedia.org/wiki/Portable_Document_Format)
- [`epub`](https://en.wikipedia.org/wiki/EPUB)
- [`mobi`](https://en.wikipedia.org/wiki/Mobipocket) - Mobipocket
- [`exe`](https://en.wikipedia.org/wiki/.exe)
- [`swf`](https://en.wikipedia.org/wiki/SWF)
- [`rtf`](https://en.wikipedia.org/wiki/Rich_Text_Format)
- [`woff`](https://en.wikipedia.org/wiki/Web_Open_Font_Format)
- [`woff2`](https://en.wikipedia.org/wiki/Web_Open_Font_Format)
- [`eot`](https://en.wikipedia.org/wiki/Embedded_OpenType)
- [`ttf`](https://en.wikipedia.org/wiki/TrueType)
- [`otf`](https://en.wikipedia.org/wiki/OpenType)
- [`ico`](https://en.wikipedia.org/wiki/ICO_(file_format))
- [`flv`](https://en.wikipedia.org/wiki/Flash_Video)
- [`ps`](https://en.wikipedia.org/wiki/Postscript)
- [`xz`](https://en.wikipedia.org/wiki/Xz)
- [`sqlite`](https://www.sqlite.org/fileformat2.html)
- [`nes`](https://fileinfo.com/extension/nes)
- [`crx`](https://developer.chrome.com/extensions/crx)
- [`xpi`](https://en.wikipedia.org/wiki/XPInstall)
- [`cab`](https://en.wikipedia.org/wiki/Cabinet_(file_format))
- [`deb`](https://en.wikipedia.org/wiki/Deb_(file_format))
- [`ar`](https://en.wikipedia.org/wiki/Ar_(Unix))
- [`rpm`](https://fileinfo.com/extension/rpm)
- [`Z`](https://fileinfo.com/extension/z)
- [`lz`](https://en.wikipedia.org/wiki/Lzip)
- [`msi`](https://en.wikipedia.org/wiki/Windows_Installer)
- [`mxf`](https://en.wikipedia.org/wiki/Material_Exchange_Format)
- [`mts`](https://en.wikipedia.org/wiki/.m2ts)
- [`wasm`](https://en.wikipedia.org/wiki/WebAssembly)
- [`blend`](https://wiki.blender.org/index.php/Dev:Source/Architecture/File_Format)
- [`bpg`](https://bellard.org/bpg/)
- [`docx`](https://en.wikipedia.org/wiki/Office_Open_XML)
- [`pptx`](https://en.wikipedia.org/wiki/Office_Open_XML)
- [`xlsx`](https://en.wikipedia.org/wiki/Office_Open_XML)
- [`3gp`](https://en.wikipedia.org/wiki/3GP_and_3G2)
- [`jp2`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`jpm`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`jpx`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`mj2`](https://en.wikipedia.org/wiki/Motion_JPEG_2000) - Motion JPEG 2000
- [`aif`](https://en.wikipedia.org/wiki/Audio_Interchange_File_Format)
- [`odt`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for word processing
- [`ods`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for spreadsheets
- [`odp`](https://en.wikipedia.org/wiki/OpenDocument) - OpenDocument for presentations
- [`xml`](https://en.wikipedia.org/wiki/XML)
- [`heic`](https://nokiatech.github.io/heif/technical.html)
- [`cur`](https://en.wikipedia.org/wiki/ICO_(file_format))
- [`ktx`](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/)
- [`ape`](https://en.wikipedia.org/wiki/Monkey%27s_Audio) - Monkey's Audio
- [`wv`](https://en.wikipedia.org/wiki/WavPack) - WavPack
- [`asf`](https://en.wikipedia.org/wiki/Advanced_Systems_Format) - Advanced Systems Format
- [`wma`](https://en.wikipedia.org/wiki/Windows_Media_Audio) - Windows Media Audio
- [`wmv`](https://en.wikipedia.org/wiki/Windows_Media_Video) - Windows Media Video
- [`dcm`](https://en.wikipedia.org/wiki/DICOM#Data_format) - DICOM Image File
- [`mpc`](https://en.wikipedia.org/wiki/Musepack) - Musepack (SV7 & SV8)
- [`ics`](https://en.wikipedia.org/wiki/ICalendar#Data_format) - iCalendar
- [`glb`](https://github.com/KhronosGroup/glTF) - GL Transmission Format
- [`pcap`](https://wiki.wireshark.org/Development/LibpcapFileFormat) - Libpcap File Format
*SVG isn't included as it requires the whole file to be read, but you can get it [here](https://github.com/sindresorhus/is-svg).*
*Pull request welcome for additional commonly used file types.*
## Related
- [file-type-cli](https://github.com/sindresorhus/file-type-cli) - CLI for this module
## Created by
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Mikael Finstad](https://github.com/mifi)
## License
MIT
{
"_from": "image-type@^4.1.0",
"_id": "image-type@4.1.0",
"_inBundle": false,
"_integrity": "sha512-CFJMJ8QK8lJvRlTCEgarL4ro6hfDQKif2HjSvYCdQZESaIPV4v9imrf7BQHK+sQeTeNeMpWciR9hyC/g8ybXEg==",
"_location": "/image-type",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "image-type@^4.1.0",
"name": "image-type",
"escapedName": "image-type",
"rawSpec": "^4.1.0",
"saveSpec": null,
"fetchSpec": "^4.1.0"
},
"_requiredBy": [
"/messaging-api-line"
],
"_resolved": "https://registry.npmjs.org/image-type/-/image-type-4.1.0.tgz",
"_shasum": "72a88d64ff5021371ed67b9a466442100be57cd1",
"_spec": "image-type@^4.1.0",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/image-type/issues"
},
"bundleDependencies": false,
"dependencies": {
"file-type": "^10.10.0"
},
"deprecated": false,
"description": "Detect the image type of a Buffer/Uint8Array",
"devDependencies": {
"@types/node": "^11.13.0",
"ava": "^1.4.1",
"read-chunk": "^3.2.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/image-type#readme",
"keywords": [
"image",
"img",
"pic",
"picture",
"photo",
"type",
"detect",
"check",
"is",
"exif",
"binary",
"buffer",
"uint8array",
"png",
"jpg",
"jpeg",
"gif",
"webp",
"tif",
"bmp",
"jxr",
"psd",
"mime"
],
"license": "MIT",
"name": "image-type",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/image-type.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "4.1.0"
}
# image-type [![Build Status](https://travis-ci.org/sindresorhus/image-type.svg?branch=master)](https://travis-ci.org/sindresorhus/image-type)
> Detect the image type of a Buffer/Uint8Array
See the [`file-type`](https://github.com/sindresorhus/file-type) module for more file types and a CLI.
## Install
```
$ npm install image-type
```
## Usage
##### Node.js
```js
const readChunk = require('read-chunk');
const imageType = require('image-type');
const buffer = readChunk.sync('unicorn.png', 0, 12);
imageType(buffer);
//=> {ext: 'png', mime: 'image/png'}
```
Or from a remote location:
```js
const http = require('http');
const imageType = require('image-type');
const url = 'https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif';
http.get(url, response => {
response.on('readable', () => {
const chunk = response.read(imageType.minimumBytes);
response.destroy();
console.log(imageType(chunk));
//=> {ext: 'gif', mime: 'image/gif'}
});
});
```
##### Browser
```js
const xhr = new XMLHttpRequest();
xhr.open('GET', 'unicorn.png');
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
imageType(new Uint8Array(this.response));
//=> {ext: 'png', mime: 'image/png'}
};
xhr.send();
```
## API
### imageType(input)
Returns an `Object` with:
- `ext` - One of the [supported file types](#supported-file-types)
- `mime` - The [MIME type](http://en.wikipedia.org/wiki/Internet_media_type)
Or `null` when there is no match.
#### input
Type: `Buffer | Uint8Array`
It only needs the first `.minimumBytes` bytes.
### imageType.minimumBytes
Type: `number`
The minimum amount of bytes needed to detect a file type. Currently, it's 4100 bytes, but it can change, so don't hardcode it.
## Supported file types
- [`jpg`](https://en.wikipedia.org/wiki/JPEG)
- [`png`](https://en.wikipedia.org/wiki/Portable_Network_Graphics)
- [`gif`](https://en.wikipedia.org/wiki/GIF)
- [`webp`](https://en.wikipedia.org/wiki/WebP)
- [`flif`](https://en.wikipedia.org/wiki/Free_Lossless_Image_Format)
- [`cr2`](https://fileinfo.com/extension/cr2)
- [`tif`](https://en.wikipedia.org/wiki/Tagged_Image_File_Format)
- [`bmp`](https://en.wikipedia.org/wiki/BMP_file_format)
- [`jxr`](https://en.wikipedia.org/wiki/JPEG_XR)
- [`psd`](https://en.wikipedia.org/wiki/Adobe_Photoshop#File_format)
- [`ico`](https://en.wikipedia.org/wiki/ICO_(file_format))
- [`bpg`](https://bellard.org/bpg/)
- [`jp2`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`jpm`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`jpx`](https://en.wikipedia.org/wiki/JPEG_2000) - JPEG 2000
- [`heic`](https://nokiatech.github.io/heif/technical.html)
- [`cur`](https://en.wikipedia.org/wiki/ICO_(file_format))
- [`dcm`](https://en.wikipedia.org/wiki/DICOM#Data_format) - DICOM Image File
*SVG isn't included as it requires the whole file to be read, but you can get it [here](https://github.com/sindresorhus/is-svg).*
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
2.2.4 / 2018-03-13
==================
* Use flow strict mode (i.e. `@flow strict`).
2.2.3 / 2018-02-19
==================
* Change license from BSD+Patents to MIT.
2.2.2 / 2016-11-15
==================
* Add LICENSE file.
* Misc housekeeping.
2.2.1 / 2016-03-09
==================
* Use `NODE_ENV` variable instead of `__DEV__` to cache `process.env.NODE_ENV`.
2.2.0 / 2015-11-17
==================
* Use `error.name` instead of `Invariant Violation`.
2.1.3 / 2015-11-17
==================
* Remove `@provideModule` pragma.
2.1.2 / 2015-10-27
==================
* Fix license.
2.1.1 / 2015-09-20
==================
* Use correct SPDX license.
* Test "browser.js" using browserify.
* Switch from "envify" to "loose-envify".
2.1.0 / 2015-06-03
==================
* Add "envify" as a dependency.
* Fixed license field in "package.json".
2.0.0 / 2015-02-21
==================
* Switch to using the "browser" field. There are now browser and server versions that respect the "format" in production.
1.0.2 / 2014-09-24
==================
* Added tests, npmignore and gitignore.
* Clarifications in README.
1.0.1 / 2014-09-24
==================
* Actually include 'invariant.js'.
1.0.0 / 2014-09-24
==================
* Initial release.
MIT License
Copyright (c) 2013-present, Facebook, Inc.
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.
# invariant
[![Build Status](https://travis-ci.org/zertosh/invariant.svg?branch=master)](https://travis-ci.org/zertosh/invariant)
A mirror of Facebook's `invariant` (e.g. [React](https://github.com/facebook/react/blob/v0.13.3/src/vendor/core/invariant.js), [flux](https://github.com/facebook/flux/blob/2.0.2/src/invariant.js)).
A way to provide descriptive errors in development but generic errors in production.
## Install
With [npm](http://npmjs.org) do:
```sh
npm install invariant
```
## `invariant(condition, message)`
```js
var invariant = require('invariant');
invariant(someTruthyVal, 'This will not throw');
// No errors
invariant(someFalseyVal, 'This will throw an error with this message');
// Error: Invariant Violation: This will throw an error with this message
```
**Note:** When `process.env.NODE_ENV` is not `production`, the message is required. If omitted, `invariant` will throw regardless of the truthiness of the condition. When `process.env.NODE_ENV` is `production`, the message is optional – so they can be minified away.
### Browser
When used with [browserify](https://github.com/substack/node-browserify), it'll use `browser.js` (instead of `invariant.js`) and the [envify](https://github.com/hughsk/envify) transform will inline the value of `process.env.NODE_ENV`.
### Node
The node version is optimized around the performance implications of accessing `process.env`. The value of `process.env.NODE_ENV` is cached, and repeatedly used instead of reading `process.env`. See [Server rendering is slower with npm react #812](https://github.com/facebook/react/issues/812)
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var NODE_ENV = process.env.NODE_ENV;
var invariant = function(condition, format, a, b, c, d, e, f) {
if (NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/* @flow strict */
declare module.exports: (
condition: any,
format?: string,
...args: Array<any>
) => void;
{
"_from": "invariant@^2.2.4",
"_id": "invariant@2.2.4",
"_inBundle": false,
"_integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==",
"_location": "/invariant",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "invariant@^2.2.4",
"name": "invariant",
"escapedName": "invariant",
"rawSpec": "^2.2.4",
"saveSpec": null,
"fetchSpec": "^2.2.4"
},
"_requiredBy": [
"/messaging-api-line"
],
"_resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
"_shasum": "610f3c92c9359ce1db616e538008d23ff35158e6",
"_spec": "invariant@^2.2.4",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line",
"author": {
"name": "Andres Suarez",
"email": "zertosh@gmail.com"
},
"browser": "browser.js",
"browserify": {
"transform": [
"loose-envify"
]
},
"bugs": {
"url": "https://github.com/zertosh/invariant/issues"
},
"bundleDependencies": false,
"dependencies": {
"loose-envify": "^1.0.0"
},
"deprecated": false,
"description": "invariant",
"devDependencies": {
"browserify": "^11.0.1",
"flow-bin": "^0.67.1",
"tap": "^1.4.0"
},
"files": [
"browser.js",
"invariant.js",
"invariant.js.flow"
],
"homepage": "https://github.com/zertosh/invariant#readme",
"keywords": [
"test",
"invariant"
],
"license": "MIT",
"main": "invariant.js",
"name": "invariant",
"repository": {
"type": "git",
"url": "git+https://github.com/zertosh/invariant.git"
},
"scripts": {
"test": "NODE_ENV=production tap test/*.js && NODE_ENV=development tap test/*.js"
},
"version": "2.2.4"
}
### Version 4.0.0 (2018-01-28) ###
- Added: Support for ES2018. The only change needed was recognizing the `s`
regex flag.
- Changed: _All_ tokens returned by the `matchToToken` function now have a
`closed` property. It is set to `undefined` for the tokens where “closed”
doesn’t make sense. This means that all tokens objects have the same shape,
which might improve performance.
These are the breaking changes:
- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but
`['/a/s']`. (There are of course other variations of this.)
- Code that rely on some token objects not having the `closed` property could
now behave differently.
### Version 3.0.2 (2017-06-28) ###
- No code changes. Just updates to the readme.
### Version 3.0.1 (2017-01-30) ###
- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched
correctly.
### Version 3.0.0 (2017-01-11) ###
This release contains one breaking change, that should [improve performance in
V8][v8-perf]:
> So how can you, as a JavaScript developer, ensure that your RegExps are fast?
> If you are not interested in hooking into RegExp internals, make sure that
> neither the RegExp instance, nor its prototype is modified in order to get the
> best performance:
>
> ```js
> var re = /./g;
> re.exec(''); // Fast path.
> re.new_property = 'slow';
> ```
This module used to export a single regex, with `.matchToToken` bolted
on, just like in the above example. This release changes the exports of
the module to avoid this issue.
Before:
```js
import jsTokens from "js-tokens"
// or:
var jsTokens = require("js-tokens")
var matchToToken = jsTokens.matchToToken
```
After:
```js
import jsTokens, {matchToToken} from "js-tokens"
// or:
var jsTokens = require("js-tokens").default
var matchToToken = require("js-tokens").matchToToken
```
[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html
### Version 2.0.0 (2016-06-19) ###
- Added: Support for ES2016. In other words, support for the `**` exponentiation
operator.
These are the breaking changes:
- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`.
- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`.
### Version 1.0.3 (2016-03-27) ###
- Improved: Made the regex ever so slightly smaller.
- Updated: The readme.
### Version 1.0.2 (2015-10-18) ###
- Improved: Limited npm package contents for a smaller download. Thanks to
@zertosh!
### Version 1.0.1 (2015-06-20) ###
- Fixed: Declared an undeclared variable.
### Version 1.0.0 (2015-02-26) ###
- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That
type is now equivalent to the Punctuator token in the ECMAScript
specification. (Backwards-incompatible change.)
- Fixed: A `-` followed by a number is now correctly matched as a punctuator
followed by a number. It used to be matched as just a number, but there is no
such thing as negative number literals. (Possibly backwards-incompatible
change.)
### Version 0.4.1 (2015-02-21) ###
- Added: Support for the regex `u` flag.
### Version 0.4.0 (2015-02-21) ###
- Improved: `jsTokens.matchToToken` performance.
- Added: Support for octal and binary number literals.
- Added: Support for template strings.
### Version 0.3.1 (2015-01-06) ###
- Fixed: Support for unicode spaces. They used to be allowed in names (which is
very confusing), and some unicode newlines were wrongly allowed in strings and
regexes.
### Version 0.3.0 (2014-12-19) ###
- Changed: The `jsTokens.names` array has been replaced with the
`jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no
longer part of the public API; instead use said function. See this [gist] for
an example. (Backwards-incompatible change.)
- Changed: The empty string is now considered an “invalid” token, instead an
“empty” token (its own group). (Backwards-incompatible change.)
- Removed: component support. (Backwards-incompatible change.)
[gist]: https://gist.github.com/lydell/be49dbf80c382c473004
### Version 0.2.0 (2014-06-19) ###
- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own
category (“functionArrow”), for simplicity. (Backwards-incompatible change.)
- Added: ES6 splats (`...`) are now matched as an operator (instead of three
punctuations). (Backwards-incompatible change.)
### Version 0.1.0 (2014-03-08) ###
- Initial release.
The MIT License (MIT)
Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell
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.
Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens)
========
A regex that tokenizes JavaScript.
```js
var jsTokens = require("js-tokens").default
var jsString = "var foo=opts.foo;\n..."
jsString.match(jsTokens)
// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...]
```
Installation
============
`npm install js-tokens`
```js
import jsTokens from "js-tokens"
// or:
var jsTokens = require("js-tokens").default
```
Usage
=====
### `jsTokens` ###
A regex with the `g` flag that matches JavaScript tokens.
The regex _always_ matches, even invalid JavaScript and the empty string.
The next match is always directly after the previous.
### `var token = matchToToken(match)` ###
```js
import {matchToToken} from "js-tokens"
// or:
var matchToToken = require("js-tokens").matchToToken
```
Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type:
String, value: String}` object. The following types are available:
- string
- comment
- regex
- number
- name
- punctuator
- whitespace
- invalid
Multi-line comments and strings also have a `closed` property indicating if the
token was closed or not (see below).
Comments and strings both come in several flavors. To distinguish them, check if
the token starts with `//`, `/*`, `'`, `"` or `` ` ``.
Names are ECMAScript IdentifierNames, that is, including both identifiers and
keywords. You may use [is-keyword-js] to tell them apart.
Whitespace includes both line terminators and other whitespace.
[is-keyword-js]: https://github.com/crissdev/is-keyword-js
ECMAScript support
==================
The intention is to always support the latest ECMAScript version whose feature
set has been finalized.
If adding support for a newer version requires changes, a new version with a
major verion bump will be released.
Currently, ECMAScript 2018 is supported.
Invalid code handling
=====================
Unterminated strings are still matched as strings. JavaScript strings cannot
contain (unescaped) newlines, so unterminated strings simply end at the end of
the line. Unterminated template strings can contain unescaped newlines, though,
so they go on to the end of input.
Unterminated multi-line comments are also still matched as comments. They
simply go on to the end of the input.
Unterminated regex literals are likely matched as division and whatever is
inside the regex.
Invalid ASCII characters have their own capturing group.
Invalid non-ASCII characters are treated as names, to simplify the matching of
names (except unicode spaces which are treated as whitespace). Note: See also
the [ES2018](#es2018) section.
Regex literals may contain invalid regex syntax. They are still matched as
regex literals. They may also contain repeated regex flags, to keep the regex
simple.
Strings may contain invalid escape sequences.
Limitations
===========
Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be
perfect. But that’s not the point either.
You may compare jsTokens with [esprima] by using `esprima-compare.js`.
See `npm run esprima-compare`!
[esprima]: http://esprima.org/
### Template string interpolation ###
Template strings are matched as single tokens, from the starting `` ` `` to the
ending `` ` ``, including interpolations (whose tokens are not matched
individually).
Matching template string interpolations requires recursive balancing of `{` and
`}`—something that JavaScript regexes cannot do. Only one level of nesting is
supported.
### Division and regex literals collision ###
Consider this example:
```js
var g = 9.82
var number = bar / 2/g
var regex = / 2/g
```
A human can easily understand that in the `number` line we’re dealing with
division, and in the `regex` line we’re dealing with a regex literal. How come?
Because humans can look at the whole code to put the `/` characters in context.
A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also
look backwards. See the [ES2018](#es2018) section).
When the `jsTokens` regex scans throught the above, it will see the following
at the end of both the `number` and `regex` rows:
```js
/ 2/g
```
It is then impossible to know if that is a regex literal, or part of an
expression dealing with division.
Here is a similar case:
```js
foo /= 2/g
foo(/= 2/g)
```
The first line divides the `foo` variable with `2/g`. The second line calls the
`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only
sees forwards, it cannot tell the two cases apart.
There are some cases where we _can_ tell division and regex literals apart,
though.
First off, we have the simple cases where there’s only one slash in the line:
```js
var foo = 2/g
foo /= 2
```
Regex literals cannot contain newlines, so the above cases are correctly
identified as division. Things are only problematic when there are more than
one non-comment slash in a single line.
Secondly, not every character is a valid regex flag.
```js
var number = bar / 2/e
```
The above example is also correctly identified as division, because `e` is not a
valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*`
(any letter) as flags, but it is not worth it since it increases the amount of
ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are
allowed. This means that the above example will be identified as division as
long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6
characters long.
Lastly, we can look _forward_ for information.
- If the token following what looks like a regex literal is not valid after a
regex literal, but is valid in a division expression, then the regex literal
is treated as division instead. For example, a flagless regex cannot be
followed by a string, number or name, but all of those three can be the
denominator of a division.
- Generally, if what looks like a regex literal is followed by an operator, the
regex literal is treated as division instead. This is because regexes are
seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division
could likely be part of such an expression.
Please consult the regex source and the test cases for precise information on
when regex or division is matched (should you need to know). In short, you
could sum it up as:
If the end of a statement looks like a regex literal (even if it isn’t), it
will be treated as one. Otherwise it should work as expected (if you write sane
code).
### ES2018 ###
ES2018 added some nice regex improvements to the language.
- [Unicode property escapes] should allow telling names and invalid non-ASCII
characters apart without blowing up the regex size.
- [Lookbehind assertions] should allow matching telling division and regex
literals apart in more cases.
- [Named capture groups] might simplify some things.
These things would be nice to do, but are not critical. They probably have to
wait until the oldest maintained Node.js LTS release supports those features.
[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html
[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html
[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html
License
=======
[MIT](LICENSE).
// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
// License: MIT. (See LICENSE.)
Object.defineProperty(exports, "__esModule", {
value: true
})
// This regex comes from regex.coffee, and is inserted here by generate-index.js
// (run `npm run build`).
exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g
exports.matchToToken = function(match) {
var token = {type: "invalid", value: match[0], closed: undefined}
if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4])
else if (match[ 5]) token.type = "comment"
else if (match[ 6]) token.type = "comment", token.closed = !!match[7]
else if (match[ 8]) token.type = "regex"
else if (match[ 9]) token.type = "number"
else if (match[10]) token.type = "name"
else if (match[11]) token.type = "punctuator"
else if (match[12]) token.type = "whitespace"
return token
}
{
"_from": "js-tokens@^3.0.0 || ^4.0.0",
"_id": "js-tokens@4.0.0",
"_inBundle": false,
"_integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"_location": "/js-tokens",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "js-tokens@^3.0.0 || ^4.0.0",
"name": "js-tokens",
"escapedName": "js-tokens",
"rawSpec": "^3.0.0 || ^4.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0 || ^4.0.0"
},
"_requiredBy": [
"/loose-envify"
],
"_resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"_shasum": "19203fb59991df98e3a287050d4647cdeaf32499",
"_spec": "js-tokens@^3.0.0 || ^4.0.0",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\loose-envify",
"author": {
"name": "Simon Lydell"
},
"bugs": {
"url": "https://github.com/lydell/js-tokens/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "A regex that tokenizes JavaScript.",
"devDependencies": {
"coffeescript": "2.1.1",
"esprima": "4.0.0",
"everything.js": "1.0.3",
"mocha": "5.0.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/lydell/js-tokens#readme",
"keywords": [
"JavaScript",
"js",
"token",
"tokenize",
"regex"
],
"license": "MIT",
"name": "js-tokens",
"repository": {
"type": "git",
"url": "git+https://github.com/lydell/js-tokens.git"
},
"scripts": {
"build": "node generate-index.js",
"dev": "npm run build && npm test",
"esprima-compare": "node esprima-compare ./index.js everything.js/es5.js",
"test": "mocha --ui tdd"
},
"version": "4.0.0"
}
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.
# lodash.omit v4.5.0
The [lodash](https://lodash.com/) method `_.omit` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.omit
```
In Node.js:
```js
var omit = require('lodash.omit');
```
See the [documentation](https://lodash.com/docs#omit) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.omit) for more details.
This diff is collapsed. Click to expand it.
{
"_from": "lodash.omit@^4.5.0",
"_id": "lodash.omit@4.5.0",
"_inBundle": false,
"_integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=",
"_location": "/lodash.omit",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "lodash.omit@^4.5.0",
"name": "lodash.omit",
"escapedName": "lodash.omit",
"rawSpec": "^4.5.0",
"saveSpec": null,
"fetchSpec": "^4.5.0"
},
"_requiredBy": [
"/messaging-api-line"
],
"_resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz",
"_shasum": "6eb19ae5a1ee1dd9df0b969e66ce0b7fa30b5e60",
"_spec": "lodash.omit@^4.5.0",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line",
"author": {
"name": "John-David Dalton",
"email": "john.david.dalton@gmail.com",
"url": "http://allyoucanleet.com/"
},
"bugs": {
"url": "https://github.com/lodash/lodash/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "John-David Dalton",
"email": "john.david.dalton@gmail.com",
"url": "http://allyoucanleet.com/"
},
{
"name": "Blaine Bublitz",
"email": "blaine.bublitz@gmail.com",
"url": "https://github.com/phated"
},
{
"name": "Mathias Bynens",
"email": "mathias@qiwi.be",
"url": "https://mathiasbynens.be/"
}
],
"deprecated": false,
"description": "The lodash method `_.omit` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"keywords": [
"lodash-modularized",
"omit"
],
"license": "MIT",
"name": "lodash.omit",
"repository": {
"type": "git",
"url": "git+https://github.com/lodash/lodash.git"
},
"scripts": {
"test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\""
},
"version": "4.5.0"
}
The MIT License (MIT)
Copyright (c) 2015 Andres Suarez <zertosh@gmail.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.
# loose-envify
[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify)
Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster.
## Gotchas
* Doesn't handle broken syntax.
* Doesn't look inside embedded expressions in template strings.
- **this won't work:**
```js
console.log(`the current env is ${process.env.NODE_ENV}`);
```
* Doesn't replace oddly-spaced or oddly-commented expressions.
- **this won't work:**
```js
console.log(process./*won't*/env./*work*/NODE_ENV);
```
## Usage/Options
loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI.
## Benchmark
```
envify:
$ for i in {1..5}; do node bench/bench.js 'envify'; done
708ms
727ms
791ms
719ms
720ms
loose-envify:
$ for i in {1..5}; do node bench/bench.js '../'; done
51ms
52ms
52ms
52ms
52ms
```
#!/usr/bin/env node
'use strict';
var looseEnvify = require('./');
var fs = require('fs');
if (process.argv[2]) {
fs.createReadStream(process.argv[2], {encoding: 'utf8'})
.pipe(looseEnvify(process.argv[2]))
.pipe(process.stdout);
} else {
process.stdin.resume()
process.stdin
.pipe(looseEnvify(__filename))
.pipe(process.stdout);
}
// envify compatibility
'use strict';
module.exports = require('./loose-envify');
'use strict';
module.exports = require('./loose-envify')(process.env);
'use strict';
var stream = require('stream');
var util = require('util');
var replace = require('./replace');
var jsonExtRe = /\.json$/;
module.exports = function(rootEnv) {
rootEnv = rootEnv || process.env;
return function (file, trOpts) {
if (jsonExtRe.test(file)) {
return stream.PassThrough();
}
var envs = trOpts ? [rootEnv, trOpts] : [rootEnv];
return new LooseEnvify(envs);
};
};
function LooseEnvify(envs) {
stream.Transform.call(this);
this._data = '';
this._envs = envs;
}
util.inherits(LooseEnvify, stream.Transform);
LooseEnvify.prototype._transform = function(buf, enc, cb) {
this._data += buf;
cb();
};
LooseEnvify.prototype._flush = function(cb) {
var replaced = replace(this._data, this._envs);
this.push(replaced);
cb();
};
{
"_from": "loose-envify@^1.0.0",
"_id": "loose-envify@1.4.0",
"_inBundle": false,
"_integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"_location": "/loose-envify",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "loose-envify@^1.0.0",
"name": "loose-envify",
"escapedName": "loose-envify",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/invariant"
],
"_resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"_shasum": "71ee51fa7be4caec1a63839f7e682d8132d30caf",
"_spec": "loose-envify@^1.0.0",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\invariant",
"author": {
"name": "Andres Suarez",
"email": "zertosh@gmail.com"
},
"bin": {
"loose-envify": "cli.js"
},
"bugs": {
"url": "https://github.com/zertosh/loose-envify/issues"
},
"bundleDependencies": false,
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"deprecated": false,
"description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST",
"devDependencies": {
"browserify": "^13.1.1",
"envify": "^3.4.0",
"tap": "^8.0.0"
},
"homepage": "https://github.com/zertosh/loose-envify",
"keywords": [
"environment",
"variables",
"browserify",
"browserify-transform",
"transform",
"source",
"configuration"
],
"license": "MIT",
"main": "index.js",
"name": "loose-envify",
"repository": {
"type": "git",
"url": "git://github.com/zertosh/loose-envify.git"
},
"scripts": {
"test": "tap test/*.js"
},
"version": "1.4.0"
}
'use strict';
var jsTokens = require('js-tokens').default;
var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/;
var spaceOrCommentRe = /^(?:\s|\/[/*])/;
function replace(src, envs) {
if (!processEnvRe.test(src)) {
return src;
}
var out = [];
var purge = envs.some(function(env) {
return env._ && env._.indexOf('purge') !== -1;
});
jsTokens.lastIndex = 0
var parts = src.match(jsTokens);
for (var i = 0; i < parts.length; i++) {
if (parts[i ] === 'process' &&
parts[i + 1] === '.' &&
parts[i + 2] === 'env' &&
parts[i + 3] === '.') {
var prevCodeToken = getAdjacentCodeToken(-1, parts, i);
var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4);
var replacement = getReplacementString(envs, parts[i + 4], purge);
if (prevCodeToken !== '.' &&
nextCodeToken !== '.' &&
nextCodeToken !== '=' &&
typeof replacement === 'string') {
out.push(replacement);
i += 4;
continue;
}
}
out.push(parts[i]);
}
return out.join('');
}
function getAdjacentCodeToken(dir, parts, i) {
while (true) {
var part = parts[i += dir];
if (!spaceOrCommentRe.test(part)) {
return part;
}
}
}
function getReplacementString(envs, name, purge) {
for (var j = 0; j < envs.length; j++) {
var env = envs[j];
if (typeof env[name] !== 'undefined') {
return JSON.stringify(env[name]);
}
}
if (purge) {
return 'undefined';
}
}
module.exports = replace;
The MIT License (MIT)
Copyright (c) 2017-present Yoctol (github.com/Yoctol/messaging-apis)
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 could not be displayed because it is too large.
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _invariant = _interopRequireDefault(require("invariant"));
var _lodash = _interopRequireDefault(require("lodash.omit"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;});keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_defineProperty(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}
function createText(text, options = {}) {
return _objectSpread({
type: 'text',
text },
(0, _lodash.default)(options, 'accessToken'));
}
function createImage(
contentUrlOrImage,
previewUrlOrOptions)
{
if (previewUrlOrOptions) {
if (
typeof contentUrlOrImage === 'object' &&
typeof previewUrlOrOptions === 'object')
{
const image = contentUrlOrImage;
const options = previewUrlOrOptions;
return _objectSpread({
type: 'image',
originalContentUrl: image.originalContentUrl,
previewImageUrl: image.previewImageUrl || image.originalContentUrl },
(0, _lodash.default)(options, 'accessToken'));
}
if (
typeof contentUrlOrImage === 'string' &&
typeof previewUrlOrOptions === 'string')
{
return {
type: 'image',
originalContentUrl: contentUrlOrImage,
previewImageUrl: previewUrlOrOptions };
}
} else {
if (typeof contentUrlOrImage === 'object') {
const image = contentUrlOrImage;
return {
type: 'image',
originalContentUrl: image.originalContentUrl,
previewImageUrl: image.previewImageUrl || image.originalContentUrl };
}
if (typeof contentUrlOrImage === 'string') {
return {
type: 'image',
originalContentUrl: contentUrlOrImage,
previewImageUrl: contentUrlOrImage };
}
}
(0, _invariant.default)(false, 'Line#createImage: Wrong type of arguments.');
}
function createVideo(
contentUrlOrVideo,
previewImageUrlOrOptions)
{
if (
typeof contentUrlOrVideo === 'string' &&
typeof previewImageUrlOrOptions === 'string')
{
return {
type: 'video',
originalContentUrl: contentUrlOrVideo,
previewImageUrl: previewImageUrlOrOptions };
}
if (
typeof contentUrlOrVideo === 'object' && (
!previewImageUrlOrOptions || typeof previewImageUrlOrOptions === 'object'))
{
const video = contentUrlOrVideo;
const options = previewImageUrlOrOptions || {};
return _objectSpread({
type: 'video',
originalContentUrl: video.originalContentUrl,
previewImageUrl: video.previewImageUrl },
(0, _lodash.default)(options, 'accessToken'));
}
(0, _invariant.default)(false, 'Line#createVideo: Wrong type of arguments.');
}
function createAudio(
contentUrlOrAudio,
durationOrOptions)
{
if (
typeof contentUrlOrAudio === 'string' &&
typeof durationOrOptions === 'number')
{
return {
type: 'audio',
originalContentUrl: contentUrlOrAudio,
duration: durationOrOptions };
}
if (
typeof contentUrlOrAudio === 'object' && (
!durationOrOptions || typeof durationOrOptions === 'object'))
{
const audio = contentUrlOrAudio;
const options = durationOrOptions || {};
return _objectSpread({
type: 'audio',
originalContentUrl: audio.originalContentUrl,
duration: audio.duration },
(0, _lodash.default)(options, 'accessToken'));
}
(0, _invariant.default)(false, 'Line#createAudio: Wrong type of arguments.');
}
function createLocation(
{ title, address, latitude, longitude },
options = {})
{
return _objectSpread({
type: 'location',
title,
address,
latitude,
longitude },
(0, _lodash.default)(options, 'accessToken'));
}
function createSticker(
packageIdOrSticker,
stickerIdOrOptions)
{
if (
typeof packageIdOrSticker === 'string' &&
typeof stickerIdOrOptions === 'string')
{
return {
type: 'sticker',
packageId: packageIdOrSticker,
stickerId: stickerIdOrOptions };
}
if (
typeof packageIdOrSticker === 'object' && (
!stickerIdOrOptions || typeof stickerIdOrOptions === 'object'))
{
const sticker = packageIdOrSticker;
const options = stickerIdOrOptions || {};
return _objectSpread({
type: 'sticker',
packageId: sticker.packageId,
stickerId: sticker.stickerId },
(0, _lodash.default)(options, 'accessToken'));
}
(0, _invariant.default)(false, 'Line#createSticker: Wrong type of arguments.');
}
function createImagemap(
altText,
{
baseUrl,
baseSize,
baseHeight,
baseWidth,
video,
actions },
options = {})
{
return _objectSpread({
type: 'imagemap',
baseUrl,
altText,
baseSize: baseSize || {
height: baseHeight,
width: baseWidth },
video,
actions },
(0, _lodash.default)(options, 'accessToken'));
}
function createTemplate(
altText,
template,
options = {})
{
return _objectSpread({
type: 'template',
altText,
template },
(0, _lodash.default)(options, 'accessToken'));
}
function createButtonTemplate(
altText,
{
thumbnailImageUrl,
imageAspectRatio,
imageSize,
imageBackgroundColor,
title,
text,
defaultAction,
actions },
options = {})
{
return createTemplate(
altText,
{
type: 'buttons',
thumbnailImageUrl,
imageAspectRatio,
imageSize,
imageBackgroundColor,
title,
text,
defaultAction,
actions },
(0, _lodash.default)(options, 'accessToken'));
}
function createConfirmTemplate(
altText,
{
text,
actions },
options = {})
{
return createTemplate(
altText,
{
type: 'confirm',
text,
actions },
(0, _lodash.default)(options, 'accessToken'));
}
function createCarouselTemplate(
altText,
columns,
{
imageAspectRatio,
imageSize,
quickReply } =
{})
{
return createTemplate(
altText,
{
type: 'carousel',
columns,
imageAspectRatio,
imageSize },
{ quickReply });
}
function createImageCarouselTemplate(
altText,
columns,
options = {})
{
return createTemplate(
altText,
{
type: 'image_carousel',
columns },
(0, _lodash.default)(options, 'accessToken'));
}
function createFlex(
altText,
contents,
options = {})
{
return _objectSpread({
type: 'flex',
altText,
contents },
(0, _lodash.default)(options, 'accessToken'));
}
const Line = {
createText,
createImage,
createVideo,
createAudio,
createLocation,
createSticker,
createImagemap,
createTemplate,
createButtonsTemplate: createButtonTemplate,
createButtonTemplate,
createConfirmTemplate,
createCarouselTemplate,
createImageCarouselTemplate,
createFlex };var _default =
Line;exports.default = _default;
\ No newline at end of file
This diff is collapsed. Click to expand it.
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _querystring = _interopRequireDefault(require("querystring"));
var _axiosError = _interopRequireDefault(require("axios-error"));
var _axios = _interopRequireDefault(require("axios"));
var _invariant = _interopRequireDefault(require("invariant"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;});keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_defineProperty(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}function _objectWithoutProperties(source, excluded) {if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];}}return target;}function _objectWithoutPropertiesLoose(source, excluded) {if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}
function handleError(err) {
if (err.response && err.response.data) {
const { returnCode, returnMessage } = err.response.data;
const msg = `LINE PAY API - ${returnCode} ${returnMessage}`;
throw new _axiosError.default(msg, err);
}
throw new _axiosError.default(err.message, err);
}
function throwWhenNotSuccess(res) {
if (res.data.returnCode !== '0000') {
const { returnCode, returnMessage } = res.data;
const msg = `LINE PAY API - ${returnCode} ${returnMessage}`;
throw new _axiosError.default(msg);
}
return res.data.info;
}
class LinePay {
static connect(config) {
return new LinePay(config);
}
constructor({
channelId,
channelSecret,
sandbox = false,
origin })
{_defineProperty(this, "_axios", void 0);
const linePayOrigin = sandbox ?
'https://sandbox-api-pay.line.me' :
'https://api-pay.line.me';
this._axios = _axios.default.create({
baseURL: `${origin || linePayOrigin}/v2/`,
headers: {
'Content-Type': 'application/json',
'X-LINE-ChannelId': channelId,
'X-LINE-ChannelSecret': channelSecret } });
}
get axios() {
return this._axios;
}
getPayments({
transactionId,
orderId } =
{}) {
(0, _invariant.default)(
transactionId || orderId,
'getPayments: One of `transactionId` or `orderId` must be provided');
const query = {};
if (transactionId) {
query.transactionId = transactionId;
}
if (orderId) {
query.orderId = orderId;
}
return this._axios.
get(`/payments?${_querystring.default.stringify(query)}`).
then(throwWhenNotSuccess, handleError);
}
getAuthorizations({
transactionId,
orderId } =
{}) {
(0, _invariant.default)(
transactionId || orderId,
'getAuthorizations: One of `transactionId` or `orderId` must be provided');
const query = {};
if (transactionId) {
query.transactionId = transactionId;
}
if (orderId) {
query.orderId = orderId;
}
return this._axios.
get(`/payments/authorizations?${_querystring.default.stringify(query)}`).
then(throwWhenNotSuccess, handleError);
}
reserve(_ref)
{let { productName, amount, currency, confirmUrl, orderId } = _ref,options = _objectWithoutProperties(_ref, ["productName", "amount", "currency", "confirmUrl", "orderId"]);
return this._axios.
post('/payments/request', _objectSpread({
productName,
amount,
currency,
confirmUrl,
orderId },
options)).
then(throwWhenNotSuccess, handleError);
}
confirm(
transactionId,
{
amount,
currency })
{
return this._axios.
post(`/payments/${transactionId}/confirm`, {
amount,
currency }).
then(throwWhenNotSuccess, handleError);
}
capture(
transactionId,
{
amount,
currency })
{
return this._axios.
post(`/payments/authorizations/${transactionId}/capture`, {
amount,
currency }).
then(throwWhenNotSuccess, handleError);
}
void(transactionId) {
return this._axios.
post(`/payments/authorizations/${transactionId}/void`).
then(throwWhenNotSuccess, handleError);
}
refund(transactionId, options = {}) {
return this._axios.
post(`/payments/${transactionId}/refund`, options).
then(throwWhenNotSuccess, handleError);
}}exports.default = LinePay;
\ No newline at end of file
"use strict";
\ No newline at end of file
"use strict";Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "Line", { enumerable: true, get: function () {return _Line.default;} });exports.default = void 0;
var _Line = _interopRequireDefault(require("./Line"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default =
{ Line: _Line.default };exports.default = _default;
\ No newline at end of file
"use strict";Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "Line", { enumerable: true, get: function () {return _Line.default;} });Object.defineProperty(exports, "LineClient", { enumerable: true, get: function () {return _LineClient.default;} });Object.defineProperty(exports, "LinePay", { enumerable: true, get: function () {return _LinePay.default;} });exports.default = void 0;
var _Line = _interopRequireDefault(require("./Line"));
var _LineClient = _interopRequireDefault(require("./LineClient"));
var _LinePay = _interopRequireDefault(require("./LinePay"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default =
{ Line: _Line.default, LineClient: _LineClient.default, LinePay: _LinePay.default };exports.default = _default;
\ No newline at end of file
This diff is collapsed. Click to expand it.
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
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.
This diff is collapsed. Click to expand it.
{
"_from": "debug@^4.1.1",
"_id": "debug@4.1.1",
"_inBundle": false,
"_integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"_location": "/messaging-api-line/debug",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "debug@^4.1.1",
"name": "debug",
"escapedName": "debug",
"rawSpec": "^4.1.1",
"saveSpec": null,
"fetchSpec": "^4.1.1"
},
"_requiredBy": [
"/messaging-api-line"
],
"_resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"_shasum": "3b72260255109c6b589cee050f1d516139664791",
"_spec": "debug@^4.1.1",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"browser": "./src/browser.js",
"bugs": {
"url": "https://github.com/visionmedia/debug/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io"
},
{
"name": "Andrew Rhyne",
"email": "rhyneandrew@gmail.com"
}
],
"dependencies": {
"ms": "^2.1.1"
},
"deprecated": false,
"description": "small debugging utility",
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"browserify": "14.4.0",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.0.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"xo": "^0.23.0"
},
"files": [
"src",
"dist/debug.js",
"LICENSE",
"README.md"
],
"homepage": "https://github.com/visionmedia/debug#readme",
"keywords": [
"debug",
"log",
"debugger"
],
"license": "MIT",
"main": "./src/index.js",
"name": "debug",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"scripts": {
"build": "npm run build:debug && npm run build:test",
"build:debug": "babel -o dist/debug.js dist/debug.es6.js > dist/debug.js",
"build:test": "babel -d dist test.js",
"clean": "rimraf dist coverage",
"lint": "xo",
"prebuild:debug": "mkdir -p dist && browserify --standalone debug -o dist/debug.es6.js .",
"pretest:browser": "npm run build",
"test": "npm run test:node && npm run test:browser",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls",
"test:node": "istanbul cover _mocha -- test.js"
},
"unpkg": "./dist/debug.js",
"version": "4.1.1"
}
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log(...args) {
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return typeof console === 'object' &&
console.log &&
console.log(...args);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend;
// Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
const index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
const instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.replace(/\s*\n\s*/g, ' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
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.
{
"_from": "ms@^2.1.1",
"_id": "ms@2.1.2",
"_inBundle": false,
"_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"_location": "/messaging-api-line/ms",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ms@^2.1.1",
"name": "ms",
"escapedName": "ms",
"rawSpec": "^2.1.1",
"saveSpec": null,
"fetchSpec": "^2.1.1"
},
"_requiredBy": [
"/messaging-api-line/debug"
],
"_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"_shasum": "d09d1f357b443f493382a8eb3ccd183872ae6009",
"_spec": "ms@^2.1.1",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT\\node_modules\\messaging-api-line\\node_modules\\debug",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Tiny millisecond conversion utility",
"devDependencies": {
"eslint": "4.12.1",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"files": [
"index.js"
],
"homepage": "https://github.com/zeit/ms#readme",
"license": "MIT",
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"main": "./index",
"name": "ms",
"repository": {
"type": "git",
"url": "git+https://github.com/zeit/ms.git"
},
"scripts": {
"lint": "eslint lib/* bin/*",
"precommit": "lint-staged",
"test": "mocha tests.js"
},
"version": "2.1.2"
}
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`
{
"_from": "messaging-api-line",
"_id": "messaging-api-line@0.8.3",
"_inBundle": false,
"_integrity": "sha512-EQRqW9UMtfQPw/PfnkFue7eSXZlxX2Ke5frFGhl6UHUW5Qfi4KPpvAqf2VTaU/cU7rGhGnZWuNbjoxkCWDyT8A==",
"_location": "/messaging-api-line",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "messaging-api-line",
"name": "messaging-api-line",
"escapedName": "messaging-api-line",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/messaging-api-line/-/messaging-api-line-0.8.3.tgz",
"_shasum": "53344ba1e88bc91da5c03df5618e32a395e176e8",
"_spec": "messaging-api-line",
"_where": "C:\\Users\\김수민\\Desktop\\ostt\\LINEBOT",
"browser": "lib/browser.js",
"bugs": {
"url": "https://github.com/Yoctol/messaging-apis/issues"
},
"bundleDependencies": false,
"dependencies": {
"axios": "^0.19.0",
"axios-error": "^0.8.1",
"debug": "^4.1.1",
"image-type": "^4.1.0",
"invariant": "^2.2.4",
"lodash.omit": "^4.5.0",
"url-join": "^4.0.1"
},
"deprecated": false,
"description": "Messaging API client for LINE",
"devDependencies": {
"axios-mock-adapter": "^1.17.0"
},
"engines": {
"node": ">=8"
},
"gitHead": "874202b421e7b302d84d9b039fbfc30b39a77ee3",
"homepage": "https://github.com/Yoctol/messaging-apis#readme",
"keywords": [
"bot",
"chatbot",
"line",
"messaging-apis"
],
"license": "MIT",
"main": "lib/index.js",
"name": "messaging-api-line",
"repository": {
"type": "git",
"url": "git+https://github.com/Yoctol/messaging-apis.git"
},
"version": "0.8.3"
}
/* @flow */
import invariant from 'invariant';
import omit from 'lodash.omit';
import {
type AudioMessage,
type ButtonsTemplate,
type CarouselTemplate,
type ColumnObject,
type ConfirmTemplate,
type FlexContainer,
type FlexMessage,
type ImageCarouselColumnObject,
type ImageCarouselTemplate,
type ImageMapAction,
type ImageMapMessage,
type ImageMapVideo,
type ImageMessage,
type Location,
type LocationMessage,
type MessageOptions,
type QuickReply,
type StickerMessage,
type Template,
type TemplateAction,
type TemplateMessage,
type TextMessage,
type VideoMessage,
} from './LineTypes';
function createText(text: string, options: MessageOptions = {}): TextMessage {
return {
type: 'text',
text,
...omit(options, 'accessToken'),
};
}
function createImage(
contentUrlOrImage: string | Object,
previewUrlOrOptions?: string | MessageOptions
): ImageMessage {
if (previewUrlOrOptions) {
if (
typeof contentUrlOrImage === 'object' &&
typeof previewUrlOrOptions === 'object'
) {
const image = contentUrlOrImage;
const options = previewUrlOrOptions;
return {
type: 'image',
originalContentUrl: image.originalContentUrl,
previewImageUrl: image.previewImageUrl || image.originalContentUrl,
...omit(options, 'accessToken'),
};
}
if (
typeof contentUrlOrImage === 'string' &&
typeof previewUrlOrOptions === 'string'
) {
return {
type: 'image',
originalContentUrl: contentUrlOrImage,
previewImageUrl: previewUrlOrOptions,
};
}
} else {
if (typeof contentUrlOrImage === 'object') {
const image = contentUrlOrImage;
return {
type: 'image',
originalContentUrl: image.originalContentUrl,
previewImageUrl: image.previewImageUrl || image.originalContentUrl,
};
}
if (typeof contentUrlOrImage === 'string') {
return {
type: 'image',
originalContentUrl: contentUrlOrImage,
previewImageUrl: contentUrlOrImage,
};
}
}
invariant(false, 'Line#createImage: Wrong type of arguments.');
}
function createVideo(
contentUrlOrVideo: string | Object,
previewImageUrlOrOptions?: string | MessageOptions
): VideoMessage {
if (
typeof contentUrlOrVideo === 'string' &&
typeof previewImageUrlOrOptions === 'string'
) {
return {
type: 'video',
originalContentUrl: contentUrlOrVideo,
previewImageUrl: previewImageUrlOrOptions,
};
}
if (
typeof contentUrlOrVideo === 'object' &&
(!previewImageUrlOrOptions || typeof previewImageUrlOrOptions === 'object')
) {
const video = contentUrlOrVideo;
const options = previewImageUrlOrOptions || {};
return {
type: 'video',
originalContentUrl: video.originalContentUrl,
previewImageUrl: video.previewImageUrl,
...omit(options, 'accessToken'),
};
}
invariant(false, 'Line#createVideo: Wrong type of arguments.');
}
function createAudio(
contentUrlOrAudio: string | Object,
durationOrOptions: number | MessageOptions
): AudioMessage {
if (
typeof contentUrlOrAudio === 'string' &&
typeof durationOrOptions === 'number'
) {
return {
type: 'audio',
originalContentUrl: contentUrlOrAudio,
duration: durationOrOptions,
};
}
if (
typeof contentUrlOrAudio === 'object' &&
(!durationOrOptions || typeof durationOrOptions === 'object')
) {
const audio = contentUrlOrAudio;
const options = durationOrOptions || {};
return {
type: 'audio',
originalContentUrl: audio.originalContentUrl,
duration: audio.duration,
...omit(options, 'accessToken'),
};
}
invariant(false, 'Line#createAudio: Wrong type of arguments.');
}
function createLocation(
{ title, address, latitude, longitude }: Location,
options?: MessageOptions = {}
): LocationMessage {
return {
type: 'location',
title,
address,
latitude,
longitude,
...omit(options, 'accessToken'),
};
}
function createSticker(
packageIdOrSticker: string | Object,
stickerIdOrOptions: string | MessageOptions
): StickerMessage {
if (
typeof packageIdOrSticker === 'string' &&
typeof stickerIdOrOptions === 'string'
) {
return {
type: 'sticker',
packageId: packageIdOrSticker,
stickerId: stickerIdOrOptions,
};
}
if (
typeof packageIdOrSticker === 'object' &&
(!stickerIdOrOptions || typeof stickerIdOrOptions === 'object')
) {
const sticker = packageIdOrSticker;
const options = stickerIdOrOptions || {};
return {
type: 'sticker',
packageId: sticker.packageId,
stickerId: sticker.stickerId,
...omit(options, 'accessToken'),
};
}
invariant(false, 'Line#createSticker: Wrong type of arguments.');
}
function createImagemap(
altText: string,
{
baseUrl,
baseSize,
baseHeight,
baseWidth,
video,
actions,
}: {
baseUrl: string,
baseSize: {
height: number,
width: number,
},
baseHeight: number,
baseWidth: number,
video?: ImageMapVideo,
actions: Array<ImageMapAction>,
},
options?: MessageOptions = {}
): ImageMapMessage {
return {
type: 'imagemap',
baseUrl,
altText,
baseSize: baseSize || {
height: baseHeight,
width: baseWidth,
},
video,
actions,
...omit(options, 'accessToken'),
};
}
function createTemplate(
altText: string,
template: Template,
options?: MessageOptions = {}
): TemplateMessage<any> {
return {
type: 'template',
altText,
template,
...omit(options, 'accessToken'),
};
}
function createButtonTemplate(
altText: string,
{
thumbnailImageUrl,
imageAspectRatio,
imageSize,
imageBackgroundColor,
title,
text,
defaultAction,
actions,
}: {
thumbnailImageUrl?: string,
imageAspectRatio?: 'rectangle' | 'square',
imageSize?: 'cover' | 'contain',
imageBackgroundColor?: string,
title?: string,
text: string,
defaultAction?: TemplateAction,
actions: Array<TemplateAction>,
},
options: MessageOptions = {}
): TemplateMessage<ButtonsTemplate> {
return createTemplate(
altText,
{
type: 'buttons',
thumbnailImageUrl,
imageAspectRatio,
imageSize,
imageBackgroundColor,
title,
text,
defaultAction,
actions,
},
omit(options, 'accessToken')
);
}
function createConfirmTemplate(
altText: string,
{
text,
actions,
}: {
text: string,
actions: Array<TemplateAction>,
},
options?: MessageOptions = {}
): TemplateMessage<ConfirmTemplate> {
return createTemplate(
altText,
{
type: 'confirm',
text,
actions,
},
omit(options, 'accessToken')
);
}
function createCarouselTemplate(
altText: string,
columns: Array<ColumnObject>,
{
imageAspectRatio,
imageSize,
quickReply,
}: {
imageAspectRatio?: 'rectangle' | 'square',
imageSize?: 'cover' | 'contain',
quickReply?: QuickReply,
} = {}
): TemplateMessage<CarouselTemplate> {
return createTemplate(
altText,
{
type: 'carousel',
columns,
imageAspectRatio,
imageSize,
},
{ quickReply }
);
}
function createImageCarouselTemplate(
altText: string,
columns: Array<ImageCarouselColumnObject>,
options?: MessageOptions = {}
): TemplateMessage<ImageCarouselTemplate> {
return createTemplate(
altText,
{
type: 'image_carousel',
columns,
},
omit(options, 'accessToken')
);
}
function createFlex(
altText: string,
contents: FlexContainer,
options?: MessageOptions = {}
): FlexMessage {
return {
type: 'flex',
altText,
contents,
...omit(options, 'accessToken'),
};
}
const Line = {
createText,
createImage,
createVideo,
createAudio,
createLocation,
createSticker,
createImagemap,
createTemplate,
createButtonsTemplate: createButtonTemplate,
createButtonTemplate,
createConfirmTemplate,
createCarouselTemplate,
createImageCarouselTemplate,
createFlex,
};
export default Line;
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.