28 Commits

Author SHA1 Message Date
Sven-Hendrik Haase
14569a2d34 Update deps 2019-12-12 06:25:17 +01:00
Sven-Hendrik Haase
9709d4a39e Merge branch 'master' into v1-release 2019-12-12 06:22:58 +01:00
Sven-Hendrik Haase
7a362f7ad8 Merge pull request #6 from sandiz/file_glob_support
File glob support
2019-12-12 06:17:43 +01:00
Sandi Chakravarty
57f48797a8 convert to iterator 2019-10-23 21:18:30 -07:00
Sandi Chakravarty
79426d2a8c update README with pr suggestions 2019-10-09 11:40:46 -07:00
Sandi Chakravarty
056edc7bfb update README with file_glob instructions 2019-10-08 14:13:21 -07:00
Sandi Chakravarty
cb3a639a0c add support for file_glob 2019-10-08 14:12:02 -07:00
Sven-Hendrik Haase
b1046bbcca Merge branch 'master' into v1-release 2019-09-04 23:03:24 +02:00
Sven-Hendrik Haase
add30524b0 Compile JS 2019-09-04 23:03:10 +02:00
Sven-Hendrik Haase
263c60b870 We don't actually need the types 2019-09-04 23:00:39 +02:00
Sven-Hendrik Haase
0067325cf2 Build js 2019-09-04 22:55:30 +02:00
Sven-Hendrik Haase
77a52a77ba Update modules 2019-09-04 22:53:08 +02:00
Sven-Hendrik Haase
3804ea559b Merge branch 'master' into v1-release 2019-09-04 22:50:22 +02:00
Sven-Hendrik Haase
dba641ace8 Update deps and set version to 1.0.1 2019-09-04 22:50:03 +02:00
Sven-Hendrik Haase
a859ccd8ed Merge branch 'master' into v1-release 2019-09-04 22:48:03 +02:00
Sven-Hendrik Haase
13aa539342 Fix README some more 2019-09-04 22:44:35 +02:00
Sven-Hendrik Haase
05f38782c2 Update README 2019-09-04 22:42:31 +02:00
Sven-Hendrik Haase
8db4b1ff15 Fix markup 2019-09-04 22:40:22 +02:00
Sven-Hendrik Haase
cef99a71be Merge branch 'master' into v1-release 2019-09-04 14:27:20 +02:00
Sven-Hendrik Haase
1eabee8e81 Sync changes 2019-09-04 14:27:03 +02:00
Sven-Hendrik Haase
0013a9b1f9 Merge branch 'master' into v1-release 2019-09-04 13:49:32 +02:00
Sven-Hendrik Haase
8eb6a035aa Change the way we parse refs 2019-09-04 13:48:18 +02:00
Sven-Hendrik Haase
8d9569a6a5 Add badge link to workflow 2019-08-24 03:30:21 +02:00
Sven-Hendrik Haase
778bbb1861 Add badge 2019-08-24 01:47:34 +02:00
Sven-Hendrik Haase
a27f407069 Add forgotten line to complex example 2019-08-23 06:07:52 +02:00
Sven-Hendrik Haase
44bfc8c770 Fix grammar 2019-08-23 05:49:27 +02:00
Sven-Hendrik Haase
21ef0e0838 Fix README syntax 2019-08-23 04:44:19 +02:00
Sven-Hendrik Haase
b0c4f46969 Fix README syntax 2019-08-23 04:44:08 +02:00
159 changed files with 6442 additions and 3648 deletions

View File

@@ -1,17 +1,21 @@
# Upload files to a GitHub release # Upload files to a GitHub release [![GitHub Actions Workflow](https://github.com/svenstaro/upload-release-action/workflows/PR%20Checks/badge.svg)](https://github.com/svenstaro/upload-release-action/actions)
This action allows you to select which files to upload to the just-tagged release. This action allows you to select which files to upload to the just-tagged release.
It runs on all operating systems types offered by GitHub. It runs on all operating systems types offered by GitHub.
## Input variables: ## Input variables
You must provide: You must provide:
- `repo_token`: Usually you'll want to set this to `${{ secrets.GITHUB_TOKEN }}` - `repo_token`: Usually you'll want to set this to `${{ secrets.GITHUB_TOKEN }}`
- `file`: A local file to be uploaded as the asset. - `file`: A local file to be uploaded as the asset.
- `asset_name`: The name the file gets as an asset on a release. - `asset_name`: The name the file gets as an asset on a release.
- `tag`: The tag to uploaded into. If you want the current event's tag, use `${{ github.event.ref }}` - `tag`: The tag to uploaded into. If you want the current event's tag, use `${{ github.ref }}`
- `overwrite`: If an asset with name already exists, overwrite it. - `overwrite`: If an asset with the same name already exists, overwrite it.
Optional Arguments
- `file_glob`: If set to true, the file argument can be a glob pattern (`asset_name` is ignored in this case)
## Usage ## Usage
@@ -24,8 +28,9 @@ Simple example:
name: Publish name: Publish
on: on:
create: push:
tags: tags:
- '*'
jobs: jobs:
build: build:
@@ -45,7 +50,7 @@ jobs:
repo_token: ${{ secrets.GITHUB_TOKEN }} repo_token: ${{ secrets.GITHUB_TOKEN }}
file: target/release/mything file: target/release/mything
asset_name: mything asset_name: mything
tag: {{ github.event.ref }} tag: ${{ github.ref }}
overwrite: true overwrite: true
``` ```
@@ -55,11 +60,12 @@ Complex example with more operating systems:
name: Publish name: Publish
on: on:
create: push:
tags: tags:
- '*'
jobs: jobs:
build: publish:
name: Publish for ${{ matrix.os }} name: Publish for ${{ matrix.os }}
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
@@ -81,11 +87,40 @@ jobs:
rust-version: stable rust-version: stable
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: Build - name: Build
run: cargo build --release run: cargo build --release --locked
- name: Upload binaries to release - name: Upload binaries to release
uses: svenstaro/upload-release-action@v1-release uses: svenstaro/upload-release-action@v1-release
with: with:
repo_token: ${{ secrets.GITHUB_TOKEN }} repo_token: ${{ secrets.GITHUB_TOKEN }}
file: target/release/${{ matrix.artifact_name }} file: target/release/${{ matrix.artifact_name }}
asset_name: ${{ matrix.asset_name }} asset_name: ${{ matrix.asset_name }}
tag: ${{ github.ref }}
```
Example with `file_glob`:
```yaml
name: Publish
on:
push:
tags:
- '*'
jobs:
build:
name: Publish binaries
runs-on: ubuntu-latest
steps:
- uses: hecrj/setup-rust-action@v1-release
with:
rust-version: stable
- uses: actions/checkout@v1
- name: Build
run: cargo build --release
- name: Upload binaries to release
uses: svenstaro/upload-release-action@v1-release
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: target/release/my*
tag: ${{ github.ref }}
overwrite: true
file_glob: true
``` ```

View File

@@ -19,6 +19,8 @@ inputs:
required: true required: true
overwrite: overwrite:
description: 'Overwrite the release in case it already exists' description: 'Overwrite the release in case it already exists'
file_glob:
description: 'if true the file can be a glob pattern, asset_name is ignored if this is true'
runs: runs:
using: 'node12' using: 'node12'
main: 'lib/main.js' main: 'lib/main.js'

View File

@@ -18,6 +18,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs")); const fs = __importStar(require("fs"));
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const github = __importStar(require("@actions/github")); const github = __importStar(require("@actions/github"));
const path = __importStar(require("path"));
const glob = require("glob");
function get_release_by_tag(tag, octokit, context) { function get_release_by_tag(tag, octokit, context) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { try {
@@ -38,7 +40,12 @@ function get_release_by_tag(tag, octokit, context) {
} }
function upload_to_release(release, file, asset_name, tag, overwrite, octokit, context) { function upload_to_release(release, file, asset_name, tag, overwrite, octokit, context) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const file_size = fs.statSync(file).size; const stat = fs.statSync(file);
if (!stat.isFile()) {
core.debug(`Skipping ${file}, since its not a file`);
return;
}
const file_size = stat.size;
const file_bytes = fs.readFileSync(file); const file_bytes = fs.readFileSync(file);
// Check for duplicates. // Check for duplicates.
const assets = yield octokit.repos.listAssetsForRelease(Object.assign({}, context.repo, { release_id: release.data.id })); const assets = yield octokit.repos.listAssetsForRelease(Object.assign({}, context.repo, { release_id: release.data.id }));
@@ -73,17 +80,29 @@ function run() {
try { try {
const token = core.getInput('repo_token', { required: true }); const token = core.getInput('repo_token', { required: true });
const file = core.getInput('file', { required: true }); const file = core.getInput('file', { required: true });
const asset_name = core.getInput('asset_name', { required: true }); const file_glob = core.getInput('file_glob');
const tag = core.getInput('tag', { required: true }); const tag = core.getInput('tag', { required: true }).replace("refs/tags/", "");
const overwrite = core.getInput('overwrite'); const overwrite = core.getInput('overwrite');
if (!fs.existsSync(file)) {
core.setFailed(`File ${file} wasn't found.`);
}
const octokit = new github.GitHub(token); const octokit = new github.GitHub(token);
const context = github.context; const context = github.context;
const release = yield get_release_by_tag(tag, octokit, context); const release = yield get_release_by_tag(tag, octokit, context);
if (file_glob === "true") {
const files = glob.sync(file);
if (files.length > 0) {
for (let file of files) {
const asset_name = path.basename(file);
yield upload_to_release(release, file, asset_name, tag, overwrite, octokit, context); yield upload_to_release(release, file, asset_name, tag, overwrite, octokit, context);
} }
}
else {
core.setFailed("No files matching the glob pattern found.");
}
}
else {
const asset_name = core.getInput('asset_name', { required: true });
yield upload_to_release(release, file, asset_name, tag, overwrite, octokit, context);
}
}
catch (error) { catch (error) {
core.setFailed(error.message); core.setFailed(error.message);
} }

View File

@@ -1,7 +0,0 @@
Copyright 2019 GitHub
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

@@ -4,9 +4,9 @@
## Usage ## Usage
Returns an [Octokit SDK] client. See https://octokit.github.io/rest.js for the API. Returns an Octokit client. See https://octokit.github.io/rest.js for the API.
``` ```js
const github = require('@actions/github'); const github = require('@actions/github');
const core = require('@actions/core'); const core = require('@actions/core');
@@ -15,7 +15,7 @@ const myToken = core.getInput('myToken');
const octokit = new github.GitHub(myToken); const octokit = new github.GitHub(myToken);
const pulls = await octokit.pulls.get({ const { data: pullRequest } = await octokit.pulls.get({
owner: 'octokit', owner: 'octokit',
repo: 'rest.js', repo: 'rest.js',
pull_number: 123, pull_number: 123,
@@ -24,18 +24,18 @@ const pulls = await octokit.pulls.get({
} }
}); });
console.log(pulls); console.log(pullRequest);
``` ```
You can also make GraphQL requests: You can also make GraphQL requests. See https://github.com/octokit/graphql.js for the API.
``` ```js
const result = await octokit.graphql(query, variables); const result = await octokit.graphql(query, variables);
``` ```
Finally, you can get the context of the current action: Finally, you can get the context of the current action:
``` ```js
const github = require('@actions/github'); const github = require('@actions/github');
const context = github.context; const context = github.context;

View File

@@ -1,14 +1,21 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-require-imports */ const fs_1 = require("fs");
const os_1 = require("os");
class Context { class Context {
/** /**
* Hydrate the context from the environment * Hydrate the context from the environment
*/ */
constructor() { constructor() {
this.payload = process.env.GITHUB_EVENT_PATH this.payload = {};
? require(process.env.GITHUB_EVENT_PATH) if (process.env.GITHUB_EVENT_PATH) {
: {}; if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {
this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));
}
else {
process.stdout.write(`GITHUB_EVENT_PATH ${process.env.GITHUB_EVENT_PATH} does not exist${os_1.EOL}`);
}
}
this.eventName = process.env.GITHUB_EVENT_NAME; this.eventName = process.env.GITHUB_EVENT_NAME;
this.sha = process.env.GITHUB_SHA; this.sha = process.env.GITHUB_SHA;
this.ref = process.env.GITHUB_REF; this.ref = process.env.GITHUB_REF;

View File

@@ -1 +1 @@
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":";;AAGA,0DAA0D;AAE1D,MAAa,OAAO;IAalB;;OAEG;IACH;QACE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB;YAC1C,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;YACxC,CAAC,CAAC,EAAE,CAAA;QACN,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,iBAA2B,CAAA;QACxD,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,eAAyB,CAAA;QACrD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,aAAuB,CAAA;QACjD,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,YAAsB,CAAA;IACjD,CAAC;IAED,IAAI,KAAK;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;QAE5B,yBACK,IAAI,CAAC,IAAI,IACZ,MAAM,EAAE,CAAC,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,CAAC,MAAM,IACjE;IACH,CAAC;IAED,IAAI,IAAI;QACN,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;YACjC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;YAC9D,OAAO,EAAC,KAAK,EAAE,IAAI,EAAC,CAAA;SACrB;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE;YAC3B,OAAO;gBACL,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK;gBAC1C,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI;aACnC,CAAA;SACF;QAED,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,CAAA;IACH,CAAC;CACF;AAtDD,0BAsDC"} {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":";;AAEA,2BAA2C;AAC3C,2BAAsB;AAEtB,MAAa,OAAO;IAalB;;OAEG;IACH;QACE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;QACjB,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;YACjC,IAAI,eAAU,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE;gBAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CACvB,iBAAY,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAC,CAAC,CAChE,CAAA;aACF;iBAAM;gBACL,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,qBACE,OAAO,CAAC,GAAG,CAAC,iBACd,kBAAkB,QAAG,EAAE,CACxB,CAAA;aACF;SACF;QACD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,iBAA2B,CAAA;QACxD,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,eAAyB,CAAA;QACrD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,aAAuB,CAAA;QACjD,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,YAAsB,CAAA;IACjD,CAAC;IAED,IAAI,KAAK;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;QAE5B,yBACK,IAAI,CAAC,IAAI,IACZ,MAAM,EAAE,CAAC,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,CAAC,MAAM,IACjE;IACH,CAAC;IAED,IAAI,IAAI;QACN,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;YACjC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;YAC9D,OAAO,EAAC,KAAK,EAAE,IAAI,EAAC,CAAA;SACrB;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE;YAC3B,OAAO;gBACL,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK;gBAC1C,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI;aACnC,CAAA;SACF;QAED,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,CAAA;IACH,CAAC;CACF;AAjED,0BAiEC"}

View File

@@ -1,32 +1,32 @@
{ {
"_args": [ "_args": [
[ [
"@actions/github@1.0.0", "@actions/github@1.0.1",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "@actions/github@1.0.0", "_from": "@actions/github@1.0.1",
"_id": "@actions/github@1.0.0", "_id": "@actions/github@1.0.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-PPbWZ5wFAD/Vr+RCECfR3KNHjTwYln4liJBihs9tQUL0/PCFqB2lSkIh9V94AcZFHxgKk8snImjuLaBE8bKR7A==", "_integrity": "sha512-fmji0JB0E4vmtXVjnqCJouLP4AyM/B5nbLe9U9ooPerxXh9r+VBlx8Lh5c+Dlvux1GooUduQxy4XVA21Lfs/Wg==",
"_location": "/@actions/github", "_location": "/@actions/github",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@actions/github@1.0.0", "raw": "@actions/github@1.0.1",
"name": "@actions/github", "name": "@actions/github",
"escapedName": "@actions%2fgithub", "escapedName": "@actions%2fgithub",
"scope": "@actions", "scope": "@actions",
"rawSpec": "1.0.0", "rawSpec": "1.0.1",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "1.0.0" "fetchSpec": "1.0.1"
}, },
"_requiredBy": [ "_requiredBy": [
"/" "/"
], ],
"_resolved": "https://registry.npmjs.org/@actions/github/-/github-1.0.0.tgz", "_resolved": "https://registry.npmjs.org/@actions/github/-/github-1.0.1.tgz",
"_spec": "1.0.0", "_spec": "1.0.1",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"bugs": { "bugs": {
"url": "https://github.com/actions/toolkit/issues" "url": "https://github.com/actions/toolkit/issues"
@@ -46,7 +46,6 @@
"files": [ "files": [
"lib" "lib"
], ],
"gitHead": "a40bce7c8d382aa3dbadaa327acbc696e9390e55",
"homepage": "https://github.com/actions/toolkit/tree/master/packages/github", "homepage": "https://github.com/actions/toolkit/tree/master/packages/github",
"keywords": [ "keywords": [
"github", "github",
@@ -67,5 +66,5 @@
"test": "jest", "test": "jest",
"tsc": "tsc" "tsc": "tsc"
}, },
"version": "1.0.0" "version": "1.0.1"
} }

View File

@@ -4,10 +4,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deepmerge = _interopDefault(require('deepmerge'));
var isPlainObject = _interopDefault(require('is-plain-object')); var isPlainObject = _interopDefault(require('is-plain-object'));
var urlTemplate = _interopDefault(require('url-template')); var universalUserAgent = require('universal-user-agent');
var getUserAgent = _interopDefault(require('universal-user-agent'));
function lowercaseKeys(object) { function lowercaseKeys(object) {
if (!object) { if (!object) {
@@ -20,6 +18,22 @@ function lowercaseKeys(object) {
}, {}); }, {});
} }
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach(key => {
if (isPlainObject(options[key])) {
if (!(key in defaults)) Object.assign(result, {
[key]: options[key]
});else result[key] = mergeDeep(defaults[key], options[key]);
} else {
Object.assign(result, {
[key]: options[key]
});
}
});
return result;
}
function merge(defaults, route, options) { function merge(defaults, route, options) {
if (typeof route === "string") { if (typeof route === "string") {
let [method, url] = route.split(" "); let [method, url] = route.split(" ");
@@ -35,9 +49,7 @@ function merge(defaults, route, options) {
options.headers = lowercaseKeys(options.headers); options.headers = lowercaseKeys(options.headers);
const mergedOptions = deepmerge.all([defaults, options].filter(Boolean), { const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
isMergeableObject: isPlainObject
}); // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) { if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
@@ -87,6 +99,173 @@ function omit(object, keysToOmit) {
}, {}); }, {});
} }
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key],
result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
} else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
} else {
return values.join(",");
}
} else {
return encodeReserved(literal);
}
});
}
function parse(options) { function parse(options) {
// https://fetch.spec.whatwg.org/#methods // https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
@@ -97,7 +276,7 @@ function parse(options) {
let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url); const urlVariableNames = extractUrlVariableNames(url);
url = urlTemplate.parse(url).expand(parameters); url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) { if (!/^http/.test(url)) {
url = options.baseUrl + url; url = options.baseUrl + url;
@@ -178,7 +357,7 @@ function withDefaults(oldDefaults, newDefaults) {
const VERSION = "0.0.0-development"; const VERSION = "0.0.0-development";
const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`;
const DEFAULTS = { const DEFAULTS = {
method: "GET", method: "GET",
baseUrl: "https://api.github.com", baseUrl: "https://api.github.com",
@@ -195,3 +374,4 @@ const DEFAULTS = {
const endpoint = withDefaults(null, DEFAULTS); const endpoint = withDefaults(null, DEFAULTS);
exports.endpoint = endpoint; exports.endpoint = endpoint;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
import getUserAgent from "universal-user-agent"; import { getUserAgent } from "universal-user-agent";
import { VERSION } from "./version"; import { VERSION } from "./version";
const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
export const DEFAULTS = { export const DEFAULTS = {

View File

@@ -1,6 +1,5 @@
import deepmerge from "deepmerge";
import isPlainObject from "is-plain-object";
import { lowercaseKeys } from "./util/lowercase-keys"; import { lowercaseKeys } from "./util/lowercase-keys";
import { mergeDeep } from "./util/merge-deep";
export function merge(defaults, route, options) { export function merge(defaults, route, options) {
if (typeof route === "string") { if (typeof route === "string") {
let [method, url] = route.split(" "); let [method, url] = route.split(" ");
@@ -11,9 +10,7 @@ export function merge(defaults, route, options) {
} }
// lowercase header names before merging with defaults to avoid duplicates // lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers); options.headers = lowercaseKeys(options.headers);
const mergedOptions = deepmerge.all([defaults, options].filter(Boolean), { const mergedOptions = mergeDeep(defaults || {}, options);
isMergeableObject: isPlainObject
});
// mediaType.previews arrays are merged, instead of overwritten // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) { if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews mergedOptions.mediaType.previews = defaults.mediaType.previews

View File

@@ -1,7 +1,7 @@
import urlTemplate from "url-template";
import { addQueryParameters } from "./util/add-query-parameters"; import { addQueryParameters } from "./util/add-query-parameters";
import { extractUrlVariableNames } from "./util/extract-url-variable-names"; import { extractUrlVariableNames } from "./util/extract-url-variable-names";
import { omit } from "./util/omit"; import { omit } from "./util/omit";
import { parseUrl } from "./util/url-template";
export function parse(options) { export function parse(options) {
// https://fetch.spec.whatwg.org/#methods // https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); let method = options.method.toUpperCase();
@@ -19,7 +19,7 @@ export function parse(options) {
]); ]);
// extract variable names from URL to calculate remaining variables later // extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url); const urlVariableNames = extractUrlVariableNames(url);
url = urlTemplate.parse(url).expand(parameters); url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) { if (!/^http/.test(url)) {
url = options.baseUrl + url; url = options.baseUrl + url;
} }

View File

@@ -0,0 +1,16 @@
import isPlainObject from "is-plain-object";
export function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach(key => {
if (isPlainObject(options[key])) {
if (!(key in defaults))
Object.assign(result, { [key]: options[key] });
else
result[key] = mergeDeep(defaults[key], options[key]);
}
else {
Object.assign(result, { [key]: options[key] });
}
});
return result;
}

View File

@@ -0,0 +1,170 @@
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str
.split(/(%[0-9A-Fa-f]{2})/g)
.map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part)
.replace(/%5B/g, "[")
.replace(/%5D/g, "]");
}
return part;
})
.join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return ("%" +
c
.charCodeAt(0)
.toString(16)
.toUpperCase());
});
}
function encodeValue(operator, value, key) {
value =
operator === "+" || operator === "#"
? encodeReserved(value)
: encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
}
else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key], result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
}
else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
}
else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
}
else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
}
else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
}
else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
}
else if (value === "") {
result.push("");
}
}
return result;
}
export function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
}
else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
}
else {
return values.join(",");
}
}
else {
return encodeReserved(literal);
}
});
}

View File

@@ -1,3 +1,5 @@
export declare function lowercaseKeys(object?: { export declare function lowercaseKeys(object?: {
[key: string]: any; [key: string]: any;
}): {}; }): {
[key: string]: any;
};

View File

@@ -0,0 +1 @@
export declare function mergeDeep(defaults: any, options: any): object;

View File

@@ -0,0 +1,3 @@
export declare function parseUrl(template: string): {
expand: (context: object) => string;
};

View File

@@ -1,200 +1,343 @@
import deepmerge from 'deepmerge';
import isPlainObject from 'is-plain-object'; import isPlainObject from 'is-plain-object';
import urlTemplate from 'url-template'; import { getUserAgent } from 'universal-user-agent';
import getUserAgent from 'universal-user-agent';
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function lowercaseKeys(object) { function lowercaseKeys(object) {
if (!object) { if (!object) {
return {}; return {};
} }
return Object.keys(object).reduce((newObj, key) => { return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key]; newObj[key.toLowerCase()] = object[key];
return newObj; return newObj;
}, {}); }, {});
} }
function merge(defaults, route, options) { function mergeDeep(defaults, options) {
if (typeof route === "string") { const result = Object.assign({}, defaults);
let _route$split = route.split(" "), Object.keys(options).forEach(key => {
_route$split2 = _slicedToArray(_route$split, 2), if (isPlainObject(options[key])) {
method = _route$split2[0], if (!(key in defaults))
url = _route$split2[1]; Object.assign(result, { [key]: options[key] });
else
options = Object.assign(url ? { result[key] = mergeDeep(defaults[key], options[key]);
method, }
url else {
} : { Object.assign(result, { [key]: options[key] });
url: method }
}, options); });
} else { return result;
options = route || {};
} // lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers);
const mergedOptions = deepmerge.all([defaults, options].filter(Boolean), {
isMergeableObject: isPlainObject
}); // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
} }
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? { method, url } : { url: method }, options);
}
else {
options = route || {};
}
// lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options);
// mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews
.filter(preview => !mergedOptions.mediaType.previews.includes(preview))
.concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map((preview) => preview.replace(/-preview/, ""));
return mergedOptions; return mergedOptions;
} }
function addQueryParameters(url, parameters) { function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?"; const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters); const names = Object.keys(parameters);
if (names.length === 0) { if (names.length === 0) {
return url; return url;
} }
return (url +
return url + separator + names.map(name => { separator +
names
.map(name => {
if (name === "q") { if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); return ("q=" +
parameters
.q.split("+")
.map(encodeURIComponent)
.join("+"));
} }
return `${name}=${encodeURIComponent(parameters[name])}`;
return "".concat(name, "=").concat(encodeURIComponent(parameters[name])); })
}).join("&"); .join("&"));
} }
const urlVariableRegex = /\{[^}]+\}/g; const urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) { function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/); return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
} }
function extractUrlVariableNames(url) { function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex); const matches = url.match(urlVariableRegex);
if (!matches) { if (!matches) {
return []; return [];
} }
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
} }
function omit(object, keysToOmit) { function omit(object, keysToOmit) {
return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { return Object.keys(object)
.filter(option => !keysToOmit.includes(option))
.reduce((obj, key) => {
obj[key] = object[key]; obj[key] = object[key];
return obj; return obj;
}, {}); }, {});
} }
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str
.split(/(%[0-9A-Fa-f]{2})/g)
.map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part)
.replace(/%5B/g, "[")
.replace(/%5D/g, "]");
}
return part;
})
.join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return ("%" +
c
.charCodeAt(0)
.toString(16)
.toUpperCase());
});
}
function encodeValue(operator, value, key) {
value =
operator === "+" || operator === "#"
? encodeReserved(value)
: encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
}
else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key], result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
}
else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
}
else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
}
else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
}
else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
}
else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
}
else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
}
else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
}
else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
}
else {
return values.join(",");
}
}
else {
return encodeReserved(literal);
}
});
}
function parse(options) { function parse(options) {
// https://fetch.spec.whatwg.org/#methods // https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible let method = options.method.toUpperCase();
// replace :varname with {varname} to make it RFC 6570 compatible
let url = options.url.replace(/:([a-z]\w+)/g, "{+$1}"); let url = options.url.replace(/:([a-z]\w+)/g, "{+$1}");
let headers = Object.assign({}, options.headers); let headers = Object.assign({}, options.headers);
let body; let body;
let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later let parameters = omit(options, [
"method",
"baseUrl",
"url",
"headers",
"request",
"mediaType"
]);
// extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url); const urlVariableNames = extractUrlVariableNames(url);
url = urlTemplate.parse(url).expand(parameters); url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) { if (!/^http/.test(url)) {
url = options.baseUrl + url; url = options.baseUrl + url;
} }
const omittedParameters = Object.keys(options)
const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); .filter(option => urlVariableNames.includes(option))
.concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters); const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequset = /application\/octet-stream/i.test(headers.accept); const isBinaryRequset = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequset) { if (!isBinaryRequset) {
if (options.mediaType.format) { if (options.mediaType.format) {
// e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, "application/vnd$1$2.".concat(options.mediaType.format))).join(","); headers.accept = headers.accept
.split(/,/)
.map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`))
.join(",");
} }
if (options.mediaType.previews.length) { if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { headers.accept = previewsFromAcceptHeader
const format = options.mediaType.format ? ".".concat(options.mediaType.format) : "+json"; .concat(options.mediaType.previews)
return "application/vnd.github.".concat(preview, "-preview").concat(format); .map(preview => {
}).join(","); const format = options.mediaType.format
? `.${options.mediaType.format}`
: "+json";
return `application/vnd.github.${preview}-preview${format}`;
})
.join(",");
} }
} // for GET/HEAD requests, set URL query parameters from remaining parameters }
// for GET/HEAD requests, set URL query parameters from remaining parameters
// for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
if (["GET", "HEAD"].includes(method)) { if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters); url = addQueryParameters(url, remainingParameters);
} else { }
else {
if ("data" in remainingParameters) { if ("data" in remainingParameters) {
body = remainingParameters.data; body = remainingParameters.data;
} else { }
else {
if (Object.keys(remainingParameters).length) { if (Object.keys(remainingParameters).length) {
body = remainingParameters; body = remainingParameters;
} else { }
else {
headers["content-length"] = 0; headers["content-length"] = 0;
} }
} }
} // default content-type for JSON if body is set }
// default content-type for JSON if body is set
if (!headers["content-type"] && typeof body !== "undefined") { if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8"; headers["content-type"] = "application/json; charset=utf-8";
} // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. }
// GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
// fetch does not allow to set `content-length` header, but we can set body to an empty string // fetch does not allow to set `content-length` header, but we can set body to an empty string
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = ""; body = "";
} // Only return body/request keys if present }
// Only return body/request keys if present
return Object.assign({ method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null);
return Object.assign({
method,
url,
headers
}, typeof body !== "undefined" ? {
body
} : null, options.request ? {
request: options.request
} : null);
} }
function endpointWithDefaults(defaults, route, options) { function endpointWithDefaults(defaults, route, options) {
@@ -214,7 +357,7 @@ function withDefaults(oldDefaults, newDefaults) {
const VERSION = "0.0.0-development"; const VERSION = "0.0.0-development";
const userAgent = "octokit-endpoint.js/".concat(VERSION, " ").concat(getUserAgent()); const userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;
const DEFAULTS = { const DEFAULTS = {
method: "GET", method: "GET",
baseUrl: "https://api.github.com", baseUrl: "https://api.github.com",
@@ -231,3 +374,4 @@ const DEFAULTS = {
const endpoint = withDefaults(null, DEFAULTS); const endpoint = withDefaults(null, DEFAULTS);
export { endpoint }; export { endpoint };
//# sourceMappingURL=index.js.map

1
node_modules/@octokit/endpoint/dist-web/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,35 +0,0 @@
language: node_js
cache: npm
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- master
- /^greenkeeper.*$/
stages:
- test
- name: release
if: branch = master AND type IN (push)
jobs:
include:
- stage: test
node_js: 12
script: npm run test
- node_js: 8
script: npm run test
- node_js: 10
env: Node 10 & coverage upload
script:
- npm run test
- npm run coverage:upload
- node_js: lts/*
env: browser tests
script: npm run test:browser
- stage: release
node_js: lts/*
env: semantic-release
script: npm run semantic-release

View File

@@ -4,13 +4,13 @@
[![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent) [![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent)
[![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent) [![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent)
[![Coverage Status](https://coveralls.io/repos/github/gr2m/universal-user-agent/badge.svg)](https://coveralls.io/github/gr2m/universal-user-agent)
[![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/) [![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/)
```js ```js
const getUserAgent = require('universal-user-agent') const { getUserAgent } = require("universal-user-agent");
const userAgent = getUserAgent() // or import { getUserAgent } from "universal-user-agent";
const userAgent = getUserAgent();
// userAgent will look like this // userAgent will look like this
// in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0" // in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
// in node: Node.js/v8.9.4 (macOS High Sierra; x64) // in node: Node.js/v8.9.4 (macOS High Sierra; x64)

View File

@@ -1,6 +0,0 @@
module.exports = getUserAgentBrowser
function getUserAgentBrowser () {
/* global navigator */
return navigator.userAgent
}

View File

@@ -1,4 +0,0 @@
{
"integrationFolder": "test",
"video": false
}

View File

@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(require('os-name'));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/node.js"],"sourcesContent":["import osName from \"os-name\";\nexport function getUserAgent() {\n try {\n return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;\n }\n catch (error) {\n if (/wmic os get Caption/.test(error.message)) {\n return \"Windows <version undetectable>\";\n }\n throw error;\n }\n}\n"],"names":["getUserAgent","process","version","substr","osName","arch","error","test","message"],"mappings":";;;;;;;;AACO,SAASA,YAAT,GAAwB;MACvB;WACQ,WAAUC,OAAO,CAACC,OAAR,CAAgBC,MAAhB,CAAuB,CAAvB,CAA0B,KAAIC,MAAM,EAAG,KAAIH,OAAO,CAACI,IAAK,GAA1E;GADJ,CAGA,OAAOC,KAAP,EAAc;QACN,sBAAsBC,IAAtB,CAA2BD,KAAK,CAACE,OAAjC,CAAJ,EAA+C;aACpC,gCAAP;;;UAEEF,KAAN;;;;;;"}

View File

@@ -0,0 +1,3 @@
export function getUserAgent() {
return navigator.userAgent;
}

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1,12 @@
import osName from "os-name";
export function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
}
catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1,6 @@
function getUserAgent() {
return navigator.userAgent;
}
export { getUserAgent };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/browser.js"],"sourcesContent":["export function getUserAgent() {\n return navigator.userAgent;\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;IAC3B,OAAO,SAAS,CAAC,SAAS,CAAC;CAC9B;;;;"}

View File

@@ -1 +0,0 @@
export default function getUserAgentNode(): string;

View File

@@ -1,15 +0,0 @@
module.exports = getUserAgentNode
const osName = require('os-name')
function getUserAgentNode () {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return 'Windows <version undetectable>'
}
throw error
}
}

View File

@@ -1,85 +1,68 @@
{ {
"_args": [ "_args": [
[ [
"universal-user-agent@3.0.0", "universal-user-agent@4.0.0",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "universal-user-agent@3.0.0", "_from": "universal-user-agent@4.0.0",
"_id": "universal-user-agent@3.0.0", "_id": "universal-user-agent@4.0.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA==", "_integrity": "sha512-eM8knLpev67iBDizr/YtqkJsF3GK8gzDc6st/WKzrTuPtcsOKW/0IdL4cnMBsU69pOx0otavLWBDGTwg+dB0aA==",
"_location": "/@octokit/endpoint/universal-user-agent", "_location": "/@octokit/endpoint/universal-user-agent",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "universal-user-agent@3.0.0", "raw": "universal-user-agent@4.0.0",
"name": "universal-user-agent", "name": "universal-user-agent",
"escapedName": "universal-user-agent", "escapedName": "universal-user-agent",
"rawSpec": "3.0.0", "rawSpec": "4.0.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "3.0.0" "fetchSpec": "4.0.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/@octokit/endpoint" "/@octokit/endpoint"
], ],
"_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-3.0.0.tgz", "_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.0.tgz",
"_spec": "3.0.0", "_spec": "4.0.0",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"author": {
"name": "Gregor Martynus",
"url": "https://github.com/gr2m"
},
"browser": "browser.js",
"bugs": { "bugs": {
"url": "https://github.com/gr2m/universal-user-agent/issues" "url": "https://github.com/gr2m/universal-user-agent/issues"
}, },
"dependencies": { "dependencies": {
"os-name": "^3.0.0" "os-name": "^3.1.0"
}, },
"description": "Get a user agent string in both browser and node", "description": "Get a user agent string in both browser and node",
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "@gr2m/pika-plugin-build-web": "^0.6.0-issue-84.1",
"coveralls": "^3.0.2", "@pika/pack": "^0.5.0",
"cypress": "^3.1.0", "@pika/plugin-build-node": "^0.6.0",
"mocha": "^6.0.0", "@pika/plugin-ts-standard-pkg": "^0.6.0",
"nyc": "^14.0.0", "@types/jest": "^24.0.18",
"proxyquire": "^2.1.0", "jest": "^24.9.0",
"prettier": "^1.18.2",
"semantic-release": "^15.9.15", "semantic-release": "^15.9.15",
"sinon": "^7.2.4", "ts-jest": "^24.0.2",
"sinon-chai": "^3.2.0", "typescript": "^3.6.2"
"standard": "^13.0.1",
"test": "^0.6.0",
"travis-deploy-once": "^5.0.7"
}, },
"files": [
"dist-*/",
"bin/"
],
"homepage": "https://github.com/gr2m/universal-user-agent#readme", "homepage": "https://github.com/gr2m/universal-user-agent#readme",
"keywords": [], "keywords": [],
"license": "ISC", "license": "ISC",
"main": "index.js", "main": "dist-node/index.js",
"module": "dist-web/index.js",
"name": "universal-user-agent", "name": "universal-user-agent",
"pika": true,
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/gr2m/universal-user-agent.git" "url": "git+https://github.com/gr2m/universal-user-agent.git"
}, },
"scripts": { "sideEffects": false,
"coverage": "nyc report --reporter=html && open coverage/index.html", "source": "dist-src/index.js",
"coverage:upload": "nyc report --reporter=text-lcov | coveralls", "types": "dist-types/index.d.ts",
"pretest": "standard", "version": "4.0.0"
"semantic-release": "semantic-release",
"test": "nyc mocha \"test/*-test.js\"",
"test:browser": "cypress run --browser chrome",
"travis-deploy-once": "travis-deploy-once"
},
"standard": {
"globals": [
"describe",
"it",
"beforeEach",
"afterEach",
"expect"
]
},
"types": "index.d.ts",
"version": "3.0.0"
} }

View File

@@ -1,57 +0,0 @@
// make tests run in both Node & Express
if (!global.cy) {
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
global.expect = chai.expect
let sandbox
beforeEach(() => {
sandbox = sinon.createSandbox()
global.cy = {
stub: function () {
return sandbox.stub.apply(sandbox, arguments)
},
log () {
console.log.apply(console, arguments)
}
}
})
afterEach(() => {
sandbox.restore()
})
}
const getUserAgent = require('..')
describe('smoke', () => {
it('works', () => {
expect(getUserAgent()).to.be.a('string')
expect(getUserAgent().length).to.be.above(10)
})
if (!process.browser) { // test on node only
const proxyquire = require('proxyquire').noCallThru()
it('works around wmic error on Windows (#5)', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('Command failed: wmic os get Caption')
}
})
expect(getUserAgent()).to.equal('Windows <version undetectable>')
})
it('does not swallow unexpected errors', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('oops')
}
})
expect(getUserAgent).to.throw('oops')
})
}
})

View File

@@ -1,14 +1,14 @@
{ {
"_args": [ "_args": [
[ [
"@octokit/endpoint@5.3.2", "@octokit/endpoint@5.3.5",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "@octokit/endpoint@5.3.2", "_from": "@octokit/endpoint@5.3.5",
"_id": "@octokit/endpoint@5.3.2", "_id": "@octokit/endpoint@5.3.5",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-gRjteEM9I6f4D8vtwU2iGUTn9RX/AJ0SVXiqBUEuYEWVGGAVjSXdT0oNmghH5lvQNWs8mwt6ZaultuG6yXivNw==", "_integrity": "sha512-f8KqzIrnzPLiezDsZZPB+K8v8YSv6aKFl7eOu59O46lmlW4HagWl1U6NWl6LmT8d1w7NsKBI3paVtzcnRGO1gw==",
"_location": "/@octokit/endpoint", "_location": "/@octokit/endpoint",
"_phantomChildren": { "_phantomChildren": {
"os-name": "3.1.0" "os-name": "3.1.0"
@@ -16,43 +16,38 @@
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@octokit/endpoint@5.3.2", "raw": "@octokit/endpoint@5.3.5",
"name": "@octokit/endpoint", "name": "@octokit/endpoint",
"escapedName": "@octokit%2fendpoint", "escapedName": "@octokit%2fendpoint",
"scope": "@octokit", "scope": "@octokit",
"rawSpec": "5.3.2", "rawSpec": "5.3.5",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "5.3.2" "fetchSpec": "5.3.5"
}, },
"_requiredBy": [ "_requiredBy": [
"/@octokit/request" "/@octokit/request"
], ],
"_resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.3.2.tgz", "_resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.3.5.tgz",
"_spec": "5.3.2", "_spec": "5.3.5",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"bugs": { "bugs": {
"url": "https://github.com/octokit/endpoint.js/issues" "url": "https://github.com/octokit/endpoint.js/issues"
}, },
"dependencies": { "dependencies": {
"deepmerge": "4.0.0",
"is-plain-object": "^3.0.0", "is-plain-object": "^3.0.0",
"universal-user-agent": "^3.0.0", "universal-user-agent": "^4.0.0"
"url-template": "^2.0.8"
}, },
"description": "Turns REST API endpoints into generic request options", "description": "Turns REST API endpoints into generic request options",
"devDependencies": { "devDependencies": {
"@octokit/routes": "20.9.2", "@octokit/routes": "20.9.2",
"@pika/pack": "^0.4.0", "@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.4.0", "@pika/plugin-build-node": "^0.6.0",
"@pika/plugin-build-web": "^0.4.0", "@pika/plugin-build-web": "^0.6.0",
"@pika/plugin-ts-standard-pkg": "^0.4.0", "@pika/plugin-ts-standard-pkg": "^0.6.0",
"@types/jest": "^24.0.11", "@types/jest": "^24.0.11",
"@types/url-template": "^2.0.28",
"glob": "^7.1.3",
"handlebars": "^4.1.2", "handlebars": "^4.1.2",
"jest": "^24.7.1", "jest": "^24.7.1",
"lodash.set": "^4.3.2", "lodash.set": "^4.3.2",
"nyc": "^14.0.0",
"pascal-case": "^2.0.1", "pascal-case": "^2.0.1",
"prettier": "1.18.2", "prettier": "1.18.2",
"semantic-release": "^15.13.8", "semantic-release": "^15.13.8",
@@ -87,5 +82,5 @@
"sideEffects": false, "sideEffects": false,
"source": "dist-src/index.js", "source": "dist-src/index.js",
"types": "dist-types/index.d.ts", "types": "dist-types/index.d.ts",
"version": "5.3.2" "version": "5.3.5"
} }

View File

@@ -42,13 +42,17 @@ request("POST /repos/:owner/:repo/issues/:number/labels", {
mediaType: { mediaType: {
previews: ["symmetra"] previews: ["symmetra"]
}, },
owner: "ocotkit", owner: "octokit",
repo: "request.js", repo: "request.js",
number: 1, number: 1,
labels: ["🐛 bug"] labels: ["🐛 bug"]
}); });
``` ```
👶 [Small bundle size](https://bundlephobia.com/result?p=@octokit/request@5.0.3) (\<4kb minified + gzipped)
😎 [Authenticate](#authentication) with any of [GitHubs Authentication Strategies](https://github.com/octokit/auth.js).
👍 Sensible defaults 👍 Sensible defaults
- `baseUrl`: `https://api.github.com` - `baseUrl`: `https://api.github.com`
@@ -59,8 +63,6 @@ request("POST /repos/:owner/:repo/issues/:number/labels", {
🧐 Simple to debug: Sets `error.request` to request options causing the error (with redacted credentials). 🧐 Simple to debug: Sets `error.request` to request options causing the error (with redacted credentials).
👶 Small bundle size (\<5kb minified + gzipped)
## Usage ## Usage
<table> <table>
@@ -110,6 +112,8 @@ console.log(`${result.data.length} repos found.`);
### GraphQL example ### GraphQL example
For GraphQL request we recommend using [`@octokit/graphql`](https://github.com/octokit/graphql.js#readme)
```js ```js
const result = await request("POST /graphql", { const result = await request("POST /graphql", {
headers: { headers: {
@@ -144,6 +148,45 @@ const result = await request({
}); });
``` ```
## Authentication
The simplest way to authenticate a request is to set the `Authorization` header directly, e.g. to a [personal access token](https://github.com/settings/tokens/).
```js
const requestWithAuth = request.defaults({
headers: {
authorization: "token 0000000000000000000000000000000000000001"
}
});
const result = await request("GET /user");
```
For more complex authentication strategies such as GitHub Apps or Basic, we recommend the according authentication library exported by [`@octokit/auth`](https://github.com/octokit/auth.js).
```js
const { createAppAuth } = require("@octokit/auth-app");
const auth = createAppAuth({
id: process.env.APP_ID,
privateKey: process.env.PRIVATE_KEY,
installationId: 123
});
const requestWithAuth = request.defaults({
request: {
hook: auth.hook
},
mediaType: {
previews: ["machine-man"]
}
});
const { data: app } = await requestWithAuth("GET /app");
const { data: app } = await requestWithAuth("POST /repos/:owner/:repo/issues", {
owner: "octocat",
repo: "hello-world",
title: "Hello from the engine room"
});
```
## request() ## request()
`request(route, options)` or `request(options)`. `request(route, options)` or `request(options)`.
@@ -425,10 +468,10 @@ const options = request.endpoint("GET /orgs/:org/repos", {
All of the [`@octokit/endpoint`](https://github.com/octokit/endpoint.js) API can be used: All of the [`@octokit/endpoint`](https://github.com/octokit/endpoint.js) API can be used:
- [`ocotkitRequest.endpoint()`](#endpoint) - [`octokitRequest.endpoint()`](#endpoint)
- [`ocotkitRequest.endpoint.defaults()`](#endpointdefaults) - [`octokitRequest.endpoint.defaults()`](#endpointdefaults)
- [`ocotkitRequest.endpoint.merge()`](#endpointdefaults) - [`octokitRequest.endpoint.merge()`](#endpointdefaults)
- [`ocotkitRequest.endpoint.parse()`](#endpointmerge) - [`octokitRequest.endpoint.parse()`](#endpointmerge)
## Special cases ## Special cases

View File

@@ -5,7 +5,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var endpoint = require('@octokit/endpoint'); var endpoint = require('@octokit/endpoint');
var getUserAgent = _interopDefault(require('universal-user-agent')); var universalUserAgent = require('universal-user-agent');
var isPlainObject = _interopDefault(require('is-plain-object')); var isPlainObject = _interopDefault(require('is-plain-object'));
var nodeFetch = _interopDefault(require('node-fetch')); var nodeFetch = _interopDefault(require('node-fetch'));
var requestError = require('@octokit/request-error'); var requestError = require('@octokit/request-error');
@@ -136,8 +136,9 @@ function withDefaults(oldEndpoint, newDefaults) {
const request = withDefaults(endpoint.endpoint, { const request = withDefaults(endpoint.endpoint, {
headers: { headers: {
"user-agent": `octokit-request.js/${VERSION} ${getUserAgent()}` "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
} }
}); });
exports.request = request; exports.request = request;
//# sourceMappingURL=index.js.map

1
node_modules/@octokit/request/dist-node/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
import { endpoint } from "@octokit/endpoint"; import { endpoint } from "@octokit/endpoint";
import getUserAgent from "universal-user-agent"; import { getUserAgent } from "universal-user-agent";
import { VERSION } from "./version"; import { VERSION } from "./version";
import withDefaults from "./with-defaults"; import withDefaults from "./with-defaults";
export const request = withDefaults(endpoint, { export const request = withDefaults(endpoint, {

View File

@@ -1,5 +1,5 @@
import { endpoint } from '@octokit/endpoint'; import { endpoint } from '@octokit/endpoint';
import getUserAgent from 'universal-user-agent'; import { getUserAgent } from 'universal-user-agent';
import isPlainObject from 'is-plain-object'; import isPlainObject from 'is-plain-object';
import nodeFetch from 'node-fetch'; import nodeFetch from 'node-fetch';
import { RequestError } from '@octokit/request-error'; import { RequestError } from '@octokit/request-error';
@@ -124,3 +124,4 @@ const request = withDefaults(endpoint, {
}); });
export { request }; export { request };
//# sourceMappingURL=index.js.map

1
node_modules/@octokit/request/dist-web/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,35 +0,0 @@
language: node_js
cache: npm
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- master
- /^greenkeeper.*$/
stages:
- test
- name: release
if: branch = master AND type IN (push)
jobs:
include:
- stage: test
node_js: 12
script: npm run test
- node_js: 8
script: npm run test
- node_js: 10
env: Node 10 & coverage upload
script:
- npm run test
- npm run coverage:upload
- node_js: lts/*
env: browser tests
script: npm run test:browser
- stage: release
node_js: lts/*
env: semantic-release
script: npm run semantic-release

View File

@@ -4,13 +4,13 @@
[![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent) [![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent)
[![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent) [![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent)
[![Coverage Status](https://coveralls.io/repos/github/gr2m/universal-user-agent/badge.svg)](https://coveralls.io/github/gr2m/universal-user-agent)
[![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/) [![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/)
```js ```js
const getUserAgent = require('universal-user-agent') const { getUserAgent } = require("universal-user-agent");
const userAgent = getUserAgent() // or import { getUserAgent } from "universal-user-agent";
const userAgent = getUserAgent();
// userAgent will look like this // userAgent will look like this
// in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0" // in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
// in node: Node.js/v8.9.4 (macOS High Sierra; x64) // in node: Node.js/v8.9.4 (macOS High Sierra; x64)

View File

@@ -1,6 +0,0 @@
module.exports = getUserAgentBrowser
function getUserAgentBrowser () {
/* global navigator */
return navigator.userAgent
}

View File

@@ -1,4 +0,0 @@
{
"integrationFolder": "test",
"video": false
}

View File

@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(require('os-name'));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/node.js"],"sourcesContent":["import osName from \"os-name\";\nexport function getUserAgent() {\n try {\n return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;\n }\n catch (error) {\n if (/wmic os get Caption/.test(error.message)) {\n return \"Windows <version undetectable>\";\n }\n throw error;\n }\n}\n"],"names":["getUserAgent","process","version","substr","osName","arch","error","test","message"],"mappings":";;;;;;;;AACO,SAASA,YAAT,GAAwB;MACvB;WACQ,WAAUC,OAAO,CAACC,OAAR,CAAgBC,MAAhB,CAAuB,CAAvB,CAA0B,KAAIC,MAAM,EAAG,KAAIH,OAAO,CAACI,IAAK,GAA1E;GADJ,CAGA,OAAOC,KAAP,EAAc;QACN,sBAAsBC,IAAtB,CAA2BD,KAAK,CAACE,OAAjC,CAAJ,EAA+C;aACpC,gCAAP;;;UAEEF,KAAN;;;;;;"}

View File

@@ -0,0 +1,3 @@
export function getUserAgent() {
return navigator.userAgent;
}

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1,12 @@
import osName from "os-name";
export function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
}
catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1,6 @@
function getUserAgent() {
return navigator.userAgent;
}
export { getUserAgent };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/browser.js"],"sourcesContent":["export function getUserAgent() {\n return navigator.userAgent;\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;IAC3B,OAAO,SAAS,CAAC,SAAS,CAAC;CAC9B;;;;"}

View File

@@ -1 +0,0 @@
export default function getUserAgentNode(): string;

View File

@@ -1,15 +0,0 @@
module.exports = getUserAgentNode
const osName = require('os-name')
function getUserAgentNode () {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return 'Windows <version undetectable>'
}
throw error
}
}

View File

@@ -1,85 +1,68 @@
{ {
"_args": [ "_args": [
[ [
"universal-user-agent@3.0.0", "universal-user-agent@4.0.0",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "universal-user-agent@3.0.0", "_from": "universal-user-agent@4.0.0",
"_id": "universal-user-agent@3.0.0", "_id": "universal-user-agent@4.0.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA==", "_integrity": "sha512-eM8knLpev67iBDizr/YtqkJsF3GK8gzDc6st/WKzrTuPtcsOKW/0IdL4cnMBsU69pOx0otavLWBDGTwg+dB0aA==",
"_location": "/@octokit/request/universal-user-agent", "_location": "/@octokit/request/universal-user-agent",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "universal-user-agent@3.0.0", "raw": "universal-user-agent@4.0.0",
"name": "universal-user-agent", "name": "universal-user-agent",
"escapedName": "universal-user-agent", "escapedName": "universal-user-agent",
"rawSpec": "3.0.0", "rawSpec": "4.0.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "3.0.0" "fetchSpec": "4.0.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/@octokit/request" "/@octokit/request"
], ],
"_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-3.0.0.tgz", "_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.0.tgz",
"_spec": "3.0.0", "_spec": "4.0.0",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"author": {
"name": "Gregor Martynus",
"url": "https://github.com/gr2m"
},
"browser": "browser.js",
"bugs": { "bugs": {
"url": "https://github.com/gr2m/universal-user-agent/issues" "url": "https://github.com/gr2m/universal-user-agent/issues"
}, },
"dependencies": { "dependencies": {
"os-name": "^3.0.0" "os-name": "^3.1.0"
}, },
"description": "Get a user agent string in both browser and node", "description": "Get a user agent string in both browser and node",
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "@gr2m/pika-plugin-build-web": "^0.6.0-issue-84.1",
"coveralls": "^3.0.2", "@pika/pack": "^0.5.0",
"cypress": "^3.1.0", "@pika/plugin-build-node": "^0.6.0",
"mocha": "^6.0.0", "@pika/plugin-ts-standard-pkg": "^0.6.0",
"nyc": "^14.0.0", "@types/jest": "^24.0.18",
"proxyquire": "^2.1.0", "jest": "^24.9.0",
"prettier": "^1.18.2",
"semantic-release": "^15.9.15", "semantic-release": "^15.9.15",
"sinon": "^7.2.4", "ts-jest": "^24.0.2",
"sinon-chai": "^3.2.0", "typescript": "^3.6.2"
"standard": "^13.0.1",
"test": "^0.6.0",
"travis-deploy-once": "^5.0.7"
}, },
"files": [
"dist-*/",
"bin/"
],
"homepage": "https://github.com/gr2m/universal-user-agent#readme", "homepage": "https://github.com/gr2m/universal-user-agent#readme",
"keywords": [], "keywords": [],
"license": "ISC", "license": "ISC",
"main": "index.js", "main": "dist-node/index.js",
"module": "dist-web/index.js",
"name": "universal-user-agent", "name": "universal-user-agent",
"pika": true,
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/gr2m/universal-user-agent.git" "url": "git+https://github.com/gr2m/universal-user-agent.git"
}, },
"scripts": { "sideEffects": false,
"coverage": "nyc report --reporter=html && open coverage/index.html", "source": "dist-src/index.js",
"coverage:upload": "nyc report --reporter=text-lcov | coveralls", "types": "dist-types/index.d.ts",
"pretest": "standard", "version": "4.0.0"
"semantic-release": "semantic-release",
"test": "nyc mocha \"test/*-test.js\"",
"test:browser": "cypress run --browser chrome",
"travis-deploy-once": "travis-deploy-once"
},
"standard": {
"globals": [
"describe",
"it",
"beforeEach",
"afterEach",
"expect"
]
},
"types": "index.d.ts",
"version": "3.0.0"
} }

View File

@@ -1,57 +0,0 @@
// make tests run in both Node & Express
if (!global.cy) {
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
global.expect = chai.expect
let sandbox
beforeEach(() => {
sandbox = sinon.createSandbox()
global.cy = {
stub: function () {
return sandbox.stub.apply(sandbox, arguments)
},
log () {
console.log.apply(console, arguments)
}
}
})
afterEach(() => {
sandbox.restore()
})
}
const getUserAgent = require('..')
describe('smoke', () => {
it('works', () => {
expect(getUserAgent()).to.be.a('string')
expect(getUserAgent().length).to.be.above(10)
})
if (!process.browser) { // test on node only
const proxyquire = require('proxyquire').noCallThru()
it('works around wmic error on Windows (#5)', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('Command failed: wmic os get Caption')
}
})
expect(getUserAgent()).to.equal('Windows <version undetectable>')
})
it('does not swallow unexpected errors', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('oops')
}
})
expect(getUserAgent).to.throw('oops')
})
}
})

View File

@@ -1,14 +1,14 @@
{ {
"_args": [ "_args": [
[ [
"@octokit/request@5.0.2", "@octokit/request@5.1.0",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "@octokit/request@5.0.2", "_from": "@octokit/request@5.1.0",
"_id": "@octokit/request@5.0.2", "_id": "@octokit/request@5.1.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-z1BQr43g4kOL4ZrIVBMHwi68Yg9VbkRUyuAgqCp1rU3vbYa69+2gIld/+gHclw15bJWQnhqqyEb7h5a5EqgZ0A==", "_integrity": "sha512-I15T9PwjFs4tbWyhtFU2Kq7WDPidYMvRB7spmxoQRZfxSmiqullG+Nz+KbSmpkfnlvHwTr1e31R5WReFRKMXjg==",
"_location": "/@octokit/request", "_location": "/@octokit/request",
"_phantomChildren": { "_phantomChildren": {
"os-name": "3.1.0" "os-name": "3.1.0"
@@ -16,20 +16,20 @@
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@octokit/request@5.0.2", "raw": "@octokit/request@5.1.0",
"name": "@octokit/request", "name": "@octokit/request",
"escapedName": "@octokit%2frequest", "escapedName": "@octokit%2frequest",
"scope": "@octokit", "scope": "@octokit",
"rawSpec": "5.0.2", "rawSpec": "5.1.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "5.0.2" "fetchSpec": "5.1.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/@octokit/graphql", "/@octokit/graphql",
"/@octokit/rest" "/@octokit/rest"
], ],
"_resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.0.2.tgz", "_resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.1.0.tgz",
"_spec": "5.0.2", "_spec": "5.1.0",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"bugs": { "bugs": {
"url": "https://github.com/octokit/request.js/issues" "url": "https://github.com/octokit/request.js/issues"
@@ -41,21 +41,24 @@
"is-plain-object": "^3.0.0", "is-plain-object": "^3.0.0",
"node-fetch": "^2.3.0", "node-fetch": "^2.3.0",
"once": "^1.4.0", "once": "^1.4.0",
"universal-user-agent": "^3.0.0" "universal-user-agent": "^4.0.0"
}, },
"description": "Send parameterized requests to GitHubs APIs with sensible defaults in browsers and Node", "description": "Send parameterized requests to GitHubs APIs with sensible defaults in browsers and Node",
"devDependencies": { "devDependencies": {
"@pika/pack": "^0.4.0", "@octokit/auth-app": "^2.1.2",
"@pika/plugin-build-node": "^0.5.1", "@pika/pack": "^0.5.0",
"@pika/plugin-build-web": "^0.5.1", "@pika/plugin-build-node": "^0.6.0",
"@pika/plugin-ts-standard-pkg": "^0.5.1", "@pika/plugin-build-web": "^0.6.0",
"@pika/plugin-ts-standard-pkg": "^0.6.0",
"@types/fetch-mock": "^7.2.4", "@types/fetch-mock": "^7.2.4",
"@types/jest": "^24.0.12", "@types/jest": "^24.0.12",
"@types/lolex": "^3.1.1",
"@types/node": "^12.0.3", "@types/node": "^12.0.3",
"@types/node-fetch": "^2.3.3", "@types/node-fetch": "^2.3.3",
"@types/once": "^1.4.0", "@types/once": "^1.4.0",
"fetch-mock": "^7.2.0", "fetch-mock": "^7.2.0",
"jest": "^24.7.1", "jest": "^24.7.1",
"lolex": "^4.2.0",
"prettier": "^1.17.0", "prettier": "^1.17.0",
"semantic-release": "^15.10.5", "semantic-release": "^15.10.5",
"semantic-release-plugin-update-version-in-files": "^1.0.0", "semantic-release-plugin-update-version-in-files": "^1.0.0",
@@ -88,5 +91,5 @@
"sideEffects": false, "sideEffects": false,
"source": "dist-src/index.js", "source": "dist-src/index.js",
"types": "dist-types/index.d.ts", "types": "dist-types/index.d.ts",
"version": "5.0.2" "version": "5.1.0"
} }

View File

@@ -1,7 +1,7 @@
module.exports = parseOptions module.exports = parseOptions
const { Deprecation } = require('deprecation') const { Deprecation } = require('deprecation')
const getUserAgent = require('universal-user-agent') const { getUserAgent } = require('universal-user-agent')
const once = require('once') const once = require('once')
const pkg = require('../package.json') const pkg = require('../package.json')

View File

@@ -1,35 +0,0 @@
language: node_js
cache: npm
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- master
- /^greenkeeper.*$/
stages:
- test
- name: release
if: branch = master AND type IN (push)
jobs:
include:
- stage: test
node_js: 12
script: npm run test
- node_js: 8
script: npm run test
- node_js: 10
env: Node 10 & coverage upload
script:
- npm run test
- npm run coverage:upload
- node_js: lts/*
env: browser tests
script: npm run test:browser
- stage: release
node_js: lts/*
env: semantic-release
script: npm run semantic-release

View File

@@ -4,13 +4,13 @@
[![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent) [![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent)
[![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent) [![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent)
[![Coverage Status](https://coveralls.io/repos/github/gr2m/universal-user-agent/badge.svg)](https://coveralls.io/github/gr2m/universal-user-agent)
[![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/) [![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/)
```js ```js
const getUserAgent = require('universal-user-agent') const { getUserAgent } = require("universal-user-agent");
const userAgent = getUserAgent() // or import { getUserAgent } from "universal-user-agent";
const userAgent = getUserAgent();
// userAgent will look like this // userAgent will look like this
// in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0" // in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
// in node: Node.js/v8.9.4 (macOS High Sierra; x64) // in node: Node.js/v8.9.4 (macOS High Sierra; x64)

View File

@@ -1,6 +0,0 @@
module.exports = getUserAgentBrowser
function getUserAgentBrowser () {
/* global navigator */
return navigator.userAgent
}

View File

@@ -1,4 +0,0 @@
{
"integrationFolder": "test",
"video": false
}

View File

@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(require('os-name'));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/node.js"],"sourcesContent":["import osName from \"os-name\";\nexport function getUserAgent() {\n try {\n return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;\n }\n catch (error) {\n if (/wmic os get Caption/.test(error.message)) {\n return \"Windows <version undetectable>\";\n }\n throw error;\n }\n}\n"],"names":["getUserAgent","process","version","substr","osName","arch","error","test","message"],"mappings":";;;;;;;;AACO,SAASA,YAAT,GAAwB;MACvB;WACQ,WAAUC,OAAO,CAACC,OAAR,CAAgBC,MAAhB,CAAuB,CAAvB,CAA0B,KAAIC,MAAM,EAAG,KAAIH,OAAO,CAACI,IAAK,GAA1E;GADJ,CAGA,OAAOC,KAAP,EAAc;QACN,sBAAsBC,IAAtB,CAA2BD,KAAK,CAACE,OAAjC,CAAJ,EAA+C;aACpC,gCAAP;;;UAEEF,KAAN;;;;;;"}

View File

@@ -0,0 +1,3 @@
export function getUserAgent() {
return navigator.userAgent;
}

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1,12 @@
import osName from "os-name";
export function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
}
catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1,6 @@
function getUserAgent() {
return navigator.userAgent;
}
export { getUserAgent };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/browser.js"],"sourcesContent":["export function getUserAgent() {\n return navigator.userAgent;\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;IAC3B,OAAO,SAAS,CAAC,SAAS,CAAC;CAC9B;;;;"}

View File

@@ -1 +0,0 @@
export default function getUserAgentNode(): string;

View File

@@ -1,15 +0,0 @@
module.exports = getUserAgentNode
const osName = require('os-name')
function getUserAgentNode () {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return 'Windows <version undetectable>'
}
throw error
}
}

View File

@@ -1,85 +1,68 @@
{ {
"_args": [ "_args": [
[ [
"universal-user-agent@3.0.0", "universal-user-agent@4.0.0",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "universal-user-agent@3.0.0", "_from": "universal-user-agent@4.0.0",
"_id": "universal-user-agent@3.0.0", "_id": "universal-user-agent@4.0.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA==", "_integrity": "sha512-eM8knLpev67iBDizr/YtqkJsF3GK8gzDc6st/WKzrTuPtcsOKW/0IdL4cnMBsU69pOx0otavLWBDGTwg+dB0aA==",
"_location": "/@octokit/rest/universal-user-agent", "_location": "/@octokit/rest/universal-user-agent",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "universal-user-agent@3.0.0", "raw": "universal-user-agent@4.0.0",
"name": "universal-user-agent", "name": "universal-user-agent",
"escapedName": "universal-user-agent", "escapedName": "universal-user-agent",
"rawSpec": "3.0.0", "rawSpec": "4.0.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "3.0.0" "fetchSpec": "4.0.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/@octokit/rest" "/@octokit/rest"
], ],
"_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-3.0.0.tgz", "_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.0.tgz",
"_spec": "3.0.0", "_spec": "4.0.0",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"author": {
"name": "Gregor Martynus",
"url": "https://github.com/gr2m"
},
"browser": "browser.js",
"bugs": { "bugs": {
"url": "https://github.com/gr2m/universal-user-agent/issues" "url": "https://github.com/gr2m/universal-user-agent/issues"
}, },
"dependencies": { "dependencies": {
"os-name": "^3.0.0" "os-name": "^3.1.0"
}, },
"description": "Get a user agent string in both browser and node", "description": "Get a user agent string in both browser and node",
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "@gr2m/pika-plugin-build-web": "^0.6.0-issue-84.1",
"coveralls": "^3.0.2", "@pika/pack": "^0.5.0",
"cypress": "^3.1.0", "@pika/plugin-build-node": "^0.6.0",
"mocha": "^6.0.0", "@pika/plugin-ts-standard-pkg": "^0.6.0",
"nyc": "^14.0.0", "@types/jest": "^24.0.18",
"proxyquire": "^2.1.0", "jest": "^24.9.0",
"prettier": "^1.18.2",
"semantic-release": "^15.9.15", "semantic-release": "^15.9.15",
"sinon": "^7.2.4", "ts-jest": "^24.0.2",
"sinon-chai": "^3.2.0", "typescript": "^3.6.2"
"standard": "^13.0.1",
"test": "^0.6.0",
"travis-deploy-once": "^5.0.7"
}, },
"files": [
"dist-*/",
"bin/"
],
"homepage": "https://github.com/gr2m/universal-user-agent#readme", "homepage": "https://github.com/gr2m/universal-user-agent#readme",
"keywords": [], "keywords": [],
"license": "ISC", "license": "ISC",
"main": "index.js", "main": "dist-node/index.js",
"module": "dist-web/index.js",
"name": "universal-user-agent", "name": "universal-user-agent",
"pika": true,
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/gr2m/universal-user-agent.git" "url": "git+https://github.com/gr2m/universal-user-agent.git"
}, },
"scripts": { "sideEffects": false,
"coverage": "nyc report --reporter=html && open coverage/index.html", "source": "dist-src/index.js",
"coverage:upload": "nyc report --reporter=text-lcov | coveralls", "types": "dist-types/index.d.ts",
"pretest": "standard", "version": "4.0.0"
"semantic-release": "semantic-release",
"test": "nyc mocha \"test/*-test.js\"",
"test:browser": "cypress run --browser chrome",
"travis-deploy-once": "travis-deploy-once"
},
"standard": {
"globals": [
"describe",
"it",
"beforeEach",
"afterEach",
"expect"
]
},
"types": "index.d.ts",
"version": "3.0.0"
} }

View File

@@ -1,57 +0,0 @@
// make tests run in both Node & Express
if (!global.cy) {
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
global.expect = chai.expect
let sandbox
beforeEach(() => {
sandbox = sinon.createSandbox()
global.cy = {
stub: function () {
return sandbox.stub.apply(sandbox, arguments)
},
log () {
console.log.apply(console, arguments)
}
}
})
afterEach(() => {
sandbox.restore()
})
}
const getUserAgent = require('..')
describe('smoke', () => {
it('works', () => {
expect(getUserAgent()).to.be.a('string')
expect(getUserAgent().length).to.be.above(10)
})
if (!process.browser) { // test on node only
const proxyquire = require('proxyquire').noCallThru()
it('works around wmic error on Windows (#5)', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('Command failed: wmic os get Caption')
}
})
expect(getUserAgent()).to.equal('Windows <version undetectable>')
})
it('does not swallow unexpected errors', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('oops')
}
})
expect(getUserAgent).to.throw('oops')
})
}
})

View File

@@ -1,14 +1,14 @@
{ {
"_args": [ "_args": [
[ [
"@octokit/rest@16.28.7", "@octokit/rest@16.28.9",
"/home/svenstaro/prj/upload-release-action" "/home/svenstaro/prj/upload-release-action"
] ]
], ],
"_from": "@octokit/rest@16.28.7", "_from": "@octokit/rest@16.28.9",
"_id": "@octokit/rest@16.28.7", "_id": "@octokit/rest@16.28.9",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-cznFSLEhh22XD3XeqJw51OLSfyL2fcFKUO+v2Ep9MTAFfFLS1cK1Zwd1yEgQJmJoDnj4/vv3+fGGZweG+xsbIA==", "_integrity": "sha512-IKGnX+Tvzt7XHhs8f4ajqxyJvYAMNX5nWfoJm4CQj8LZToMiaJgutf5KxxpxoC3y5w7JTJpW5rnWnF4TsIvCLA==",
"_location": "/@octokit/rest", "_location": "/@octokit/rest",
"_phantomChildren": { "_phantomChildren": {
"os-name": "3.1.0" "os-name": "3.1.0"
@@ -16,19 +16,19 @@
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@octokit/rest@16.28.7", "raw": "@octokit/rest@16.28.9",
"name": "@octokit/rest", "name": "@octokit/rest",
"escapedName": "@octokit%2frest", "escapedName": "@octokit%2frest",
"scope": "@octokit", "scope": "@octokit",
"rawSpec": "16.28.7", "rawSpec": "16.28.9",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "16.28.7" "fetchSpec": "16.28.9"
}, },
"_requiredBy": [ "_requiredBy": [
"/@actions/github" "/@actions/github"
], ],
"_resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.28.7.tgz", "_resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.28.9.tgz",
"_spec": "16.28.7", "_spec": "16.28.9",
"_where": "/home/svenstaro/prj/upload-release-action", "_where": "/home/svenstaro/prj/upload-release-action",
"author": { "author": {
"name": "Gregor Martynus", "name": "Gregor Martynus",
@@ -73,8 +73,7 @@
"lodash.uniq": "^4.5.0", "lodash.uniq": "^4.5.0",
"octokit-pagination-methods": "^1.1.0", "octokit-pagination-methods": "^1.1.0",
"once": "^1.4.0", "once": "^1.4.0",
"universal-user-agent": "^3.0.0", "universal-user-agent": "^4.0.0"
"url-template": "^2.0.8"
}, },
"description": "GitHub REST API client for Node.js", "description": "GitHub REST API client for Node.js",
"devDependencies": { "devDependencies": {
@@ -102,8 +101,8 @@
"semantic-release": "^15.0.0", "semantic-release": "^15.0.0",
"sinon": "^7.2.4", "sinon": "^7.2.4",
"sinon-chai": "^3.0.0", "sinon-chai": "^3.0.0",
"sort-keys": "^3.0.0", "sort-keys": "^4.0.0",
"standard": "^13.0.1", "standard": "^14.0.2",
"string-to-arraybuffer": "^1.0.0", "string-to-arraybuffer": "^1.0.0",
"string-to-jsdoc-comment": "^1.0.0", "string-to-jsdoc-comment": "^1.0.0",
"typescript": "^3.3.1", "typescript": "^3.3.1",
@@ -185,5 +184,5 @@
] ]
}, },
"types": "index.d.ts", "types": "index.d.ts",
"version": "16.28.7" "version": "16.28.9"
} }

View File

@@ -10,20 +10,20 @@ function authenticationBeforeRequest (state, options) {
if (state.auth.type === 'basic') { if (state.auth.type === 'basic') {
const hash = btoa(`${state.auth.username}:${state.auth.password}`) const hash = btoa(`${state.auth.username}:${state.auth.password}`)
options.headers['authorization'] = `Basic ${hash}` options.headers.authorization = `Basic ${hash}`
return return
} }
if (state.auth.type === 'token') { if (state.auth.type === 'token') {
options.headers['authorization'] = `token ${state.auth.token}` options.headers.authorization = `token ${state.auth.token}`
return return
} }
if (state.auth.type === 'app') { if (state.auth.type === 'app') {
options.headers['authorization'] = `Bearer ${state.auth.token}` options.headers.authorization = `Bearer ${state.auth.token}`
const acceptHeaders = options.headers['accept'].split(',') const acceptHeaders = options.headers.accept.split(',')
.concat('application/vnd.github.machine-man-preview+json') .concat('application/vnd.github.machine-man-preview+json')
options.headers['accept'] = uniq(acceptHeaders).filter(Boolean).join(',') options.headers.accept = uniq(acceptHeaders).filter(Boolean).join(',')
return return
} }

View File

@@ -6,13 +6,13 @@ const withAuthorizationPrefix = require('./with-authorization-prefix')
function authenticationBeforeRequest (state, options) { function authenticationBeforeRequest (state, options) {
if (typeof state.auth === 'string') { if (typeof state.auth === 'string') {
options.headers['authorization'] = withAuthorizationPrefix(state.auth) options.headers.authorization = withAuthorizationPrefix(state.auth)
// https://developer.github.com/v3/previews/#integrations // https://developer.github.com/v3/previews/#integrations
if (/^bearer /i.test(state.auth) && !/machine-man/.test(options.headers['accept'])) { if (/^bearer /i.test(state.auth) && !/machine-man/.test(options.headers.accept)) {
const acceptHeaders = options.headers['accept'].split(',') const acceptHeaders = options.headers.accept.split(',')
.concat('application/vnd.github.machine-man-preview+json') .concat('application/vnd.github.machine-man-preview+json')
options.headers['accept'] = acceptHeaders.filter(Boolean).join(',') options.headers.accept = acceptHeaders.filter(Boolean).join(',')
} }
return return
@@ -20,7 +20,7 @@ function authenticationBeforeRequest (state, options) {
if (state.auth.username) { if (state.auth.username) {
const hash = btoa(`${state.auth.username}:${state.auth.password}`) const hash = btoa(`${state.auth.username}:${state.auth.password}`)
options.headers['authorization'] = `Basic ${hash}` options.headers.authorization = `Basic ${hash}`
if (state.otp) { if (state.otp) {
options.headers['x-github-otp'] = state.otp options.headers['x-github-otp'] = state.otp
} }
@@ -40,7 +40,7 @@ function authenticationBeforeRequest (state, options) {
// as well as "/applications/123/tokens/token456" // as well as "/applications/123/tokens/token456"
if (/\/applications\/:?[\w_]+\/tokens\/:?[\w_]+($|\?)/.test(options.url)) { if (/\/applications\/:?[\w_]+\/tokens\/:?[\w_]+($|\?)/.test(options.url)) {
const hash = btoa(`${state.auth.clientId}:${state.auth.clientSecret}`) const hash = btoa(`${state.auth.clientId}:${state.auth.clientSecret}`)
options.headers['authorization'] = `Basic ${hash}` options.headers.authorization = `Basic ${hash}`
return return
} }
@@ -56,6 +56,6 @@ function authenticationBeforeRequest (state, options) {
}) })
.then((authorization) => { .then((authorization) => {
options.headers['authorization'] = withAuthorizationPrefix(authorization) options.headers.authorization = withAuthorizationPrefix(authorization)
}) })
} }

View File

@@ -2,7 +2,7 @@ module.exports = octokitDebug
function octokitDebug (octokit) { function octokitDebug (octokit) {
octokit.hook.wrap('request', (request, options) => { octokit.hook.wrap('request', (request, options) => {
octokit.log.debug(`request`, options) octokit.log.debug('request', options)
const start = Date.now() const start = Date.now()
const requestOptions = octokit.request.endpoint.parse(options) const requestOptions = octokit.request.endpoint.parse(options)
const path = requestOptions.url.replace(options.baseUrl, '') const path = requestOptions.url.replace(options.baseUrl, '')

5
node_modules/balanced-match/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,5 @@
test
.gitignore
.travis.yml
Makefile
example.js

21
node_modules/balanced-match/LICENSE.md generated vendored Normal file
View File

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

91
node_modules/balanced-match/README.md generated vendored Normal file
View File

@@ -0,0 +1,91 @@
# balanced-match
Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)
## Example
Get the first matching pair of braces:
```js
var balanced = require('balanced-match');
console.log(balanced('{', '}', 'pre{in{nested}}post'));
console.log(balanced('{', '}', 'pre{first}between{second}post'));
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'));
```
The matches are:
```bash
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
end: 9,
pre: 'pre',
body: 'first',
post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
```
## API
### var m = balanced(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
object with those keys:
* **start** the index of the first match of `a`
* **end** the index of the matching `b`
* **pre** the preamble, `a` and `b` not included
* **body** the match, `a` and `b` not included
* **post** the postscript, `a` and `b` not included
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
### var r = balanced.range(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
array with indexes: `[ <a index>, <b index> ]`.
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install balanced-match
```
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

59
node_modules/balanced-match/index.js generated vendored Normal file
View File

@@ -0,0 +1,59 @@
'use strict';
module.exports = balanced;
function balanced(a, b, str) {
if (a instanceof RegExp) a = maybeMatch(a, str);
if (b instanceof RegExp) b = maybeMatch(b, str);
var r = range(a, b, str);
return r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + a.length, r[1]),
post: str.slice(r[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m = str.match(reg);
return m ? m[0] : null;
}
balanced.range = range;
function range(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i = ai;
if (ai >= 0 && bi > 0) {
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i == ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length == 1) {
result = [ begs.pop(), bi ];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [ left, right ];
}
}
return result;
}

80
node_modules/balanced-match/package.json generated vendored Normal file
View File

@@ -0,0 +1,80 @@
{
"_args": [
[
"balanced-match@1.0.0",
"/home/svenstaro/prj/upload-release-action"
]
],
"_from": "balanced-match@1.0.0",
"_id": "balanced-match@1.0.0",
"_inBundle": false,
"_integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"_location": "/balanced-match",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "balanced-match@1.0.0",
"name": "balanced-match",
"escapedName": "balanced-match",
"rawSpec": "1.0.0",
"saveSpec": null,
"fetchSpec": "1.0.0"
},
"_requiredBy": [
"/brace-expansion"
],
"_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"_spec": "1.0.0",
"_where": "/home/svenstaro/prj/upload-release-action",
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/balanced-match/issues"
},
"dependencies": {},
"description": "Match balanced character pairs, like \"{\" and \"}\"",
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"homepage": "https://github.com/juliangruber/balanced-match",
"keywords": [
"match",
"regexp",
"test",
"balanced",
"parse"
],
"license": "MIT",
"main": "index.js",
"name": "balanced-match",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/balanced-match.git"
},
"scripts": {
"bench": "make bench",
"test": "make test"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "1.0.0"
}

21
node_modules/brace-expansion/LICENSE generated vendored Normal file
View File

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

129
node_modules/brace-expansion/README.md generated vendored Normal file
View File

@@ -0,0 +1,129 @@
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

201
node_modules/brace-expansion/index.js generated vendored Normal file
View File

@@ -0,0 +1,201 @@
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}

78
node_modules/brace-expansion/package.json generated vendored Normal file
View File

@@ -0,0 +1,78 @@
{
"_args": [
[
"brace-expansion@1.1.11",
"/home/svenstaro/prj/upload-release-action"
]
],
"_from": "brace-expansion@1.1.11",
"_id": "brace-expansion@1.1.11",
"_inBundle": false,
"_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"_location": "/brace-expansion",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "brace-expansion@1.1.11",
"name": "brace-expansion",
"escapedName": "brace-expansion",
"rawSpec": "1.1.11",
"saveSpec": null,
"fetchSpec": "1.1.11"
},
"_requiredBy": [
"/minimatch"
],
"_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"_spec": "1.1.11",
"_where": "/home/svenstaro/prj/upload-release-action",
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/brace-expansion/issues"
},
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
},
"description": "Brace expansion as known from sh/bash",
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"keywords": [],
"license": "MIT",
"main": "index.js",
"name": "brace-expansion",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"scripts": {
"bench": "matcha test/perf/bench.js",
"gentest": "bash test/generate.sh",
"test": "tape test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "1.1.11"
}

4
node_modules/concat-map/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.4
- 0.6

18
node_modules/concat-map/LICENSE generated vendored Normal file
View File

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

62
node_modules/concat-map/README.markdown generated vendored Normal file
View File

@@ -0,0 +1,62 @@
concat-map
==========
Concatenative mapdashery.
[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map)
[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map)
example
=======
``` js
var concatMap = require('concat-map');
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ys = concatMap(xs, function (x) {
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
console.dir(ys);
```
***
```
[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]
```
methods
=======
``` js
var concatMap = require('concat-map')
```
concatMap(xs, fn)
-----------------
Return an array of concatenated elements by calling `fn(x, i)` for each element
`x` and each index `i` in the array `xs`.
When `fn(x, i)` returns an array, its result will be concatenated with the
result array. If `fn(x, i)` returns anything else, that value will be pushed
onto the end of the result array.
install
=======
With [npm](http://npmjs.org) do:
```
npm install concat-map
```
license
=======
MIT
notes
=====
This module was written while sitting high above the ground in a tree.

6
node_modules/concat-map/example/map.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
var concatMap = require('../');
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ys = concatMap(xs, function (x) {
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
console.dir(ys);

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