Prune node_modules

This commit is contained in:
CrazyMax 2020-04-09 02:24:12 +02:00
parent 29273a44aa
commit 74111003d6
No known key found for this signature in database
GPG Key ID: 3248E46B6BB8C7F7
731 changed files with 0 additions and 80412 deletions

1
node_modules/.bin/seek-bunzip generated vendored
View File

@ -1 +0,0 @@
../seek-bzip/bin/seek-bunzip

1
node_modules/.bin/seek-table generated vendored
View File

@ -1 +0,0 @@
../seek-bzip/bin/seek-bzip-table

1
node_modules/.bin/semver generated vendored
View File

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

1
node_modules/.bin/uuid generated vendored
View File

@ -1 +0,0 @@
../uuid/bin/uuid

146
node_modules/@actions/core/README.md generated vendored
View File

@ -1,146 +0,0 @@
# `@actions/core`
> Core functions for setting results, logging, registering secrets and exporting variables across actions
## Usage
### Import the package
```js
// javascript
const core = require('@actions/core');
// typescript
import * as core from '@actions/core';
```
#### Inputs/Outputs
Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
```js
const myInput = core.getInput('inputName', { required: true });
core.setOutput('outputKey', 'outputVal');
```
#### Exporting variables
Since each step runs in a separate process, you can use `exportVariable` to add it to this step and future steps environment blocks.
```js
core.exportVariable('envVar', 'Val');
```
#### Setting a secret
Setting a secret registers the secret with the runner to ensure it is masked in logs.
```js
core.setSecret('myPassword');
```
#### PATH Manipulation
To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use `addPath`. The runner will prepend the path given to the jobs PATH.
```js
core.addPath('/path/to/mytool');
```
#### Exit codes
You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.
```js
const core = require('@actions/core');
try {
// Do stuff
}
catch (err) {
// setFailed logs the message and sets a failing exit code
core.setFailed(`Action failed with error ${err}`);
}
Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned.
```
#### Logging
Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs).
```js
const core = require('@actions/core');
const myInput = core.getInput('input');
try {
core.debug('Inside try block');
if (!myInput) {
core.warning('myInput was not set');
}
if (core.isDebug()) {
// curl -v https://github.com
} else {
// curl https://github.com
}
// Do stuff
}
catch (err) {
core.error(`Error ${err}, action may still succeed though`);
}
```
This library can also wrap chunks of output in foldable groups.
```js
const core = require('@actions/core')
// Manually wrap output
core.startGroup('Do some function')
doSomeFunction()
core.endGroup()
// Wrap an asynchronous function call
const result = await core.group('Do something async', async () => {
const response = await doSomeHTTPRequest()
return response
})
```
#### Action state
You can use this library to save state and get state for sharing information between a given wrapper action:
**action.yml**
```yaml
name: 'Wrapper action sample'
inputs:
name:
default: 'GitHub'
runs:
using: 'node12'
main: 'main.js'
post: 'cleanup.js'
```
In action's `main.js`:
```js
const core = require('@actions/core');
core.saveState("pidToKill", 12345);
```
In action's `cleanup.js`:
```js
const core = require('@actions/core');
var pid = core.getState("pidToKill");
process.kill(pid);
```

View File

@ -1,16 +0,0 @@
interface CommandProperties {
[key: string]: string;
}
/**
* Commands
*
* Command Format:
* ::name key=value,key=value::message
*
* Examples:
* ::warning::This is the message
* ::set-env name=MY_VAR::some value
*/
export declare function issueCommand(command: string, properties: CommandProperties, message: string): void;
export declare function issue(name: string, message?: string): void;
export {};

View File

@ -1,78 +0,0 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = __importStar(require("os"));
/**
* Commands
*
* Command Format:
* ::name key=value,key=value::message
*
* Examples:
* ::warning::This is the message
* ::set-env name=MY_VAR::some value
*/
function issueCommand(command, properties, message) {
const cmd = new Command(command, properties, message);
process.stdout.write(cmd.toString() + os.EOL);
}
exports.issueCommand = issueCommand;
function issue(name, message = '') {
issueCommand(name, {}, message);
}
exports.issue = issue;
const CMD_STRING = '::';
class Command {
constructor(command, properties, message) {
if (!command) {
command = 'missing.command';
}
this.command = command;
this.properties = properties;
this.message = message;
}
toString() {
let cmdStr = CMD_STRING + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' ';
let first = true;
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
if (first) {
first = false;
}
else {
cmdStr += ',';
}
cmdStr += `${key}=${escapeProperty(val)}`;
}
}
}
}
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
return cmdStr;
}
}
function escapeData(s) {
return (s || '')
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A');
}
function escapeProperty(s) {
return (s || '')
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/:/g, '%3A')
.replace(/,/g, '%2C');
}
//# sourceMappingURL=command.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AAQxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAe;IAEf,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAS;IAC/B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}

View File

@ -1,116 +0,0 @@
/**
* Interface for getInput options
*/
export interface InputOptions {
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
required?: boolean;
}
/**
* The code to exit an action
*/
export declare enum ExitCode {
/**
* A code indicating that the action was successful
*/
Success = 0,
/**
* A code indicating that the action was a failure
*/
Failure = 1
}
/**
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable
*/
export declare function exportVariable(name: string, val: string): void;
/**
* Registers a secret which will get masked from logs
* @param secret value of the secret
*/
export declare function setSecret(secret: string): void;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
export declare function addPath(inputPath: string): void;
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
export declare function getInput(name: string, options?: InputOptions): string;
/**
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store
*/
export declare function setOutput(name: string, value: string): void;
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
export declare function setFailed(message: string): void;
/**
* Gets whether Actions Step Debug is on or not
*/
export declare function isDebug(): boolean;
/**
* Writes debug message to user log
* @param message debug message
*/
export declare function debug(message: string): void;
/**
* Adds an error issue
* @param message error issue message
*/
export declare function error(message: string): void;
/**
* Adds an warning issue
* @param message warning issue message
*/
export declare function warning(message: string): void;
/**
* Writes info to log with console.log.
* @param message info message
*/
export declare function info(message: string): void;
/**
* Begin an output group.
*
* Output until the next `groupEnd` will be foldable in this group
*
* @param name The name of the output group
*/
export declare function startGroup(name: string): void;
/**
* End an output group.
*/
export declare function endGroup(): void;
/**
* Wrap an asynchronous function call in a group.
*
* Returns the same type as the function itself.
*
* @param name The name of the group
* @param fn The function to wrap in the group
*/
export declare function group<T>(name: string, fn: () => Promise<T>): Promise<T>;
/**
* Saves state for current action, the state can only be retrieved by this action's post job execution.
*
* @param name name of the state to store
* @param value value to store
*/
export declare function saveState(name: string, value: string): void;
/**
* Gets the value of an state set by this action's main execution.
*
* @param name name of the state to get
* @returns string
*/
export declare function getState(name: string): string;

View File

@ -1,209 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("./command");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
/**
* The code to exit an action
*/
var ExitCode;
(function (ExitCode) {
/**
* A code indicating that the action was successful
*/
ExitCode[ExitCode["Success"] = 0] = "Success";
/**
* A code indicating that the action was a failure
*/
ExitCode[ExitCode["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
//-----------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------
/**
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable
*/
function exportVariable(name, val) {
process.env[name] = val;
command_1.issueCommand('set-env', { name }, val);
}
exports.exportVariable = exportVariable;
/**
* Registers a secret which will get masked from logs
* @param secret value of the secret
*/
function setSecret(secret) {
command_1.issueCommand('add-mask', {}, secret);
}
exports.setSecret = setSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
function addPath(inputPath) {
command_1.issueCommand('add-path', {}, inputPath);
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
exports.addPath = addPath;
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
function getInput(name, options) {
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
exports.getInput = getInput;
/**
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store
*/
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
function setFailed(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Gets whether Actions Step Debug is on or not
*/
function isDebug() {
return process.env['RUNNER_DEBUG'] === '1';
}
exports.isDebug = isDebug;
/**
* Writes debug message to user log
* @param message debug message
*/
function debug(message) {
command_1.issueCommand('debug', {}, message);
}
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message
*/
function error(message) {
command_1.issue('error', message);
}
exports.error = error;
/**
* Adds an warning issue
* @param message warning issue message
*/
function warning(message) {
command_1.issue('warning', message);
}
exports.warning = warning;
/**
* Writes info to log with console.log.
* @param message info message
*/
function info(message) {
process.stdout.write(message + os.EOL);
}
exports.info = info;
/**
* Begin an output group.
*
* Output until the next `groupEnd` will be foldable in this group
*
* @param name The name of the output group
*/
function startGroup(name) {
command_1.issue('group', name);
}
exports.startGroup = startGroup;
/**
* End an output group.
*/
function endGroup() {
command_1.issue('endgroup');
}
exports.endGroup = endGroup;
/**
* Wrap an asynchronous function call in a group.
*
* Returns the same type as the function itself.
*
* @param name The name of the group
* @param fn The function to wrap in the group
*/
function group(name, fn) {
return __awaiter(this, void 0, void 0, function* () {
startGroup(name);
let result;
try {
result = yield fn();
}
finally {
endGroup();
}
return result;
});
}
exports.group = group;
//-----------------------------------------------------------------------
// Wrapper action state
//-----------------------------------------------------------------------
/**
* Saves state for current action, the state can only be retrieved by this action's post job execution.
*
* @param name name of the state to store
* @param value value to store
*/
function saveState(name, value) {
command_1.issueCommand('save-state', { name }, value);
}
exports.saveState = saveState;
/**
* Gets the value of an state set by this action's main execution.
*
* @param name name of the state to get
* @returns string
*/
function getState(name) {
return process.env[`STATE_${name}`] || '';
}
exports.getState = getState;
//# sourceMappingURL=core.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,uCAA6C;AAE7C,uCAAwB;AACxB,2CAA4B;AAU5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAW;IACtD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAA;IACvB,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,GAAG,CAAC,CAAA;AACtC,CAAC;AAHD,wCAGC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAc;IACtC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,SAAS,CAAC,CAAA;IACvC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;AAC7E,CAAC;AAHD,0BAGC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,IAAY,EAAE,OAAsB;IAC3D,MAAM,GAAG,GACP,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,CAAA;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;KAC5D;IAED,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AARD,4BAQC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED,yEAAyE;AACzE,UAAU;AACV,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAe;IACvC,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAA;IACnC,KAAK,CAAC,OAAO,CAAC,CAAA;AAChB,CAAC;AAHD,8BAGC;AAED,yEAAyE;AACzE,mBAAmB;AACnB,yEAAyE;AAEzE;;GAEG;AACH,SAAgB,OAAO;IACrB,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,GAAG,CAAA;AAC5C,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,sBAAY,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,eAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACzB,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,OAAe;IACrC,eAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;AAC3B,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"}

View File

@ -1,63 +0,0 @@
{
"_from": "@actions/core@1.2.3",
"_id": "@actions/core@1.2.3",
"_inBundle": false,
"_integrity": "sha512-Wp4xnyokakM45Uuj4WLUxdsa8fJjKVl1fDTsPbTEcTcuu0Nb26IPQbOtjmnfaCPGcaoPOOqId8H9NapZ8gii4w==",
"_location": "/@actions/core",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@actions/core@1.2.3",
"name": "@actions/core",
"escapedName": "@actions%2fcore",
"scope": "@actions",
"rawSpec": "1.2.3",
"saveSpec": null,
"fetchSpec": "1.2.3"
},
"_requiredBy": [
"/",
"/@actions/tool-cache"
],
"_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.3.tgz",
"_spec": "1.2.3",
"bugs": {
"url": "https://github.com/actions/toolkit/issues"
},
"description": "Actions core lib",
"devDependencies": {
"@types/node": "^12.0.2"
},
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib"
],
"homepage": "https://github.com/actions/toolkit/tree/master/packages/core",
"keywords": [
"github",
"actions",
"core"
],
"license": "MIT",
"main": "lib/core.js",
"name": "@actions/core",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/core"
},
"scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc"
},
"types": "lib/core.d.ts",
"version": "1.2.3"
}

57
node_modules/@actions/exec/README.md generated vendored
View File

@ -1,57 +0,0 @@
# `@actions/exec`
## Usage
#### Basic
You can use this package to execute tools in a cross platform way:
```js
const exec = require('@actions/exec');
await exec.exec('node index.js');
```
#### Args
You can also pass in arg arrays:
```js
const exec = require('@actions/exec');
await exec.exec('node', ['index.js', 'foo=bar']);
```
#### Output/options
Capture output or specify [other options](https://github.com/actions/toolkit/blob/d9347d4ab99fd507c0b9104b2cf79fb44fcc827d/packages/exec/src/interfaces.ts#L5):
```js
const exec = require('@actions/exec');
let myOutput = '';
let myError = '';
const options = {};
options.listeners = {
stdout: (data: Buffer) => {
myOutput += data.toString();
},
stderr: (data: Buffer) => {
myError += data.toString();
}
};
options.cwd = './lib';
await exec.exec('node', ['index.js', 'foo=bar'], options);
```
#### Exec tools not in the PATH
You can specify the full path for tools not in the PATH:
```js
const exec = require('@actions/exec');
await exec.exec('"/path/to/my-tool"', ['arg1']);
```

View File

@ -1,12 +0,0 @@
import * as im from './interfaces';
/**
* Exec a command.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
* @param args optional arguments for tool. Escaping is handled by the lib.
* @param options optional exec options. See ExecOptions
* @returns Promise<number> exit code
*/
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>;

View File

@ -1,37 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const tr = require("./toolrunner");
/**
* Exec a command.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
* @param args optional arguments for tool. Escaping is handled by the lib.
* @param options optional exec options. See ExecOptions
* @returns Promise<number> exit code
*/
function exec(commandLine, args, options) {
return __awaiter(this, void 0, void 0, function* () {
const commandArgs = tr.argStringToArray(commandLine);
if (commandArgs.length === 0) {
throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
}
// Path to tool to execute should be first arg
const toolPath = commandArgs[0];
args = commandArgs.slice(1).concat(args || []);
const runner = new tr.ToolRunner(toolPath, args, options);
return runner.exec();
});
}
exports.exec = exec;
//# sourceMappingURL=exec.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,mCAAkC;AAElC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAwB;;QAExB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"}

View File

@ -1,35 +0,0 @@
/// <reference types="node" />
import * as stream from 'stream';
/**
* Interface for exec options
*/
export interface ExecOptions {
/** optional working directory. defaults to current */
cwd?: string;
/** optional envvar dictionary. defaults to current process's env */
env?: {
[key: string]: string;
};
/** optional. defaults to false */
silent?: boolean;
/** optional out stream to use. Defaults to process.stdout */
outStream?: stream.Writable;
/** optional err stream to use. Defaults to process.stderr */
errStream?: stream.Writable;
/** optional. whether to skip quoting/escaping arguments if needed. defaults to false. */
windowsVerbatimArguments?: boolean;
/** optional. whether to fail if output to stderr. defaults to false */
failOnStdErr?: boolean;
/** optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */
ignoreReturnCode?: boolean;
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
delay?: number;
/** optional. Listeners for output. Callback functions that will be called on these events */
listeners?: {
stdout?: (data: Buffer) => void;
stderr?: (data: Buffer) => void;
stdline?: (data: string) => void;
errline?: (data: string) => void;
debug?: (data: string) => void;
};
}

View File

@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=interfaces.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":""}

View File

@ -1,37 +0,0 @@
/// <reference types="node" />
import * as events from 'events';
import * as im from './interfaces';
export declare class ToolRunner extends events.EventEmitter {
constructor(toolPath: string, args?: string[], options?: im.ExecOptions);
private toolPath;
private args;
private options;
private _debug;
private _getCommandString;
private _processLineBuffer;
private _getSpawnFileName;
private _getSpawnArgs;
private _endsWith;
private _isCmdFile;
private _windowsQuoteCmdArg;
private _uvQuoteCmdArg;
private _cloneExecOptions;
private _getSpawnOptions;
/**
* Exec a tool.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param tool path to tool to exec
* @param options optional exec options. See ExecOptions
* @returns number
*/
exec(): Promise<number>;
}
/**
* Convert an arg string to an array of args. Handles escaping
*
* @param argString string of arguments
* @returns string[] array of arguments
*/
export declare function argStringToArray(argString: string): string[];

View File

@ -1,587 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const events = require("events");
const child = require("child_process");
const path = require("path");
const io = require("@actions/io");
const ioUtil = require("@actions/io/lib/io-util");
/* eslint-disable @typescript-eslint/unbound-method */
const IS_WINDOWS = process.platform === 'win32';
/*
* Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
*/
class ToolRunner extends events.EventEmitter {
constructor(toolPath, args, options) {
super();
if (!toolPath) {
throw new Error("Parameter 'toolPath' cannot be null or empty.");
}
this.toolPath = toolPath;
this.args = args || [];
this.options = options || {};
}
_debug(message) {
if (this.options.listeners && this.options.listeners.debug) {
this.options.listeners.debug(message);
}
}
_getCommandString(options, noPrefix) {
const toolPath = this._getSpawnFileName();
const args = this._getSpawnArgs(options);
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
if (IS_WINDOWS) {
// Windows + cmd file
if (this._isCmdFile()) {
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows + verbatim
else if (options.windowsVerbatimArguments) {
cmd += `"${toolPath}"`;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows (regular)
else {
cmd += this._windowsQuoteCmdArg(toolPath);
for (const a of args) {
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
}
}
}
else {
// OSX/Linux - this can likely be improved with some form of quoting.
// creating processes on Unix is fundamentally different than Windows.
// on Unix, execvp() takes an arg array.
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
return cmd;
}
_processLineBuffer(data, strBuffer, onLine) {
try {
let s = strBuffer + data.toString();
let n = s.indexOf(os.EOL);
while (n > -1) {
const line = s.substring(0, n);
onLine(line);
// the rest of the string ...
s = s.substring(n + os.EOL.length);
n = s.indexOf(os.EOL);
}
strBuffer = s;
}
catch (err) {
// streaming lines to console is best effort. Don't fail a build.
this._debug(`error processing line. Failed with error ${err}`);
}
}
_getSpawnFileName() {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
return process.env['COMSPEC'] || 'cmd.exe';
}
}
return this.toolPath;
}
_getSpawnArgs(options) {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
for (const a of this.args) {
argline += ' ';
argline += options.windowsVerbatimArguments
? a
: this._windowsQuoteCmdArg(a);
}
argline += '"';
return [argline];
}
}
return this.args;
}
_endsWith(str, end) {
return str.endsWith(end);
}
_isCmdFile() {
const upperToolPath = this.toolPath.toUpperCase();
return (this._endsWith(upperToolPath, '.CMD') ||
this._endsWith(upperToolPath, '.BAT'));
}
_windowsQuoteCmdArg(arg) {
// for .exe, apply the normal quoting rules that libuv applies
if (!this._isCmdFile()) {
return this._uvQuoteCmdArg(arg);
}
// otherwise apply quoting rules specific to the cmd.exe command line parser.
// the libuv rules are generic and are not designed specifically for cmd.exe
// command line parser.
//
// for a detailed description of the cmd.exe command line parser, refer to
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
// need quotes for empty arg
if (!arg) {
return '""';
}
// determine whether the arg needs to be quoted
const cmdSpecialChars = [
' ',
'\t',
'&',
'(',
')',
'[',
']',
'{',
'}',
'^',
'=',
';',
'!',
"'",
'+',
',',
'`',
'~',
'|',
'<',
'>',
'"'
];
let needsQuotes = false;
for (const char of arg) {
if (cmdSpecialChars.some(x => x === char)) {
needsQuotes = true;
break;
}
}
// short-circuit if quotes not needed
if (!needsQuotes) {
return arg;
}
// the following quoting rules are very similar to the rules that by libuv applies.
//
// 1) wrap the string in quotes
//
// 2) double-up quotes - i.e. " => ""
//
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
// doesn't work well with a cmd.exe command line.
//
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
// for example, the command line:
// foo.exe "myarg:""my val"""
// is parsed by a .NET console app into an arg array:
// [ "myarg:\"my val\"" ]
// which is the same end result when applying libuv quoting rules. although the actual
// command line from libuv quoting rules would look like:
// foo.exe "myarg:\"my val\""
//
// 3) double-up slashes that precede a quote,
// e.g. hello \world => "hello \world"
// hello\"world => "hello\\""world"
// hello\\"world => "hello\\\\""world"
// hello world\ => "hello world\\"
//
// technically this is not required for a cmd.exe command line, or the batch argument parser.
// the reasons for including this as a .cmd quoting rule are:
//
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
//
// b) it's what we've been doing previously (by deferring to node default behavior) and we
// haven't heard any complaints about that aspect.
//
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
// by using %%.
//
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
//
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
// to an external program.
//
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
// % can be escaped within a .cmd file.
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\'; // double the slash
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '"'; // double the quote
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_uvQuoteCmdArg(arg) {
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
// is used.
//
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
// pasting copyright notice from Node within this function:
//
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
//
// 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.
if (!arg) {
// Need double quotation for empty argument
return '""';
}
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
// No quotation needed
return arg;
}
if (!arg.includes('"') && !arg.includes('\\')) {
// No embedded double quotes or backslashes, so I can just wrap
// quote marks around the whole thing.
return `"${arg}"`;
}
// Expected input/output:
// input : hello"world
// output: "hello\"world"
// input : hello""world
// output: "hello\"\"world"
// input : hello\world
// output: hello\world
// input : hello\\world
// output: hello\\world
// input : hello\"world
// output: "hello\\\"world"
// input : hello\\"world
// output: "hello\\\\\"world"
// input : hello world\
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
// but it appears the comment is wrong, it should be "hello world\\"
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\';
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '\\';
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_cloneExecOptions(options) {
options = options || {};
const result = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: options.silent || false,
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
failOnStdErr: options.failOnStdErr || false,
ignoreReturnCode: options.ignoreReturnCode || false,
delay: options.delay || 10000
};
result.outStream = options.outStream || process.stdout;
result.errStream = options.errStream || process.stderr;
return result;
}
_getSpawnOptions(options, toolPath) {
options = options || {};
const result = {};
result.cwd = options.cwd;
result.env = options.env;
result['windowsVerbatimArguments'] =
options.windowsVerbatimArguments || this._isCmdFile();
if (options.windowsVerbatimArguments) {
result.argv0 = `"${toolPath}"`;
}
return result;
}
/**
* Exec a tool.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param tool path to tool to exec
* @param options optional exec options. See ExecOptions
* @returns number
*/
exec() {
return __awaiter(this, void 0, void 0, function* () {
// root the tool path if it is unrooted and contains relative pathing
if (!ioUtil.isRooted(this.toolPath) &&
(this.toolPath.includes('/') ||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
}
// if the tool is only a file name, then resolve it from the PATH
// otherwise verify it exists (add extension on Windows if necessary)
this.toolPath = yield io.which(this.toolPath, true);
return new Promise((resolve, reject) => {
this._debug(`exec tool: ${this.toolPath}`);
this._debug('arguments:');
for (const arg of this.args) {
this._debug(` ${arg}`);
}
const optionsNonNull = this._cloneExecOptions(this.options);
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
}
const state = new ExecState(optionsNonNull, this.toolPath);
state.on('debug', (message) => {
this._debug(message);
});
const fileName = this._getSpawnFileName();
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
const stdbuffer = '';
if (cp.stdout) {
cp.stdout.on('data', (data) => {
if (this.options.listeners && this.options.listeners.stdout) {
this.options.listeners.stdout(data);
}
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(data);
}
this._processLineBuffer(data, stdbuffer, (line) => {
if (this.options.listeners && this.options.listeners.stdline) {
this.options.listeners.stdline(line);
}
});
});
}
const errbuffer = '';
if (cp.stderr) {
cp.stderr.on('data', (data) => {
state.processStderr = true;
if (this.options.listeners && this.options.listeners.stderr) {
this.options.listeners.stderr(data);
}
if (!optionsNonNull.silent &&
optionsNonNull.errStream &&
optionsNonNull.outStream) {
const s = optionsNonNull.failOnStdErr
? optionsNonNull.errStream
: optionsNonNull.outStream;
s.write(data);
}
this._processLineBuffer(data, errbuffer, (line) => {
if (this.options.listeners && this.options.listeners.errline) {
this.options.listeners.errline(line);
}
});
});
}
cp.on('error', (err) => {
state.processError = err.message;
state.processExited = true;
state.processClosed = true;
state.CheckComplete();
});
cp.on('exit', (code) => {
state.processExitCode = code;
state.processExited = true;
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
state.CheckComplete();
});
cp.on('close', (code) => {
state.processExitCode = code;
state.processExited = true;
state.processClosed = true;
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
state.CheckComplete();
});
state.on('done', (error, exitCode) => {
if (stdbuffer.length > 0) {
this.emit('stdline', stdbuffer);
}
if (errbuffer.length > 0) {
this.emit('errline', errbuffer);
}
cp.removeAllListeners();
if (error) {
reject(error);
}
else {
resolve(exitCode);
}
});
});
});
}
}
exports.ToolRunner = ToolRunner;
/**
* Convert an arg string to an array of args. Handles escaping
*
* @param argString string of arguments
* @returns string[] array of arguments
*/
function argStringToArray(argString) {
const args = [];
let inQuotes = false;
let escaped = false;
let arg = '';
function append(c) {
// we only escape double quotes.
if (escaped && c !== '"') {
arg += '\\';
}
arg += c;
escaped = false;
}
for (let i = 0; i < argString.length; i++) {
const c = argString.charAt(i);
if (c === '"') {
if (!escaped) {
inQuotes = !inQuotes;
}
else {
append(c);
}
continue;
}
if (c === '\\' && escaped) {
append(c);
continue;
}
if (c === '\\' && inQuotes) {
escaped = true;
continue;
}
if (c === ' ' && !inQuotes) {
if (arg.length > 0) {
args.push(arg);
arg = '';
}
continue;
}
append(c);
}
if (arg.length > 0) {
args.push(arg.trim());
}
return args;
}
exports.argStringToArray = argStringToArray;
class ExecState extends events.EventEmitter {
constructor(options, toolPath) {
super();
this.processClosed = false; // tracks whether the process has exited and stdio is closed
this.processError = '';
this.processExitCode = 0;
this.processExited = false; // tracks whether the process has exited
this.processStderr = false; // tracks whether stderr was written to
this.delay = 10000; // 10 seconds
this.done = false;
this.timeout = null;
if (!toolPath) {
throw new Error('toolPath must not be empty');
}
this.options = options;
this.toolPath = toolPath;
if (options.delay) {
this.delay = options.delay;
}
}
CheckComplete() {
if (this.done) {
return;
}
if (this.processClosed) {
this._setResult();
}
else if (this.processExited) {
this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this);
}
}
_debug(message) {
this.emit('debug', message);
}
_setResult() {
// determine whether there is an error
let error;
if (this.processExited) {
if (this.processError) {
error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
}
else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
}
else if (this.processStderr && this.options.failOnStdErr) {
error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
}
}
// clear the timeout
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.done = true;
this.emit('done', error, this.processExitCode);
}
static HandleTimeout(state) {
if (state.done) {
return;
}
if (!state.processClosed && state.processExited) {
const message = `The STDIO streams did not close within ${state.delay /
1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
state._debug(message);
}
state._setResult();
}
}
//# sourceMappingURL=toolrunner.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,63 +0,0 @@
{
"_from": "@actions/exec@1.0.3",
"_id": "@actions/exec@1.0.3",
"_inBundle": false,
"_integrity": "sha512-TogJGnueOmM7ntCi0ASTUj4LapRRtDfj57Ja4IhPmg2fls28uVOPbAn8N+JifaOumN2UG3oEO/Ixek2A4NcYSA==",
"_location": "/@actions/exec",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@actions/exec@1.0.3",
"name": "@actions/exec",
"escapedName": "@actions%2fexec",
"scope": "@actions",
"rawSpec": "1.0.3",
"saveSpec": null,
"fetchSpec": "1.0.3"
},
"_requiredBy": [
"/",
"/@actions/tool-cache"
],
"_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.3.tgz",
"_spec": "1.0.3",
"bugs": {
"url": "https://github.com/actions/toolkit/issues"
},
"dependencies": {
"@actions/io": "^1.0.1"
},
"description": "Actions exec lib",
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib"
],
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
"keywords": [
"github",
"actions",
"exec"
],
"license": "MIT",
"main": "lib/exec.js",
"name": "@actions/exec",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/exec"
},
"scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc"
},
"types": "lib/exec.d.ts",
"version": "1.0.3"
}

View File

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

View File

@ -1,79 +0,0 @@
<p align="center">
<img src="actions.png">
</p>
# Actions Http-Client
[![Http Status](https://github.com/actions/http-client/workflows/http-tests/badge.svg)](https://github.com/actions/http-client/actions)
A lightweight HTTP client optimized for use with actions, TypeScript with generics and async await.
## Features
- HTTP client with TypeScript generics and async/await/Promises
- Typings included so no need to acquire separately (great for intellisense and no versioning drift)
- [Proxy support](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/about-self-hosted-runners#using-a-proxy-server-with-self-hosted-runners) just works with actions and the runner
- Targets ES2019 (runner runs actions with node 12+). Only supported on node 12+.
- Basic, Bearer and PAT Support out of the box. Extensible handlers for others.
- Redirects supported
Features and releases [here](./RELEASES.md)
## Install
```
npm install @actions/http-client --save
```
## Samples
See the [HTTP](./__tests__) tests for detailed examples.
## Errors
### HTTP
The HTTP client does not throw unless truly exceptional.
* A request that successfully executes resulting in a 404, 500 etc... will return a response object with a status code and a body.
* Redirects (3xx) will be followed by default.
See [HTTP tests](./__tests__) for detailed examples.
## Debugging
To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible:
```
export NODE_DEBUG=http
```
## Node support
The http-client is built using the latest LTS version of Node 12. It may work on previous node LTS versions but it's tested and officially supported on Node12+.
## Support and Versioning
We follow semver and will hold compatibility between major versions and increment the minor version with new features and capabilities (while holding compat).
## Contributing
We welcome PRs. Please create an issue and if applicable, a design before proceeding with code.
once:
```bash
$ npm install
```
To build:
```bash
$ npm run build
```
To run all tests:
```bash
$ npm test
```

View File

@ -1,13 +0,0 @@
## Releases
## 1.0.6
Automatically sends Content-Type and Accept application/json headers for \<verb>Json() helper methods if not set in the client or parameters.
## 1.0.5
Adds \<verb>Json() helper methods for json over http scenarios.
## 1.0.4
Started to add \<verb>Json() helper methods. Do not use this release for that. Use >= 1.0.5 since there was an issue with types.
## 1.0.1 to 1.0.3
Adds proxy support.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

View File

@ -1,23 +0,0 @@
import ifm = require('./interfaces');
export declare class BasicCredentialHandler implements ifm.IRequestHandler {
username: string;
password: string;
constructor(username: string, password: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}
export declare class BearerCredentialHandler implements ifm.IRequestHandler {
token: string;
constructor(token: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}
export declare class PersonalAccessTokenCredentialHandler implements ifm.IRequestHandler {
token: string;
constructor(token: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}

View File

@ -1,55 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class BasicCredentialHandler {
constructor(username, password) {
this.username = username;
this.password = password;
}
prepareRequest(options) {
options.headers['Authorization'] = 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BasicCredentialHandler = BasicCredentialHandler;
class BearerCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] = 'Bearer ' + this.token;
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BearerCredentialHandler = BearerCredentialHandler;
class PersonalAccessTokenCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] = 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;

View File

@ -1,118 +0,0 @@
/// <reference types="node" />
import http = require("http");
import ifm = require('./interfaces');
export declare enum HttpCodes {
OK = 200,
MultipleChoices = 300,
MovedPermanently = 301,
ResourceMoved = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
SwitchProxy = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504
}
export declare enum Headers {
Accept = "accept",
ContentType = "content-type"
}
export declare enum MediaTypes {
ApplicationJson = "application/json"
}
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
export declare function getProxyUrl(serverUrl: string): string;
export declare class HttpClientResponse implements ifm.IHttpClientResponse {
constructor(message: http.IncomingMessage);
message: http.IncomingMessage;
readBody(): Promise<string>;
}
export declare function isHttps(requestUrl: string): boolean;
export declare class HttpClient {
userAgent: string | undefined;
handlers: ifm.IRequestHandler[];
requestOptions: ifm.IRequestOptions;
private _ignoreSslError;
private _socketTimeout;
private _allowRedirects;
private _allowRedirectDowngrade;
private _maxRedirects;
private _allowRetries;
private _maxRetries;
private _agent;
private _proxyAgent;
private _keepAlive;
private _disposed;
constructor(userAgent?: string, handlers?: ifm.IRequestHandler[], requestOptions?: ifm.IRequestOptions);
options(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
get(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
del(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
post(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
patch(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
put(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
head(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
getJson<T>(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
postJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
putJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
patchJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose(): void;
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream): Promise<ifm.IHttpClientResponse>;
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: ifm.IHttpClientResponse) => void): void;
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl: string): http.Agent;
private _prepareRequest;
private _mergeHeaders;
private _getExistingOrDefaultHeader;
private _getAgent;
private _performExponentialBackoff;
private static dateTimeDeserializer;
private _processResponse;
}

View File

@ -1,500 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = require("url");
const http = require("http");
const https = require("https");
const pm = require("./proxy");
let tunnel;
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
var Headers;
(function (Headers) {
Headers["Accept"] = "accept";
Headers["ContentType"] = "content-type";
})(Headers = exports.Headers || (exports.Headers = {}));
var MediaTypes;
(function (MediaTypes) {
MediaTypes["ApplicationJson"] = "application/json";
})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
function getProxyUrl(serverUrl) {
let proxyUrl = pm.getProxyUrl(url.parse(serverUrl));
return proxyUrl ? proxyUrl.href : '';
}
exports.getProxyUrl = getProxyUrl;
const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect];
const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout];
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
const ExponentialBackoffCeiling = 10;
const ExponentialBackoffTimeSlice = 5;
class HttpClientResponse {
constructor(message) {
this.message = message;
}
readBody() {
return new Promise(async (resolve, reject) => {
let output = Buffer.alloc(0);
this.message.on('data', (chunk) => {
output = Buffer.concat([output, chunk]);
});
this.message.on('end', () => {
resolve(output.toString());
});
});
}
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
let parsedUrl = url.parse(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, requestOptions) {
this._ignoreSslError = false;
this._allowRedirects = true;
this._allowRedirectDowngrade = false;
this._maxRedirects = 50;
this._allowRetries = false;
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
if (requestOptions.ignoreSslError != null) {
this._ignoreSslError = requestOptions.ignoreSslError;
}
this._socketTimeout = requestOptions.socketTimeout;
if (requestOptions.allowRedirects != null) {
this._allowRedirects = requestOptions.allowRedirects;
}
if (requestOptions.allowRedirectDowngrade != null) {
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
}
if (requestOptions.maxRedirects != null) {
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
}
if (requestOptions.keepAlive != null) {
this._keepAlive = requestOptions.keepAlive;
}
if (requestOptions.allowRetries != null) {
this._allowRetries = requestOptions.allowRetries;
}
if (requestOptions.maxRetries != null) {
this._maxRetries = requestOptions.maxRetries;
}
}
}
options(requestUrl, additionalHeaders) {
return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
}
get(requestUrl, additionalHeaders) {
return this.request('GET', requestUrl, null, additionalHeaders || {});
}
del(requestUrl, additionalHeaders) {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
}
post(requestUrl, data, additionalHeaders) {
return this.request('POST', requestUrl, data, additionalHeaders || {});
}
patch(requestUrl, data, additionalHeaders) {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
}
put(requestUrl, data, additionalHeaders) {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
}
head(requestUrl, additionalHeaders) {
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return this.request(verb, requestUrl, stream, additionalHeaders);
}
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
async getJson(requestUrl, additionalHeaders = {}) {
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
let res = await this.get(requestUrl, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async postJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.post(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async putJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.put(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async patchJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.patch(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
async request(verb, requestUrl, data, headers) {
if (this._disposed) {
throw new Error("Client has already been disposed.");
}
let parsedUrl = url.parse(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1;
let numTries = 0;
let response;
while (numTries < maxTries) {
response = await this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) {
authenticationHandler = this.handlers[i];
break;
}
}
if (authenticationHandler) {
return authenticationHandler.handleAuthentication(this, info, data);
}
else {
// We have received an unauthorized response but have no handlers to handle it.
// Let the response return to the caller.
return response;
}
}
let redirectsRemaining = this._maxRedirects;
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1
&& this._allowRedirects
&& redirectsRemaining > 0) {
const redirectUrl = response.message.headers["location"];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
let parsedRedirectUrl = url.parse(redirectUrl);
if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
}
// we need to finish reading the response before reassigning response
// which will leak the open socket.
await response.readBody();
// let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = await this.requestRaw(info, data);
redirectsRemaining--;
}
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
await response.readBody();
await this._performExponentialBackoff(numTries);
}
}
return response;
}
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose() {
if (this._agent) {
this._agent.destroy();
}
this._disposed = true;
}
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info, data) {
return new Promise((resolve, reject) => {
let callbackForResult = function (err, res) {
if (err) {
reject(err);
}
resolve(res);
};
this.requestRawWithCallback(info, data, callbackForResult);
});
}
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info, data, onResult) {
let socket;
if (typeof (data) === 'string') {
info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
}
let callbackCalled = false;
let handleResult = (err, res) => {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
};
let req = info.httpModule.request(info.options, (msg) => {
let res = new HttpClientResponse(msg);
handleResult(null, res);
});
req.on('socket', (sock) => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
if (socket) {
socket.end();
}
handleResult(new Error('Request timeout: ' + info.options.path), null);
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err, null);
});
if (data && typeof (data) === 'string') {
req.write(data, 'utf8');
}
if (data && typeof (data) !== 'string') {
data.on('close', function () {
req.end();
});
data.pipe(req);
}
else {
req.end();
}
}
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl) {
let parsedUrl = url.parse(serverUrl);
return this._getAgent(parsedUrl);
}
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
const usingSsl = info.parsedUrl.protocol === 'https:';
info.httpModule = usingSsl ? https : http;
const defaultPort = usingSsl ? 443 : 80;
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort;
info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method;
info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) {
info.options.headers["user-agent"] = this.userAgent;
}
info.options.agent = this._getAgent(info.parsedUrl);
// gives handlers an opportunity to participate
if (this.handlers) {
this.handlers.forEach((handler) => {
handler.prepareRequest(info.options);
});
}
return info;
}
_mergeHeaders(headers) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
let proxyUrl = pm.getProxyUrl(parsedUrl);
let useProxy = proxyUrl && proxyUrl.hostname;
if (this._keepAlive && useProxy) {
agent = this._proxyAgent;
}
if (this._keepAlive && !useProxy) {
agent = this._agent;
}
// if agent is already assigned use that agent.
if (!!agent) {
return agent;
}
const usingSsl = parsedUrl.protocol === 'https:';
let maxSockets = 100;
if (!!this.requestOptions) {
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
}
if (useProxy) {
// If using proxy, need tunnel
if (!tunnel) {
tunnel = require('tunnel');
}
const agentOptions = {
maxSockets: maxSockets,
keepAlive: this._keepAlive,
proxy: {
proxyAuth: proxyUrl.auth,
host: proxyUrl.hostname,
port: proxyUrl.port
},
};
let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
agent = tunnelAgent(agentOptions);
this._proxyAgent = agent;
}
// if reusing agent across request and tunneling agent isn't assigned create a new agent
if (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
// if not using private agent and tunnel agent isn't setup then use global agent
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false });
}
return agent;
}
_performExponentialBackoff(retryNumber) {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
}
static dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
async _processResponse(res, options) {
return new Promise(async (resolve, reject) => {
const statusCode = res.message.statusCode;
const response = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == HttpCodes.NotFound) {
resolve(response);
}
let obj;
let contents;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);
}
else {
obj = JSON.parse(contents);
}
response.result = obj;
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
}
else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
}
else {
msg = "Failed request: (" + statusCode + ")";
}
let err = new Error(msg);
// attach statusCode and body obj (if available) to the error object
err['statusCode'] = statusCode;
if (response.result) {
err['result'] = response.result;
}
reject(err);
}
else {
resolve(response);
}
});
}
}
exports.HttpClient = HttpClient;

View File

@ -1,50 +0,0 @@
/// <reference types="node" />
import http = require("http");
import url = require("url");
export interface IHeaders {
[key: string]: any;
}
export interface IHttpClient {
options(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
get(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
del(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
post(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
patch(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
put(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: IHeaders): Promise<IHttpClientResponse>;
requestRaw(info: IRequestInfo, data: string | NodeJS.ReadableStream): Promise<IHttpClientResponse>;
requestRawWithCallback(info: IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: IHttpClientResponse) => void): void;
}
export interface IRequestHandler {
prepareRequest(options: http.RequestOptions): void;
canHandleAuthentication(response: IHttpClientResponse): boolean;
handleAuthentication(httpClient: IHttpClient, requestInfo: IRequestInfo, objs: any): Promise<IHttpClientResponse>;
}
export interface IHttpClientResponse {
message: http.IncomingMessage;
readBody(): Promise<string>;
}
export interface IRequestInfo {
options: http.RequestOptions;
parsedUrl: url.Url;
httpModule: any;
}
export interface IRequestOptions {
headers?: IHeaders;
socketTimeout?: number;
ignoreSslError?: boolean;
allowRedirects?: boolean;
allowRedirectDowngrade?: boolean;
maxRedirects?: number;
maxSockets?: number;
keepAlive?: boolean;
deserializeDates?: boolean;
allowRetries?: boolean;
maxRetries?: number;
}
export interface ITypedResponse<T> {
statusCode: number;
result: T | null;
headers: Object;
}

View File

@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
;

View File

@ -1,59 +0,0 @@
{
"_from": "@actions/http-client@1.0.6",
"_id": "@actions/http-client@1.0.6",
"_inBundle": false,
"_integrity": "sha512-LGmio4w98UyGX33b/W6V6Nx/sQHRXZ859YlMkn36wPsXPB82u8xTVlA/Dq2DXrm6lEq9RVmisRJa1c+HETAIJA==",
"_location": "/@actions/http-client",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@actions/http-client@1.0.6",
"name": "@actions/http-client",
"escapedName": "@actions%2fhttp-client",
"scope": "@actions",
"rawSpec": "1.0.6",
"saveSpec": null,
"fetchSpec": "1.0.6"
},
"_requiredBy": [
"/@actions/tool-cache"
],
"_resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.6.tgz",
"_spec": "1.0.6",
"author": {
"name": "GitHub, Inc."
},
"bugs": {
"url": "https://github.com/actions/http-client/issues"
},
"dependencies": {
"tunnel": "0.0.6"
},
"description": "Actions Http Client",
"devDependencies": {
"@types/jest": "^24.0.25",
"@types/node": "^12.12.24",
"jest": "^24.9.0",
"proxy": "^1.0.1",
"ts-jest": "^24.3.0",
"typescript": "^3.7.4"
},
"homepage": "https://github.com/actions/http-client#readme",
"keywords": [
"Actions",
"Http"
],
"license": "MIT",
"main": "index.js",
"name": "@actions/http-client",
"repository": {
"type": "git",
"url": "git+https://github.com/actions/http-client.git"
},
"scripts": {
"build": "rm -Rf ./_out && tsc && cp package*.json ./_out && cp *.md ./_out && cp LICENSE ./_out && cp actions.png ./_out",
"test": "jest"
},
"version": "1.0.6"
}

View File

@ -1,4 +0,0 @@
/// <reference types="node" />
import * as url from 'url';
export declare function getProxyUrl(reqUrl: url.Url): url.Url | undefined;
export declare function checkBypass(reqUrl: url.Url): boolean;

View File

@ -1,57 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = require("url");
function getProxyUrl(reqUrl) {
let usingSsl = reqUrl.protocol === 'https:';
let proxyUrl;
if (checkBypass(reqUrl)) {
return proxyUrl;
}
let proxyVar;
if (usingSsl) {
proxyVar = process.env["https_proxy"] ||
process.env["HTTPS_PROXY"];
}
else {
proxyVar = process.env["http_proxy"] ||
process.env["HTTP_PROXY"];
}
if (proxyVar) {
proxyUrl = url.parse(proxyVar);
}
return proxyUrl;
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || '';
if (!noProxy) {
return false;
}
// Determine the request port
let reqPort;
if (reqUrl.port) {
reqPort = Number(reqUrl.port);
}
else if (reqUrl.protocol === 'http:') {
reqPort = 80;
}
else if (reqUrl.protocol === 'https:') {
reqPort = 443;
}
// Format the request hostname and hostname with port
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
// Compare request host against noproxy
for (let upperNoProxyItem of noProxy.split(',').map(x => x.trim().toUpperCase()).filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;

53
node_modules/@actions/io/README.md generated vendored
View File

@ -1,53 +0,0 @@
# `@actions/io`
> Core functions for cli filesystem scenarios
## Usage
#### mkdir -p
Recursively make a directory. Follows rules specified in [man mkdir](https://linux.die.net/man/1/mkdir) with the `-p` option specified:
```js
const io = require('@actions/io');
await io.mkdirP('path/to/make');
```
#### cp/mv
Copy or move files or folders. Follows rules specified in [man cp](https://linux.die.net/man/1/cp) and [man mv](https://linux.die.net/man/1/mv):
```js
const io = require('@actions/io');
// Recursive must be true for directories
const options = { recursive: true, force: false }
await io.cp('path/to/directory', 'path/to/dest', options);
await io.mv('path/to/file', 'path/to/dest');
```
#### rm -rf
Remove a file or folder recursively. Follows rules specified in [man rm](https://linux.die.net/man/1/rm) with the `-r` and `-f` rules specified.
```js
const io = require('@actions/io');
await io.rmRF('path/to/directory');
await io.rmRF('path/to/file');
```
#### which
Get the path to a tool and resolves via paths. Follows the rules specified in [man which](https://linux.die.net/man/1/which).
```js
const exec = require('@actions/exec');
const io = require('@actions/io');
const pythonPath: string = await io.which('python', true)
await exec.exec(`"${pythonPath}"`, ['main.py']);
```

View File

@ -1,29 +0,0 @@
/// <reference types="node" />
import * as fs from 'fs';
export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink;
export declare const IS_WINDOWS: boolean;
export declare function exists(fsPath: string): Promise<boolean>;
export declare function isDirectory(fsPath: string, useStat?: boolean): Promise<boolean>;
/**
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
*/
export declare function isRooted(p: string): boolean;
/**
* Recursively create a directory at `fsPath`.
*
* This implementation is optimistic, meaning it attempts to create the full
* path first, and backs up the path stack from there.
*
* @param fsPath The path to create
* @param maxDepth The maximum recursion depth
* @param depth The current recursion depth
*/
export declare function mkdirP(fsPath: string, maxDepth?: number, depth?: number): Promise<void>;
/**
* Best effort attempt to determine whether a file exists and is executable.
* @param filePath file path to check
* @param extensions additional file extensions to try
* @return if file exists and is executable, returns the file path. otherwise empty string.
*/
export declare function tryGetExecutablePath(filePath: string, extensions: string[]): Promise<string>;

View File

@ -1,195 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = require("assert");
const fs = require("fs");
const path = require("path");
_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
exports.IS_WINDOWS = process.platform === 'win32';
function exists(fsPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield exports.stat(fsPath);
}
catch (err) {
if (err.code === 'ENOENT') {
return false;
}
throw err;
}
return true;
});
}
exports.exists = exists;
function isDirectory(fsPath, useStat = false) {
return __awaiter(this, void 0, void 0, function* () {
const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
return stats.isDirectory();
});
}
exports.isDirectory = isDirectory;
/**
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
*/
function isRooted(p) {
p = normalizeSeparators(p);
if (!p) {
throw new Error('isRooted() parameter "p" cannot be empty');
}
if (exports.IS_WINDOWS) {
return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
); // e.g. C: or C:\hello
}
return p.startsWith('/');
}
exports.isRooted = isRooted;
/**
* Recursively create a directory at `fsPath`.
*
* This implementation is optimistic, meaning it attempts to create the full
* path first, and backs up the path stack from there.
*
* @param fsPath The path to create
* @param maxDepth The maximum recursion depth
* @param depth The current recursion depth
*/
function mkdirP(fsPath, maxDepth = 1000, depth = 1) {
return __awaiter(this, void 0, void 0, function* () {
assert_1.ok(fsPath, 'a path argument must be provided');
fsPath = path.resolve(fsPath);
if (depth >= maxDepth)
return exports.mkdir(fsPath);
try {
yield exports.mkdir(fsPath);
return;
}
catch (err) {
switch (err.code) {
case 'ENOENT': {
yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);
yield exports.mkdir(fsPath);
return;
}
default: {
let stats;
try {
stats = yield exports.stat(fsPath);
}
catch (err2) {
throw err;
}
if (!stats.isDirectory())
throw err;
}
}
}
});
}
exports.mkdirP = mkdirP;
/**
* Best effort attempt to determine whether a file exists and is executable.
* @param filePath file path to check
* @param extensions additional file extensions to try
* @return if file exists and is executable, returns the file path. otherwise empty string.
*/
function tryGetExecutablePath(filePath, extensions) {
return __awaiter(this, void 0, void 0, function* () {
let stats = undefined;
try {
// test file exists
stats = yield exports.stat(filePath);
}
catch (err) {
if (err.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
}
}
if (stats && stats.isFile()) {
if (exports.IS_WINDOWS) {
// on Windows, test for valid extension
const upperExt = path.extname(filePath).toUpperCase();
if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
return filePath;
}
}
else {
if (isUnixExecutable(stats)) {
return filePath;
}
}
}
// try each extension
const originalFilePath = filePath;
for (const extension of extensions) {
filePath = originalFilePath + extension;
stats = undefined;
try {
stats = yield exports.stat(filePath);
}
catch (err) {
if (err.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
}
}
if (stats && stats.isFile()) {
if (exports.IS_WINDOWS) {
// preserve the case of the actual file (since an extension was appended)
try {
const directory = path.dirname(filePath);
const upperName = path.basename(filePath).toUpperCase();
for (const actualName of yield exports.readdir(directory)) {
if (upperName === actualName.toUpperCase()) {
filePath = path.join(directory, actualName);
break;
}
}
}
catch (err) {
// eslint-disable-next-line no-console
console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
}
return filePath;
}
else {
if (isUnixExecutable(stats)) {
return filePath;
}
}
}
}
return '';
});
}
exports.tryGetExecutablePath = tryGetExecutablePath;
function normalizeSeparators(p) {
p = p || '';
if (exports.IS_WINDOWS) {
// convert slashes on Windows
p = p.replace(/\//g, '\\');
// remove redundant slashes
return p.replace(/\\\\+/g, '\\');
}
// remove redundant slashes
return p.replace(/\/\/+/g, '/');
}
// on Mac/Linux, test the execute bit
// R W X R W X R W X
// 256 128 64 32 16 8 4 2 1
function isUnixExecutable(stats) {
return ((stats.mode & 1) > 0 ||
((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
((stats.mode & 64) > 0 && stats.uid === process.getuid()));
}
//# sourceMappingURL=io-util.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"io-util.js","sourceRoot":"","sources":["../src/io-util.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAyB;AACzB,yBAAwB;AACxB,6BAA4B;AAEf,gBAYE,qTAAA;AAEF,QAAA,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;AAEtD,SAAsB,MAAM,CAAC,MAAc;;QACzC,IAAI;YACF,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;SACnB;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,OAAO,KAAK,CAAA;aACb;YAED,MAAM,GAAG,CAAA;SACV;QAED,OAAO,IAAI,CAAA;IACb,CAAC;CAAA;AAZD,wBAYC;AAED,SAAsB,WAAW,CAC/B,MAAc,EACd,UAAmB,KAAK;;QAExB,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,YAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;QAChE,OAAO,KAAK,CAAC,WAAW,EAAE,CAAA;IAC5B,CAAC;CAAA;AAND,kCAMC;AAED;;;GAGG;AACH,SAAgB,QAAQ,CAAC,CAAS;IAChC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAA;IAC1B,IAAI,CAAC,CAAC,EAAE;QACN,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;KAC5D;IAED,IAAI,kBAAU,EAAE;QACd,OAAO,CACL,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,8BAA8B;SACxE,CAAA,CAAC,sBAAsB;KACzB;IAED,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AAbD,4BAaC;AAED;;;;;;;;;GASG;AACH,SAAsB,MAAM,CAC1B,MAAc,EACd,WAAmB,IAAI,EACvB,QAAgB,CAAC;;QAEjB,WAAE,CAAC,MAAM,EAAE,kCAAkC,CAAC,CAAA;QAE9C,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAE7B,IAAI,KAAK,IAAI,QAAQ;YAAE,OAAO,aAAK,CAAC,MAAM,CAAC,CAAA;QAE3C,IAAI;YACF,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;YACnB,OAAM;SACP;QAAC,OAAO,GAAG,EAAE;YACZ,QAAQ,GAAG,CAAC,IAAI,EAAE;gBAChB,KAAK,QAAQ,CAAC,CAAC;oBACb,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,GAAG,CAAC,CAAC,CAAA;oBACvD,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;oBACnB,OAAM;iBACP;gBACD,OAAO,CAAC,CAAC;oBACP,IAAI,KAAe,CAAA;oBAEnB,IAAI;wBACF,KAAK,GAAG,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;qBAC3B;oBAAC,OAAO,IAAI,EAAE;wBACb,MAAM,GAAG,CAAA;qBACV;oBAED,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE;wBAAE,MAAM,GAAG,CAAA;iBACpC;aACF;SACF;IACH,CAAC;CAAA;AAlCD,wBAkCC;AAED;;;;;GAKG;AACH,SAAsB,oBAAoB,CACxC,QAAgB,EAChB,UAAoB;;QAEpB,IAAI,KAAK,GAAyB,SAAS,CAAA;QAC3C,IAAI;YACF,mBAAmB;YACnB,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;aACF;SACF;QACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;YAC3B,IAAI,kBAAU,EAAE;gBACd,uCAAuC;gBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;gBACrD,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,QAAQ,CAAC,EAAE;oBACpE,OAAO,QAAQ,CAAA;iBAChB;aACF;iBAAM;gBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;oBAC3B,OAAO,QAAQ,CAAA;iBAChB;aACF;SACF;QAED,qBAAqB;QACrB,MAAM,gBAAgB,GAAG,QAAQ,CAAA;QACjC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CAAA;YAEvC,KAAK,GAAG,SAAS,CAAA;YACjB,IAAI;gBACF,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;oBACzB,sCAAsC;oBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;iBACF;aACF;YAED,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBAC3B,IAAI,kBAAU,EAAE;oBACd,yEAAyE;oBACzE,IAAI;wBACF,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;wBACxC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;wBACvD,KAAK,MAAM,UAAU,IAAI,MAAM,eAAO,CAAC,SAAS,CAAC,EAAE;4BACjD,IAAI,SAAS,KAAK,UAAU,CAAC,WAAW,EAAE,EAAE;gCAC1C,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;gCAC3C,MAAK;6BACN;yBACF;qBACF;oBAAC,OAAO,GAAG,EAAE;wBACZ,sCAAsC;wBACtC,OAAO,CAAC,GAAG,CACT,yEAAyE,QAAQ,MAAM,GAAG,EAAE,CAC7F,CAAA;qBACF;oBAED,OAAO,QAAQ,CAAA;iBAChB;qBAAM;oBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;wBAC3B,OAAO,QAAQ,CAAA;qBAChB;iBACF;aACF;SACF;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CAAA;AA5ED,oDA4EC;AAED,SAAS,mBAAmB,CAAC,CAAS;IACpC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACX,IAAI,kBAAU,EAAE;QACd,6BAA6B;QAC7B,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAE1B,2BAA2B;QAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;KACjC;IAED,2BAA2B;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjC,CAAC;AAED,qCAAqC;AACrC,6BAA6B;AAC7B,6BAA6B;AAC7B,SAAS,gBAAgB,CAAC,KAAe;IACvC,OAAO,CACL,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;QACpB,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;QACxD,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAC1D,CAAA;AACH,CAAC"}

56
node_modules/@actions/io/lib/io.d.ts generated vendored
View File

@ -1,56 +0,0 @@
/**
* Interface for cp/mv options
*/
export interface CopyOptions {
/** Optional. Whether to recursively copy all subdirectories. Defaults to false */
recursive?: boolean;
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
force?: boolean;
}
/**
* Interface for cp/mv options
*/
export interface MoveOptions {
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
force?: boolean;
}
/**
* Copies a file or folder.
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
*
* @param source source path
* @param dest destination path
* @param options optional. See CopyOptions.
*/
export declare function cp(source: string, dest: string, options?: CopyOptions): Promise<void>;
/**
* Moves a path.
*
* @param source source path
* @param dest destination path
* @param options optional. See MoveOptions.
*/
export declare function mv(source: string, dest: string, options?: MoveOptions): Promise<void>;
/**
* Remove a path recursively with force
*
* @param inputPath path to remove
*/
export declare function rmRF(inputPath: string): Promise<void>;
/**
* Make a directory. Creates the full path with folders in between
* Will throw if it fails
*
* @param fsPath path to create
* @returns Promise<void>
*/
export declare function mkdirP(fsPath: string): Promise<void>;
/**
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
* If you check and the tool does not exist, it will throw.
*
* @param tool name of the tool
* @param check whether to check if tool exists
* @returns Promise<string> path to tool
*/
export declare function which(tool: string, check?: boolean): Promise<string>;

290
node_modules/@actions/io/lib/io.js generated vendored
View File

@ -1,290 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const childProcess = require("child_process");
const path = require("path");
const util_1 = require("util");
const ioUtil = require("./io-util");
const exec = util_1.promisify(childProcess.exec);
/**
* Copies a file or folder.
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
*
* @param source source path
* @param dest destination path
* @param options optional. See CopyOptions.
*/
function cp(source, dest, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
const { force, recursive } = readCopyOptions(options);
const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
// Dest is an existing file, but not forcing
if (destStat && destStat.isFile() && !force) {
return;
}
// If dest is an existing directory, should copy inside.
const newDest = destStat && destStat.isDirectory()
? path.join(dest, path.basename(source))
: dest;
if (!(yield ioUtil.exists(source))) {
throw new Error(`no such file or directory: ${source}`);
}
const sourceStat = yield ioUtil.stat(source);
if (sourceStat.isDirectory()) {
if (!recursive) {
throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
}
else {
yield cpDirRecursive(source, newDest, 0, force);
}
}
else {
if (path.relative(source, newDest) === '') {
// a file cannot be copied to itself
throw new Error(`'${newDest}' and '${source}' are the same file`);
}
yield copyFile(source, newDest, force);
}
});
}
exports.cp = cp;
/**
* Moves a path.
*
* @param source source path
* @param dest destination path
* @param options optional. See MoveOptions.
*/
function mv(source, dest, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
if (yield ioUtil.exists(dest)) {
let destExists = true;
if (yield ioUtil.isDirectory(dest)) {
// If dest is directory copy src into dest
dest = path.join(dest, path.basename(source));
destExists = yield ioUtil.exists(dest);
}
if (destExists) {
if (options.force == null || options.force) {
yield rmRF(dest);
}
else {
throw new Error('Destination already exists');
}
}
}
yield mkdirP(path.dirname(dest));
yield ioUtil.rename(source, dest);
});
}
exports.mv = mv;
/**
* Remove a path recursively with force
*
* @param inputPath path to remove
*/
function rmRF(inputPath) {
return __awaiter(this, void 0, void 0, function* () {
if (ioUtil.IS_WINDOWS) {
// Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
// program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
try {
if (yield ioUtil.isDirectory(inputPath, true)) {
yield exec(`rd /s /q "${inputPath}"`);
}
else {
yield exec(`del /f /a "${inputPath}"`);
}
}
catch (err) {
// if you try to delete a file that doesn't exist, desired result is achieved
// other errors are valid
if (err.code !== 'ENOENT')
throw err;
}
// Shelling out fails to remove a symlink folder with missing source, this unlink catches that
try {
yield ioUtil.unlink(inputPath);
}
catch (err) {
// if you try to delete a file that doesn't exist, desired result is achieved
// other errors are valid
if (err.code !== 'ENOENT')
throw err;
}
}
else {
let isDir = false;
try {
isDir = yield ioUtil.isDirectory(inputPath);
}
catch (err) {
// if you try to delete a file that doesn't exist, desired result is achieved
// other errors are valid
if (err.code !== 'ENOENT')
throw err;
return;
}
if (isDir) {
yield exec(`rm -rf "${inputPath}"`);
}
else {
yield ioUtil.unlink(inputPath);
}
}
});
}
exports.rmRF = rmRF;
/**
* Make a directory. Creates the full path with folders in between
* Will throw if it fails
*
* @param fsPath path to create
* @returns Promise<void>
*/
function mkdirP(fsPath) {
return __awaiter(this, void 0, void 0, function* () {
yield ioUtil.mkdirP(fsPath);
});
}
exports.mkdirP = mkdirP;
/**
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
* If you check and the tool does not exist, it will throw.
*
* @param tool name of the tool
* @param check whether to check if tool exists
* @returns Promise<string> path to tool
*/
function which(tool, check) {
return __awaiter(this, void 0, void 0, function* () {
if (!tool) {
throw new Error("parameter 'tool' is required");
}
// recursive when check=true
if (check) {
const result = yield which(tool, false);
if (!result) {
if (ioUtil.IS_WINDOWS) {
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
}
else {
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
}
}
}
try {
// build the list of extensions to try
const extensions = [];
if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {
for (const extension of process.env.PATHEXT.split(path.delimiter)) {
if (extension) {
extensions.push(extension);
}
}
}
// if it's rooted, return it if exists. otherwise return empty.
if (ioUtil.isRooted(tool)) {
const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
if (filePath) {
return filePath;
}
return '';
}
// if any path separators, return empty
if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) {
return '';
}
// build the list of directories
//
// Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
// it feels like we should not do this. Checking the current directory seems like more of a use
// case of a shell, and the which() function exposed by the toolkit should strive for consistency
// across platforms.
const directories = [];
if (process.env.PATH) {
for (const p of process.env.PATH.split(path.delimiter)) {
if (p) {
directories.push(p);
}
}
}
// return the first match
for (const directory of directories) {
const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);
if (filePath) {
return filePath;
}
}
return '';
}
catch (err) {
throw new Error(`which failed with message ${err.message}`);
}
});
}
exports.which = which;
function readCopyOptions(options) {
const force = options.force == null ? true : options.force;
const recursive = Boolean(options.recursive);
return { force, recursive };
}
function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
return __awaiter(this, void 0, void 0, function* () {
// Ensure there is not a run away recursive copy
if (currentDepth >= 255)
return;
currentDepth++;
yield mkdirP(destDir);
const files = yield ioUtil.readdir(sourceDir);
for (const fileName of files) {
const srcFile = `${sourceDir}/${fileName}`;
const destFile = `${destDir}/${fileName}`;
const srcFileStat = yield ioUtil.lstat(srcFile);
if (srcFileStat.isDirectory()) {
// Recurse
yield cpDirRecursive(srcFile, destFile, currentDepth, force);
}
else {
yield copyFile(srcFile, destFile, force);
}
}
// Change the mode for the newly created directory
yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
});
}
// Buffered file copy
function copyFile(srcFile, destFile, force) {
return __awaiter(this, void 0, void 0, function* () {
if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
// unlink/re-link it
try {
yield ioUtil.lstat(destFile);
yield ioUtil.unlink(destFile);
}
catch (e) {
// Try to override file permission
if (e.code === 'EPERM') {
yield ioUtil.chmod(destFile, '0666');
yield ioUtil.unlink(destFile);
}
// other errors = it doesn't exist, no work to do
}
// Copy over symlink
const symlinkFull = yield ioUtil.readlink(srcFile);
yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
}
else if (!(yield ioUtil.exists(destFile)) || force) {
yield ioUtil.copyFile(srcFile, destFile);
}
});
}
//# sourceMappingURL=io.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,60 +0,0 @@
{
"_from": "@actions/io@1.0.2",
"_id": "@actions/io@1.0.2",
"_inBundle": false,
"_integrity": "sha512-J8KuFqVPr3p6U8W93DOXlXW6zFvrQAJANdS+vw0YhusLIq+bszW8zmK2Fh1C2kDPX8FMvwIl1OUcFgvJoXLbAg==",
"_location": "/@actions/io",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@actions/io@1.0.2",
"name": "@actions/io",
"escapedName": "@actions%2fio",
"scope": "@actions",
"rawSpec": "1.0.2",
"saveSpec": null,
"fetchSpec": "1.0.2"
},
"_requiredBy": [
"/@actions/exec",
"/@actions/tool-cache"
],
"_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.2.tgz",
"_spec": "1.0.2",
"bugs": {
"url": "https://github.com/actions/toolkit/issues"
},
"description": "Actions io lib",
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib"
],
"homepage": "https://github.com/actions/toolkit/tree/master/packages/io",
"keywords": [
"github",
"actions",
"io"
],
"license": "MIT",
"main": "lib/io.js",
"name": "@actions/io",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/io"
},
"scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc"
},
"types": "lib/io.d.ts",
"version": "1.0.2"
}

View File

@ -1,82 +0,0 @@
# `@actions/tool-cache`
> Functions necessary for downloading and caching tools.
## Usage
#### Download
You can use this to download tools (or other files) from a download URL:
```js
const tc = require('@actions/tool-cache');
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
```
#### Extract
These can then be extracted in platform specific ways:
```js
const tc = require('@actions/tool-cache');
if (process.platform === 'win32') {
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
// Or alternately
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
}
else {
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
}
```
#### Cache
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for self-hosted runners.
You'll often want to add it to the path as part of this step:
```js
const tc = require('@actions/tool-cache');
const core = require('@actions/core');
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
core.addPath(cachedPath);
```
You can also cache files for reuse.
```js
const tc = require('@actions/tool-cache');
const cachedPath = await tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
```
#### Find
Finally, you can find directories and files you've previously cached:
```js
const tc = require('@actions/tool-cache');
const core = require('@actions/core');
const nodeDirectory = tc.find('node', '12.x', 'x64');
core.addPath(nodeDirectory);
```
You can even find all cached versions of a tool:
```js
const tc = require('@actions/tool-cache');
const allNodeVersions = tc.findAllVersions('node');
console.log(`Versions of node available: ${allNodeVersions}`);
```

View File

@ -1,12 +0,0 @@
/**
* Internal class for retries
*/
export declare class RetryHelper {
private maxAttempts;
private minSeconds;
private maxSeconds;
constructor(maxAttempts: number, minSeconds: number, maxSeconds: number);
execute<T>(action: () => Promise<T>, isRetryable?: (e: Error) => boolean): Promise<T>;
private getSleepAmount;
private sleep;
}

View File

@ -1,70 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
/**
* Internal class for retries
*/
class RetryHelper {
constructor(maxAttempts, minSeconds, maxSeconds) {
if (maxAttempts < 1) {
throw new Error('max attempts should be greater than or equal to 1');
}
this.maxAttempts = maxAttempts;
this.minSeconds = Math.floor(minSeconds);
this.maxSeconds = Math.floor(maxSeconds);
if (this.minSeconds > this.maxSeconds) {
throw new Error('min seconds should be less than or equal to max seconds');
}
}
execute(action, isRetryable) {
return __awaiter(this, void 0, void 0, function* () {
let attempt = 1;
while (attempt < this.maxAttempts) {
// Try
try {
return yield action();
}
catch (err) {
if (isRetryable && !isRetryable(err)) {
throw err;
}
core.info(err.message);
}
// Sleep
const seconds = this.getSleepAmount();
core.info(`Waiting ${seconds} seconds before trying again`);
yield this.sleep(seconds);
attempt++;
}
// Last attempt
return yield action();
});
}
getSleepAmount() {
return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) +
this.minSeconds);
}
sleep(seconds) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
});
}
}
exports.RetryHelper = RetryHelper;
//# sourceMappingURL=retry-helper.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"retry-helper.js","sourceRoot":"","sources":["../src/retry-helper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC;;GAEG;AACH,MAAa,WAAW;IAKtB,YAAY,WAAmB,EAAE,UAAkB,EAAE,UAAkB;QACrE,IAAI,WAAW,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;SACrE;QAED,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;IACH,CAAC;IAEK,OAAO,CACX,MAAwB,EACxB,WAAmC;;YAEnC,IAAI,OAAO,GAAG,CAAC,CAAA;YACf,OAAO,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE;gBACjC,MAAM;gBACN,IAAI;oBACF,OAAO,MAAM,MAAM,EAAE,CAAA;iBACtB;gBAAC,OAAO,GAAG,EAAE;oBACZ,IAAI,WAAW,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE;wBACpC,MAAM,GAAG,CAAA;qBACV;oBAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;iBACvB;gBAED,QAAQ;gBACR,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,EAAE,CAAA;gBACrC,IAAI,CAAC,IAAI,CAAC,WAAW,OAAO,8BAA8B,CAAC,CAAA;gBAC3D,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;gBACzB,OAAO,EAAE,CAAA;aACV;YAED,eAAe;YACf,OAAO,MAAM,MAAM,EAAE,CAAA;QACvB,CAAC;KAAA;IAEO,cAAc;QACpB,OAAO,CACL,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;YACnE,IAAI,CAAC,UAAU,CAChB,CAAA;IACH,CAAC;IAEa,KAAK,CAAC,OAAe;;YACjC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAA;QACpE,CAAC;KAAA;CACF;AAxDD,kCAwDC"}

View File

@ -1,80 +0,0 @@
export declare class HTTPError extends Error {
readonly httpStatusCode: number | undefined;
constructor(httpStatusCode: number | undefined);
}
/**
* Download a tool from an url and stream it into a file
*
* @param url url of tool to download
* @param dest path to download tool
* @returns path to downloaded tool
*/
export declare function downloadTool(url: string, dest?: string): Promise<string>;
/**
* Extract a .7z file
*
* @param file path to the .7z file
* @param dest destination directory. Optional.
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
* interface, it is smaller than the full command line interface, and it does support long paths. At the
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
* to 7zr.exe can be pass to this function.
* @returns path to the destination directory
*/
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
/**
* Extract a compressed tar archive
*
* @param file path to the tar
* @param dest destination directory. Optional.
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
* @returns path to the destination directory
*/
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>;
/**
* Extract a zip
*
* @param file path to the zip
* @param dest destination directory. Optional.
* @returns path to the destination directory
*/
export declare function extractZip(file: string, dest?: string): Promise<string>;
/**
* Caches a directory and installs it into the tool cacheDir
*
* @param sourceDir the directory to cache into tools
* @param tool tool name
* @param version version of the tool. semver format
* @param arch architecture of the tool. Optional. Defaults to machine architecture
*/
export declare function cacheDir(sourceDir: string, tool: string, version: string, arch?: string): Promise<string>;
/**
* Caches a downloaded file (GUID) and installs it
* into the tool cache with a given targetName
*
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
* @param targetFile the name of the file name in the tools directory
* @param tool tool name
* @param version version of the tool. semver format
* @param arch architecture of the tool. Optional. Defaults to machine architecture
*/
export declare function cacheFile(sourceFile: string, targetFile: string, tool: string, version: string, arch?: string): Promise<string>;
/**
* Finds the path to a tool version in the local installed tool cache
*
* @param toolName name of the tool
* @param versionSpec version of the tool
* @param arch optional arch. defaults to arch of computer
*/
export declare function find(toolName: string, versionSpec: string, arch?: string): string;
/**
* Finds the paths to all versions of a tool that are installed in the local tool cache
*
* @param toolName name of the tool
* @param arch optional arch. defaults to arch of computer
*/
export declare function findAllVersions(toolName: string, arch?: string): string[];

View File

@ -1,500 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const io = __importStar(require("@actions/io"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const httpm = __importStar(require("@actions/http-client"));
const semver = __importStar(require("semver"));
const stream = __importStar(require("stream"));
const util = __importStar(require("util"));
const v4_1 = __importDefault(require("uuid/v4"));
const exec_1 = require("@actions/exec/lib/exec");
const assert_1 = require("assert");
const retry_helper_1 = require("./retry-helper");
class HTTPError extends Error {
constructor(httpStatusCode) {
super(`Unexpected HTTP response: ${httpStatusCode}`);
this.httpStatusCode = httpStatusCode;
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.HTTPError = HTTPError;
const IS_WINDOWS = process.platform === 'win32';
const userAgent = 'actions/tool-cache';
/**
* Download a tool from an url and stream it into a file
*
* @param url url of tool to download
* @param dest path to download tool
* @returns path to downloaded tool
*/
function downloadTool(url, dest) {
return __awaiter(this, void 0, void 0, function* () {
dest = dest || path.join(_getTempDirectory(), v4_1.default());
yield io.mkdirP(path.dirname(dest));
core.debug(`Downloading ${url}`);
core.debug(`Destination ${dest}`);
const maxAttempts = 3;
const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10);
const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20);
const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () {
return yield downloadToolAttempt(url, dest || '');
}), (err) => {
if (err instanceof HTTPError && err.httpStatusCode) {
// Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests
if (err.httpStatusCode < 500 &&
err.httpStatusCode !== 408 &&
err.httpStatusCode !== 429) {
return false;
}
}
// Otherwise retry
return true;
});
});
}
exports.downloadTool = downloadTool;
function downloadToolAttempt(url, dest) {
return __awaiter(this, void 0, void 0, function* () {
if (fs.existsSync(dest)) {
throw new Error(`Destination file path ${dest} already exists`);
}
// Get the response headers
const http = new httpm.HttpClient(userAgent, [], {
allowRetries: false
});
const response = yield http.get(url);
if (response.message.statusCode !== 200) {
const err = new HTTPError(response.message.statusCode);
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
throw err;
}
// Download the response body
const pipeline = util.promisify(stream.pipeline);
const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message);
const readStream = responseMessageFactory();
let succeeded = false;
try {
yield pipeline(readStream, fs.createWriteStream(dest));
core.debug('download complete');
succeeded = true;
return dest;
}
finally {
// Error, delete dest before retry
if (!succeeded) {
core.debug('download failed');
try {
yield io.rmRF(dest);
}
catch (err) {
core.debug(`Failed to delete '${dest}'. ${err.message}`);
}
}
}
});
}
/**
* Extract a .7z file
*
* @param file path to the .7z file
* @param dest destination directory. Optional.
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
* interface, it is smaller than the full command line interface, and it does support long paths. At the
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
* to 7zr.exe can be pass to this function.
* @returns path to the destination directory
*/
function extract7z(file, dest, _7zPath) {
return __awaiter(this, void 0, void 0, function* () {
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
assert_1.ok(file, 'parameter "file" is required');
dest = yield _createExtractFolder(dest);
const originalCwd = process.cwd();
process.chdir(dest);
if (_7zPath) {
try {
const args = [
'x',
'-bb1',
'-bd',
'-sccUTF-8',
file
];
const options = {
silent: true
};
yield exec_1.exec(`"${_7zPath}"`, args, options);
}
finally {
process.chdir(originalCwd);
}
}
else {
const escapedScript = path
.join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1')
.replace(/'/g, "''")
.replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, '');
const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
const args = [
'-NoLogo',
'-Sta',
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Unrestricted',
'-Command',
command
];
const options = {
silent: true
};
try {
const powershellPath = yield io.which('powershell', true);
yield exec_1.exec(`"${powershellPath}"`, args, options);
}
finally {
process.chdir(originalCwd);
}
}
return dest;
});
}
exports.extract7z = extract7z;
/**
* Extract a compressed tar archive
*
* @param file path to the tar
* @param dest destination directory. Optional.
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
* @returns path to the destination directory
*/
function extractTar(file, dest, flags = 'xz') {
return __awaiter(this, void 0, void 0, function* () {
if (!file) {
throw new Error("parameter 'file' is required");
}
// Create dest
dest = yield _createExtractFolder(dest);
// Determine whether GNU tar
core.debug('Checking tar --version');
let versionOutput = '';
yield exec_1.exec('tar --version', [], {
ignoreReturnCode: true,
silent: true,
listeners: {
stdout: (data) => (versionOutput += data.toString()),
stderr: (data) => (versionOutput += data.toString())
}
});
core.debug(versionOutput.trim());
const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR');
// Initialize args
const args = [flags];
let destArg = dest;
let fileArg = file;
if (IS_WINDOWS && isGnuTar) {
args.push('--force-local');
destArg = dest.replace(/\\/g, '/');
// Technically only the dest needs to have `/` but for aesthetic consistency
// convert slashes in the file arg too.
fileArg = file.replace(/\\/g, '/');
}
if (isGnuTar) {
// Suppress warnings when using GNU tar to extract archives created by BSD tar
args.push('--warning=no-unknown-keyword');
}
args.push('-C', destArg, '-f', fileArg);
yield exec_1.exec(`tar`, args);
return dest;
});
}
exports.extractTar = extractTar;
/**
* Extract a zip
*
* @param file path to the zip
* @param dest destination directory. Optional.
* @returns path to the destination directory
*/
function extractZip(file, dest) {
return __awaiter(this, void 0, void 0, function* () {
if (!file) {
throw new Error("parameter 'file' is required");
}
dest = yield _createExtractFolder(dest);
if (IS_WINDOWS) {
yield extractZipWin(file, dest);
}
else {
yield extractZipNix(file, dest);
}
return dest;
});
}
exports.extractZip = extractZip;
function extractZipWin(file, dest) {
return __awaiter(this, void 0, void 0, function* () {
// build the powershell command
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
// run powershell
const powershellPath = yield io.which('powershell');
const args = [
'-NoLogo',
'-Sta',
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Unrestricted',
'-Command',
command
];
yield exec_1.exec(`"${powershellPath}"`, args);
});
}
function extractZipNix(file, dest) {
return __awaiter(this, void 0, void 0, function* () {
const unzipPath = yield io.which('unzip');
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
});
}
/**
* Caches a directory and installs it into the tool cacheDir
*
* @param sourceDir the directory to cache into tools
* @param tool tool name
* @param version version of the tool. semver format
* @param arch architecture of the tool. Optional. Defaults to machine architecture
*/
function cacheDir(sourceDir, tool, version, arch) {
return __awaiter(this, void 0, void 0, function* () {
version = semver.clean(version) || version;
arch = arch || os.arch();
core.debug(`Caching tool ${tool} ${version} ${arch}`);
core.debug(`source dir: ${sourceDir}`);
if (!fs.statSync(sourceDir).isDirectory()) {
throw new Error('sourceDir is not a directory');
}
// Create the tool dir
const destPath = yield _createToolPath(tool, version, arch);
// copy each child item. do not move. move can fail on Windows
// due to anti-virus software having an open handle on a file.
for (const itemName of fs.readdirSync(sourceDir)) {
const s = path.join(sourceDir, itemName);
yield io.cp(s, destPath, { recursive: true });
}
// write .complete
_completeToolPath(tool, version, arch);
return destPath;
});
}
exports.cacheDir = cacheDir;
/**
* Caches a downloaded file (GUID) and installs it
* into the tool cache with a given targetName
*
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
* @param targetFile the name of the file name in the tools directory
* @param tool tool name
* @param version version of the tool. semver format
* @param arch architecture of the tool. Optional. Defaults to machine architecture
*/
function cacheFile(sourceFile, targetFile, tool, version, arch) {
return __awaiter(this, void 0, void 0, function* () {
version = semver.clean(version) || version;
arch = arch || os.arch();
core.debug(`Caching tool ${tool} ${version} ${arch}`);
core.debug(`source file: ${sourceFile}`);
if (!fs.statSync(sourceFile).isFile()) {
throw new Error('sourceFile is not a file');
}
// create the tool dir
const destFolder = yield _createToolPath(tool, version, arch);
// copy instead of move. move can fail on Windows due to
// anti-virus software having an open handle on a file.
const destPath = path.join(destFolder, targetFile);
core.debug(`destination file ${destPath}`);
yield io.cp(sourceFile, destPath);
// write .complete
_completeToolPath(tool, version, arch);
return destFolder;
});
}
exports.cacheFile = cacheFile;
/**
* Finds the path to a tool version in the local installed tool cache
*
* @param toolName name of the tool
* @param versionSpec version of the tool
* @param arch optional arch. defaults to arch of computer
*/
function find(toolName, versionSpec, arch) {
if (!toolName) {
throw new Error('toolName parameter is required');
}
if (!versionSpec) {
throw new Error('versionSpec parameter is required');
}
arch = arch || os.arch();
// attempt to resolve an explicit version
if (!_isExplicitVersion(versionSpec)) {
const localVersions = findAllVersions(toolName, arch);
const match = _evaluateVersions(localVersions, versionSpec);
versionSpec = match;
}
// check for the explicit version in the cache
let toolPath = '';
if (versionSpec) {
versionSpec = semver.clean(versionSpec) || '';
const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch);
core.debug(`checking cache: ${cachePath}`);
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
toolPath = cachePath;
}
else {
core.debug('not found');
}
}
return toolPath;
}
exports.find = find;
/**
* Finds the paths to all versions of a tool that are installed in the local tool cache
*
* @param toolName name of the tool
* @param arch optional arch. defaults to arch of computer
*/
function findAllVersions(toolName, arch) {
const versions = [];
arch = arch || os.arch();
const toolPath = path.join(_getCacheDirectory(), toolName);
if (fs.existsSync(toolPath)) {
const children = fs.readdirSync(toolPath);
for (const child of children) {
if (_isExplicitVersion(child)) {
const fullPath = path.join(toolPath, child, arch || '');
if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) {
versions.push(child);
}
}
}
}
return versions;
}
exports.findAllVersions = findAllVersions;
function _createExtractFolder(dest) {
return __awaiter(this, void 0, void 0, function* () {
if (!dest) {
// create a temp dir
dest = path.join(_getTempDirectory(), v4_1.default());
}
yield io.mkdirP(dest);
return dest;
});
}
function _createToolPath(tool, version, arch) {
return __awaiter(this, void 0, void 0, function* () {
const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
core.debug(`destination ${folderPath}`);
const markerPath = `${folderPath}.complete`;
yield io.rmRF(folderPath);
yield io.rmRF(markerPath);
yield io.mkdirP(folderPath);
return folderPath;
});
}
function _completeToolPath(tool, version, arch) {
const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
const markerPath = `${folderPath}.complete`;
fs.writeFileSync(markerPath, '');
core.debug('finished caching tool');
}
function _isExplicitVersion(versionSpec) {
const c = semver.clean(versionSpec) || '';
core.debug(`isExplicit: ${c}`);
const valid = semver.valid(c) != null;
core.debug(`explicit? ${valid}`);
return valid;
}
function _evaluateVersions(versions, versionSpec) {
let version = '';
core.debug(`evaluating ${versions.length} versions`);
versions = versions.sort((a, b) => {
if (semver.gt(a, b)) {
return 1;
}
return -1;
});
for (let i = versions.length - 1; i >= 0; i--) {
const potential = versions[i];
const satisfied = semver.satisfies(potential, versionSpec);
if (satisfied) {
version = potential;
break;
}
}
if (version) {
core.debug(`matched: ${version}`);
}
else {
core.debug('match not found');
}
return version;
}
/**
* Gets RUNNER_TOOL_CACHE
*/
function _getCacheDirectory() {
const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || '';
assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined');
return cacheDirectory;
}
/**
* Gets RUNNER_TEMP
*/
function _getTempDirectory() {
const tempDirectory = process.env['RUNNER_TEMP'] || '';
assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined');
return tempDirectory;
}
/**
* Gets a global variable
*/
function _getGlobal(key, defaultValue) {
/* eslint-disable @typescript-eslint/no-explicit-any */
const value = global[key];
/* eslint-enable @typescript-eslint/no-explicit-any */
return value !== undefined ? value : defaultValue;
}
//# sourceMappingURL=tool-cache.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,74 +0,0 @@
{
"_from": "@actions/tool-cache@1.3.3",
"_id": "@actions/tool-cache@1.3.3",
"_inBundle": false,
"_integrity": "sha512-AFVyTLcIxusDVI1gMhbZW8m/On7YNJG+xYaxorV+qic+f7lO7h37aT2mfzxqAq7mwHxtP1YlVFNrXe9QDf/bPg==",
"_location": "/@actions/tool-cache",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@actions/tool-cache@1.3.3",
"name": "@actions/tool-cache",
"escapedName": "@actions%2ftool-cache",
"scope": "@actions",
"rawSpec": "1.3.3",
"saveSpec": null,
"fetchSpec": "1.3.3"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.3.3.tgz",
"_spec": "1.3.3",
"bugs": {
"url": "https://github.com/actions/toolkit/issues"
},
"dependencies": {
"@actions/core": "^1.2.0",
"@actions/exec": "^1.0.0",
"@actions/http-client": "^1.0.3",
"@actions/io": "^1.0.1",
"semver": "^6.1.0",
"uuid": "^3.3.2"
},
"description": "Actions tool-cache lib",
"devDependencies": {
"@types/nock": "^10.0.3",
"@types/semver": "^6.0.0",
"@types/uuid": "^3.4.4",
"nock": "^10.0.6"
},
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib",
"scripts"
],
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
"keywords": [
"github",
"actions",
"exec"
],
"license": "MIT",
"main": "lib/tool-cache.js",
"name": "@actions/tool-cache",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/tool-cache"
},
"scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc"
},
"types": "lib/tool-cache.d.ts",
"version": "1.3.3"
}

View File

@ -1,60 +0,0 @@
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Source,
[Parameter(Mandatory = $true)]
[string]$Target)
# This script translates the output from 7zdec into UTF8. Node has limited
# built-in support for encodings.
#
# 7zdec uses the system default code page. The system default code page varies
# depending on the locale configuration. On an en-US box, the system default code
# page is Windows-1252.
#
# Note, on a typical en-US box, testing with the 'ç' character is a good way to
# determine whether data is passed correctly between processes. This is because
# the 'ç' character has a different code point across each of the common encodings
# on a typical en-US box, i.e.
# 1) the default console-output code page (IBM437)
# 2) the system default code page (i.e. CP_ACP) (Windows-1252)
# 3) UTF8
$ErrorActionPreference = 'Stop'
# Redefine the wrapper over STDOUT to use UTF8. Node expects UTF8 by default.
$stdout = [System.Console]::OpenStandardOutput()
$utf8 = New-Object System.Text.UTF8Encoding($false) # do not emit BOM
$writer = New-Object System.IO.StreamWriter($stdout, $utf8)
[System.Console]::SetOut($writer)
# All subsequent output must be written using [System.Console]::WriteLine(). In
# PowerShell 4, Write-Host and Out-Default do not consider the updated stream writer.
Set-Location -LiteralPath $Target
# Print the ##command.
$_7zdec = Join-Path -Path "$PSScriptRoot" -ChildPath "externals/7zdec.exe"
[System.Console]::WriteLine("##[command]$_7zdec x `"$Source`"")
# The $OutputEncoding variable instructs PowerShell how to interpret the output
# from the external command.
$OutputEncoding = [System.Text.Encoding]::Default
# Note, the output from 7zdec.exe needs to be iterated over. Otherwise PowerShell.exe
# will launch the external command in such a way that it inherits the streams.
& $_7zdec x $Source 2>&1 |
ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) {
[System.Console]::WriteLine($_.Exception.Message)
}
else {
[System.Console]::WriteLine($_)
}
}
[System.Console]::WriteLine("##[debug]7zdec.exe exit code '$LASTEXITCODE'")
[System.Console]::Out.Flush()
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
}

Binary file not shown.

View File

View File

@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=example.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"example.js","sourceRoot":"","sources":["../example.ts"],"names":[],"mappings":""}

View File

@ -1,95 +0,0 @@
/// <reference types="node" />
export declare const enum TypeName {
null = "null",
boolean = "boolean",
undefined = "undefined",
string = "string",
number = "number",
symbol = "symbol",
Function = "Function",
Array = "Array",
Buffer = "Buffer",
Object = "Object",
RegExp = "RegExp",
Date = "Date",
Error = "Error",
Map = "Map",
Set = "Set",
WeakMap = "WeakMap",
WeakSet = "WeakSet",
Int8Array = "Int8Array",
Uint8Array = "Uint8Array",
Uint8ClampedArray = "Uint8ClampedArray",
Int16Array = "Int16Array",
Uint16Array = "Uint16Array",
Int32Array = "Int32Array",
Uint32Array = "Uint32Array",
Float32Array = "Float32Array",
Float64Array = "Float64Array",
ArrayBuffer = "ArrayBuffer",
SharedArrayBuffer = "SharedArrayBuffer",
DataView = "DataView",
Promise = "Promise",
}
declare function is(value: any): TypeName;
declare namespace is {
const undefined: (value: any) => boolean;
const string: (value: any) => boolean;
const number: (value: any) => boolean;
const function_: (value: any) => boolean;
const null_: (value: any) => boolean;
const class_: (value: any) => any;
const boolean: (value: any) => boolean;
const symbol: (value: any) => boolean;
const array: (arg: any) => arg is any[];
const buffer: (obj: any) => obj is Buffer;
const nullOrUndefined: (value: any) => boolean;
const object: (value: any) => boolean;
const iterable: (value: any) => boolean;
const generator: (value: any) => boolean;
const nativePromise: (value: any) => boolean;
const promise: (value: any) => boolean;
const generatorFunction: (value: any) => boolean;
const asyncFunction: (value: any) => boolean;
const boundFunction: (value: any) => boolean;
const regExp: (value: any) => boolean;
const date: (value: any) => boolean;
const error: (value: any) => boolean;
const map: (value: any) => boolean;
const set: (value: any) => boolean;
const weakMap: (value: any) => boolean;
const weakSet: (value: any) => boolean;
const int8Array: (value: any) => boolean;
const uint8Array: (value: any) => boolean;
const uint8ClampedArray: (value: any) => boolean;
const int16Array: (value: any) => boolean;
const uint16Array: (value: any) => boolean;
const int32Array: (value: any) => boolean;
const uint32Array: (value: any) => boolean;
const float32Array: (value: any) => boolean;
const float64Array: (value: any) => boolean;
const arrayBuffer: (value: any) => boolean;
const sharedArrayBuffer: (value: any) => boolean;
const dataView: (value: any) => boolean;
const directInstanceOf: (instance: any, klass: any) => boolean;
const truthy: (value: any) => boolean;
const falsy: (value: any) => boolean;
const nan: (value: any) => boolean;
const primitive: (value: any) => boolean;
const integer: (value: any) => boolean;
const safeInteger: (value: any) => boolean;
const plainObject: (value: any) => boolean;
const typedArray: (value: any) => boolean;
const arrayLike: (value: any) => boolean;
const inRange: (value: number, range: number | number[]) => boolean;
const domElement: (value: any) => boolean;
const nodeStream: (value: any) => boolean;
const infinite: (value: any) => boolean;
const even: (rem: number) => boolean;
const odd: (rem: number) => boolean;
const empty: (value: any) => boolean;
const emptyOrWhitespace: (value: any) => boolean;
function any(...predicate: any[]): any;
function all(...predicate: any[]): any;
}
export default is;

View File

@ -1,215 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const toString = Object.prototype.toString;
const isOfType = (type) => (value) => typeof value === type; // tslint:disable-line:strict-type-predicates
const getObjectType = (value) => {
const objectName = toString.call(value).slice(8, -1);
if (objectName) {
return objectName;
}
return null;
};
const isObjectOfType = (typeName) => (value) => {
return getObjectType(value) === typeName;
};
function is(value) {
if (value === null) {
return "null" /* null */;
}
if (value === true || value === false) {
return "boolean" /* boolean */;
}
const type = typeof value;
if (type === 'undefined') {
return "undefined" /* undefined */;
}
if (type === 'string') {
return "string" /* string */;
}
if (type === 'number') {
return "number" /* number */;
}
if (type === 'symbol') {
return "symbol" /* symbol */;
}
if (is.function_(value)) {
return "Function" /* Function */;
}
if (Array.isArray(value)) {
return "Array" /* Array */;
}
if (Buffer.isBuffer(value)) {
return "Buffer" /* Buffer */;
}
const tagType = getObjectType(value);
if (tagType) {
return tagType;
}
if (value instanceof String || value instanceof Boolean || value instanceof Number) {
throw new TypeError('Please don\'t use object wrappers for primitive types');
}
return "Object" /* Object */;
}
(function (is) {
const isObject = (value) => typeof value === 'object';
// tslint:disable:variable-name
is.undefined = isOfType('undefined');
is.string = isOfType('string');
is.number = isOfType('number');
is.function_ = isOfType('function');
is.null_ = (value) => value === null;
is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
is.boolean = (value) => value === true || value === false;
// tslint:enable:variable-name
is.symbol = isOfType('symbol');
is.array = Array.isArray;
is.buffer = Buffer.isBuffer;
is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value));
is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]);
is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);
is.nativePromise = isObjectOfType("Promise" /* Promise */);
const hasPromiseAPI = (value) => !is.null_(value) &&
isObject(value) &&
is.function_(value.then) &&
is.function_(value.catch);
is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);
// TODO: Change to use `isObjectOfType` once Node.js 6 or higher is targeted
const isFunctionOfType = (type) => (value) => is.function_(value) && is.function_(value.constructor) && value.constructor.name === type;
is.generatorFunction = isFunctionOfType('GeneratorFunction');
is.asyncFunction = isFunctionOfType('AsyncFunction');
is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');
is.regExp = isObjectOfType("RegExp" /* RegExp */);
is.date = isObjectOfType("Date" /* Date */);
is.error = isObjectOfType("Error" /* Error */);
is.map = isObjectOfType("Map" /* Map */);
is.set = isObjectOfType("Set" /* Set */);
is.weakMap = isObjectOfType("WeakMap" /* WeakMap */);
is.weakSet = isObjectOfType("WeakSet" /* WeakSet */);
is.int8Array = isObjectOfType("Int8Array" /* Int8Array */);
is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */);
is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */);
is.int16Array = isObjectOfType("Int16Array" /* Int16Array */);
is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */);
is.int32Array = isObjectOfType("Int32Array" /* Int32Array */);
is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */);
is.float32Array = isObjectOfType("Float32Array" /* Float32Array */);
is.float64Array = isObjectOfType("Float64Array" /* Float64Array */);
is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */);
is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */);
is.dataView = isObjectOfType("DataView" /* DataView */);
// TODO: Remove `object` checks when targeting ES2015 or higher
// See `Notes`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
is.directInstanceOf = (instance, klass) => is.object(instance) && is.object(klass) && Object.getPrototypeOf(instance) === klass.prototype;
is.truthy = (value) => Boolean(value);
is.falsy = (value) => !value;
is.nan = (value) => Number.isNaN(value);
const primitiveTypes = new Set([
'undefined',
'string',
'number',
'boolean',
'symbol'
]);
is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value);
is.integer = (value) => Number.isInteger(value);
is.safeInteger = (value) => Number.isSafeInteger(value);
is.plainObject = (value) => {
// From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js
let prototype;
return getObjectType(value) === "Object" /* Object */ &&
(prototype = Object.getPrototypeOf(value), prototype === null || // tslint:disable-line:ban-comma-operator
prototype === Object.getPrototypeOf({}));
};
const typedArrayTypes = new Set([
"Int8Array" /* Int8Array */,
"Uint8Array" /* Uint8Array */,
"Uint8ClampedArray" /* Uint8ClampedArray */,
"Int16Array" /* Int16Array */,
"Uint16Array" /* Uint16Array */,
"Int32Array" /* Int32Array */,
"Uint32Array" /* Uint32Array */,
"Float32Array" /* Float32Array */,
"Float64Array" /* Float64Array */
]);
is.typedArray = (value) => {
const objectType = getObjectType(value);
if (objectType === null) {
return false;
}
return typedArrayTypes.has(objectType);
};
const isValidLength = (value) => is.safeInteger(value) && value > -1;
is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
is.inRange = (value, range) => {
if (is.number(range)) {
return value >= Math.min(0, range) && value <= Math.max(range, 0);
}
if (is.array(range) && range.length === 2) {
// TODO: Use spread operator here when targeting Node.js 6 or higher
return value >= Math.min.apply(null, range) && value <= Math.max.apply(null, range);
}
throw new TypeError(`Invalid range: ${util.inspect(range)}`);
};
const NODE_TYPE_ELEMENT = 1;
const DOM_PROPERTIES_TO_CHECK = [
'innerHTML',
'ownerDocument',
'style',
'attributes',
'nodeValue'
];
is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) &&
!is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value);
is.nodeStream = (value) => !is.nullOrUndefined(value) && isObject(value) && is.function_(value.pipe);
is.infinite = (value) => value === Infinity || value === -Infinity;
const isAbsoluteMod2 = (value) => (rem) => is.integer(rem) && Math.abs(rem % 2) === value;
is.even = isAbsoluteMod2(0);
is.odd = isAbsoluteMod2(1);
const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false;
const isEmptyStringOrArray = (value) => (is.string(value) || is.array(value)) && value.length === 0;
const isEmptyObject = (value) => !is.map(value) && !is.set(value) && is.object(value) && Object.keys(value).length === 0;
const isEmptyMapOrSet = (value) => (is.map(value) || is.set(value)) && value.size === 0;
is.empty = (value) => is.falsy(value) || isEmptyStringOrArray(value) || isEmptyObject(value) || isEmptyMapOrSet(value);
is.emptyOrWhitespace = (value) => is.empty(value) || isWhiteSpaceString(value);
const predicateOnArray = (method, predicate, args) => {
// `args` is the calling function's "arguments object".
// We have to do it this way to keep node v4 support.
// So here we convert it to an array and slice off the first item.
const values = Array.prototype.slice.call(args, 1);
if (is.function_(predicate) === false) {
throw new TypeError(`Invalid predicate: ${util.inspect(predicate)}`);
}
if (values.length === 0) {
throw new TypeError('Invalid number of values');
}
return method.call(values, predicate);
};
function any(predicate) {
return predicateOnArray(Array.prototype.some, predicate, arguments);
}
is.any = any;
function all(predicate) {
return predicateOnArray(Array.prototype.every, predicate, arguments);
}
is.all = all;
// tslint:enable:only-arrow-functions no-function-expression
})(is || (is = {}));
// Some few keywords are reserved, but we'll populate them for Node.js users
// See https://github.com/Microsoft/TypeScript/issues/2536
Object.defineProperties(is, {
class: {
value: is.class_
},
function: {
value: is.function_
},
null: {
value: is.null_
}
});
exports.default = is;
// For CommonJS default export support
module.exports = is;
module.exports.default = is;

File diff suppressed because one or more lines are too long

View File

@ -1,59 +0,0 @@
/// <reference types="node" />
declare function is(value: any): string;
declare namespace is {
const undefined: (value: any) => boolean;
const string: (value: any) => boolean;
const number: (value: any) => boolean;
const function_: (value: any) => boolean;
const null_: (value: any) => boolean;
const class_: (value: any) => any;
const boolean: (value: any) => boolean;
const symbol: (value: any) => boolean;
const array: (arg: any) => arg is any[];
const buffer: (obj: any) => obj is Buffer;
const nullOrUndefined: (value: any) => boolean;
const object: (value: any) => boolean;
const iterable: (value: any) => boolean;
const generator: (value: any) => boolean;
const nativePromise: (value: any) => boolean;
const promise: (value: any) => boolean;
const generatorFunction: (value: any) => boolean;
const asyncFunction: (value: any) => boolean;
const regExp: (value: any) => boolean;
const date: (value: any) => boolean;
const error: (value: any) => boolean;
const map: (value: any) => boolean;
const set: (value: any) => boolean;
const weakMap: (value: any) => boolean;
const weakSet: (value: any) => boolean;
const int8Array: (value: any) => boolean;
const uint8Array: (value: any) => boolean;
const uint8ClampedArray: (value: any) => boolean;
const int16Array: (value: any) => boolean;
const uint16Array: (value: any) => boolean;
const int32Array: (value: any) => boolean;
const uint32Array: (value: any) => boolean;
const float32Array: (value: any) => boolean;
const float64Array: (value: any) => boolean;
const arrayBuffer: (value: any) => boolean;
const sharedArrayBuffer: (value: any) => boolean;
const truthy: (value: any) => boolean;
const falsy: (value: any) => boolean;
const nan: (value: any) => boolean;
const primitive: (value: any) => boolean;
const integer: (value: any) => boolean;
const safeInteger: (value: any) => boolean;
const plainObject: (value: any) => boolean;
const typedArray: (value: any) => boolean;
const arrayLike: (value: any) => boolean;
const inRange: (value: number, range: number | number[]) => boolean;
const domElement: (value: any) => boolean;
const infinite: (value: any) => boolean;
const even: (rem: number) => boolean;
const odd: (rem: number) => boolean;
const empty: (value: any) => boolean;
const emptyOrWhitespace: (value: any) => boolean;
function any(...predicate: any[]): any;
function all(...predicate: any[]): any;
}
export default is;

View File

@ -1,182 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const toString = Object.prototype.toString;
const getObjectType = (value) => toString.call(value).slice(8, -1);
const isOfType = (type) => (value) => typeof value === type;
const isObjectOfType = (type) => (value) => getObjectType(value) === type;
function is(value) {
if (value === null) {
return 'null';
}
if (value === true || value === false) {
return 'boolean';
}
const type = typeof value;
if (type === 'undefined') {
return 'undefined';
}
if (type === 'string') {
return 'string';
}
if (type === 'number') {
return 'number';
}
if (type === 'symbol') {
return 'symbol';
}
if (is.function_(value)) {
return 'Function';
}
if (Array.isArray(value)) {
return 'Array';
}
if (Buffer.isBuffer(value)) {
return 'Buffer';
}
const tagType = getObjectType(value);
if (tagType) {
return tagType;
}
if (value instanceof String || value instanceof Boolean || value instanceof Number) {
throw new TypeError('Please don\'t use object wrappers for primitive types');
}
return 'Object';
}
(function (is) {
const isObject = (value) => typeof value === 'object';
is.undefined = isOfType('undefined');
is.string = isOfType('string');
is.number = isOfType('number');
is.function_ = isOfType('function');
is.null_ = (value) => value === null;
is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
is.boolean = (value) => value === true || value === false;
is.symbol = isOfType('symbol');
is.array = Array.isArray;
is.buffer = Buffer.isBuffer;
is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value));
is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]);
is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw);
is.nativePromise = isObjectOfType('Promise');
const hasPromiseAPI = (value) => !is.null_(value) &&
isObject(value) &&
is.function_(value.then) &&
is.function_(value.catch);
is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);
const isFunctionOfType = (type) => (value) => is.function_(value) && is.function_(value.constructor) && value.constructor.name === type;
is.generatorFunction = isFunctionOfType('GeneratorFunction');
is.asyncFunction = isFunctionOfType('AsyncFunction');
is.regExp = isObjectOfType('RegExp');
is.date = isObjectOfType('Date');
is.error = isObjectOfType('Error');
is.map = isObjectOfType('Map');
is.set = isObjectOfType('Set');
is.weakMap = isObjectOfType('WeakMap');
is.weakSet = isObjectOfType('WeakSet');
is.int8Array = isObjectOfType('Int8Array');
is.uint8Array = isObjectOfType('Uint8Array');
is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');
is.int16Array = isObjectOfType('Int16Array');
is.uint16Array = isObjectOfType('Uint16Array');
is.int32Array = isObjectOfType('Int32Array');
is.uint32Array = isObjectOfType('Uint32Array');
is.float32Array = isObjectOfType('Float32Array');
is.float64Array = isObjectOfType('Float64Array');
is.arrayBuffer = isObjectOfType('ArrayBuffer');
is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');
is.truthy = (value) => Boolean(value);
is.falsy = (value) => !value;
is.nan = (value) => Number.isNaN(value);
const primitiveTypes = new Set([
'undefined',
'string',
'number',
'boolean',
'symbol'
]);
is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value);
is.integer = (value) => Number.isInteger(value);
is.safeInteger = (value) => Number.isSafeInteger(value);
is.plainObject = (value) => {
let prototype;
return getObjectType(value) === 'Object' &&
(prototype = Object.getPrototypeOf(value), prototype === null ||
prototype === Object.getPrototypeOf({}));
};
const typedArrayTypes = new Set([
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
]);
is.typedArray = (value) => typedArrayTypes.has(getObjectType(value));
const isValidLength = (value) => is.safeInteger(value) && value > -1;
is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
is.inRange = (value, range) => {
if (is.number(range)) {
return value >= Math.min(0, range) && value <= Math.max(range, 0);
}
if (is.array(range) && range.length === 2) {
return value >= Math.min.apply(null, range) && value <= Math.max.apply(null, range);
}
throw new TypeError(`Invalid range: ${util.inspect(range)}`);
};
const NODE_TYPE_ELEMENT = 1;
const DOM_PROPERTIES_TO_CHECK = [
'innerHTML',
'ownerDocument',
'style',
'attributes',
'nodeValue'
];
is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) &&
!is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value);
is.infinite = (value) => value === Infinity || value === -Infinity;
const isAbsoluteMod2 = (value) => (rem) => is.integer(rem) && Math.abs(rem % 2) === value;
is.even = isAbsoluteMod2(0);
is.odd = isAbsoluteMod2(1);
const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false;
const isEmptyStringOrArray = (value) => (is.string(value) || is.array(value)) && value.length === 0;
const isEmptyObject = (value) => !is.map(value) && !is.set(value) && is.object(value) && Object.keys(value).length === 0;
const isEmptyMapOrSet = (value) => (is.map(value) || is.set(value)) && value.size === 0;
is.empty = (value) => is.falsy(value) || isEmptyStringOrArray(value) || isEmptyObject(value) || isEmptyMapOrSet(value);
is.emptyOrWhitespace = (value) => is.empty(value) || isWhiteSpaceString(value);
const predicateOnArray = (method, predicate, args) => {
const values = Array.prototype.slice.call(args, 1);
if (is.function_(predicate) === false) {
throw new TypeError(`Invalid predicate: ${util.inspect(predicate)}`);
}
if (values.length === 0) {
throw new TypeError('Invalid number of values');
}
return method.call(values, predicate);
};
function any(predicate) {
return predicateOnArray(Array.prototype.some, predicate, arguments);
}
is.any = any;
function all(predicate) {
return predicateOnArray(Array.prototype.every, predicate, arguments);
}
is.all = all;
})(is || (is = {}));
Object.defineProperties(is, {
class: {
value: is.class_
},
function: {
value: is.function_
},
null: {
value: is.null_
}
});
exports.default = is;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,622 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const ava_1 = require("ava");
const jsdom_1 = require("jsdom");
const __1 = require("..");
const isNode8orHigher = Number(process.versions.node.split('.')[0]) >= 8;
class ErrorSubclassFixture extends Error {
}
const document = jsdom_1.jsdom();
const createDomElement = (el) => document.createElement(el);
const types = new Map([
['undefined', {
is: __1.default.undefined,
fixtures: [
undefined
]
}],
['null', {
is: __1.default.null_,
fixtures: [
null
]
}],
['string', {
is: __1.default.string,
fixtures: [
'🦄',
'hello world',
''
]
}],
['number', {
is: __1.default.number,
fixtures: [
6,
1.4,
0,
-0,
Infinity,
-Infinity
]
}],
['boolean', {
is: __1.default.boolean,
fixtures: [
true, false
]
}],
['symbol', {
is: __1.default.symbol,
fixtures: [
Symbol('🦄')
]
}],
['array', {
is: __1.default.array,
fixtures: [
[1, 2],
new Array(2)
]
}],
['function', {
is: __1.default.function_,
fixtures: [
function foo() { },
function () { },
() => { },
function () {
return __awaiter(this, void 0, void 0, function* () { });
},
function* () { }
]
}],
['buffer', {
is: __1.default.buffer,
fixtures: [
Buffer.from('🦄')
]
}],
['object', {
is: __1.default.object,
fixtures: [
{ x: 1 },
Object.create({ x: 1 })
]
}],
['regExp', {
is: __1.default.regExp,
fixtures: [
/\w/,
new RegExp('\\w')
]
}],
['date', {
is: __1.default.date,
fixtures: [
new Date()
]
}],
['error', {
is: __1.default.error,
fixtures: [
new Error('🦄'),
new ErrorSubclassFixture()
]
}],
['nativePromise', {
is: __1.default.nativePromise,
fixtures: [
Promise.resolve(),
]
}],
['promise', {
is: __1.default.promise,
fixtures: [
{ then() { }, catch() { } }
]
}],
['generator', {
is: __1.default.generator,
fixtures: [
(function* () { yield 4; })()
]
}],
['generatorFunction', {
is: __1.default.generatorFunction,
fixtures: [
function* () { yield 4; }
]
}],
['asyncFunction', {
is: __1.default.asyncFunction,
fixtures: [
function () {
return __awaiter(this, void 0, void 0, function* () { });
},
() => __awaiter(this, void 0, void 0, function* () { })
]
}],
['map', {
is: __1.default.map,
fixtures: [
new Map()
]
}],
['set', {
is: __1.default.set,
fixtures: [
new Set()
]
}],
['weakSet', {
is: __1.default.weakSet,
fixtures: [
new WeakSet()
]
}],
['weakMap', {
is: __1.default.weakMap,
fixtures: [
new WeakMap()
]
}],
['int8Array', {
is: __1.default.int8Array,
fixtures: [
new Int8Array(0)
]
}],
['uint8Array', {
is: __1.default.uint8Array,
fixtures: [
new Uint8Array(0)
]
}],
['uint8ClampedArray', {
is: __1.default.uint8ClampedArray,
fixtures: [
new Uint8ClampedArray(0)
]
}],
['int16Array', {
is: __1.default.int16Array,
fixtures: [
new Int16Array(0)
]
}],
['uint16Array', {
is: __1.default.uint16Array,
fixtures: [
new Uint16Array(0)
]
}],
['int32Array', {
is: __1.default.int32Array,
fixtures: [
new Int32Array(0)
]
}],
['uint32Array', {
is: __1.default.uint32Array,
fixtures: [
new Uint32Array(0)
]
}],
['float32Array', {
is: __1.default.float32Array,
fixtures: [
new Float32Array(0)
]
}],
['float64Array', {
is: __1.default.float64Array,
fixtures: [
new Float64Array(0)
]
}],
['arrayBuffer', {
is: __1.default.arrayBuffer,
fixtures: [
new ArrayBuffer(10)
]
}],
['nan', {
is: __1.default.nan,
fixtures: [
NaN,
Number.NaN
]
}],
['nullOrUndefined', {
is: __1.default.nullOrUndefined,
fixtures: [
null,
undefined
]
}],
['plainObject', {
is: __1.default.plainObject,
fixtures: [
{ x: 1 },
Object.create(null),
new Object()
]
}],
['integer', {
is: __1.default.integer,
fixtures: [
6
]
}],
['safeInteger', {
is: __1.default.safeInteger,
fixtures: [
Math.pow(2, 53) - 1,
-Math.pow(2, 53) + 1
]
}],
['domElement', {
is: __1.default.domElement,
fixtures: [
'div',
'input',
'span',
'img',
'canvas',
'script'
].map(createDomElement)
}
], ['non-domElements', {
is: value => !__1.default.domElement(value),
fixtures: [
document.createTextNode('data'),
document.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'),
document.createComment('This is a comment'),
document,
document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'),
document.createDocumentFragment()
]
}],
['infinite', {
is: __1.default.infinite,
fixtures: [
Infinity,
-Infinity
]
}]
]);
const testType = (t, type, exclude) => {
const testData = types.get(type);
if (testData === undefined) {
t.fail(`is.${type} not defined`);
return;
}
const { is } = testData;
for (const [key, { fixtures }] of types) {
if (exclude && exclude.indexOf(key) !== -1) {
continue;
}
const assert = key === type ? t.true.bind(t) : t.false.bind(t);
for (const fixture of fixtures) {
assert(is(fixture), `Value: ${util.inspect(fixture)}`);
}
}
};
ava_1.default('is', t => {
t.is(__1.default(null), 'null');
t.is(__1.default(undefined), 'undefined');
});
ava_1.default('is.undefined', t => {
testType(t, 'undefined', ['nullOrUndefined']);
});
ava_1.default('is.null', t => {
testType(t, 'null', ['nullOrUndefined']);
});
ava_1.default('is.string', t => {
testType(t, 'string');
});
ava_1.default('is.number', t => {
testType(t, 'number', ['nan', 'integer', 'safeInteger', 'infinite']);
});
ava_1.default('is.boolean', t => {
testType(t, 'boolean');
});
ava_1.default('is.symbol', t => {
testType(t, 'symbol');
});
ava_1.default('is.array', t => {
testType(t, 'array');
});
ava_1.default('is.function', t => {
testType(t, 'function', ['generatorFunction', 'asyncFunction']);
});
ava_1.default('is.buffer', t => {
testType(t, 'buffer');
});
ava_1.default('is.object', t => {
const testData = types.get('object');
if (testData === undefined) {
t.fail('is.object not defined');
return;
}
for (const el of testData.fixtures) {
t.true(__1.default.object(el));
}
});
ava_1.default('is.regExp', t => {
testType(t, 'regExp');
});
ava_1.default('is.date', t => {
testType(t, 'date');
});
ava_1.default('is.error', t => {
testType(t, 'error');
});
if (isNode8orHigher) {
ava_1.default('is.nativePromise', t => {
testType(t, 'nativePromise');
});
ava_1.default('is.promise', t => {
testType(t, 'promise', ['nativePromise']);
});
}
ava_1.default('is.generator', t => {
testType(t, 'generator');
});
ava_1.default('is.generatorFunction', t => {
testType(t, 'generatorFunction', ['function']);
});
ava_1.default('is.map', t => {
testType(t, 'map');
});
ava_1.default('is.set', t => {
testType(t, 'set');
});
ava_1.default('is.weakMap', t => {
testType(t, 'weakMap');
});
ava_1.default('is.weakSet', t => {
testType(t, 'weakSet');
});
ava_1.default('is.int8Array', t => {
testType(t, 'int8Array');
});
ava_1.default('is.uint8Array', t => {
testType(t, 'uint8Array', ['buffer']);
});
ava_1.default('is.uint8ClampedArray', t => {
testType(t, 'uint8ClampedArray');
});
ava_1.default('is.int16Array', t => {
testType(t, 'int16Array');
});
ava_1.default('is.uint16Array', t => {
testType(t, 'uint16Array');
});
ava_1.default('is.int32Array', t => {
testType(t, 'int32Array');
});
ava_1.default('is.uint32Array', t => {
testType(t, 'uint32Array');
});
ava_1.default('is.float32Array', t => {
testType(t, 'float32Array');
});
ava_1.default('is.float64Array', t => {
testType(t, 'float64Array');
});
ava_1.default('is.arrayBuffer', t => {
testType(t, 'arrayBuffer');
});
ava_1.default('is.dataView', t => {
testType(t, 'arrayBuffer');
});
ava_1.default('is.truthy', t => {
t.true(__1.default.truthy('unicorn'));
t.true(__1.default.truthy('🦄'));
t.true(__1.default.truthy(new Set()));
t.true(__1.default.truthy(Symbol('🦄')));
t.true(__1.default.truthy(true));
});
ava_1.default('is.falsy', t => {
t.true(__1.default.falsy(false));
t.true(__1.default.falsy(0));
t.true(__1.default.falsy(''));
t.true(__1.default.falsy(null));
t.true(__1.default.falsy(undefined));
t.true(__1.default.falsy(NaN));
});
ava_1.default('is.nan', t => {
testType(t, 'nan');
});
ava_1.default('is.nullOrUndefined', t => {
testType(t, 'nullOrUndefined', ['undefined', 'null']);
});
ava_1.default('is.primitive', t => {
const primitives = [
undefined,
null,
'🦄',
6,
Infinity,
-Infinity,
true,
false,
Symbol('🦄')
];
for (const el of primitives) {
t.true(__1.default.primitive(el));
}
});
ava_1.default('is.integer', t => {
testType(t, 'integer', ['number', 'safeInteger']);
t.false(__1.default.integer(1.4));
});
ava_1.default('is.safeInteger', t => {
testType(t, 'safeInteger', ['number', 'integer']);
t.false(__1.default.safeInteger(Math.pow(2, 53)));
t.false(__1.default.safeInteger(-Math.pow(2, 53)));
});
ava_1.default('is.plainObject', t => {
testType(t, 'plainObject', ['object', 'promise']);
});
ava_1.default('is.iterable', t => {
t.true(__1.default.iterable(''));
t.true(__1.default.iterable([]));
t.true(__1.default.iterable(new Map()));
t.false(__1.default.iterable(null));
t.false(__1.default.iterable(undefined));
t.false(__1.default.iterable(0));
t.false(__1.default.iterable(NaN));
t.false(__1.default.iterable(Infinity));
t.false(__1.default.iterable({}));
});
ava_1.default('is.class', t => {
class Foo {
}
const classDeclarations = [
Foo,
class Bar extends Foo {
}
];
for (const x of classDeclarations) {
t.true(__1.default.class_(x));
}
});
ava_1.default('is.typedArray', t => {
const typedArrays = [
new Int8Array(0),
new Uint8Array(0),
new Uint8ClampedArray(0),
new Uint16Array(0),
new Int32Array(0),
new Uint32Array(0),
new Float32Array(0),
new Float64Array(0)
];
for (const el of typedArrays) {
t.true(__1.default.typedArray(el));
}
t.false(__1.default.typedArray(new ArrayBuffer(1)));
t.false(__1.default.typedArray([]));
t.false(__1.default.typedArray({}));
});
ava_1.default('is.arrayLike', t => {
(() => {
t.true(__1.default.arrayLike(arguments));
})();
t.true(__1.default.arrayLike([]));
t.true(__1.default.arrayLike('unicorn'));
t.false(__1.default.arrayLike({}));
t.false(__1.default.arrayLike(() => { }));
t.false(__1.default.arrayLike(new Map()));
});
ava_1.default('is.inRange', t => {
const x = 3;
t.true(__1.default.inRange(x, [0, 5]));
t.true(__1.default.inRange(x, [5, 0]));
t.true(__1.default.inRange(x, [-5, 5]));
t.true(__1.default.inRange(x, [5, -5]));
t.false(__1.default.inRange(x, [4, 8]));
t.true(__1.default.inRange(-7, [-5, -10]));
t.true(__1.default.inRange(-5, [-5, -10]));
t.true(__1.default.inRange(-10, [-5, -10]));
t.true(__1.default.inRange(x, 10));
t.true(__1.default.inRange(0, 0));
t.true(__1.default.inRange(-2, -3));
t.false(__1.default.inRange(x, 2));
t.false(__1.default.inRange(-3, -2));
t.throws(() => {
__1.default.inRange(0, []);
});
t.throws(() => {
__1.default.inRange(0, [5]);
});
t.throws(() => {
__1.default.inRange(0, [1, 2, 3]);
});
});
ava_1.default('is.domElement', t => {
testType(t, 'domElement');
t.false(__1.default.domElement({ nodeType: 1, nodeName: 'div' }));
});
ava_1.default('is.infinite', t => {
testType(t, 'infinite', ['number']);
});
ava_1.default('is.even', t => {
for (const el of [-6, 2, 4]) {
t.true(__1.default.even(el));
}
for (const el of [-3, 1, 5]) {
t.false(__1.default.even(el));
}
});
ava_1.default('is.odd', t => {
for (const el of [-5, 7, 13]) {
t.true(__1.default.odd(el));
}
for (const el of [-8, 8, 10]) {
t.false(__1.default.odd(el));
}
});
ava_1.default('is.empty', t => {
t.true(__1.default.empty(null));
t.true(__1.default.empty(undefined));
t.true(__1.default.empty(false));
t.false(__1.default.empty(true));
t.true(__1.default.empty(''));
t.false(__1.default.empty('🦄'));
t.true(__1.default.empty([]));
t.false(__1.default.empty(['🦄']));
t.true(__1.default.empty({}));
t.false(__1.default.empty({ unicorn: '🦄' }));
const tempMap = new Map();
t.true(__1.default.empty(tempMap));
tempMap.set('unicorn', '🦄');
t.false(__1.default.empty(tempMap));
const tempSet = new Set();
t.true(__1.default.empty(tempSet));
tempSet.add(1);
t.false(__1.default.empty(tempSet));
});
ava_1.default('is.emptyOrWhitespace', t => {
t.true(__1.default.emptyOrWhitespace(''));
t.true(__1.default.emptyOrWhitespace(' '));
t.false(__1.default.emptyOrWhitespace('🦄'));
t.false(__1.default.emptyOrWhitespace('unicorn'));
});
ava_1.default('is.any', t => {
t.true(__1.default.any(__1.default.string, {}, true, '🦄'));
t.true(__1.default.any(__1.default.object, false, {}, 'unicorns'));
t.false(__1.default.any(__1.default.boolean, '🦄', [], 3));
t.false(__1.default.any(__1.default.integer, true, 'lol', {}));
t.throws(() => {
__1.default.any(null, true);
});
t.throws(() => {
__1.default.any(__1.default.string);
});
});
ava_1.default('is.all', t => {
t.true(__1.default.all(__1.default.object, {}, new Set(), new Map()));
t.true(__1.default.all(__1.default.boolean, true, false));
t.false(__1.default.all(__1.default.string, '🦄', []));
t.false(__1.default.all(__1.default.set, new Map(), {}));
t.throws(() => {
__1.default.all(null, true);
});
t.throws(() => {
__1.default.all(__1.default.string);
});
});
//# sourceMappingURL=test.js.map

File diff suppressed because one or more lines are too long

View File

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

View File

@ -1,91 +0,0 @@
{
"_from": "@sindresorhus/is@0.7.0",
"_id": "@sindresorhus/is@0.7.0",
"_inBundle": false,
"_integrity": "sha512-ONhaKPIufzzrlNbqtWFFd+jlnemX6lJAgq9ZeiZtS7I1PIf/la7CW4m83rTXRnVnsMbW2k56pGYu7AUFJD9Pow==",
"_location": "/@sindresorhus/is",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@sindresorhus/is@0.7.0",
"name": "@sindresorhus/is",
"escapedName": "@sindresorhus%2fis",
"scope": "@sindresorhus",
"rawSpec": "0.7.0",
"saveSpec": null,
"fetchSpec": "0.7.0"
},
"_requiredBy": [
"/got"
],
"_resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.7.0.tgz",
"_spec": "0.7.0",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/is/issues"
},
"description": "Type check values: `is.string('🦄') //=> true`",
"devDependencies": {
"@types/jsdom": "^2.0.31",
"@types/node": "^8.0.47",
"@types/tempy": "^0.1.0",
"ava": "*",
"del-cli": "^1.1.0",
"jsdom": "^9.12.0",
"tempy": "^0.2.1",
"tslint": "^5.8.0",
"tslint-xo": "^0.3.0",
"typescript": "^2.6.1"
},
"engines": {
"node": ">=4"
},
"files": [
"dist"
],
"homepage": "https://github.com/sindresorhus/is#readme",
"keywords": [
"type",
"types",
"is",
"check",
"checking",
"validate",
"validation",
"utility",
"util",
"typeof",
"instanceof",
"object",
"assert",
"assertion",
"test",
"kind",
"primitive",
"verify",
"compare"
],
"license": "MIT",
"main": "dist/index.js",
"name": "@sindresorhus/is",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/is.git"
},
"scripts": {
"build": "tsc",
"lint": "tslint --format stylish --project .",
"prepublish": "npm run build && del dist/tests",
"test": "npm run lint && npm run build && ava dist/tests"
},
"types": "dist/index.d.ts",
"version": "0.7.0"
}

View File

@ -1,323 +0,0 @@
# is [![Build Status](https://travis-ci.org/sindresorhus/is.svg?branch=master)](https://travis-ci.org/sindresorhus/is)
> Type check values: `is.string('🦄') //=> true`
<img src="header.gif" width="182" align="right">
## Install
```
$ npm install @sindresorhus/is
```
## Usage
```js
const is = require('@sindresorhus/is');
is('🦄');
//=> 'string'
is(new Map());
//=> 'Map'
is.number(6);
//=> true
```
## API
### is(value)
Returns the type of `value`.
Primitives are lowercase and object types are camelcase.
Example:
- `'undefined'`
- `'null'`
- `'string'`
- `'symbol'`
- `'Array'`
- `'Function'`
- `'Object'`
Note: It will throw if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`.
### is.{method}
All the below methods accept a value and returns a boolean for whether the value is of the desired type.
#### Primitives
##### .undefined(value)
##### .null(value)
##### .string(value)
##### .number(value)
##### .boolean(value)
##### .symbol(value)
#### Built-in types
##### .array(value)
##### .function(value)
##### .buffer(value)
##### .object(value)
Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions).
##### .regExp(value)
##### .date(value)
##### .error(value)
##### .nativePromise(value)
##### .promise(value)
Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too.
##### .generator(value)
Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`.
##### .generatorFunction(value)
##### .asyncFunction(value)
Returns `true` for any `async` function that can be called with the `await` operator.
```js
is.asyncFunction(async () => {});
// => true
is.asyncFunction(() => {});
// => false
```
##### .boundFunction(value)
Returns `true` for any `bound` function.
```js
is.boundFunction(() => {});
// => true
is.boundFunction(function () {}.bind(null));
// => true
is.boundFunction(function () {});
// => false
```
##### .map(value)
##### .set(value)
##### .weakMap(value)
##### .weakSet(value)
#### Typed arrays
##### .int8Array(value)
##### .uint8Array(value)
##### .uint8ClampedArray(value)
##### .int16Array(value)
##### .uint16Array(value)
##### .int32Array(value)
##### .uint32Array(value)
##### .float32Array(value)
##### .float64Array(value)
#### Structured data
##### .arrayBuffer(value)
##### .sharedArrayBuffer(value)
##### .dataView(value)
#### Miscellaneous
##### .directInstanceOf(value, class)
Returns `true` if `value` is a direct instance of `class`.
```js
is.directInstanceOf(new Error(), Error);
//=> true
class UnicornError extends Error {};
is.directInstanceOf(new UnicornError(), Error);
//=> false
```
##### .truthy(value)
Returns `true` for all values that evaluate to true in a boolean context:
```js
is.truthy('🦄');
//=> true
is.truthy(undefined);
//=> false
```
##### .falsy(value)
Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `NaN`.
##### .nan(value)
##### .nullOrUndefined(value)
##### .primitive(value)
JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`.
##### .integer(value)
##### .safeInteger(value)
Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
##### .plainObject(value)
An object is plain if it's created by either `{}`, `new Object()`, or `Object.create(null)`.
##### .iterable(value)
##### .class(value)
Returns `true` for instances created by a ES2015 class.
##### .typedArray(value)
##### .arrayLike(value)
A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0.
```js
is.arrayLike(document.forms);
//=> true
function () {
is.arrayLike(arguments);
//=> true
}
```
##### .inRange(value, range)
Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order.
```js
is.inRange(3, [0, 5]);
is.inRange(3, [5, 0]);
is.inRange(0, [-2, 2]);
```
##### .inRange(value, upperBound)
Check if `value` (number) is in the range of `0` to `upperBound`.
```js
is.inRange(3, 10);
```
##### .domElement(value)
Returns `true` if `value` is a DOM Element.
##### .nodeStream(value)
Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html).
```js
const fs = require('fs');
is.nodeStream(fs.createReadStream('unicorn.png'));
//=> true
```
##### .infinite(value)
Check if `value` is `Infinity` or `-Infinity`.
##### .even(value)
Returns `true` if `value` is an even integer.
##### .odd(value)
Returns `true` if `value` is an odd integer.
##### .empty(value)
Returns `true` if `value` is falsy or an empty string, array, object, map, or set.
##### .emptyOrWhitespace(value)
Returns `true` if `is.empty(value)` or a string that is all whitespace.
##### .any(predicate, ...values)
Returns `true` if **any** of the input `values` returns true in the `predicate`:
```js
is.any(is.string, {}, true, '🦄');
//=> true
is.any(is.boolean, 'unicorns', [], new Map());
//=> false
```
##### .all(predicate, ...values)
Returns `true` if **all** of the input `values` returns true in the `predicate`:
```js
is.all(is.object, {}, new Map(), new Set());
//=> true
is.all(is.string, '🦄', [], 'unicorns');
//=> false
```
## FAQ
### Why yet another type checking module?
There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:
- Includes both type methods and ability to get the type
- Types of primitives returned as lowercase and object types as camelcase
- Covers all built-ins
- Unsurprising behavior
- Well-maintained
- Comprehensive test suite
For the ones I found, pick 3 of these.
The most common mistakes I noticed in these modules was using `instanceof` for type checking, forgetting that functions are objects, and omitting `symbol` as a primitive.
## Related
- [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream
- [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable
- [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array
- [is-ip](https://github.com/sindresorhus/is-ip) - Check if a string is an IP address
- [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted
- [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor
- [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty
- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data
- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji
## Created by
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Giora Guttsait](https://github.com/gioragutt)
- [Brandon Smith](https://github.com/brandon93s)
## License
MIT

18
node_modules/archive-type/index.js generated vendored
View File

@ -1,18 +0,0 @@
'use strict';
const fileType = require('file-type');
const exts = new Set([
'7z',
'bz2',
'gz',
'rar',
'tar',
'zip',
'xz',
'gz'
]);
module.exports = input => {
const ret = fileType(input);
return exts.has(ret && ret.ext) ? ret : null;
};

21
node_modules/archive-type/license generated vendored
View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Kevin Mårtensson <kevinmartensson@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.

View File

@ -1,545 +0,0 @@
'use strict';
module.exports = input => {
const buf = new Uint8Array(input);
if (!(buf && buf.length > 1)) {
return null;
}
const check = (header, opts) => {
opts = Object.assign({
offset: 0
}, opts);
for (let i = 0; i < header.length; i++) {
if (header[i] !== buf[i + opts.offset]) {
return false;
}
}
return true;
};
if (check([0xFF, 0xD8, 0xFF])) {
return {
ext: 'jpg',
mime: 'image/jpeg'
};
}
if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
return {
ext: 'png',
mime: 'image/png'
};
}
if (check([0x47, 0x49, 0x46])) {
return {
ext: 'gif',
mime: 'image/gif'
};
}
if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) {
return {
ext: 'webp',
mime: 'image/webp'
};
}
if (check([0x46, 0x4C, 0x49, 0x46])) {
return {
ext: 'flif',
mime: 'image/flif'
};
}
// Needs to be before `tif` check
if (
(check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) &&
check([0x43, 0x52], {offset: 8})
) {
return {
ext: 'cr2',
mime: 'image/x-canon-cr2'
};
}
if (
check([0x49, 0x49, 0x2A, 0x0]) ||
check([0x4D, 0x4D, 0x0, 0x2A])
) {
return {
ext: 'tif',
mime: 'image/tiff'
};
}
if (check([0x42, 0x4D])) {
return {
ext: 'bmp',
mime: 'image/bmp'
};
}
if (check([0x49, 0x49, 0xBC])) {
return {
ext: 'jxr',
mime: 'image/vnd.ms-photo'
};
}
if (check([0x38, 0x42, 0x50, 0x53])) {
return {
ext: 'psd',
mime: 'image/vnd.adobe.photoshop'
};
}
// Needs to be before the `zip` check
if (
check([0x50, 0x4B, 0x3, 0x4]) &&
check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30})
) {
return {
ext: 'epub',
mime: 'application/epub+zip'
};
}
// Needs to be before `zip` check
// Assumes signed `.xpi` from addons.mozilla.org
if (
check([0x50, 0x4B, 0x3, 0x4]) &&
check([0x4D, 0x45, 0x54, 0x41, 0x2D, 0x49, 0x4E, 0x46, 0x2F, 0x6D, 0x6F, 0x7A, 0x69, 0x6C, 0x6C, 0x61, 0x2E, 0x72, 0x73, 0x61], {offset: 30})
) {
return {
ext: 'xpi',
mime: 'application/x-xpinstall'
};
}
if (
check([0x50, 0x4B]) &&
(buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) &&
(buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)
) {
return {
ext: 'zip',
mime: 'application/zip'
};
}
if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) {
return {
ext: 'tar',
mime: 'application/x-tar'
};
}
if (
check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) &&
(buf[6] === 0x0 || buf[6] === 0x1)
) {
return {
ext: 'rar',
mime: 'application/x-rar-compressed'
};
}
if (check([0x1F, 0x8B, 0x8])) {
return {
ext: 'gz',
mime: 'application/gzip'
};
}
if (check([0x42, 0x5A, 0x68])) {
return {
ext: 'bz2',
mime: 'application/x-bzip2'
};
}
if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
return {
ext: '7z',
mime: 'application/x-7z-compressed'
};
}
if (check([0x78, 0x01])) {
return {
ext: 'dmg',
mime: 'application/x-apple-diskimage'
};
}
if (
(
check([0x0, 0x0, 0x0]) &&
(buf[3] === 0x18 || buf[3] === 0x20) &&
check([0x66, 0x74, 0x79, 0x70], {offset: 4})
) ||
check([0x33, 0x67, 0x70, 0x35]) ||
(
check([0x0, 0x0, 0x0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32]) &&
check([0x6D, 0x70, 0x34, 0x31, 0x6D, 0x70, 0x34, 0x32, 0x69, 0x73, 0x6F, 0x6D], {offset: 16})
) ||
check([0x0, 0x0, 0x0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6F, 0x6D]) ||
check([0x0, 0x0, 0x0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, 0x32, 0x0, 0x0, 0x0, 0x0])
) {
return {
ext: 'mp4',
mime: 'video/mp4'
};
}
if (check([0x0, 0x0, 0x0, 0x1C, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x56])) {
return {
ext: 'm4v',
mime: 'video/x-m4v'
};
}
if (check([0x4D, 0x54, 0x68, 0x64])) {
return {
ext: 'mid',
mime: 'audio/midi'
};
}
// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
if (check([0x1A, 0x45, 0xDF, 0xA3])) {
const sliced = buf.subarray(4, 4 + 4096);
const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);
if (idPos >= 0) {
const docTypePos = idPos + 3;
const findDocType = type => Array.from(type).every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));
if (findDocType('matroska')) {
return {
ext: 'mkv',
mime: 'video/x-matroska'
};
}
if (findDocType('webm')) {
return {
ext: 'webm',
mime: 'video/webm'
};
}
}
}
if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) ||
check([0x66, 0x72, 0x65, 0x65], {offset: 4}) ||
check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) ||
check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG
check([0x77, 0x69, 0x64, 0x65], {offset: 4})) {
return {
ext: 'mov',
mime: 'video/quicktime'
};
}
if (
check([0x52, 0x49, 0x46, 0x46]) &&
check([0x41, 0x56, 0x49], {offset: 8})
) {
return {
ext: 'avi',
mime: 'video/x-msvideo'
};
}
if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
return {
ext: 'wmv',
mime: 'video/x-ms-wmv'
};
}
if (check([0x0, 0x0, 0x1, 0xBA])) {
return {
ext: 'mpg',
mime: 'video/mpeg'
};
}
if (
check([0x49, 0x44, 0x33]) ||
check([0xFF, 0xFB])
) {
return {
ext: 'mp3',
mime: 'audio/mpeg'
};
}
if (
check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) ||
check([0x4D, 0x34, 0x41, 0x20])
) {
return {
ext: 'm4a',
mime: 'audio/m4a'
};
}
// Needs to be before `ogg` check
if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) {
return {
ext: 'opus',
mime: 'audio/opus'
};
}
if (check([0x4F, 0x67, 0x67, 0x53])) {
return {
ext: 'ogg',
mime: 'audio/ogg'
};
}
if (check([0x66, 0x4C, 0x61, 0x43])) {
return {
ext: 'flac',
mime: 'audio/x-flac'
};
}
if (
check([0x52, 0x49, 0x46, 0x46]) &&
check([0x57, 0x41, 0x56, 0x45], {offset: 8})
) {
return {
ext: 'wav',
mime: 'audio/x-wav'
};
}
if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
return {
ext: 'amr',
mime: 'audio/amr'
};
}
if (check([0x25, 0x50, 0x44, 0x46])) {
return {
ext: 'pdf',
mime: 'application/pdf'
};
}
if (check([0x4D, 0x5A])) {
return {
ext: 'exe',
mime: 'application/x-msdownload'
};
}
if (
(buf[0] === 0x43 || buf[0] === 0x46) &&
check([0x57, 0x53], {offset: 1})
) {
return {
ext: 'swf',
mime: 'application/x-shockwave-flash'
};
}
if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
return {
ext: 'rtf',
mime: 'application/rtf'
};
}
if (check([0x00, 0x61, 0x73, 0x6D])) {
return {
ext: 'wasm',
mime: 'application/wasm'
};
}
if (
check([0x77, 0x4F, 0x46, 0x46]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff',
mime: 'application/font-woff'
};
}
if (
check([0x77, 0x4F, 0x46, 0x32]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff2',
mime: 'application/font-woff'
};
}
if (
check([0x4C, 0x50], {offset: 34}) &&
(
check([0x00, 0x00, 0x01], {offset: 8}) ||
check([0x01, 0x00, 0x02], {offset: 8}) ||
check([0x02, 0x00, 0x02], {offset: 8})
)
) {
return {
ext: 'eot',
mime: 'application/octet-stream'
};
}
if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
return {
ext: 'ttf',
mime: 'application/font-sfnt'
};
}
if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
return {
ext: 'otf',
mime: 'application/font-sfnt'
};
}
if (check([0x00, 0x00, 0x01, 0x00])) {
return {
ext: 'ico',
mime: 'image/x-icon'
};
}
if (check([0x46, 0x4C, 0x56, 0x01])) {
return {
ext: 'flv',
mime: 'video/x-flv'
};
}
if (check([0x25, 0x21])) {
return {
ext: 'ps',
mime: 'application/postscript'
};
}
if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
return {
ext: 'xz',
mime: 'application/x-xz'
};
}
if (check([0x53, 0x51, 0x4C, 0x69])) {
return {
ext: 'sqlite',
mime: 'application/x-sqlite3'
};
}
if (check([0x4E, 0x45, 0x53, 0x1A])) {
return {
ext: 'nes',
mime: 'application/x-nintendo-nes-rom'
};
}
if (check([0x43, 0x72, 0x32, 0x34])) {
return {
ext: 'crx',
mime: 'application/x-google-chrome-extension'
};
}
if (
check([0x4D, 0x53, 0x43, 0x46]) ||
check([0x49, 0x53, 0x63, 0x28])
) {
return {
ext: 'cab',
mime: 'application/vnd.ms-cab-compressed'
};
}
// Needs to be before `ar` check
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
return {
ext: 'deb',
mime: 'application/x-deb'
};
}
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
return {
ext: 'ar',
mime: 'application/x-unix-archive'
};
}
if (check([0xED, 0xAB, 0xEE, 0xDB])) {
return {
ext: 'rpm',
mime: 'application/x-rpm'
};
}
if (
check([0x1F, 0xA0]) ||
check([0x1F, 0x9D])
) {
return {
ext: 'Z',
mime: 'application/x-compress'
};
}
if (check([0x4C, 0x5A, 0x49, 0x50])) {
return {
ext: 'lz',
mime: 'application/x-lzip'
};
}
if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
return {
ext: 'msi',
mime: 'application/x-msi'
};
}
if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
return {
ext: 'mxf',
mime: 'application/mxf'
};
}
if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
return {
ext: 'blend',
mime: 'application/x-blender'
};
}
return null;
};

View File

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

View File

@ -1,135 +0,0 @@
{
"_from": "file-type@4.4.0",
"_id": "file-type@4.4.0",
"_inBundle": false,
"_integrity": "sha1-G2AOX8ofvcboDApwxxyNul95BsU=",
"_location": "/archive-type/file-type",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "file-type@4.4.0",
"name": "file-type",
"escapedName": "file-type",
"rawSpec": "4.4.0",
"saveSpec": null,
"fetchSpec": "4.4.0"
},
"_requiredBy": [
"/archive-type"
],
"_resolved": "https://registry.npmjs.org/file-type/-/file-type-4.4.0.tgz",
"_spec": "4.4.0",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/file-type/issues"
},
"description": "Detect the file type of a Buffer/Uint8Array",
"devDependencies": {
"ava": "*",
"read-chunk": "^2.0.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/file-type#readme",
"keywords": [
"mime",
"file",
"type",
"archive",
"image",
"img",
"pic",
"picture",
"flash",
"photo",
"video",
"type",
"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",
"mp3",
"m4a",
"ogg",
"opus",
"flac",
"wav",
"amr",
"pdf",
"epub",
"exe",
"swf",
"rtf",
"woff",
"woff2",
"eot",
"ttf",
"otf",
"ico",
"flv",
"ps",
"xz",
"sqlite",
"xpi",
"cab",
"deb",
"ar",
"rpm",
"Z",
"lz",
"msi",
"mxf",
"wasm",
"webassembly",
"blend"
],
"license": "MIT",
"name": "file-type",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/file-type.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "4.4.0"
}

View File

@ -1,154 +0,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
The file type is detected by checking the [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer.
## Install
```
$ npm install --save file-type
```
## Usage
##### Node.js
```js
const readChunk = require('read-chunk');
const fileType = require('file-type');
const buffer = readChunk.sync('unicorn.png', 0, 4100);
fileType(buffer);
//=> {ext: 'png', mime: 'image/png'}
```
Or from a remote location:
```js
const http = require('http');
const fileType = require('file-type');
const url = 'http://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif';
http.get(url, res => {
res.once('data', chunk => {
res.destroy();
console.log(fileType(chunk));
//=> {ext: 'gif', mime: 'image/gif'}
});
});
```
##### 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](http://en.wikipedia.org/wiki/Internet_media_type)
Or `null` when no match.
#### input
Type: `Buffer` `Uint8Array`
It only needs the first 4100 bytes.
## 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`](http://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)
- [`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)
- [`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)
- [`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`](http://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`](http://fileinfo.com/extension/rpm)
- [`Z`](http://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)
- [`wasm`](https://en.wikipedia.org/wiki/WebAssembly)
- [`blend`](https://wiki.blender.org/index.php/Dev:Source/Architecture/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
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -1,73 +0,0 @@
{
"_from": "archive-type@4.0.0",
"_id": "archive-type@4.0.0",
"_inBundle": false,
"_integrity": "sha1-+S5yIzBW38aWlHJ0nCZ72wRrHXA=",
"_location": "/archive-type",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "archive-type@4.0.0",
"name": "archive-type",
"escapedName": "archive-type",
"rawSpec": "4.0.0",
"saveSpec": null,
"fetchSpec": "4.0.0"
},
"_requiredBy": [
"/download"
],
"_resolved": "https://registry.npmjs.org/archive-type/-/archive-type-4.0.0.tgz",
"_spec": "4.0.0",
"author": {
"name": "Kevin Mårtensson",
"email": "kevinmartensson@gmail.com",
"url": "https://github.com/kevva"
},
"bugs": {
"url": "https://github.com/kevva/archive-type/issues"
},
"dependencies": {
"file-type": "^4.2.0"
},
"description": "Detect the archive type of a Buffer/Uint8Array",
"devDependencies": {
"ava": "*",
"pify": "^2.3.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/kevva/archive-type#readme",
"keywords": [
"7zip",
"archive",
"buffer",
"bz2",
"bzip2",
"check",
"detect",
"gz",
"gzip",
"mime",
"rar",
"zip",
"file",
"type"
],
"license": "MIT",
"name": "archive-type",
"repository": {
"type": "git",
"url": "git+https://github.com/kevva/archive-type.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "4.0.0"
}

62
node_modules/archive-type/readme.md generated vendored
View File

@ -1,62 +0,0 @@
# archive-type [![Build Status](https://travis-ci.org/kevva/archive-type.svg?branch=master)](https://travis-ci.org/kevva/archive-type)
> Detect the archive type of a Buffer/Uint8Array
## Install
```
$ npm install --save archive-type
```
## Usage
```js
const archiveType = require('archive-type');
const readChunk = require('read-chunk');
const buffer = readChunk.sync('unicorn.zip', 0, 262);
archiveType(buffer);
//=> {ext: 'zip', mime: 'application/zip'}
```
## API
### archiveType(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 no match.
#### input
Type: `Buffer` `Uint8Array`
It only needs the first 262 bytes.
## Supported file types
- `7z`
- `bz2`
- `gz`
- `rar`
- `tar`
- `zip`
- `xz`
- `gz`
## Related
- [archive-type-cli](https://github.com/kevva/archive-type-cli) - CLI for this module
## License
MIT © [Kevin Mårtensson](https://github.com/kevva)

21
node_modules/base64-js/LICENSE generated vendored
View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Jameson Little
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.

32
node_modules/base64-js/README.md generated vendored
View File

@ -1,32 +0,0 @@
base64-js
=========
`base64-js` does basic base64 encoding/decoding in pure JS.
[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js)
Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data.
Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does.
## install
With [npm](https://npmjs.org) do:
`npm install base64-js` and `var base64js = require('base64-js')`
For use in web browsers do:
`<script src="base64js.min.js"></script>`
## methods
`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument.
* `byteLength` - Takes a base64 string and returns length of byte array
* `toByteArray` - Takes a base64 string and returns a byte array
* `fromByteArray` - Takes a byte array and returns a base64 string
## license
MIT

View File

@ -1 +0,0 @@
(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.base64js=r()}})(function(){var r,e,n;return function(){function d(a,f,i){function u(n,r){if(!f[n]){if(!a[n]){var e="function"==typeof require&&require;if(!r&&e)return e(n,!0);if(v)return v(n,!0);var t=new Error("Cannot find module '"+n+"'");throw t.code="MODULE_NOT_FOUND",t}var o=f[n]={exports:{}};a[n][0].call(o.exports,function(r){var e=a[n][1][r];return u(e||r)},o,o.exports,d,a,f,i)}return f[n].exports}for(var v="function"==typeof require&&require,r=0;r<i.length;r++)u(i[r]);return u}return d}()({"/":[function(r,e,n){"use strict";n.byteLength=f;n.toByteArray=i;n.fromByteArray=p;var u=[];var v=[];var d=typeof Uint8Array!=="undefined"?Uint8Array:Array;var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var o=0,a=t.length;o<a;++o){u[o]=t[o];v[t.charCodeAt(o)]=o}v["-".charCodeAt(0)]=62;v["_".charCodeAt(0)]=63;function c(r){var e=r.length;if(e%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var n=r.indexOf("=");if(n===-1)n=e;var t=n===e?0:4-n%4;return[n,t]}function f(r){var e=c(r);var n=e[0];var t=e[1];return(n+t)*3/4-t}function h(r,e,n){return(e+n)*3/4-n}function i(r){var e;var n=c(r);var t=n[0];var o=n[1];var a=new d(h(r,t,o));var f=0;var i=o>0?t-4:t;var u;for(u=0;u<i;u+=4){e=v[r.charCodeAt(u)]<<18|v[r.charCodeAt(u+1)]<<12|v[r.charCodeAt(u+2)]<<6|v[r.charCodeAt(u+3)];a[f++]=e>>16&255;a[f++]=e>>8&255;a[f++]=e&255}if(o===2){e=v[r.charCodeAt(u)]<<2|v[r.charCodeAt(u+1)]>>4;a[f++]=e&255}if(o===1){e=v[r.charCodeAt(u)]<<10|v[r.charCodeAt(u+1)]<<4|v[r.charCodeAt(u+2)]>>2;a[f++]=e>>8&255;a[f++]=e&255}return a}function s(r){return u[r>>18&63]+u[r>>12&63]+u[r>>6&63]+u[r&63]}function l(r,e,n){var t;var o=[];for(var a=e;a<n;a+=3){t=(r[a]<<16&16711680)+(r[a+1]<<8&65280)+(r[a+2]&255);o.push(s(t))}return o.join("")}function p(r){var e;var n=r.length;var t=n%3;var o=[];var a=16383;for(var f=0,i=n-t;f<i;f+=a){o.push(l(r,f,f+a>i?i:f+a))}if(t===1){e=r[n-1];o.push(u[e>>2]+u[e<<4&63]+"==")}else if(t===2){e=(r[n-2]<<8)+r[n-1];o.push(u[e>>10]+u[e>>4&63]+u[e<<2&63]+"=")}return o.join("")}},{}]},{},[])("/")});

152
node_modules/base64-js/index.js generated vendored
View File

@ -1,152 +0,0 @@
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}

56
node_modules/base64-js/package.json generated vendored
View File

@ -1,56 +0,0 @@
{
"_from": "base64-js@1.3.1",
"_id": "base64-js@1.3.1",
"_inBundle": false,
"_integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==",
"_location": "/base64-js",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "base64-js@1.3.1",
"name": "base64-js",
"escapedName": "base64-js",
"rawSpec": "1.3.1",
"saveSpec": null,
"fetchSpec": "1.3.1"
},
"_requiredBy": [
"/buffer"
],
"_resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz",
"_spec": "1.3.1",
"author": {
"name": "T. Jameson Little",
"email": "t.jameson.little@gmail.com"
},
"bugs": {
"url": "https://github.com/beatgammit/base64-js/issues"
},
"description": "Base64 encoding/decoding in pure JS",
"devDependencies": {
"benchmark": "^2.1.4",
"browserify": "^16.3.0",
"standard": "*",
"tape": "4.x",
"uglify-js": "^3.6.0"
},
"homepage": "https://github.com/beatgammit/base64-js",
"keywords": [
"base64"
],
"license": "MIT",
"main": "index.js",
"name": "base64-js",
"repository": {
"type": "git",
"url": "git://github.com/beatgammit/base64-js.git"
},
"scripts": {
"build": "browserify -s base64js -r ./ | uglifyjs -m > base64js.min.js",
"lint": "standard",
"test": "npm run lint && npm run unit",
"unit": "tape test/*.js"
},
"version": "1.3.1"
}

59
node_modules/bl/.jshintrc generated vendored
View File

@ -1,59 +0,0 @@
{
"predef": [ ]
, "bitwise": false
, "camelcase": false
, "curly": false
, "eqeqeq": false
, "forin": false
, "immed": false
, "latedef": false
, "noarg": true
, "noempty": true
, "nonew": true
, "plusplus": false
, "quotmark": true
, "regexp": false
, "undef": true
, "unused": true
, "strict": false
, "trailing": true
, "maxlen": 120
, "asi": true
, "boss": true
, "debug": true
, "eqnull": true
, "esnext": true
, "evil": true
, "expr": true
, "funcscope": false
, "globalstrict": false
, "iterator": false
, "lastsemic": true
, "laxbreak": true
, "laxcomma": true
, "loopfunc": true
, "multistr": false
, "onecase": false
, "proto": false
, "regexdash": false
, "scripturl": true
, "smarttabs": false
, "shadow": false
, "sub": true
, "supernew": false
, "validthis": true
, "browser": true
, "couch": false
, "devel": false
, "dojo": false
, "mootools": false
, "node": true
, "nonstandard": true
, "prototypejs": false
, "rhino": false
, "worker": true
, "wsh": false
, "nomen": false
, "onevar": false
, "passfail": false
}

16
node_modules/bl/.travis.yml generated vendored
View File

@ -1,16 +0,0 @@
sudo: false
language: node_js
node_js:
- '0.10'
- '0.12'
- '4'
- '6'
- '8'
- '9'
branches:
only:
- master
notifications:
email:
- rod@vagg.org
- matteo.collina@gmail.com

13
node_modules/bl/LICENSE.md generated vendored
View File

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

208
node_modules/bl/README.md generated vendored
View File

@ -1,208 +0,0 @@
# bl *(BufferList)*
[![Build Status](https://travis-ci.org/rvagg/bl.svg?branch=master)](https://travis-ci.org/rvagg/bl)
**A Node.js Buffer list collector, reader and streamer thingy.**
[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/)
[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/)
**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!
The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently.
```js
const BufferList = require('bl')
var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
bl.append('hi') // bl will also accept & convert Strings
bl.append(new Buffer('j'))
bl.append(new Buffer([ 0x3, 0x4 ]))
console.log(bl.length) // 12
console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij'
console.log(bl.slice(3, 10).toString('ascii')) // 'defghij'
console.log(bl.slice(3, 6).toString('ascii')) // 'def'
console.log(bl.slice(3, 8).toString('ascii')) // 'defgh'
console.log(bl.slice(5, 10).toString('ascii')) // 'fghij'
// or just use toString!
console.log(bl.toString()) // 'abcdefghij\u0003\u0004'
console.log(bl.toString('ascii', 3, 8)) // 'defgh'
console.log(bl.toString('ascii', 5, 10)) // 'fghij'
// other standard Buffer readables
console.log(bl.readUInt16BE(10)) // 0x0304
console.log(bl.readUInt16LE(10)) // 0x0403
```
Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**:
```js
const bl = require('bl')
, fs = require('fs')
fs.createReadStream('README.md')
.pipe(bl(function (err, data) { // note 'new' isn't strictly required
// `data` is a complete Buffer object containing the full data
console.log(data.toString())
}))
```
Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream.
Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!):
```js
const hyperquest = require('hyperquest')
, bl = require('bl')
, url = 'https://raw.github.com/rvagg/bl/master/README.md'
hyperquest(url).pipe(bl(function (err, data) {
console.log(data.toString())
}))
```
Or, use it as a readable stream to recompose a list of Buffers to an output source:
```js
const BufferList = require('bl')
, fs = require('fs')
var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
bl.append(new Buffer('hi'))
bl.append(new Buffer('j'))
bl.pipe(fs.createWriteStream('gibberish.txt'))
```
## API
* <a href="#ctor"><code><b>new BufferList([ callback ])</b></code></a>
* <a href="#length"><code>bl.<b>length</b></code></a>
* <a href="#append"><code>bl.<b>append(buffer)</b></code></a>
* <a href="#get"><code>bl.<b>get(index)</b></code></a>
* <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a>
* <a href="#shallowSlice"><code>bl.<b>shallowSlice([ start[, end ] ])</b></code></a>
* <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a>
* <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a>
* <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a>
* <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a>
* <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a>
* <a href="#streams">Streams</a>
--------------------------------------------------------
<a name="ctor"></a>
### new BufferList([ callback | Buffer | Buffer array | BufferList | BufferList array | String ])
The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream.
Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object.
`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:
```js
var bl = require('bl')
var myinstance = bl()
// equivalent to:
var BufferList = require('bl')
var myinstance = new BufferList()
```
--------------------------------------------------------
<a name="length"></a>
### bl.length
Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list.
--------------------------------------------------------
<a name="append"></a>
### bl.append(Buffer | Buffer array | BufferList | BufferList array | String)
`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained.
--------------------------------------------------------
<a name="get"></a>
### bl.get(index)
`get()` will return the byte at the specified index.
--------------------------------------------------------
<a name="slice"></a>
### bl.slice([ start, [ end ] ])
`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.
If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer.
--------------------------------------------------------
<a name="shallowSlice"></a>
### bl.shallowSlice([ start, [ end ] ])
`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.
No copies will be performed. All buffers in the result share memory with the original list.
--------------------------------------------------------
<a name="copy"></a>
### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])
`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively.
--------------------------------------------------------
<a name="duplicate"></a>
### bl.duplicate()
`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example:
```js
var bl = new BufferList()
bl.append('hello')
bl.append(' world')
bl.append('\n')
bl.duplicate().pipe(process.stdout, { end: false })
console.log(bl.toString())
```
--------------------------------------------------------
<a name="consume"></a>
### bl.consume(bytes)
`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers&mdash;initial offsets will be calculated accordingly in order to give you a consistent view of the data.
--------------------------------------------------------
<a name="toString"></a>
### bl.toString([encoding, [ start, [ end ]]])
`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information.
--------------------------------------------------------
<a name="readXX"></a>
### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()
All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently.
See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work.
--------------------------------------------------------
<a name="streams"></a>
### Streams
**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance.
--------------------------------------------------------
## Contributors
**bl** is brought to you by the following hackers:
* [Rod Vagg](https://github.com/rvagg)
* [Matteo Collina](https://github.com/mcollina)
* [Jarett Cruger](https://github.com/jcrugzz)
=======
<a name="license"></a>
## License &amp; copyright
Copyright (c) 2013-2016 bl contributors (listed above).
bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

281
node_modules/bl/bl.js generated vendored
View File

@ -1,281 +0,0 @@
var DuplexStream = require('readable-stream/duplex')
, util = require('util')
, Buffer = require('safe-buffer').Buffer
function BufferList (callback) {
if (!(this instanceof BufferList))
return new BufferList(callback)
this._bufs = []
this.length = 0
if (typeof callback == 'function') {
this._callback = callback
var piper = function piper (err) {
if (this._callback) {
this._callback(err)
this._callback = null
}
}.bind(this)
this.on('pipe', function onPipe (src) {
src.on('error', piper)
})
this.on('unpipe', function onUnpipe (src) {
src.removeListener('error', piper)
})
} else {
this.append(callback)
}
DuplexStream.call(this)
}
util.inherits(BufferList, DuplexStream)
BufferList.prototype._offset = function _offset (offset) {
var tot = 0, i = 0, _t
if (offset === 0) return [ 0, 0 ]
for (; i < this._bufs.length; i++) {
_t = tot + this._bufs[i].length
if (offset < _t || i == this._bufs.length - 1)
return [ i, offset - tot ]
tot = _t
}
}
BufferList.prototype.append = function append (buf) {
var i = 0
if (Buffer.isBuffer(buf)) {
this._appendBuffer(buf);
} else if (Array.isArray(buf)) {
for (; i < buf.length; i++)
this.append(buf[i])
} else if (buf instanceof BufferList) {
// unwrap argument into individual BufferLists
for (; i < buf._bufs.length; i++)
this.append(buf._bufs[i])
} else if (buf != null) {
// coerce number arguments to strings, since Buffer(number) does
// uninitialized memory allocation
if (typeof buf == 'number')
buf = buf.toString()
this._appendBuffer(Buffer.from(buf));
}
return this
}
BufferList.prototype._appendBuffer = function appendBuffer (buf) {
this._bufs.push(buf)
this.length += buf.length
}
BufferList.prototype._write = function _write (buf, encoding, callback) {
this._appendBuffer(buf)
if (typeof callback == 'function')
callback()
}
BufferList.prototype._read = function _read (size) {
if (!this.length)
return this.push(null)
size = Math.min(size, this.length)
this.push(this.slice(0, size))
this.consume(size)
}
BufferList.prototype.end = function end (chunk) {
DuplexStream.prototype.end.call(this, chunk)
if (this._callback) {
this._callback(null, this.slice())
this._callback = null
}
}
BufferList.prototype.get = function get (index) {
return this.slice(index, index + 1)[0]
}
BufferList.prototype.slice = function slice (start, end) {
if (typeof start == 'number' && start < 0)
start += this.length
if (typeof end == 'number' && end < 0)
end += this.length
return this.copy(null, 0, start, end)
}
BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
if (typeof srcStart != 'number' || srcStart < 0)
srcStart = 0
if (typeof srcEnd != 'number' || srcEnd > this.length)
srcEnd = this.length
if (srcStart >= this.length)
return dst || Buffer.alloc(0)
if (srcEnd <= 0)
return dst || Buffer.alloc(0)
var copy = !!dst
, off = this._offset(srcStart)
, len = srcEnd - srcStart
, bytes = len
, bufoff = (copy && dstStart) || 0
, start = off[1]
, l
, i
// copy/slice everything
if (srcStart === 0 && srcEnd == this.length) {
if (!copy) { // slice, but full concat if multiple buffers
return this._bufs.length === 1
? this._bufs[0]
: Buffer.concat(this._bufs, this.length)
}
// copy, need to copy individual buffers
for (i = 0; i < this._bufs.length; i++) {
this._bufs[i].copy(dst, bufoff)
bufoff += this._bufs[i].length
}
return dst
}
// easy, cheap case where it's a subset of one of the buffers
if (bytes <= this._bufs[off[0]].length - start) {
return copy
? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
: this._bufs[off[0]].slice(start, start + bytes)
}
if (!copy) // a slice, we need something to copy in to
dst = Buffer.allocUnsafe(len)
for (i = off[0]; i < this._bufs.length; i++) {
l = this._bufs[i].length - start
if (bytes > l) {
this._bufs[i].copy(dst, bufoff, start)
} else {
this._bufs[i].copy(dst, bufoff, start, start + bytes)
break
}
bufoff += l
bytes -= l
if (start)
start = 0
}
return dst
}
BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
start = start || 0
end = end || this.length
if (start < 0)
start += this.length
if (end < 0)
end += this.length
var startOffset = this._offset(start)
, endOffset = this._offset(end)
, buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
if (endOffset[1] == 0)
buffers.pop()
else
buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
if (startOffset[1] != 0)
buffers[0] = buffers[0].slice(startOffset[1])
return new BufferList(buffers)
}
BufferList.prototype.toString = function toString (encoding, start, end) {
return this.slice(start, end).toString(encoding)
}
BufferList.prototype.consume = function consume (bytes) {
while (this._bufs.length) {
if (bytes >= this._bufs[0].length) {
bytes -= this._bufs[0].length
this.length -= this._bufs[0].length
this._bufs.shift()
} else {
this._bufs[0] = this._bufs[0].slice(bytes)
this.length -= bytes
break
}
}
return this
}
BufferList.prototype.duplicate = function duplicate () {
var i = 0
, copy = new BufferList()
for (; i < this._bufs.length; i++)
copy.append(this._bufs[i])
return copy
}
BufferList.prototype.destroy = function destroy () {
this._bufs.length = 0
this.length = 0
this.push(null)
}
;(function () {
var methods = {
'readDoubleBE' : 8
, 'readDoubleLE' : 8
, 'readFloatBE' : 4
, 'readFloatLE' : 4
, 'readInt32BE' : 4
, 'readInt32LE' : 4
, 'readUInt32BE' : 4
, 'readUInt32LE' : 4
, 'readInt16BE' : 2
, 'readInt16LE' : 2
, 'readUInt16BE' : 2
, 'readUInt16LE' : 2
, 'readInt8' : 1
, 'readUInt8' : 1
}
for (var m in methods) {
(function (m) {
BufferList.prototype[m] = function (offset) {
return this.slice(offset, offset + methods[m])[m](0)
}
}(m))
}
}())
module.exports = BufferList

59
node_modules/bl/package.json generated vendored
View File

@ -1,59 +0,0 @@
{
"_from": "bl@1.2.2",
"_id": "bl@1.2.2",
"_inBundle": false,
"_integrity": "sha512-e8tQYnZodmebYDWGH7KMRvtzKXaJHx3BbilrgZCfvyLUYdKpK1t5PSPmpkny/SgiTSCnjfLW7v5rlONXVFkQEA==",
"_location": "/bl",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "bl@1.2.2",
"name": "bl",
"escapedName": "bl",
"rawSpec": "1.2.2",
"saveSpec": null,
"fetchSpec": "1.2.2"
},
"_requiredBy": [
"/tar-stream"
],
"_resolved": "https://registry.npmjs.org/bl/-/bl-1.2.2.tgz",
"_spec": "1.2.2",
"authors": [
"Rod Vagg <rod@vagg.org> (https://github.com/rvagg)",
"Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)",
"Jarett Cruger <jcrugzz@gmail.com> (https://github.com/jcrugzz)"
],
"bugs": {
"url": "https://github.com/rvagg/bl/issues"
},
"dependencies": {
"readable-stream": "^2.3.5",
"safe-buffer": "^5.1.1"
},
"description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!",
"devDependencies": {
"faucet": "0.0.1",
"hash_file": "~0.1.1",
"tape": "~4.9.0"
},
"homepage": "https://github.com/rvagg/bl",
"keywords": [
"buffer",
"buffers",
"stream",
"awesomesauce"
],
"license": "MIT",
"main": "bl.js",
"name": "bl",
"repository": {
"type": "git",
"url": "git+https://github.com/rvagg/bl.git"
},
"scripts": {
"test": "node test/test.js | faucet"
},
"version": "1.2.2"
}

702
node_modules/bl/test/test.js generated vendored
View File

@ -1,702 +0,0 @@
var tape = require('tape')
, crypto = require('crypto')
, fs = require('fs')
, hash = require('hash_file')
, BufferList = require('../')
, Buffer = require('safe-buffer').Buffer
, encodings =
('hex utf8 utf-8 ascii binary base64'
+ (process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ')
tape('single bytes from single buffer', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
t.equal(bl.length, 4)
t.equal(bl.get(0), 97)
t.equal(bl.get(1), 98)
t.equal(bl.get(2), 99)
t.equal(bl.get(3), 100)
t.end()
})
tape('single bytes from multiple buffers', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
t.equal(bl.length, 10)
t.equal(bl.get(0), 97)
t.equal(bl.get(1), 98)
t.equal(bl.get(2), 99)
t.equal(bl.get(3), 100)
t.equal(bl.get(4), 101)
t.equal(bl.get(5), 102)
t.equal(bl.get(6), 103)
t.equal(bl.get(7), 104)
t.equal(bl.get(8), 105)
t.equal(bl.get(9), 106)
t.end()
})
tape('multi bytes from single buffer', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
t.equal(bl.length, 4)
t.equal(bl.slice(0, 4).toString('ascii'), 'abcd')
t.equal(bl.slice(0, 3).toString('ascii'), 'abc')
t.equal(bl.slice(1, 4).toString('ascii'), 'bcd')
t.equal(bl.slice(-4, -1).toString('ascii'), 'abc')
t.end()
})
tape('multi bytes from single buffer (negative indexes)', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('buffer'))
t.equal(bl.length, 6)
t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe')
t.equal(bl.slice(-6, -2).toString('ascii'), 'buff')
t.equal(bl.slice(-5, -2).toString('ascii'), 'uff')
t.end()
})
tape('multiple bytes from multiple buffers', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
t.equal(bl.length, 10)
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
t.equal(bl.slice(-7, -4).toString('ascii'), 'def')
t.end()
})
tape('multiple bytes from multiple buffer lists', function (t) {
var bl = new BufferList()
bl.append(new BufferList([ Buffer.from('abcd'), Buffer.from('efg') ]))
bl.append(new BufferList([ Buffer.from('hi'), Buffer.from('j') ]))
t.equal(bl.length, 10)
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
t.end()
})
// same data as previous test, just using nested constructors
tape('multiple bytes from crazy nested buffer lists', function (t) {
var bl = new BufferList()
bl.append(new BufferList([
new BufferList([
new BufferList(Buffer.from('abc'))
, Buffer.from('d')
, new BufferList(Buffer.from('efg'))
])
, new BufferList([ Buffer.from('hi') ])
, new BufferList(Buffer.from('j'))
]))
t.equal(bl.length, 10)
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij')
t.equal(bl.slice(3, 6).toString('ascii'), 'def')
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh')
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij')
t.end()
})
tape('append accepts arrays of Buffers', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abc'))
bl.append([ Buffer.from('def') ])
bl.append([ Buffer.from('ghi'), Buffer.from('jkl') ])
bl.append([ Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz') ])
t.equal(bl.length, 26)
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
t.end()
})
tape('append accepts arrays of BufferLists', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abc'))
bl.append([ new BufferList('def') ])
bl.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ]))
bl.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ])
t.equal(bl.length, 26)
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
t.end()
})
tape('append chainable', function (t) {
var bl = new BufferList()
t.ok(bl.append(Buffer.from('abcd')) === bl)
t.ok(bl.append([ Buffer.from('abcd') ]) === bl)
t.ok(bl.append(new BufferList(Buffer.from('abcd'))) === bl)
t.ok(bl.append([ new BufferList(Buffer.from('abcd')) ]) === bl)
t.end()
})
tape('append chainable (test results)', function (t) {
var bl = new BufferList('abc')
.append([ new BufferList('def') ])
.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ]))
.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ])
t.equal(bl.length, 26)
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz')
t.end()
})
tape('consuming from multiple buffers', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
t.equal(bl.length, 10)
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij')
bl.consume(3)
t.equal(bl.length, 7)
t.equal(bl.slice(0, 7).toString('ascii'), 'defghij')
bl.consume(2)
t.equal(bl.length, 5)
t.equal(bl.slice(0, 5).toString('ascii'), 'fghij')
bl.consume(1)
t.equal(bl.length, 4)
t.equal(bl.slice(0, 4).toString('ascii'), 'ghij')
bl.consume(1)
t.equal(bl.length, 3)
t.equal(bl.slice(0, 3).toString('ascii'), 'hij')
bl.consume(2)
t.equal(bl.length, 1)
t.equal(bl.slice(0, 1).toString('ascii'), 'j')
t.end()
})
tape('complete consumption', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('a'))
bl.append(Buffer.from('b'))
bl.consume(2)
t.equal(bl.length, 0)
t.equal(bl._bufs.length, 0)
t.end()
})
tape('test readUInt8 / readInt8', function (t) {
var buf1 = Buffer.alloc(1)
, buf2 = Buffer.alloc(3)
, buf3 = Buffer.alloc(3)
, bl = new BufferList()
buf2[1] = 0x3
buf2[2] = 0x4
buf3[0] = 0x23
buf3[1] = 0x42
bl.append(buf1)
bl.append(buf2)
bl.append(buf3)
t.equal(bl.readUInt8(2), 0x3)
t.equal(bl.readInt8(2), 0x3)
t.equal(bl.readUInt8(3), 0x4)
t.equal(bl.readInt8(3), 0x4)
t.equal(bl.readUInt8(4), 0x23)
t.equal(bl.readInt8(4), 0x23)
t.equal(bl.readUInt8(5), 0x42)
t.equal(bl.readInt8(5), 0x42)
t.end()
})
tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) {
var buf1 = Buffer.alloc(1)
, buf2 = Buffer.alloc(3)
, buf3 = Buffer.alloc(3)
, bl = new BufferList()
buf2[1] = 0x3
buf2[2] = 0x4
buf3[0] = 0x23
buf3[1] = 0x42
bl.append(buf1)
bl.append(buf2)
bl.append(buf3)
t.equal(bl.readUInt16BE(2), 0x0304)
t.equal(bl.readUInt16LE(2), 0x0403)
t.equal(bl.readInt16BE(2), 0x0304)
t.equal(bl.readInt16LE(2), 0x0403)
t.equal(bl.readUInt16BE(3), 0x0423)
t.equal(bl.readUInt16LE(3), 0x2304)
t.equal(bl.readInt16BE(3), 0x0423)
t.equal(bl.readInt16LE(3), 0x2304)
t.equal(bl.readUInt16BE(4), 0x2342)
t.equal(bl.readUInt16LE(4), 0x4223)
t.equal(bl.readInt16BE(4), 0x2342)
t.equal(bl.readInt16LE(4), 0x4223)
t.end()
})
tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) {
var buf1 = Buffer.alloc(1)
, buf2 = Buffer.alloc(3)
, buf3 = Buffer.alloc(3)
, bl = new BufferList()
buf2[1] = 0x3
buf2[2] = 0x4
buf3[0] = 0x23
buf3[1] = 0x42
bl.append(buf1)
bl.append(buf2)
bl.append(buf3)
t.equal(bl.readUInt32BE(2), 0x03042342)
t.equal(bl.readUInt32LE(2), 0x42230403)
t.equal(bl.readInt32BE(2), 0x03042342)
t.equal(bl.readInt32LE(2), 0x42230403)
t.end()
})
tape('test readFloatLE / readFloatBE', function (t) {
var buf1 = Buffer.alloc(1)
, buf2 = Buffer.alloc(3)
, buf3 = Buffer.alloc(3)
, bl = new BufferList()
buf2[1] = 0x00
buf2[2] = 0x00
buf3[0] = 0x80
buf3[1] = 0x3f
bl.append(buf1)
bl.append(buf2)
bl.append(buf3)
t.equal(bl.readFloatLE(2), 0x01)
t.end()
})
tape('test readDoubleLE / readDoubleBE', function (t) {
var buf1 = Buffer.alloc(1)
, buf2 = Buffer.alloc(3)
, buf3 = Buffer.alloc(10)
, bl = new BufferList()
buf2[1] = 0x55
buf2[2] = 0x55
buf3[0] = 0x55
buf3[1] = 0x55
buf3[2] = 0x55
buf3[3] = 0x55
buf3[4] = 0xd5
buf3[5] = 0x3f
bl.append(buf1)
bl.append(buf2)
bl.append(buf3)
t.equal(bl.readDoubleLE(2), 0.3333333333333333)
t.end()
})
tape('test toString', function (t) {
var bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
t.equal(bl.toString('ascii', 0, 10), 'abcdefghij')
t.equal(bl.toString('ascii', 3, 10), 'defghij')
t.equal(bl.toString('ascii', 3, 6), 'def')
t.equal(bl.toString('ascii', 3, 8), 'defgh')
t.equal(bl.toString('ascii', 5, 10), 'fghij')
t.end()
})
tape('test toString encoding', function (t) {
var bl = new BufferList()
, b = Buffer.from('abcdefghij\xff\x00')
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
bl.append(Buffer.from('\xff\x00'))
encodings.forEach(function (enc) {
t.equal(bl.toString(enc), b.toString(enc), enc)
})
t.end()
})
!process.browser && tape('test stream', function (t) {
var random = crypto.randomBytes(65534)
, rndhash = hash(random, 'md5')
, md5sum = crypto.createHash('md5')
, bl = new BufferList(function (err, buf) {
t.ok(Buffer.isBuffer(buf))
t.ok(err === null)
t.equal(rndhash, hash(bl.slice(), 'md5'))
t.equal(rndhash, hash(buf, 'md5'))
bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat'))
.on('close', function () {
var s = fs.createReadStream('/tmp/bl_test_rnd_out.dat')
s.on('data', md5sum.update.bind(md5sum))
s.on('end', function() {
t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!')
t.end()
})
})
})
fs.writeFileSync('/tmp/bl_test_rnd.dat', random)
fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl)
})
tape('instantiation with Buffer', function (t) {
var buf = crypto.randomBytes(1024)
, buf2 = crypto.randomBytes(1024)
, b = BufferList(buf)
t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer')
b = BufferList([ buf, buf2 ])
t.equal(b.slice().toString('hex'), Buffer.concat([ buf, buf2 ]).toString('hex'), 'same buffer')
t.end()
})
tape('test String appendage', function (t) {
var bl = new BufferList()
, b = Buffer.from('abcdefghij\xff\x00')
bl.append('abcd')
bl.append('efg')
bl.append('hi')
bl.append('j')
bl.append('\xff\x00')
encodings.forEach(function (enc) {
t.equal(bl.toString(enc), b.toString(enc))
})
t.end()
})
tape('test Number appendage', function (t) {
var bl = new BufferList()
, b = Buffer.from('1234567890')
bl.append(1234)
bl.append(567)
bl.append(89)
bl.append(0)
encodings.forEach(function (enc) {
t.equal(bl.toString(enc), b.toString(enc))
})
t.end()
})
tape('write nothing, should get empty buffer', function (t) {
t.plan(3)
BufferList(function (err, data) {
t.notOk(err, 'no error')
t.ok(Buffer.isBuffer(data), 'got a buffer')
t.equal(0, data.length, 'got a zero-length buffer')
t.end()
}).end()
})
tape('unicode string', function (t) {
t.plan(2)
var inp1 = '\u2600'
, inp2 = '\u2603'
, exp = inp1 + ' and ' + inp2
, bl = BufferList()
bl.write(inp1)
bl.write(' and ')
bl.write(inp2)
t.equal(exp, bl.toString())
t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex'))
})
tape('should emit finish', function (t) {
var source = BufferList()
, dest = BufferList()
source.write('hello')
source.pipe(dest)
dest.on('finish', function () {
t.equal(dest.toString('utf8'), 'hello')
t.end()
})
})
tape('basic copy', function (t) {
var buf = crypto.randomBytes(1024)
, buf2 = Buffer.alloc(1024)
, b = BufferList(buf)
b.copy(buf2)
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer')
t.end()
})
tape('copy after many appends', function (t) {
var buf = crypto.randomBytes(512)
, buf2 = Buffer.alloc(1024)
, b = BufferList(buf)
b.append(buf)
b.copy(buf2)
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer')
t.end()
})
tape('copy at a precise position', function (t) {
var buf = crypto.randomBytes(1004)
, buf2 = Buffer.alloc(1024)
, b = BufferList(buf)
b.copy(buf2, 20)
t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer')
t.end()
})
tape('copy starting from a precise location', function (t) {
var buf = crypto.randomBytes(10)
, buf2 = Buffer.alloc(5)
, b = BufferList(buf)
b.copy(buf2, 0, 5)
t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer')
t.end()
})
tape('copy in an interval', function (t) {
var rnd = crypto.randomBytes(10)
, b = BufferList(rnd) // put the random bytes there
, actual = Buffer.alloc(3)
, expected = Buffer.alloc(3)
rnd.copy(expected, 0, 5, 8)
b.copy(actual, 0, 5, 8)
t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer')
t.end()
})
tape('copy an interval between two buffers', function (t) {
var buf = crypto.randomBytes(10)
, buf2 = Buffer.alloc(10)
, b = BufferList(buf)
b.append(buf)
b.copy(buf2, 0, 5, 15)
t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer')
t.end()
})
tape('shallow slice across buffer boundaries', function (t) {
var bl = new BufferList(['First', 'Second', 'Third'])
t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh')
t.end()
})
tape('shallow slice within single buffer', function (t) {
t.plan(2)
var bl = new BufferList(['First', 'Second', 'Third'])
t.equal(bl.shallowSlice(5, 10).toString(), 'Secon')
t.equal(bl.shallowSlice(7, 10).toString(), 'con')
t.end()
})
tape('shallow slice single buffer', function (t) {
t.plan(3)
var bl = new BufferList(['First', 'Second', 'Third'])
t.equal(bl.shallowSlice(0, 5).toString(), 'First')
t.equal(bl.shallowSlice(5, 11).toString(), 'Second')
t.equal(bl.shallowSlice(11, 16).toString(), 'Third')
})
tape('shallow slice with negative or omitted indices', function (t) {
t.plan(4)
var bl = new BufferList(['First', 'Second', 'Third'])
t.equal(bl.shallowSlice().toString(), 'FirstSecondThird')
t.equal(bl.shallowSlice(5).toString(), 'SecondThird')
t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh')
t.equal(bl.shallowSlice(-8).toString(), 'ondThird')
})
tape('shallow slice does not make a copy', function (t) {
t.plan(1)
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
var bl = (new BufferList(buffers)).shallowSlice(5, -3)
buffers[1].fill('h')
buffers[2].fill('h')
t.equal(bl.toString(), 'hhhhhhhh')
})
tape('duplicate', function (t) {
t.plan(2)
var bl = new BufferList('abcdefghij\xff\x00')
, dup = bl.duplicate()
t.equal(bl.prototype, dup.prototype)
t.equal(bl.toString('hex'), dup.toString('hex'))
})
tape('destroy no pipe', function (t) {
t.plan(2)
var bl = new BufferList('alsdkfja;lsdkfja;lsdk')
bl.destroy()
t.equal(bl._bufs.length, 0)
t.equal(bl.length, 0)
})
!process.browser && tape('destroy with pipe before read end', function (t) {
t.plan(2)
var bl = new BufferList()
fs.createReadStream(__dirname + '/test.js')
.pipe(bl)
bl.destroy()
t.equal(bl._bufs.length, 0)
t.equal(bl.length, 0)
})
!process.browser && tape('destroy with pipe before read end with race', function (t) {
t.plan(2)
var bl = new BufferList()
fs.createReadStream(__dirname + '/test.js')
.pipe(bl)
setTimeout(function () {
bl.destroy()
setTimeout(function () {
t.equal(bl._bufs.length, 0)
t.equal(bl.length, 0)
}, 500)
}, 500)
})
!process.browser && tape('destroy with pipe after read end', function (t) {
t.plan(2)
var bl = new BufferList()
fs.createReadStream(__dirname + '/test.js')
.on('end', onEnd)
.pipe(bl)
function onEnd () {
bl.destroy()
t.equal(bl._bufs.length, 0)
t.equal(bl.length, 0)
}
})
!process.browser && tape('destroy with pipe while writing to a destination', function (t) {
t.plan(4)
var bl = new BufferList()
, ds = new BufferList()
fs.createReadStream(__dirname + '/test.js')
.on('end', onEnd)
.pipe(bl)
function onEnd () {
bl.pipe(ds)
setTimeout(function () {
bl.destroy()
t.equals(bl._bufs.length, 0)
t.equals(bl.length, 0)
ds.destroy()
t.equals(bl._bufs.length, 0)
t.equals(bl.length, 0)
}, 100)
}
})
!process.browser && tape('handle error', function (t) {
t.plan(2)
fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) {
t.ok(err instanceof Error, 'has error')
t.notOk(data, 'no data')
}))
})

View File

@ -1,17 +0,0 @@
function allocUnsafe (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
}
if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
if (Buffer.allocUnsafe) {
return Buffer.allocUnsafe(size)
} else {
return new Buffer(size)
}
}
module.exports = allocUnsafe

View File

@ -1,53 +0,0 @@
{
"_from": "buffer-alloc-unsafe@1.1.0",
"_id": "buffer-alloc-unsafe@1.1.0",
"_inBundle": false,
"_integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==",
"_location": "/buffer-alloc-unsafe",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "buffer-alloc-unsafe@1.1.0",
"name": "buffer-alloc-unsafe",
"escapedName": "buffer-alloc-unsafe",
"rawSpec": "1.1.0",
"saveSpec": null,
"fetchSpec": "1.1.0"
},
"_requiredBy": [
"/buffer-alloc"
],
"_resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz",
"_spec": "1.1.0",
"bugs": {
"url": "https://github.com/LinusU/buffer-alloc-unsafe/issues"
},
"description": "A [ponyfill](https://ponyfill.com) for `Buffer.allocUnsafe`.",
"devDependencies": {
"standard": "^7.1.2"
},
"files": [
"index.js"
],
"homepage": "https://github.com/LinusU/buffer-alloc-unsafe#readme",
"keywords": [
"allocUnsafe",
"allocate",
"buffer allocUnsafe",
"buffer unsafe allocate",
"buffer",
"ponyfill",
"unsafe allocate"
],
"license": "MIT",
"name": "buffer-alloc-unsafe",
"repository": {
"type": "git",
"url": "git+https://github.com/LinusU/buffer-alloc-unsafe.git"
},
"scripts": {
"test": "standard && node test"
},
"version": "1.1.0"
}

View File

@ -1,46 +0,0 @@
# Buffer Alloc Unsafe
A [ponyfill](https://ponyfill.com) for `Buffer.allocUnsafe`.
Works as Node.js: `v7.0.0` <br>
Works on Node.js: `v0.10.0`
## Installation
```sh
npm install --save buffer-alloc-unsafe
```
## Usage
```js
const allocUnsafe = require('buffer-alloc-unsafe')
console.log(allocUnsafe(10))
//=> <Buffer 78 0c 80 03 01 00 00 00 05 00>
console.log(allocUnsafe(10))
//=> <Buffer 58 ed bf 5f ff 7f 00 00 01 00>
console.log(allocUnsafe(10))
//=> <Buffer 50 0c 80 03 01 00 00 00 0a 00>
allocUnsafe(-10)
//=> RangeError: "size" argument must not be negative
```
## API
### allocUnsafe(size)
- `size` &lt;Integer&gt; The desired length of the new `Buffer`
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be
less than or equal to the value of `buffer.kMaxLength` and greater than or equal
to zero. Otherwise, a `RangeError` is thrown.
## See also
- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
- [buffer-fill](https://github.com/LinusU/buffer-fill) A ponyfill for `Buffer.fill`
- [buffer-from](https://github.com/LinusU/buffer-from) A ponyfill for `Buffer.from`

32
node_modules/buffer-alloc/index.js generated vendored
View File

@ -1,32 +0,0 @@
var bufferFill = require('buffer-fill')
var allocUnsafe = require('buffer-alloc-unsafe')
module.exports = function alloc (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
}
if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
if (Buffer.alloc) {
return Buffer.alloc(size, fill, encoding)
}
var buffer = allocUnsafe(size)
if (size === 0) {
return buffer
}
if (fill === undefined) {
return bufferFill(buffer, 0)
}
if (typeof encoding !== 'string') {
encoding = undefined
}
return bufferFill(buffer, fill, encoding)
}

View File

@ -1,55 +0,0 @@
{
"_from": "buffer-alloc@1.2.0",
"_id": "buffer-alloc@1.2.0",
"_inBundle": false,
"_integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==",
"_location": "/buffer-alloc",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "buffer-alloc@1.2.0",
"name": "buffer-alloc",
"escapedName": "buffer-alloc",
"rawSpec": "1.2.0",
"saveSpec": null,
"fetchSpec": "1.2.0"
},
"_requiredBy": [
"/tar-stream"
],
"_resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz",
"_spec": "1.2.0",
"bugs": {
"url": "https://github.com/LinusU/buffer-alloc/issues"
},
"dependencies": {
"buffer-alloc-unsafe": "^1.1.0",
"buffer-fill": "^1.0.0"
},
"description": "A [ponyfill](https://ponyfill.com) for `Buffer.alloc`.",
"devDependencies": {
"standard": "^7.1.2"
},
"files": [
"index.js"
],
"homepage": "https://github.com/LinusU/buffer-alloc#readme",
"keywords": [
"alloc",
"allocate",
"buffer alloc",
"buffer allocate",
"buffer"
],
"license": "MIT",
"name": "buffer-alloc",
"repository": {
"type": "git",
"url": "git+https://github.com/LinusU/buffer-alloc.git"
},
"scripts": {
"test": "standard && node test"
},
"version": "1.2.0"
}

43
node_modules/buffer-alloc/readme.md generated vendored
View File

@ -1,43 +0,0 @@
# Buffer Alloc
A [ponyfill](https://ponyfill.com) for `Buffer.alloc`.
Works as Node.js: `v7.0.0` <br>
Works on Node.js: `v0.10.0`
## Installation
```sh
npm install --save buffer-alloc
```
## Usage
```js
const alloc = require('buffer-alloc')
console.log(alloc(4))
//=> <Buffer 00 00 00 00>
console.log(alloc(6, 0x41))
//=> <Buffer 41 41 41 41 41 41>
console.log(alloc(10, 'linus', 'utf8'))
//=> <Buffer 6c 69 6e 75 73 6c 69 6e 75 73>
```
## API
### alloc(size[, fill[, encoding]])
- `size` &lt;Integer&gt; The desired length of the new `Buffer`
- `fill` &lt;String&gt; | &lt;Buffer&gt; | &lt;Integer&gt; A value to pre-fill the new `Buffer` with. **Default:** `0`
- `encoding` &lt;String&gt; If `fill` is a string, this is its encoding. **Default:** `'utf8'`
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be zero-filled.
## See also
- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`
- [buffer-fill](https://github.com/LinusU/buffer-fill) A ponyfill for `Buffer.fill`
- [buffer-from](https://github.com/LinusU/buffer-from) A ponyfill for `Buffer.from`

19
node_modules/buffer-crc32/LICENSE generated vendored
View File

@ -1,19 +0,0 @@
The MIT License
Copyright (c) 2013 Brian J. Brennan
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.

47
node_modules/buffer-crc32/README.md generated vendored
View File

@ -1,47 +0,0 @@
# buffer-crc32
[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)
crc32 that works with binary data and fancy character sets, outputs
buffer, signed or unsigned data and has tests.
Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix
# install
```
npm install buffer-crc32
```
# example
```js
var crc32 = require('buffer-crc32');
// works with buffers
var buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])
crc32(buf) // -> <Buffer 94 5a ab 4a>
// has convenience methods for getting signed or unsigned ints
crc32.signed(buf) // -> -1805997238
crc32.unsigned(buf) // -> 2488970058
// will cast to buffer if given a string, so you can
// directly use foreign characters safely
crc32('自動販売機') // -> <Buffer cb 03 1a c5>
// and works in append mode too
var partialCrc = crc32('hey');
var partialCrc = crc32(' ', partialCrc);
var partialCrc = crc32('sup', partialCrc);
var partialCrc = crc32(' ', partialCrc);
var finalCrc = crc32('bros', partialCrc); // -> <Buffer 47 fa 55 70>
```
# tests
This was tested against the output of zlib's crc32 method. You can run
the tests with`npm test` (requires tap)
# see also
https://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also
supports buffer inputs and return unsigned ints (thanks @tjholowaychuk).
# license
MIT/X11

111
node_modules/buffer-crc32/index.js generated vendored
View File

@ -1,111 +0,0 @@
var Buffer = require('buffer').Buffer;
var CRC_TABLE = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
];
if (typeof Int32Array !== 'undefined') {
CRC_TABLE = new Int32Array(CRC_TABLE);
}
function ensureBuffer(input) {
if (Buffer.isBuffer(input)) {
return input;
}
var hasNewBufferAPI =
typeof Buffer.alloc === "function" &&
typeof Buffer.from === "function";
if (typeof input === "number") {
return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input);
}
else if (typeof input === "string") {
return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input);
}
else {
throw new Error("input must be buffer, number, or string, received " +
typeof input);
}
}
function bufferizeInt(num) {
var tmp = ensureBuffer(4);
tmp.writeInt32BE(num, 0);
return tmp;
}
function _crc32(buf, previous) {
buf = ensureBuffer(buf);
if (Buffer.isBuffer(previous)) {
previous = previous.readUInt32BE(0);
}
var crc = ~~previous ^ -1;
for (var n = 0; n < buf.length; n++) {
crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
}
return (crc ^ -1);
}
function crc32() {
return bufferizeInt(_crc32.apply(null, arguments));
}
crc32.signed = function () {
return _crc32.apply(null, arguments);
};
crc32.unsigned = function () {
return _crc32.apply(null, arguments) >>> 0;
};
module.exports = crc32;

View File

@ -1,65 +0,0 @@
{
"_from": "buffer-crc32@0.2.13",
"_id": "buffer-crc32@0.2.13",
"_inBundle": false,
"_integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=",
"_location": "/buffer-crc32",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "buffer-crc32@0.2.13",
"name": "buffer-crc32",
"escapedName": "buffer-crc32",
"rawSpec": "0.2.13",
"saveSpec": null,
"fetchSpec": "0.2.13"
},
"_requiredBy": [
"/yauzl"
],
"_resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
"_spec": "0.2.13",
"author": {
"name": "Brian J. Brennan",
"email": "brianloveswords@gmail.com"
},
"bugs": {
"url": "https://github.com/brianloveswords/buffer-crc32/issues"
},
"contributors": [
{
"name": "Vladimir Kuznetsov"
}
],
"dependencies": {},
"description": "A pure javascript CRC32 algorithm that plays nice with binary data",
"devDependencies": {
"tap": "~0.2.5"
},
"engines": {
"node": "*"
},
"files": [
"index.js"
],
"homepage": "https://github.com/brianloveswords/buffer-crc32",
"license": "MIT",
"licenses": [
{
"type": "MIT",
"url": "https://github.com/brianloveswords/buffer-crc32/raw/master/LICENSE"
}
],
"main": "index.js",
"name": "buffer-crc32",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git://github.com/brianloveswords/buffer-crc32.git"
},
"scripts": {
"test": "tap tests/*.test.js"
},
"version": "0.2.13"
}

113
node_modules/buffer-fill/index.js generated vendored
View File

@ -1,113 +0,0 @@
/* Node.js 6.4.0 and up has full support */
var hasFullSupport = (function () {
try {
if (!Buffer.isEncoding('latin1')) {
return false
}
var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4)
buf.fill('ab', 'ucs2')
return (buf.toString('hex') === '61006200')
} catch (_) {
return false
}
}())
function isSingleByte (val) {
return (val.length === 1 && val.charCodeAt(0) < 256)
}
function fillWithNumber (buffer, val, start, end) {
if (start < 0 || end > buffer.length) {
throw new RangeError('Out of range index')
}
start = start >>> 0
end = end === undefined ? buffer.length : end >>> 0
if (end > start) {
buffer.fill(val, start, end)
}
return buffer
}
function fillWithBuffer (buffer, val, start, end) {
if (start < 0 || end > buffer.length) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return buffer
}
start = start >>> 0
end = end === undefined ? buffer.length : end >>> 0
var pos = start
var len = val.length
while (pos <= (end - len)) {
val.copy(buffer, pos)
pos += len
}
if (pos !== end) {
val.copy(buffer, pos, 0, end - pos)
}
return buffer
}
function fill (buffer, val, start, end, encoding) {
if (hasFullSupport) {
return buffer.fill(val, start, end, encoding)
}
if (typeof val === 'number') {
return fillWithNumber(buffer, val, start, end)
}
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = buffer.length
} else if (typeof end === 'string') {
encoding = end
end = buffer.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (encoding === 'latin1') {
encoding = 'binary'
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val === '') {
return fillWithNumber(buffer, 0, start, end)
}
if (isSingleByte(val)) {
return fillWithNumber(buffer, val.charCodeAt(0), start, end)
}
val = new Buffer(val, encoding)
}
if (Buffer.isBuffer(val)) {
return fillWithBuffer(buffer, val, start, end)
}
// Other values (e.g. undefined, boolean, object) results in zero-fill
return fillWithNumber(buffer, 0, start, end)
}
module.exports = fill

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