diff --git a/.eslintignore b/.eslintignore
deleted file mode 100644
index 42ceb9a..0000000
--- a/.eslintignore
+++ /dev/null
@@ -1,4 +0,0 @@
-dist/
-lib/
-node_modules/
-jest.config.js
diff --git a/.eslintrc.json b/.eslintrc.json
index 1bfbcbe..6534e5b 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -1,88 +1 @@
-{
- "plugins": [
- "jest",
- "@typescript-eslint"
- ],
- "extends": [
- "plugin:github/recommended",
- "plugin:prettier/recommended"
- ],
- "parser": "@typescript-eslint/parser",
- "parserOptions": {
- "ecmaVersion": 9,
- "sourceType": "module",
- "project": "./tsconfig.json"
- },
- "rules": {
- "i18n-text/no-en": "off",
- "eslint-comments/no-use": "off",
- "import/no-namespace": "off",
- "no-unused-vars": "off",
- "@typescript-eslint/no-unused-vars": "error",
- "@typescript-eslint/explicit-member-accessibility": [
- "error",
- {
- "accessibility": "no-public"
- }
- ],
- "@typescript-eslint/no-require-imports": "error",
- "@typescript-eslint/array-type": "error",
- "@typescript-eslint/await-thenable": "error",
- "@typescript-eslint/ban-ts-comment": "error",
- "camelcase": "off",
- "@typescript-eslint/consistent-type-assertions": "error",
- "@typescript-eslint/explicit-function-return-type": [
- "error",
- {
- "allowExpressions": true
- }
- ],
- "@typescript-eslint/no-array-constructor": "error",
- "@typescript-eslint/no-empty-interface": "error",
- "@typescript-eslint/no-explicit-any": "error",
- "@typescript-eslint/no-extraneous-class": "error",
- "@typescript-eslint/no-for-in-array": "error",
- "@typescript-eslint/no-inferrable-types": "error",
- "@typescript-eslint/no-misused-new": "error",
- "@typescript-eslint/no-namespace": "error",
- "@typescript-eslint/no-non-null-assertion": "warn",
- "@typescript-eslint/no-unnecessary-qualifier": "error",
- "@typescript-eslint/no-unnecessary-type-assertion": "error",
- "@typescript-eslint/no-useless-constructor": "error",
- "@typescript-eslint/no-var-requires": "error",
- "@typescript-eslint/prefer-for-of": "warn",
- "@typescript-eslint/prefer-function-type": "warn",
- "@typescript-eslint/prefer-includes": "error",
- "@typescript-eslint/prefer-string-starts-ends-with": "error",
- "@typescript-eslint/promise-function-async": "error",
- "@typescript-eslint/require-array-sort-compare": "error",
- "@typescript-eslint/restrict-plus-operands": "error",
- "semi": "off",
- "@typescript-eslint/semi": [
- "error",
- "always"
- ],
- "@typescript-eslint/unbound-method": "error",
- "sort-imports": "off",
- "no-console": [
- "error",
- {
- "allow": [
- "warn",
- "error"
- ]
- }
- ],
- "import/named": "off",
- "no-shadow": "off",
- "@typescript-eslint/no-shadow": [
- "error"
- ],
- "prettier/prettier": "error"
- },
- "env": {
- "node": true,
- "es6": true,
- "jest/globals": true
- }
-}
\ No newline at end of file
+// delete this file; eslint.config.js is now used for configuration
\ No newline at end of file
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
index 3f3d68d..788f1e2 100644
--- a/.github/workflows/CI.yml
+++ b/.github/workflows/CI.yml
@@ -23,10 +23,10 @@ jobs:
with:
ref: ${{ github.event.pull_request.head.ref || github.ref_name }}
- - name: Set Node.js 18.x
+ - name: Set Node.js 22.x
uses: actions/setup-node@v4
with:
- node-version: 18.x
+ node-version: 22.x
cache: "yarn"
- run: yarn install
diff --git a/.prettierrc.json b/.prettierrc.json
index 36f50d9..c9f994c 100644
--- a/.prettierrc.json
+++ b/.prettierrc.json
@@ -7,6 +7,7 @@
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "avoid",
+ "endOfLine": "auto",
"overrides": [
{
"files": "*.yml|*.yaml",
diff --git a/__tests__/execute.test.ts b/__tests__/execute.test.ts
index 34b4146..be93287 100644
--- a/__tests__/execute.test.ts
+++ b/__tests__/execute.test.ts
@@ -1,6 +1,14 @@
import { describe, expect, it } from '@jest/globals';
import { execute } from '../src/execute';
+const originalConsoleLog = console.log;
+beforeAll(() => {
+ console.log = jest.fn();
+});
+afterAll(() => {
+ console.log = originalConsoleLog;
+});
+
describe('execute', () => {
it('should execute a command successfully', async () => {
// Arrange
diff --git a/__tests__/readConfig.test.ts b/__tests__/readConfig.test.ts
index 5846637..d83d104 100644
--- a/__tests__/readConfig.test.ts
+++ b/__tests__/readConfig.test.ts
@@ -1,13 +1,18 @@
import * as fs from 'fs';
import { readConfig, readJSONSync } from '../src/readConfig';
-jest.mock('fs', () => ({
- existsSync: jest.fn(),
- readFileSync: jest.fn(),
- promises: {
- access: jest.fn()
- }
-}));
+jest.mock('fs', () => {
+ const actualFs = jest.requireActual('fs');
+ return {
+ ...actualFs,
+ existsSync: jest.fn(),
+ readFileSync: jest.fn(),
+ promises: {
+ ...actualFs.promises,
+ access: jest.fn()
+ }
+ };
+});
jest.mock('@actions/core');
describe('readJSONSync', () => {
diff --git a/babel.config.js b/babel.config.js
new file mode 100644
index 0000000..13f1d53
--- /dev/null
+++ b/babel.config.js
@@ -0,0 +1,3 @@
+export default {
+ presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript']
+};
diff --git a/dist/101.index.js b/dist/101.index.js
new file mode 100644
index 0000000..210d349
--- /dev/null
+++ b/dist/101.index.js
@@ -0,0 +1,452 @@
+"use strict";
+exports.id = 101;
+exports.ids = [101];
+exports.modules = {
+
+/***/ 29101:
+/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
+
+/* harmony export */ __webpack_require__.d(__webpack_exports__, {
+/* harmony export */ toFormData: () => (/* binding */ toFormData)
+/* harmony export */ });
+/* harmony import */ var fetch_blob_from_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(90995);
+/* harmony import */ var formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83018);
+
+
+
+let s = 0;
+const S = {
+ START_BOUNDARY: s++,
+ HEADER_FIELD_START: s++,
+ HEADER_FIELD: s++,
+ HEADER_VALUE_START: s++,
+ HEADER_VALUE: s++,
+ HEADER_VALUE_ALMOST_DONE: s++,
+ HEADERS_ALMOST_DONE: s++,
+ PART_DATA_START: s++,
+ PART_DATA: s++,
+ END: s++
+};
+
+let f = 1;
+const F = {
+ PART_BOUNDARY: f,
+ LAST_BOUNDARY: f *= 2
+};
+
+const LF = 10;
+const CR = 13;
+const SPACE = 32;
+const HYPHEN = 45;
+const COLON = 58;
+const A = 97;
+const Z = 122;
+
+const lower = c => c | 0x20;
+
+const noop = () => {};
+
+class MultipartParser {
+ /**
+ * @param {string} boundary
+ */
+ constructor(boundary) {
+ this.index = 0;
+ this.flags = 0;
+
+ this.onHeaderEnd = noop;
+ this.onHeaderField = noop;
+ this.onHeadersEnd = noop;
+ this.onHeaderValue = noop;
+ this.onPartBegin = noop;
+ this.onPartData = noop;
+ this.onPartEnd = noop;
+
+ this.boundaryChars = {};
+
+ boundary = '\r\n--' + boundary;
+ const ui8a = new Uint8Array(boundary.length);
+ for (let i = 0; i < boundary.length; i++) {
+ ui8a[i] = boundary.charCodeAt(i);
+ this.boundaryChars[ui8a[i]] = true;
+ }
+
+ this.boundary = ui8a;
+ this.lookbehind = new Uint8Array(this.boundary.length + 8);
+ this.state = S.START_BOUNDARY;
+ }
+
+ /**
+ * @param {Uint8Array} data
+ */
+ write(data) {
+ let i = 0;
+ const length_ = data.length;
+ let previousIndex = this.index;
+ let {lookbehind, boundary, boundaryChars, index, state, flags} = this;
+ const boundaryLength = this.boundary.length;
+ const boundaryEnd = boundaryLength - 1;
+ const bufferLength = data.length;
+ let c;
+ let cl;
+
+ const mark = name => {
+ this[name + 'Mark'] = i;
+ };
+
+ const clear = name => {
+ delete this[name + 'Mark'];
+ };
+
+ const callback = (callbackSymbol, start, end, ui8a) => {
+ if (start === undefined || start !== end) {
+ this[callbackSymbol](ui8a && ui8a.subarray(start, end));
+ }
+ };
+
+ const dataCallback = (name, clear) => {
+ const markSymbol = name + 'Mark';
+ if (!(markSymbol in this)) {
+ return;
+ }
+
+ if (clear) {
+ callback(name, this[markSymbol], i, data);
+ delete this[markSymbol];
+ } else {
+ callback(name, this[markSymbol], data.length, data);
+ this[markSymbol] = 0;
+ }
+ };
+
+ for (i = 0; i < length_; i++) {
+ c = data[i];
+
+ switch (state) {
+ case S.START_BOUNDARY:
+ if (index === boundary.length - 2) {
+ if (c === HYPHEN) {
+ flags |= F.LAST_BOUNDARY;
+ } else if (c !== CR) {
+ return;
+ }
+
+ index++;
+ break;
+ } else if (index - 1 === boundary.length - 2) {
+ if (flags & F.LAST_BOUNDARY && c === HYPHEN) {
+ state = S.END;
+ flags = 0;
+ } else if (!(flags & F.LAST_BOUNDARY) && c === LF) {
+ index = 0;
+ callback('onPartBegin');
+ state = S.HEADER_FIELD_START;
+ } else {
+ return;
+ }
+
+ break;
+ }
+
+ if (c !== boundary[index + 2]) {
+ index = -2;
+ }
+
+ if (c === boundary[index + 2]) {
+ index++;
+ }
+
+ break;
+ case S.HEADER_FIELD_START:
+ state = S.HEADER_FIELD;
+ mark('onHeaderField');
+ index = 0;
+ // falls through
+ case S.HEADER_FIELD:
+ if (c === CR) {
+ clear('onHeaderField');
+ state = S.HEADERS_ALMOST_DONE;
+ break;
+ }
+
+ index++;
+ if (c === HYPHEN) {
+ break;
+ }
+
+ if (c === COLON) {
+ if (index === 1) {
+ // empty header field
+ return;
+ }
+
+ dataCallback('onHeaderField', true);
+ state = S.HEADER_VALUE_START;
+ break;
+ }
+
+ cl = lower(c);
+ if (cl < A || cl > Z) {
+ return;
+ }
+
+ break;
+ case S.HEADER_VALUE_START:
+ if (c === SPACE) {
+ break;
+ }
+
+ mark('onHeaderValue');
+ state = S.HEADER_VALUE;
+ // falls through
+ case S.HEADER_VALUE:
+ if (c === CR) {
+ dataCallback('onHeaderValue', true);
+ callback('onHeaderEnd');
+ state = S.HEADER_VALUE_ALMOST_DONE;
+ }
+
+ break;
+ case S.HEADER_VALUE_ALMOST_DONE:
+ if (c !== LF) {
+ return;
+ }
+
+ state = S.HEADER_FIELD_START;
+ break;
+ case S.HEADERS_ALMOST_DONE:
+ if (c !== LF) {
+ return;
+ }
+
+ callback('onHeadersEnd');
+ state = S.PART_DATA_START;
+ break;
+ case S.PART_DATA_START:
+ state = S.PART_DATA;
+ mark('onPartData');
+ // falls through
+ case S.PART_DATA:
+ previousIndex = index;
+
+ if (index === 0) {
+ // boyer-moore derrived algorithm to safely skip non-boundary data
+ i += boundaryEnd;
+ while (i < bufferLength && !(data[i] in boundaryChars)) {
+ i += boundaryLength;
+ }
+
+ i -= boundaryEnd;
+ c = data[i];
+ }
+
+ if (index < boundary.length) {
+ if (boundary[index] === c) {
+ if (index === 0) {
+ dataCallback('onPartData', true);
+ }
+
+ index++;
+ } else {
+ index = 0;
+ }
+ } else if (index === boundary.length) {
+ index++;
+ if (c === CR) {
+ // CR = part boundary
+ flags |= F.PART_BOUNDARY;
+ } else if (c === HYPHEN) {
+ // HYPHEN = end boundary
+ flags |= F.LAST_BOUNDARY;
+ } else {
+ index = 0;
+ }
+ } else if (index - 1 === boundary.length) {
+ if (flags & F.PART_BOUNDARY) {
+ index = 0;
+ if (c === LF) {
+ // unset the PART_BOUNDARY flag
+ flags &= ~F.PART_BOUNDARY;
+ callback('onPartEnd');
+ callback('onPartBegin');
+ state = S.HEADER_FIELD_START;
+ break;
+ }
+ } else if (flags & F.LAST_BOUNDARY) {
+ if (c === HYPHEN) {
+ callback('onPartEnd');
+ state = S.END;
+ flags = 0;
+ } else {
+ index = 0;
+ }
+ } else {
+ index = 0;
+ }
+ }
+
+ if (index > 0) {
+ // when matching a possible boundary, keep a lookbehind reference
+ // in case it turns out to be a false lead
+ lookbehind[index - 1] = c;
+ } else if (previousIndex > 0) {
+ // if our boundary turned out to be rubbish, the captured lookbehind
+ // belongs to partData
+ const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
+ callback('onPartData', 0, previousIndex, _lookbehind);
+ previousIndex = 0;
+ mark('onPartData');
+
+ // reconsider the current character even so it interrupted the sequence
+ // it could be the beginning of a new sequence
+ i--;
+ }
+
+ break;
+ case S.END:
+ break;
+ default:
+ throw new Error(`Unexpected state entered: ${state}`);
+ }
+ }
+
+ dataCallback('onHeaderField');
+ dataCallback('onHeaderValue');
+ dataCallback('onPartData');
+
+ // Update properties for the next call
+ this.index = index;
+ this.state = state;
+ this.flags = flags;
+ }
+
+ end() {
+ if ((this.state === S.HEADER_FIELD_START && this.index === 0) ||
+ (this.state === S.PART_DATA && this.index === this.boundary.length)) {
+ this.onPartEnd();
+ } else if (this.state !== S.END) {
+ throw new Error('MultipartParser.end(): stream ended unexpectedly');
+ }
+ }
+}
+
+function _fileName(headerValue) {
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
+ const m = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
+ if (!m) {
+ return;
+ }
+
+ const match = m[2] || m[3] || '';
+ let filename = match.slice(match.lastIndexOf('\\') + 1);
+ filename = filename.replace(/%22/g, '"');
+ filename = filename.replace(/(\d{4});/g, (m, code) => {
+ return String.fromCharCode(code);
+ });
+ return filename;
+}
+
+async function toFormData(Body, ct) {
+ if (!/multipart/i.test(ct)) {
+ throw new TypeError('Failed to fetch');
+ }
+
+ const m = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
+
+ if (!m) {
+ throw new TypeError('no or bad content-type header, no multipart boundary');
+ }
+
+ const parser = new MultipartParser(m[1] || m[2]);
+
+ let headerField;
+ let headerValue;
+ let entryValue;
+ let entryName;
+ let contentType;
+ let filename;
+ const entryChunks = [];
+ const formData = new formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_1__/* .FormData */ .fS();
+
+ const onPartData = ui8a => {
+ entryValue += decoder.decode(ui8a, {stream: true});
+ };
+
+ const appendToFile = ui8a => {
+ entryChunks.push(ui8a);
+ };
+
+ const appendFileToFormData = () => {
+ const file = new fetch_blob_from_js__WEBPACK_IMPORTED_MODULE_0__/* .File */ .ZH(entryChunks, filename, {type: contentType});
+ formData.append(entryName, file);
+ };
+
+ const appendEntryToFormData = () => {
+ formData.append(entryName, entryValue);
+ };
+
+ const decoder = new TextDecoder('utf-8');
+ decoder.decode();
+
+ parser.onPartBegin = function () {
+ parser.onPartData = onPartData;
+ parser.onPartEnd = appendEntryToFormData;
+
+ headerField = '';
+ headerValue = '';
+ entryValue = '';
+ entryName = '';
+ contentType = '';
+ filename = null;
+ entryChunks.length = 0;
+ };
+
+ parser.onHeaderField = function (ui8a) {
+ headerField += decoder.decode(ui8a, {stream: true});
+ };
+
+ parser.onHeaderValue = function (ui8a) {
+ headerValue += decoder.decode(ui8a, {stream: true});
+ };
+
+ parser.onHeaderEnd = function () {
+ headerValue += decoder.decode();
+ headerField = headerField.toLowerCase();
+
+ if (headerField === 'content-disposition') {
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
+ const m = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
+
+ if (m) {
+ entryName = m[2] || m[3] || '';
+ }
+
+ filename = _fileName(headerValue);
+
+ if (filename) {
+ parser.onPartData = appendToFile;
+ parser.onPartEnd = appendFileToFormData;
+ }
+ } else if (headerField === 'content-type') {
+ contentType = headerValue;
+ }
+
+ headerValue = '';
+ headerField = '';
+ };
+
+ for await (const chunk of Body) {
+ parser.write(chunk);
+ }
+
+ parser.end();
+
+ return formData;
+}
+
+
+/***/ })
+
+};
+;
+//# sourceMappingURL=101.index.js.map
\ No newline at end of file
diff --git a/dist/101.index.js.map b/dist/101.index.js.map
new file mode 100644
index 0000000..8961c15
--- /dev/null
+++ b/dist/101.index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"101.index.js","mappings":";;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","sources":[".././node_modules/node-fetch/src/utils/multipart-parser.js"],"sourcesContent":["import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n"],"names":[],"sourceRoot":""}
\ No newline at end of file
diff --git a/dist/index.js b/dist/index.js
index 0f03f95..0b4ba9d 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -1,4922 +1,1937 @@
-require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap
-/******/ var __webpack_modules__ = ({
-
-/***/ 86979:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "G9": () => (/* binding */ getInputs),
-/* harmony export */ "GB": () => (/* binding */ REPORT_ARTIFACT_NAME),
-/* harmony export */ "IT": () => (/* binding */ getOctokitRest),
-/* harmony export */ "Pw": () => (/* binding */ formatOnlyChangedFiles),
-/* harmony export */ "TS": () => (/* binding */ getReportFooter),
-/* harmony export */ "UJ": () => (/* binding */ getCurrentBranch),
-/* harmony export */ "VO": () => (/* binding */ RemoveReportFiles),
-/* harmony export */ "kG": () => (/* binding */ REPORT_PATH)
-/* harmony export */ });
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(42186);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core__WEBPACK_IMPORTED_MODULE_0__);
-/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(95438);
-/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(_actions_github__WEBPACK_IMPORTED_MODULE_1__);
-/* harmony import */ var _octokit_rest__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(55375);
-/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(80467);
-/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__nccwpck_require__.n(node_fetch__WEBPACK_IMPORTED_MODULE_2__);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(73837);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__nccwpck_require__.n(util__WEBPACK_IMPORTED_MODULE_3__);
-/* harmony import */ var _execute__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(3532);
-/* harmony import */ var _modals__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(74062);
-
-
-
-
-
-
-
-const REPORT_PATH = `${process.cwd()}/.dotnet-format`;
-const REPORT_ARTIFACT_NAME = 'dotnet-format-report';
-function getInputs() {
- const inputs = {
- authToken: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.authToken */ .A.authToken),
- action: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.action */ .A.action),
- onlyChangedFiles: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.onlyChangedFiles */ .A.onlyChangedFiles),
- failFast: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.failFast */ .A.failFast),
- workspace: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.workspace */ .A.workspace),
- projectFileName: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.projectFileName */ .A.projectFileName),
- severityLevel: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.severityLevel */ .A.severityLevel),
- logLevel: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.logLevel */ .A.logLevel),
- problemMatcherEnabled: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.problemMatcherEnabled */ .A.problemMatcherEnabled),
- skipCommit: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.skipCommit */ .A.skipCommit),
- commitUsername: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.commitUsername */ .A.commitUsername),
- commitUserEmail: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.commitUserEmail */ .A.commitUserEmail),
- commitMessage: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.commitMessage */ .A.commitMessage),
- nugetConfigPath: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.nugetConfigPath */ .A.nugetConfigPath),
- dotnetFormatConfigPath: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.dotnetFormatConfigPath */ .A.dotnetFormatConfigPath),
- jscpdConfigPath: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.jscpdConfigPath */ .A.jscpdConfigPath),
- jscpdCheck: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.jscpdCheck */ .A.jscpdCheck),
- jscpdCheckAsError: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.jscpdCheckAsError */ .A.jscpdCheckAsError),
- postNewComment: _actions_core__WEBPACK_IMPORTED_MODULE_0__.getBooleanInput(_modals__WEBPACK_IMPORTED_MODULE_5__/* .INPUTS.postNewComment */ .A.postNewComment)
- };
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.debug(`Inputs: ${(0,util__WEBPACK_IMPORTED_MODULE_3__.inspect)(inputs)}`);
- return inputs;
+import './sourcemap-register.cjs';import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";
+/******/ var __webpack_modules__ = ({
+
+/***/ 4914:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.issue = exports.issueCommand = void 0;
+const os = __importStar(__nccwpck_require__(857));
+const utils_1 = __nccwpck_require__(302);
+/**
+ * Commands
+ *
+ * Command Format:
+ * ::name key=value,key=value::message
+ *
+ * Examples:
+ * ::warning::This is the message
+ * ::set-env name=MY_VAR::some value
+ */
+function issueCommand(command, properties, message) {
+ const cmd = new Command(command, properties, message);
+ process.stdout.write(cmd.toString() + os.EOL);
}
-function getOctokitRest(authToken, userAgent = 'github-action') {
- try {
- const octokit = new _octokit_rest__WEBPACK_IMPORTED_MODULE_6__/* .Octokit */ .v({
- auth: authToken,
- userAgent,
- baseUrl: 'https://api.github.com',
- log: {
- debug: () => { },
- info: () => { },
- warn: console.warn,
- error: console.error
- },
- request: {
- fetch: (node_fetch__WEBPACK_IMPORTED_MODULE_2___default())
- }
- });
- return octokit;
+exports.issueCommand = issueCommand;
+function issue(name, message = '') {
+ issueCommand(name, {}, message);
+}
+exports.issue = issue;
+const CMD_STRING = '::';
+class Command {
+ constructor(command, properties, message) {
+ if (!command) {
+ command = 'missing.command';
+ }
+ this.command = command;
+ this.properties = properties;
+ this.message = message;
}
- catch (error) {
- if (error instanceof Error) {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.setFailed(` Error creating octokit:\n${error.message}`);
+ toString() {
+ let cmdStr = CMD_STRING + this.command;
+ if (this.properties && Object.keys(this.properties).length > 0) {
+ cmdStr += ' ';
+ let first = true;
+ for (const key in this.properties) {
+ if (this.properties.hasOwnProperty(key)) {
+ const val = this.properties[key];
+ if (val) {
+ if (first) {
+ first = false;
+ }
+ else {
+ cmdStr += ',';
+ }
+ cmdStr += `${key}=${escapeProperty(val)}`;
+ }
+ }
+ }
}
- throw error;
+ cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
+ return cmdStr;
}
}
-function getCurrentBranch() {
- const branch = _actions_github__WEBPACK_IMPORTED_MODULE_1__.context.payload?.pull_request?.head?.ref || _actions_github__WEBPACK_IMPORTED_MODULE_1__.context.ref;
- const current = branch.replace('refs/heads/', '');
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`Current branch: "${current}"`);
- return current;
-}
-async function RemoveReportFiles() {
- const { result } = await (0,_execute__WEBPACK_IMPORTED_MODULE_4__/* .execute */ .h)(`rm -rf ${REPORT_PATH}/`);
- return result;
-}
-function formatOnlyChangedFiles(onlyChangedFiles) {
- if (onlyChangedFiles && ['issue_comment', 'pull_request'].includes(_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.eventName)) {
- return true;
- }
- onlyChangedFiles && _actions_core__WEBPACK_IMPORTED_MODULE_0__.warning('Formatting only changed files is available on the issue_comment and pull_request events only');
- return false;
+function escapeData(s) {
+ return (0, utils_1.toCommandValue)(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A');
}
-function getReportFooter() {
- const commit = _actions_github__WEBPACK_IMPORTED_MODULE_1__.context.payload?.pull_request?.head?.sha || _actions_github__WEBPACK_IMPORTED_MODULE_1__.context.sha;
- const commitLink = `[${commit.substring(0, 7)}](https://github.com/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.owner}/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.repo}/commit/${commit})`;
- const workflowLink = `[Workflow](https://github.com/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.owner}/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.repo}/actions/runs/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.runId})`;
- return commit ? `
_✏️ updated for commit ${commitLink} by ${workflowLink}_ \n\n` : '';
+function escapeProperty(s) {
+ return (0, utils_1.toCommandValue)(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A')
+ .replace(/:/g, '%3A')
+ .replace(/,/g, '%2C');
}
-
+//# sourceMappingURL=command.js.map
/***/ }),
-/***/ 93562:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "O": () => (/* binding */ duplicatedCheck)
-/* harmony export */ });
-/* unused harmony export REPORT_ARTIFACT_NAME */
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(42186);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core__WEBPACK_IMPORTED_MODULE_0__);
-/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(95438);
-/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(_actions_github__WEBPACK_IMPORTED_MODULE_1__);
-/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(57147);
-/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__nccwpck_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
-/* harmony import */ var jscpd__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(84849);
-/* harmony import */ var jscpd__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__nccwpck_require__.n(jscpd__WEBPACK_IMPORTED_MODULE_3__);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(73837);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__nccwpck_require__.n(util__WEBPACK_IMPORTED_MODULE_4__);
-/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(86979);
-/* harmony import */ var _execute__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(3532);
-/* harmony import */ var _git__WEBPACK_IMPORTED_MODULE_7__ = __nccwpck_require__(63350);
-/* harmony import */ var _readConfig__WEBPACK_IMPORTED_MODULE_8__ = __nccwpck_require__(22094);
-
-
-
-
-
-
-
+/***/ 7484:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-const REPORT_ARTIFACT_NAME = 'jscpd-report';
-const ANNOTATION_OPTIONS = {
- title: 'JSCPD Check'
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
};
-async function duplicatedCheck(workspace, jscpdConfigPath, jscpdCheckAsError, postNewComment, githubClient) {
- const cwd = process.cwd();
- const path = checkWorkspace(workspace);
- const options = getOptions(jscpdConfigPath, path, cwd);
- const clones = await (0,jscpd__WEBPACK_IMPORTED_MODULE_3__.detectClones)(options);
- if (clones.length > 0) {
- const reportFiles = getReportFiles(cwd);
- const markdownReport = reportFiles.find(file => file.endsWith('.md'));
- const jsonReport = reportFiles.find(file => file.endsWith('.json'));
- const message = await postReport(githubClient, markdownReport, clones, workspace, postNewComment);
- fs__WEBPACK_IMPORTED_MODULE_2__.writeFileSync(markdownReport, message);
- await _git__WEBPACK_IMPORTED_MODULE_7__/* .UploadReportToArtifacts */ .BC([markdownReport, jsonReport], REPORT_ARTIFACT_NAME);
- const isOverThreshold = checkThreshold(jsonReport, options.threshold || 0);
- jscpdCheckAsError && isOverThreshold ? _actions_core__WEBPACK_IMPORTED_MODULE_0__.setFailed('❌ DUPLICATED CODE FOUND') : _actions_core__WEBPACK_IMPORTED_MODULE_0__.warning('DUPLICATED CODE FOUND', ANNOTATION_OPTIONS);
- showAnnotation(clones, cwd, jscpdCheckAsError && isOverThreshold);
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.setOutput('hasDuplicates', `${isOverThreshold}`);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
+const command_1 = __nccwpck_require__(4914);
+const file_command_1 = __nccwpck_require__(4753);
+const utils_1 = __nccwpck_require__(302);
+const os = __importStar(__nccwpck_require__(857));
+const path = __importStar(__nccwpck_require__(6928));
+const oidc_utils_1 = __nccwpck_require__(5306);
+/**
+ * The code to exit an action
+ */
+var ExitCode;
+(function (ExitCode) {
+ /**
+ * A code indicating that the action was successful
+ */
+ ExitCode[ExitCode["Success"] = 0] = "Success";
+ /**
+ * A code indicating that the action was a failure
+ */
+ ExitCode[ExitCode["Failure"] = 1] = "Failure";
+})(ExitCode || (exports.ExitCode = ExitCode = {}));
+//-----------------------------------------------------------------------
+// Variables
+//-----------------------------------------------------------------------
+/**
+ * Sets env variable for this action and future actions in the job
+ * @param name the name of the variable to set
+ * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function exportVariable(name, val) {
+ const convertedVal = (0, utils_1.toCommandValue)(val);
+ process.env[name] = convertedVal;
+ const filePath = process.env['GITHUB_ENV'] || '';
+ if (filePath) {
+ return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val));
+ }
+ (0, command_1.issueCommand)('set-env', { name }, convertedVal);
+}
+exports.exportVariable = exportVariable;
+/**
+ * Registers a secret which will get masked from logs
+ * @param secret value of the secret
+ */
+function setSecret(secret) {
+ (0, command_1.issueCommand)('add-mask', {}, secret);
+}
+exports.setSecret = setSecret;
+/**
+ * Prepends inputPath to the PATH (for this action and future actions)
+ * @param inputPath
+ */
+function addPath(inputPath) {
+ const filePath = process.env['GITHUB_PATH'] || '';
+ if (filePath) {
+ (0, file_command_1.issueFileCommand)('PATH', inputPath);
}
else {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.setOutput('hasDuplicates', 'false');
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.notice('✅ NO DUPLICATED CODE FOUND', ANNOTATION_OPTIONS);
+ (0, command_1.issueCommand)('add-path', {}, inputPath);
}
- await (0,_execute__WEBPACK_IMPORTED_MODULE_6__/* .execute */ .h)(`rm -rf ${cwd}/${REPORT_ARTIFACT_NAME}`);
+ process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
-function getOptions(jscpdConfigPath, workspace, cwd) {
- const configOptions = (0,_readConfig__WEBPACK_IMPORTED_MODULE_8__/* .readConfig */ .z)({}, jscpdConfigPath, workspace, '.jscpd.json');
- const defaultOptions = {
- path: [`${workspace}`],
- reporters: ['markdown', 'json', 'consoleFull'],
- output: `${cwd}/${REPORT_ARTIFACT_NAME}`
- };
- const options = { ...configOptions, ...defaultOptions };
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.startGroup('🔎 loaded options');
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`${(0,util__WEBPACK_IMPORTED_MODULE_4__.inspect)(options)}`);
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.endGroup();
- return options;
-}
-function getReportFiles(cwd) {
- const files = fs__WEBPACK_IMPORTED_MODULE_2__.readdirSync(`${cwd}/${REPORT_ARTIFACT_NAME}`);
- const filePaths = files.map(file => `${cwd}/${REPORT_ARTIFACT_NAME}/${file}`);
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`reportFiles: ${filePaths.join(',')}`);
- return filePaths;
-}
-function checkWorkspace(workspace) {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`workspace: ${workspace}`);
- //check if workspace path is a file
- const isFile = fs__WEBPACK_IMPORTED_MODULE_2__.existsSync(workspace) && fs__WEBPACK_IMPORTED_MODULE_2__.lstatSync(workspace).isFile();
- if (isFile) {
- // if it is a file, get the directory
- return workspace.substring(0, workspace.lastIndexOf('/'));
- }
- return workspace;
-}
-function showAnnotation(clones, cwd, isError) {
- const show = isError ? _actions_core__WEBPACK_IMPORTED_MODULE_0__.error : _actions_core__WEBPACK_IMPORTED_MODULE_0__.warning;
- for (const clone of clones) {
- show(`${clone.duplicationA.sourceId.replace(cwd, '')} (${clone.duplicationA.start.line}-${clone.duplicationA.end.line})
- and ${clone.duplicationB.sourceId.replace(cwd, '')} (${clone.duplicationB.start.line}-${clone.duplicationB.end.line})`, {
- title: ANNOTATION_OPTIONS.title,
- file: clone.duplicationA.sourceId,
- startLine: clone.duplicationA.start.line,
- endLine: clone.duplicationA.end.line
- });
+exports.addPath = addPath;
+/**
+ * Gets the value of an input.
+ * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
+ * Returns an empty string if the value is not defined.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string
+ */
+function getInput(name, options) {
+ const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
+ if (options && options.required && !val) {
+ throw new Error(`Input required and not supplied: ${name}`);
}
-}
-function getReportHeader(workspace) {
- return `## ❌ DUPLICATED CODE FOUND - ${workspace}`;
-}
-async function postReport(githubClient, markdownReport, clones, workspace, postNewComment) {
- let report = fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync(markdownReport, 'utf8');
- // remove existing header
- report = report.replace('# Copy/paste detection report', '');
- const cwd = process.cwd();
- let markdown = '\n';
- markdown += ` JSCPD Details
\n\n`;
- for (const c of clones) {
- markdown += `- **${c.duplicationA.sourceId.split('/').pop()}** & **${c.duplicationB.sourceId.split('/').pop()}**\n`;
- markdown += ` - ${toGithubLink(c.duplicationA.sourceId, cwd, [c.duplicationA.start.line, c.duplicationA.end.line])}\n`;
- markdown += ` - ${toGithubLink(c.duplicationB.sourceId, cwd, [c.duplicationB.start.line, c.duplicationB.end.line])}\n`;
- markdown += '\n';
- }
- markdown += ' \n';
- const header = getReportHeader(workspace);
- const message = `${header} \n\n${report}\n\n ${markdown}\n\n ${(0,_common__WEBPACK_IMPORTED_MODULE_5__/* .getReportFooter */ .TS)()}`;
- await _git__WEBPACK_IMPORTED_MODULE_7__/* .setSummary */ .Li(message);
- if (_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.eventName === 'pull_request') {
- const existingCommentId = await _git__WEBPACK_IMPORTED_MODULE_7__/* .getExistingCommentId */ .Iy(githubClient, header);
- if (!postNewComment && existingCommentId) {
- await _git__WEBPACK_IMPORTED_MODULE_7__/* .updateComment */ .uA(githubClient, existingCommentId, message);
- }
- else {
- await _git__WEBPACK_IMPORTED_MODULE_7__/* .comment */ .UI(githubClient, message);
- }
+ if (options && options.trimWhitespace === false) {
+ return val;
}
- return message;
+ return val.trim();
}
-function toGithubLink(path, cwd, range) {
- const main = path.replace(`${cwd}/`, '');
- return `[${main}#L${range[0]}-L${range[1]}](https://github.com/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.owner}/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.repo}/blob/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.sha}/${main}#L${range[0]}-L${range[1]})`;
+exports.getInput = getInput;
+/**
+ * Gets the values of an multiline input. Each value is also trimmed.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string[]
+ *
+ */
+function getMultilineInput(name, options) {
+ const inputs = getInput(name, options)
+ .split('\n')
+ .filter(x => x !== '');
+ if (options && options.trimWhitespace === false) {
+ return inputs;
+ }
+ return inputs.map(input => input.trim());
}
-function checkThreshold(jsonReport, threshold) {
- // read json report
- const report = JSON.parse(fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync(jsonReport, 'utf8'));
- if (report.statistics.total.percentage > threshold) {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.error(`DUPLICATED CODE FOUND ${report.statistics.total.percentage}% IS OVER THRESHOLD ${threshold}%`, ANNOTATION_OPTIONS);
+exports.getMultilineInput = getMultilineInput;
+/**
+ * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
+ * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
+ * The return value is also in boolean type.
+ * ref: https://yaml.org/spec/1.2/spec.html#id2804923
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns boolean
+ */
+function getBooleanInput(name, options) {
+ const trueValue = ['true', 'True', 'TRUE'];
+ const falseValue = ['false', 'False', 'FALSE'];
+ const val = getInput(name, options);
+ if (trueValue.includes(val))
return true;
+ if (falseValue.includes(val))
+ return false;
+ throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
+ `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
+}
+exports.getBooleanInput = getBooleanInput;
+/**
+ * Sets the value of an output.
+ *
+ * @param name name of the output to set
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function setOutput(name, value) {
+ const filePath = process.env['GITHUB_OUTPUT'] || '';
+ if (filePath) {
+ return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value));
}
- return false;
+ process.stdout.write(os.EOL);
+ (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value));
}
-
-
-/***/ }),
-
-/***/ 3532:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "h": () => (/* binding */ execute)
-/* harmony export */ });
-/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(71514);
-/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(_actions_exec__WEBPACK_IMPORTED_MODULE_0__);
-
-/** Wrapper around the GitHub toolkit exec command which returns the output.
- * Also allows you to easily toggle the current working directory.
- * on a non-zero exit status or to leave implementation up to the caller.
+exports.setOutput = setOutput;
+/**
+ * Enables or disables the echoing of commands into stdout for the rest of the step.
+ * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
+ *
*/
-async function execute(cmd, cwd = process.cwd(), args = [], silent = false, ignoreReturnCode = false) {
- const stdout = [];
- const stderr = [];
- const exitCode = await (0,_actions_exec__WEBPACK_IMPORTED_MODULE_0__.exec)(cmd, args, {
- silent,
- cwd,
- listeners: {
- stdout: (data) => {
- stdout.push(data.toString());
- },
- stderr: (data) => {
- stderr.push(data.toString());
- }
- },
- ignoreReturnCode
- });
- return { stdout, stderr, result: exitCode === 0 };
+function setCommandEcho(enabled) {
+ (0, command_1.issue)('echo', enabled ? 'on' : 'off');
}
-
-
-/***/ }),
-
-/***/ 19118:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-
-// EXPORTS
-__nccwpck_require__.d(__webpack_exports__, {
- "W": () => (/* binding */ format)
-});
-
-// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
-var core = __nccwpck_require__(42186);
-// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js
-var github = __nccwpck_require__(95438);
-// EXTERNAL MODULE: ./lib/common.js
-var common = __nccwpck_require__(86979);
-// EXTERNAL MODULE: external "fs"
-var external_fs_ = __nccwpck_require__(57147);
-// EXTERNAL MODULE: external "path"
-var external_path_ = __nccwpck_require__(71017);
-var external_path_default = /*#__PURE__*/__nccwpck_require__.n(external_path_);
-// EXTERNAL MODULE: external "util"
-var external_util_ = __nccwpck_require__(73837);
-// EXTERNAL MODULE: ./lib/execute.js
-var execute = __nccwpck_require__(3532);
-// EXTERNAL MODULE: ./lib/modals.js
-var modals = __nccwpck_require__(74062);
-;// CONCATENATED MODULE: ./lib/dotnet.js
-
-
-
-
-
-
-
-
-const ANNOTATION_OPTIONS = {
- title: 'DOTNET FORMAT Check'
-};
-const DOTNET_FORMAT = 'format';
-const BASE_REPORT_PATH = `${common/* REPORT_PATH */.kG}/`;
-const FORMAT_COMPLETE = 'Format complete';
-function setDotnetEnvironmentVariables() {
- process.env.DOTNET_CLI_TELEMETRY_OPTOUT = 'true';
- process.env.DOTNET_NOLOGO = 'true';
-}
-function generateFormatCommandArgs(config, workspace, changedFiles) {
- if (!workspace) {
- core.setFailed('Specify PROJECT | SOLUTION, .sln or .csproj');
- return [];
- }
- const dotnetFormatOptions = [external_path_default().join(workspace, config.projectFileName || '')];
- const isOnlyChangedFiles = (0,common/* formatOnlyChangedFiles */.Pw)(config.onlyChangedFiles || false);
- if (isOnlyChangedFiles) {
- core.debug(`filesToCheck: ${(0,external_util_.inspect)(changedFiles)}`);
- core.info(`🔍 Checking ${changedFiles.length} files`);
- }
- if (config.options?.isEabled) {
- const args = buildArgs(config.options, isOnlyChangedFiles, changedFiles, modals/* FormatType.all */.a.all);
- return [[DOTNET_FORMAT, ...dotnetFormatOptions, ...args, '--report', `${BASE_REPORT_PATH}dotnet-format.json`]];
- }
- const allArgs = [];
- const formatOptionsMapping = {
- whitespace: config.whitespaceOptions,
- analyzers: config.analyzersOptions,
- style: config.styleOptions
- };
- for (const [type, options] of Object.entries(formatOptionsMapping)) {
- if (options?.isEabled) {
- const args = buildArgs(options, isOnlyChangedFiles, changedFiles, type);
- allArgs.push([DOTNET_FORMAT, type, ...dotnetFormatOptions, ...args, '--report', `${BASE_REPORT_PATH}${type}-format.json`]);
- }
- }
- return allArgs;
-}
-function buildArgs(options, onlyChangedFiles, changedFiles, type) {
- const dotnetFormatOptions = [];
- options.verifyNoChanges && dotnetFormatOptions.push('--verify-no-changes');
- type === modals/* FormatType.whitespace */.a.whitespace && options.folder && dotnetFormatOptions.push('--folder');
- if (onlyChangedFiles && changedFiles.length) {
- dotnetFormatOptions.push('--include', `${changedFiles.join(' ')} ${options.include?.join(' ')}`);
- }
- else if (options.include) {
- dotnetFormatOptions.push('--include', options.include.join(' '));
- }
- options.exclude && dotnetFormatOptions.push('--exclude', options.exclude.join(' '));
- dotnetFormatOptions.push('--verbosity', options.verbosity || 'normal');
- options.noRestore && dotnetFormatOptions.push('--no-restore');
- type !== modals/* FormatType.whitespace */.a.whitespace && dotnetFormatOptions.push('--severity', options.severity || 'error');
- return dotnetFormatOptions;
-}
-async function execFormat(formatArgs) {
- core.startGroup('🏃Dotnet Format');
- const { stdout, stderr } = await (0,execute/* execute */.h)('dotnet', process.cwd(), formatArgs, false, true);
- // dotnet format returns non-zero exit code if there are formatting issues
- // but we don't want to fail the action in this case
- // stdout will always end with Format complete ...
- // stderr will be empty if there are no formatting issues
- core.endGroup();
- const result = stdout[stdout.length - 1].includes(FORMAT_COMPLETE);
- return { stdout, stderr, formatResult: result };
-}
-function getReportFiles() {
- const reportPaths = [
- `${common/* REPORT_PATH */.kG}/dotnet-format.json`,
- `${common/* REPORT_PATH */.kG}/style-format.json`,
- `${common/* REPORT_PATH */.kG}/analyzers-format.json`,
- `${common/* REPORT_PATH */.kG}/whitespace-format.json`
- ];
- // check if file size is greater than 2 bytes to avoid empty report
- return reportPaths.filter(p => external_fs_.existsSync(p) && external_fs_.statSync(p).size > 2);
-}
-function getReportHeader(workspace) {
- return `## ✅ DOT NET FORMAT - ${workspace}`;
-}
-function generateReport(reports, header) {
- let markdownReport = '';
- for (const report of reports) {
- // get file name from report path without extension
- const fileName = report.split('/').pop()?.split('.')[0] || '';
- const reportJson = JSON.parse(external_fs_.readFileSync(report, 'utf8'));
- markdownReport += generateMarkdownReport(reportJson, fileName.toLocaleUpperCase());
- }
- if (!markdownReport) {
- return '';
- }
- return `${header}\n\n ${markdownReport}\n\n ${(0,common/* getReportFooter */.TS)()}`;
+exports.setCommandEcho = setCommandEcho;
+//-----------------------------------------------------------------------
+// Results
+//-----------------------------------------------------------------------
+/**
+ * Sets the action status to failed.
+ * When the action exits it will be with an exit code of 1
+ * @param message add error issue message
+ */
+function setFailed(message) {
+ process.exitCode = ExitCode.Failure;
+ error(message);
}
-async function nugetRestore(nugetConfigPath, workspace) {
- core.startGroup('📦 Nuget Restore');
- const { result } = await (0,execute/* execute */.h)('dotnet restore', process.cwd(),
- // for some reason dotnet restore doesn't work with --configfile
- [`-p:RestoreConfigFile=${workspace}${nugetConfigPath}`, `${workspace}`], false, false);
- core.endGroup();
- return result;
+exports.setFailed = setFailed;
+//-----------------------------------------------------------------------
+// Logging Commands
+//-----------------------------------------------------------------------
+/**
+ * Gets whether Actions Step Debug is on or not
+ */
+function isDebug() {
+ return process.env['RUNNER_DEBUG'] === '1';
}
-function generateMarkdownReport(documents, title) {
- let markdown = '\n';
- markdown += ` ${title} Report
\n\n`;
- const cwd = process.cwd();
- for (const doc of documents) {
- const [main, link] = toGithubLink(doc.FilePath, cwd);
- markdown += `- **${doc.FileName}**\n`;
- markdown += ` - **Path:** [${main}](${link})\n`;
- for (const change of doc.FileChanges) {
- markdown += ` - **Description:** ${change.FormatDescription} ([L${change.LineNumber}:${change.CharNumber}](${link}#L${change.LineNumber})) \n`;
- }
- markdown += '\n';
- }
- markdown += ' \n';
- return markdown;
+exports.isDebug = isDebug;
+/**
+ * Writes debug message to user log
+ * @param message debug message
+ */
+function debug(message) {
+ (0, command_1.issueCommand)('debug', {}, message);
}
-function toGithubLink(filePath, cwd) {
- const main = filePath.replace(`${cwd}/`, '');
- const link = `https://github.com/${github.context.repo.owner}/${github.context.repo.repo}/blob/${github.context.sha}/${main}`;
- return [main, link];
+exports.debug = debug;
+/**
+ * Adds an error issue
+ * @param message error issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function error(message, properties = {}) {
+ (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);
}
-
-// EXTERNAL MODULE: ./lib/git.js + 1 modules
-var git = __nccwpck_require__(63350);
-// EXTERNAL MODULE: ./lib/readConfig.js + 1 modules
-var readConfig = __nccwpck_require__(22094);
-;// CONCATENATED MODULE: ./lib/format.js
-
-
-
-
-
-
-
-async function format(inputs, githubClient) {
- const configOptions = getOptions(inputs);
- const cwd = process.cwd();
- core.info(`🔍 cwd: ${cwd}`);
- setDotnetEnvironmentVariables();
- configOptions.nugetConfigPath && (await nugetRestore(inputs.nugetConfigPath, inputs.workspace));
- let changedFiles = [];
- if (common/* formatOnlyChangedFiles */.Pw(configOptions.onlyChangedFiles || false)) {
- changedFiles = await git/* getPullRequestFiles */.p0(githubClient);
- if (!changedFiles.length) {
- core.warning('No files found for formatting', ANNOTATION_OPTIONS);
- return true;
- }
- }
- const formatArgs = generateFormatCommandArgs(configOptions, inputs.workspace, changedFiles);
- const finalFormatResult = await format_execFormat(formatArgs);
- const reportFiles = getReportFiles();
- await git/* UploadReportToArtifacts */.BC(reportFiles, common/* REPORT_ARTIFACT_NAME */.GB);
- const isDryRun = checkIsDryRun(configOptions);
- const isReportPosted = await postReport(reportFiles, githubClient, inputs.workspace, inputs.postNewComment);
- const isReportRemoved = isReportPosted && (await common/* RemoveReportFiles */.VO());
- const isChanged = isReportRemoved && (await git/* checkIsFileChanged */.gr());
- setOutput(isDryRun, isChanged);
- if (!isDryRun && isChanged && isReportRemoved && !inputs.skipCommit && github.context.eventName === 'pull_request') {
- await commitChanges(cwd, inputs);
- }
- finalFormatResult
- ? core.notice('✅ DOTNET FORMAT SUCCESS', ANNOTATION_OPTIONS)
- : core.error('DOTNET FORMAT FAILED', ANNOTATION_OPTIONS);
- return finalFormatResult;
-}
-async function postReport(reportFiles, githubClient, workspace, postNewComment) {
- if (reportFiles.length) {
- const header = getReportHeader(workspace);
- const message = generateReport(reportFiles, header);
- await git/* setSummary */.Li(message);
- if (github.context.eventName === 'pull_request') {
- const existingCommentId = await git/* getExistingCommentId */.Iy(githubClient, header);
- if (!postNewComment && existingCommentId) {
- return await git/* updateComment */.uA(githubClient, existingCommentId, message);
- }
- else {
- return await git/* comment */.UI(githubClient, message);
- }
- }
- }
- return true;
-}
-async function commitChanges(cwd, inputs) {
- const isInit = await git/* init */.S1(cwd, inputs.commitUsername, inputs.commitUserEmail);
- const currentBranch = common/* getCurrentBranch */.UJ();
- const isCommit = isInit && (await git/* commit */.th(cwd, inputs.commitMessage, currentBranch));
- return isCommit && (await git/* push */.VF(currentBranch));
-}
-async function format_execFormat(formatArgs) {
- let finalFormatResult = true;
- for (const args of formatArgs) {
- const { stdout, formatResult } = await execFormat(args);
- core.info(`✅✅✅✅✅ DOTNET FORMAT SUCCESS: ${formatResult} ✅✅✅✅✅`);
- if (stdout.join('').includes('Unable to fix')) {
- core.error('Unable to fix all formatting issues', ANNOTATION_OPTIONS);
- finalFormatResult = false;
- }
- finalFormatResult = finalFormatResult && formatResult;
- }
- return finalFormatResult;
-}
-function getOptions(inputs) {
- const defaultOptions = {
- nugetConfigPath: inputs.nugetConfigPath,
- projectFileName: inputs.projectFileName,
- onlyChangedFiles: inputs.onlyChangedFiles,
- options: {
- isEabled: true,
- verifyNoChanges: inputs.action === 'check',
- severity: inputs.severityLevel,
- verbosity: inputs.logLevel,
- noRestore: !!inputs.nugetConfigPath
- },
- whitespaceOptions: {
- isEabled: false,
- verifyNoChanges: inputs.action === 'check',
- folder: true,
- severity: inputs.severityLevel,
- verbosity: inputs.logLevel,
- noRestore: !!inputs.nugetConfigPath
- },
- analyzersOptions: {
- isEabled: false,
- verifyNoChanges: inputs.action === 'check',
- severity: inputs.severityLevel,
- verbosity: inputs.logLevel,
- noRestore: !!inputs.nugetConfigPath
- },
- styleOptions: {
- isEabled: false,
- verifyNoChanges: inputs.action === 'check',
- severity: inputs.severityLevel,
- verbosity: inputs.logLevel,
- noRestore: !!inputs.dotnetFormatConfigPath
- }
- };
- const configOptions = (0,readConfig/* readConfig */.z)(defaultOptions, inputs.dotnetFormatConfigPath, inputs.workspace, '.dotnet-format.json');
- return configOptions;
+exports.error = error;
+/**
+ * Adds a warning issue
+ * @param message warning issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function warning(message, properties = {}) {
+ (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);
}
-function setOutput(isDryRun, isFileChanged) {
- if (isDryRun) {
- core.setOutput('hasChanges', 'false');
- core.notice('Dry run mode. No changes will be committed.', ANNOTATION_OPTIONS);
- }
- else {
- core.warning(`Dotnet Format File Changed: ${isFileChanged}`, ANNOTATION_OPTIONS);
- core.setOutput('hasChanges', isFileChanged.toString());
- }
+exports.warning = warning;
+/**
+ * Adds a notice issue
+ * @param message notice issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function notice(message, properties = {}) {
+ (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message);
}
-function checkIsDryRun(config) {
- if (config.options?.isEabled) {
- return config.options?.verifyNoChanges;
- }
- else {
- const w = (config.whitespaceOptions?.isEabled && config.whitespaceOptions?.verifyNoChanges) || !config.whitespaceOptions?.isEabled;
- const a = (config.analyzersOptions?.isEabled && config.analyzersOptions?.verifyNoChanges) || !config.analyzersOptions?.isEabled;
- const s = (config.styleOptions?.isEabled && config.styleOptions?.verifyNoChanges) || !config.styleOptions?.isEabled;
- return w && a && s;
- }
+exports.notice = notice;
+/**
+ * Writes info to log with console.log.
+ * @param message info message
+ */
+function info(message) {
+ process.stdout.write(message + os.EOL);
}
-
-
-/***/ }),
-
-/***/ 63350:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-
-// EXPORTS
-__nccwpck_require__.d(__webpack_exports__, {
- "BC": () => (/* binding */ UploadReportToArtifacts),
- "gr": () => (/* binding */ checkIsFileChanged),
- "UI": () => (/* binding */ comment),
- "th": () => (/* binding */ commit),
- "Iy": () => (/* binding */ getExistingCommentId),
- "p0": () => (/* binding */ getPullRequestFiles),
- "S1": () => (/* binding */ init),
- "VF": () => (/* binding */ push),
- "Li": () => (/* binding */ setSummary),
- "uA": () => (/* binding */ updateComment)
-});
-
-// EXTERNAL MODULE: ./node_modules/@actions/artifact/lib/artifact-client.js
-var artifact_client = __nccwpck_require__(52605);
-// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
-var core = __nccwpck_require__(42186);
-// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js
-var github = __nccwpck_require__(95438);
-// EXTERNAL MODULE: external "path"
-var external_path_ = __nccwpck_require__(71017);
-;// CONCATENATED MODULE: ./lib/const.js
-const includedFileTypes = ['.cs', '.vb', '.cspoj', '.vbproj', '.fs', '.fsproj', '.cshtml', '.vbhtml'];
-
-// EXTERNAL MODULE: ./lib/execute.js
-var execute = __nccwpck_require__(3532);
-;// CONCATENATED MODULE: ./lib/git.js
-
-
-
-
-
-
-async function getPullRequestFiles(githubClient) {
- if (!github.context.issue.number) {
- throw Error('Unable to get pull request number from action event');
- }
- const files = await githubClient.paginate(githubClient.rest.pulls.listFiles, {
- ...github.context.repo,
- pull_number: github.context.issue.number
- });
- return files
- .filter(file => file.status !== "removed" /* FileStatus.Removed */)
- .filter(file => includedFileTypes.includes((0,external_path_.extname)(file.filename)))
- .map(file => file.filename);
+exports.info = info;
+/**
+ * Begin an output group.
+ *
+ * Output until the next `groupEnd` will be foldable in this group
+ *
+ * @param name The name of the output group
+ */
+function startGroup(name) {
+ (0, command_1.issue)('group', name);
}
-async function init(workspace, username, email) {
- try {
- core.info('Configuring git…');
- let result = await (0,execute/* execute */.h)(`git config --global --add safe.directory "${workspace}"`, workspace, [], true);
- if (!result.result) {
- core.error(`Unable to configure git: ${result.stderr.join('')}`);
- }
- result = await (0,execute/* execute */.h)(`git config user.name "${username}"`, workspace);
- if (result.result) {
- result = await (0,execute/* execute */.h)(`git config user.email "${email}"`, workspace);
- await (0,execute/* execute */.h)(`git config core.ignorecase false`, workspace);
- }
- return result.result;
- }
- catch (ex) {
- core.error(`Unable to configure git: ${ex}`);
- throw ex;
- }
+exports.startGroup = startGroup;
+/**
+ * End an output group.
+ */
+function endGroup() {
+ (0, command_1.issue)('endgroup');
}
-async function checkIsFileChanged() {
- core.debug('Checking changed files');
- const { stdout, stderr } = await (0,execute/* execute */.h)('git', process.cwd(), ['status', '-s'], false, false);
- await (0,execute/* execute */.h)('git', process.cwd(), ['status', '-s'], false, false);
- if (stderr.join('') !== '') {
- core.error(`Errors while checking git status for changed files. Error: ${stderr.join('\n')}`);
- }
- if (stdout.join('') === '') {
- core.info('Did not find any changed files');
- return false;
- }
- core.info('Found changed files');
- return true;
-}
-async function commit(workspace, message, branch) {
- // check what is the current branch
- const { stdout } = await (0,execute/* execute */.h)(`git branch --show-current`);
- if (stdout.join('').trim() !== branch) {
- core.info(`It is on "${stdout.join('').trim()}" branch, Checking out "${branch}"`);
- await (0,execute/* execute */.h)(`git fetch origin ${branch} --depth=1`);
- await (0,execute/* execute */.h)(`git stash`);
- await (0,execute/* execute */.h)(`git checkout -b ${branch} FETCH_HEAD`);
- await (0,execute/* execute */.h)(`git stash pop`);
- }
- core.info(`Committing changes to ${branch}…`);
- await (0,execute/* execute */.h)(`git add .`, workspace);
- const result = await (0,execute/* execute */.h)(`git commit -m "${message}"`, workspace);
- if (result.result) {
- core.info('Changes committed');
- }
- else {
- throw new Error(`Commit failed`);
- }
- return result.result;
-}
-const ATTEMPT_LIMIT = 3;
-const REJECTED_KEYWORDS = ['[rejected]', '[remote rejected]'];
-async function push(branch) {
- for (let attempt = 1; attempt <= ATTEMPT_LIMIT; attempt++) {
- core.info(`Pushing changes… (attempt ${attempt} of ${ATTEMPT_LIMIT})`);
- const pushResult = await (0,execute/* execute */.h)(`git push --porcelain origin ${branch}:${branch}`, process.cwd(), [], false, true);
- const stdout = pushResult.stdout.join('');
- const stderr = pushResult.stderr.join('\n');
- if (wasPushRejected(stdout)) {
- await handleRejectedPush(branch);
- }
- else if (stderr.startsWith('fatal:')) {
- throw new Error(stderr);
+exports.endGroup = endGroup;
+/**
+ * Wrap an asynchronous function call in a group.
+ *
+ * Returns the same type as the function itself.
+ *
+ * @param name The name of the group
+ * @param fn The function to wrap in the group
+ */
+function group(name, fn) {
+ return __awaiter(this, void 0, void 0, function* () {
+ startGroup(name);
+ let result;
+ try {
+ result = yield fn();
}
- else {
- return true;
+ finally {
+ endGroup();
}
- }
- throw new Error(`Attempt limit exceeded`);
-}
-function wasPushRejected(stdout) {
- return REJECTED_KEYWORDS.some(keyword => stdout.includes(keyword));
-}
-async function handleRejectedPush(branch) {
- core.info('Updates were rejected');
- core.info('Fetching upstream changes…');
- await (0,execute/* execute */.h)(`git fetch`);
- core.info(`Rebasing local changes onto ${branch}…`);
- const result = await (0,execute/* execute */.h)(`git pull --rebase`);
- if (result.result) {
- core.info(`Rebase successful`);
- }
- else {
- throw new Error(`Rebase failed`);
- }
-}
-// add report to github action artifacts
-async function UploadReportToArtifacts(reports, artifactName) {
- const artifactClient = artifact_client/* create */.U();
- if (reports.length === 0) {
- core.info(`No reports found`);
- return;
- }
- const uploadResponse = await artifactClient.uploadArtifact(artifactName, reports, process.cwd(), {
- continueOnError: true
+ return result;
});
- if (uploadResponse.failedItems.length > 0) {
- core.error(`Failed to upload artifact ${artifactName}: ${uploadResponse.failedItems.join(', ')}`);
- }
- else {
- core.info(`Artifact ${artifactName} uploaded successfully`);
- }
-}
-// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary
-async function setSummary(text) {
- await core.summary.addRaw(text).write();
}
-async function tryGetUserLogin(octokit) {
- try {
- const username = await octokit.rest.users.getAuthenticated();
- return username.data?.login;
- }
- catch {
- core.warning('⚠️ Failed to get username without user scope, will check comment with user type instead');
- // when token doesn't have user scope
- return undefined;
+exports.group = group;
+//-----------------------------------------------------------------------
+// Wrapper action state
+//-----------------------------------------------------------------------
+/**
+ * Saves state for current action, the state can only be retrieved by this action's post job execution.
+ *
+ * @param name name of the state to store
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function saveState(name, value) {
+ const filePath = process.env['GITHUB_STATE'] || '';
+ if (filePath) {
+ return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value));
}
+ (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value));
}
-async function getExistingCommentId(octokit, header) {
- const comments = await octokit.rest.issues.listComments({
- owner: github.context.repo.owner,
- repo: github.context.repo.repo,
- issue_number: github.context.issue.number
- });
- const userLogin = await tryGetUserLogin(octokit);
- const existingComment = comments.data?.find(c => {
- const isBotUserType = c.user?.type === 'Bot' || c.user?.login === userLogin;
- const startsWithHeader = c.body?.startsWith(header);
- return isBotUserType && startsWithHeader;
- });
- return existingComment?.id;
-}
-async function comment(githubClient, message) {
- const { owner, repo, number } = github.context.issue;
- if (!number) {
- throw new Error('Unable to get pull request number from action event');
- }
- core.info(`Commenting on PR #${number}`);
- const resp = await githubClient.rest.issues.createComment({
- owner,
- repo,
- issue_number: number,
- body: message
- });
- resp.status === 201 ? core.info('Commented on PR') : core.error(`Failed to comment on PR. Response: ${resp}`);
- return resp.status === 201;
-}
-async function updateComment(githubClient, commentId, body) {
- const { owner, repo, number } = github.context.issue;
- core.info(`♻️ Updating comment #${commentId} on PR #${number}`);
- const resp = await githubClient.rest.issues.updateComment({
- owner,
- repo,
- comment_id: commentId,
- body
+exports.saveState = saveState;
+/**
+ * Gets the value of an state set by this action's main execution.
+ *
+ * @param name name of the state to get
+ * @returns string
+ */
+function getState(name) {
+ return process.env[`STATE_${name}`] || '';
+}
+exports.getState = getState;
+function getIDToken(aud) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return yield oidc_utils_1.OidcClient.getIDToken(aud);
});
- resp.status === 200 ? core.info('Comment updated') : core.error(`Failed to update comment. Response: ${resp}`);
- return resp.status === 200;
}
-
+exports.getIDToken = getIDToken;
+/**
+ * Summary exports
+ */
+var summary_1 = __nccwpck_require__(1847);
+Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } }));
+/**
+ * @deprecated use core.summary
+ */
+var summary_2 = __nccwpck_require__(1847);
+Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } }));
+/**
+ * Path exports
+ */
+var path_utils_1 = __nccwpck_require__(1976);
+Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } }));
+Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } }));
+Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }));
+/**
+ * Platform utilities exports
+ */
+exports.platform = __importStar(__nccwpck_require__(8968));
+//# sourceMappingURL=core.js.map
/***/ }),
-/***/ 3109:
-/***/ ((module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-__nccwpck_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
-__nccwpck_require__.r(__webpack_exports__);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(42186);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core__WEBPACK_IMPORTED_MODULE_0__);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(73837);
-/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(util__WEBPACK_IMPORTED_MODULE_1__);
-/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(86979);
-/* harmony import */ var _duplicated__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(93562);
-/* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(19118);
-/* harmony import */ var _problem_matcher__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(6702);
-
+/***/ 4753:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-
-
-async function run() {
- try {
- const inputs = _common__WEBPACK_IMPORTED_MODULE_2__/* .getInputs */ .G9();
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.debug(`🔍Inputs: ${(0,util__WEBPACK_IMPORTED_MODULE_1__.inspect)(inputs)}`);
- const githubClient = _common__WEBPACK_IMPORTED_MODULE_2__/* .getOctokitRest */ .IT(inputs.authToken);
- inputs.problemMatcherEnabled && (0,_problem_matcher__WEBPACK_IMPORTED_MODULE_5__/* .addProblemMatcher */ .J)();
- const finalFormatResult = await (0,_format__WEBPACK_IMPORTED_MODULE_4__/* .format */ .W)(inputs, githubClient);
- inputs.problemMatcherEnabled && (0,_problem_matcher__WEBPACK_IMPORTED_MODULE_5__/* .removeProblemMatcher */ .b)();
- if (inputs.jscpdCheck) {
- await (0,_duplicated__WEBPACK_IMPORTED_MODULE_3__/* .duplicatedCheck */ .O)(inputs.workspace, inputs.jscpdConfigPath, inputs.jscpdCheckAsError, inputs.postNewComment, githubClient);
- }
- if (!finalFormatResult && inputs.failFast) {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.setFailed(`Action failed with format issue`);
- }
- return finalFormatResult;
+// For internal use, subject to change.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
}
- catch (error) {
- if (error instanceof Error) {
- _actions_core__WEBPACK_IMPORTED_MODULE_0__.setFailed(`Action failed with error ${error.message}`);
- }
- return false;
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+const crypto = __importStar(__nccwpck_require__(6982));
+const fs = __importStar(__nccwpck_require__(9896));
+const os = __importStar(__nccwpck_require__(857));
+const utils_1 = __nccwpck_require__(302);
+function issueFileCommand(command, message) {
+ const filePath = process.env[`GITHUB_${command}`];
+ if (!filePath) {
+ throw new Error(`Unable to find environment variable for file command ${command}`);
}
+ if (!fs.existsSync(filePath)) {
+ throw new Error(`Missing file at path: ${filePath}`);
+ }
+ fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, {
+ encoding: 'utf8'
+ });
}
-await run();
-
-__webpack_async_result__();
-} catch(e) { __webpack_async_result__(e); } }, 1);
-
-/***/ }),
-
-/***/ 74062:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "A": () => (/* binding */ INPUTS),
-/* harmony export */ "a": () => (/* binding */ FormatType)
-/* harmony export */ });
-var INPUTS;
-(function (INPUTS) {
- INPUTS["authToken"] = "authToken";
- INPUTS["action"] = "action";
- INPUTS["onlyChangedFiles"] = "onlyChangedFiles";
- INPUTS["failFast"] = "failFast";
- INPUTS["workspace"] = "workspace";
- INPUTS["projectFileName"] = "projectFileName";
- INPUTS["severityLevel"] = "severityLevel";
- INPUTS["logLevel"] = "logLevel";
- INPUTS["commitUsername"] = "commitUsername";
- INPUTS["commitUserEmail"] = "commitUserEmail";
- INPUTS["commitMessage"] = "commitMessage";
- INPUTS["nugetConfigPath"] = "nugetConfigPath";
- INPUTS["dotnetFormatConfigPath"] = "dotnetFormatConfigPath";
- INPUTS["jscpdCheck"] = "jscpdCheck";
- INPUTS["jscpdConfigPath"] = "jscpdConfigPath";
- INPUTS["jscpdCheckAsError"] = "jscpdCheckAsError";
- INPUTS["problemMatcherEnabled"] = "problemMatcherEnabled";
- INPUTS["skipCommit"] = "skipCommit";
- INPUTS["postNewComment"] = "postNewComment";
-})(INPUTS || (INPUTS = {}));
-var FormatType;
-(function (FormatType) {
- FormatType["all"] = "all";
- FormatType["style"] = "style";
- FormatType["analyzers"] = "analyzers";
- FormatType["whitespace"] = "whitespace";
-})(FormatType || (FormatType = {}));
-
+exports.issueFileCommand = issueFileCommand;
+function prepareKeyValueMessage(key, value) {
+ const delimiter = `ghadelimiter_${crypto.randomUUID()}`;
+ const convertedValue = (0, utils_1.toCommandValue)(value);
+ // These should realistically never happen, but just in case someone finds a
+ // way to exploit uuid generation let's not allow keys or values that contain
+ // the delimiter.
+ if (key.includes(delimiter)) {
+ throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
+ }
+ if (convertedValue.includes(delimiter)) {
+ throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
+ }
+ return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
+}
+exports.prepareKeyValueMessage = prepareKeyValueMessage;
+//# sourceMappingURL=file-command.js.map
/***/ }),
-/***/ 6702:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "J": () => (/* binding */ addProblemMatcher),
-/* harmony export */ "b": () => (/* binding */ removeProblemMatcher)
-/* harmony export */ });
-/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(71017);
-/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(42186);
-/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core__WEBPACK_IMPORTED_MODULE_1__);
-/* harmony import */ var _actions_core_lib_command__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(87351);
-/* harmony import */ var _actions_core_lib_command__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core_lib_command__WEBPACK_IMPORTED_MODULE_2__);
-
+/***/ 5306:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-function addProblemMatcher() {
- try {
- _actions_core__WEBPACK_IMPORTED_MODULE_1__.info(`Adding problem matcher from ${(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(__dirname, 'problem-matcher.json')}`);
- (0,_actions_core_lib_command__WEBPACK_IMPORTED_MODULE_2__.issueCommand)('add-matcher', {}, (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(__dirname, 'problem-matcher.json'));
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.OidcClient = void 0;
+const http_client_1 = __nccwpck_require__(4844);
+const auth_1 = __nccwpck_require__(4552);
+const core_1 = __nccwpck_require__(7484);
+class OidcClient {
+ static createHttpClient(allowRetry = true, maxRetry = 10) {
+ const requestOptions = {
+ allowRetries: allowRetry,
+ maxRetries: maxRetry
+ };
+ return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
}
- catch (error) {
- if (error instanceof Error) {
- _actions_core__WEBPACK_IMPORTED_MODULE_1__.setFailed(error.message);
+ static getRequestToken() {
+ const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
+ if (!token) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
}
- else {
- throw error;
+ return token;
+ }
+ static getIDTokenUrl() {
+ const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
+ if (!runtimeUrl) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
}
+ return runtimeUrl;
}
-}
-function removeProblemMatcher() {
- try {
- _actions_core__WEBPACK_IMPORTED_MODULE_1__.info(`Removing problem matcher`);
- (0,_actions_core_lib_command__WEBPACK_IMPORTED_MODULE_2__.issueCommand)('remove-matcher', { owner: 'dotnet-format-plus' }, '');
+ static getCall(id_token_url) {
+ var _a;
+ return __awaiter(this, void 0, void 0, function* () {
+ const httpclient = OidcClient.createHttpClient();
+ const res = yield httpclient
+ .getJson(id_token_url)
+ .catch(error => {
+ throw new Error(`Failed to get ID Token. \n
+ Error Code : ${error.statusCode}\n
+ Error Message: ${error.message}`);
+ });
+ const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
+ if (!id_token) {
+ throw new Error('Response json body do not have ID Token field');
+ }
+ return id_token;
+ });
}
- catch (error) {
- if (error instanceof Error) {
- _actions_core__WEBPACK_IMPORTED_MODULE_1__.setFailed(error.message);
- }
- else {
- throw error;
- }
+ static getIDToken(audience) {
+ return __awaiter(this, void 0, void 0, function* () {
+ try {
+ // New ID Token is requested from action service
+ let id_token_url = OidcClient.getIDTokenUrl();
+ if (audience) {
+ const encodedAudience = encodeURIComponent(audience);
+ id_token_url = `${id_token_url}&audience=${encodedAudience}`;
+ }
+ (0, core_1.debug)(`ID token url is ${id_token_url}`);
+ const id_token = yield OidcClient.getCall(id_token_url);
+ (0, core_1.setSecret)(id_token);
+ return id_token;
+ }
+ catch (error) {
+ throw new Error(`Error message: ${error.message}`);
+ }
+ });
}
}
-
+exports.OidcClient = OidcClient;
+//# sourceMappingURL=oidc-utils.js.map
/***/ }),
-/***/ 22094:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
+/***/ 1976:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-"use strict";
-// EXPORTS
-__nccwpck_require__.d(__webpack_exports__, {
- "z": () => (/* binding */ readConfig)
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
});
-
-// UNUSED EXPORTS: readJSONSync
-
-// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
-var core = __nccwpck_require__(42186);
-// EXTERNAL MODULE: ./node_modules/deepmerge/dist/cjs.js
-var cjs = __nccwpck_require__(56323);
-var cjs_default = /*#__PURE__*/__nccwpck_require__.n(cjs);
-// EXTERNAL MODULE: external "fs"
-var external_fs_ = __nccwpck_require__(57147);
-;// CONCATENATED MODULE: ./node_modules/js-yaml/dist/js-yaml.mjs
-
-/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
-function isNothing(subject) {
- return (typeof subject === 'undefined') || (subject === null);
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
+const path = __importStar(__nccwpck_require__(6928));
+/**
+ * toPosixPath converts the given path to the posix form. On Windows, \\ will be
+ * replaced with /.
+ *
+ * @param pth. Path to transform.
+ * @return string Posix path.
+ */
+function toPosixPath(pth) {
+ return pth.replace(/[\\]/g, '/');
}
-
-
-function isObject(subject) {
- return (typeof subject === 'object') && (subject !== null);
+exports.toPosixPath = toPosixPath;
+/**
+ * toWin32Path converts the given path to the win32 form. On Linux, / will be
+ * replaced with \\.
+ *
+ * @param pth. Path to transform.
+ * @return string Win32 path.
+ */
+function toWin32Path(pth) {
+ return pth.replace(/[/]/g, '\\');
}
-
-
-function toArray(sequence) {
- if (Array.isArray(sequence)) return sequence;
- else if (isNothing(sequence)) return [];
-
- return [ sequence ];
+exports.toWin32Path = toWin32Path;
+/**
+ * toPlatformPath converts the given path to a platform-specific path. It does
+ * this by replacing instances of / and \ with the platform-specific path
+ * separator.
+ *
+ * @param pth The path to platformize.
+ * @return string The platform-specific path.
+ */
+function toPlatformPath(pth) {
+ return pth.replace(/[/\\]/g, path.sep);
}
+exports.toPlatformPath = toPlatformPath;
+//# sourceMappingURL=path-utils.js.map
+/***/ }),
-function extend(target, source) {
- var index, length, key, sourceKeys;
+/***/ 8968:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- if (source) {
- sourceKeys = Object.keys(source);
- for (index = 0, length = sourceKeys.length; index < length; index += 1) {
- key = sourceKeys[index];
- target[key] = source[key];
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
}
- }
-
- return target;
-}
-
-
-function repeat(string, count) {
- var result = '', cycle;
-
- for (cycle = 0; cycle < count; cycle += 1) {
- result += string;
- }
-
- return result;
-}
-
-
-function isNegativeZero(number) {
- return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
-}
-
-
-var isNothing_1 = isNothing;
-var isObject_1 = isObject;
-var toArray_1 = toArray;
-var repeat_1 = repeat;
-var isNegativeZero_1 = isNegativeZero;
-var extend_1 = extend;
-
-var common = {
- isNothing: isNothing_1,
- isObject: isObject_1,
- toArray: toArray_1,
- repeat: repeat_1,
- isNegativeZero: isNegativeZero_1,
- extend: extend_1
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
};
-
-// YAML error class. http://stackoverflow.com/questions/8458984
-
-
-function formatError(exception, compact) {
- var where = '', message = exception.reason || '(unknown reason)';
-
- if (!exception.mark) return message;
-
- if (exception.mark.name) {
- where += 'in "' + exception.mark.name + '" ';
- }
-
- where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
-
- if (!compact && exception.mark.snippet) {
- where += '\n\n' + exception.mark.snippet;
- }
-
- return message + ' ' + where;
-}
-
-
-function YAMLException$1(reason, mark) {
- // Super constructor
- Error.call(this);
-
- this.name = 'YAMLException';
- this.reason = reason;
- this.mark = mark;
- this.message = formatError(this, false);
-
- // Include stack trace in error object
- if (Error.captureStackTrace) {
- // Chrome and NodeJS
- Error.captureStackTrace(this, this.constructor);
- } else {
- // FF, IE 10+ and Safari 6+. Fallback for others
- this.stack = (new Error()).stack || '';
- }
-}
-
-
-// Inherit from Error
-YAMLException$1.prototype = Object.create(Error.prototype);
-YAMLException$1.prototype.constructor = YAMLException$1;
-
-
-YAMLException$1.prototype.toString = function toString(compact) {
- return this.name + ': ' + formatError(this, compact);
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
};
-
-
-var exception = YAMLException$1;
-
-// get snippet for a single line, respecting maxLength
-function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
- var head = '';
- var tail = '';
- var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
-
- if (position - lineStart > maxHalfLength) {
- head = ' ... ';
- lineStart = position - maxHalfLength + head.length;
- }
-
- if (lineEnd - position > maxHalfLength) {
- tail = ' ...';
- lineEnd = position + maxHalfLength - tail.length;
- }
-
- return {
- str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
- pos: position - lineStart + head.length // relative position
- };
-}
-
-
-function padStart(string, max) {
- return common.repeat(' ', max - string.length) + string;
-}
-
-
-function makeSnippet(mark, options) {
- options = Object.create(options || null);
-
- if (!mark.buffer) return null;
-
- if (!options.maxLength) options.maxLength = 79;
- if (typeof options.indent !== 'number') options.indent = 1;
- if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
- if (typeof options.linesAfter !== 'number') options.linesAfter = 2;
-
- var re = /\r?\n|\r|\0/g;
- var lineStarts = [ 0 ];
- var lineEnds = [];
- var match;
- var foundLineNo = -1;
-
- while ((match = re.exec(mark.buffer))) {
- lineEnds.push(match.index);
- lineStarts.push(match.index + match[0].length);
-
- if (mark.position <= match.index && foundLineNo < 0) {
- foundLineNo = lineStarts.length - 2;
- }
- }
-
- if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
-
- var result = '', i, line;
- var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
- var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
-
- for (i = 1; i <= options.linesBefore; i++) {
- if (foundLineNo - i < 0) break;
- line = getLine(
- mark.buffer,
- lineStarts[foundLineNo - i],
- lineEnds[foundLineNo - i],
- mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
- maxLineLength
- );
- result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
- ' | ' + line.str + '\n' + result;
- }
-
- line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
- result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
- ' | ' + line.str + '\n';
- result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
-
- for (i = 1; i <= options.linesAfter; i++) {
- if (foundLineNo + i >= lineEnds.length) break;
- line = getLine(
- mark.buffer,
- lineStarts[foundLineNo + i],
- lineEnds[foundLineNo + i],
- mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
- maxLineLength
- );
- result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
- ' | ' + line.str + '\n';
- }
-
- return result.replace(/\n$/, '');
-}
-
-
-var snippet = makeSnippet;
-
-var TYPE_CONSTRUCTOR_OPTIONS = [
- 'kind',
- 'multi',
- 'resolve',
- 'construct',
- 'instanceOf',
- 'predicate',
- 'represent',
- 'representName',
- 'defaultStyle',
- 'styleAliases'
-];
-
-var YAML_NODE_KINDS = [
- 'scalar',
- 'sequence',
- 'mapping'
-];
-
-function compileStyleAliases(map) {
- var result = {};
-
- if (map !== null) {
- Object.keys(map).forEach(function (style) {
- map[style].forEach(function (alias) {
- result[String(alias)] = style;
- });
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0;
+const os_1 = __importDefault(__nccwpck_require__(857));
+const exec = __importStar(__nccwpck_require__(5236));
+const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () {
+ const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, {
+ silent: true
+ });
+ const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, {
+ silent: true
+ });
+ return {
+ name: name.trim(),
+ version: version.trim()
+ };
+});
+const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () {
+ var _a, _b, _c, _d;
+ const { stdout } = yield exec.getExecOutput('sw_vers', undefined, {
+ silent: true
+ });
+ const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : '';
+ const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : '';
+ return {
+ name,
+ version
+ };
+});
+const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () {
+ const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], {
+ silent: true
+ });
+ const [name, version] = stdout.trim().split('\n');
+ return {
+ name,
+ version
+ };
+});
+exports.platform = os_1.default.platform();
+exports.arch = os_1.default.arch();
+exports.isWindows = exports.platform === 'win32';
+exports.isMacOS = exports.platform === 'darwin';
+exports.isLinux = exports.platform === 'linux';
+function getDetails() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return Object.assign(Object.assign({}, (yield (exports.isWindows
+ ? getWindowsInfo()
+ : exports.isMacOS
+ ? getMacOsInfo()
+ : getLinuxInfo()))), { platform: exports.platform,
+ arch: exports.arch,
+ isWindows: exports.isWindows,
+ isMacOS: exports.isMacOS,
+ isLinux: exports.isLinux });
});
- }
-
- return result;
-}
-
-function Type$1(tag, options) {
- options = options || {};
-
- Object.keys(options).forEach(function (name) {
- if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
- throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
- }
- });
-
- // TODO: Add tag format check.
- this.options = options; // keep original options in case user wants to extend this type later
- this.tag = tag;
- this.kind = options['kind'] || null;
- this.resolve = options['resolve'] || function () { return true; };
- this.construct = options['construct'] || function (data) { return data; };
- this.instanceOf = options['instanceOf'] || null;
- this.predicate = options['predicate'] || null;
- this.represent = options['represent'] || null;
- this.representName = options['representName'] || null;
- this.defaultStyle = options['defaultStyle'] || null;
- this.multi = options['multi'] || false;
- this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
-
- if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
- throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
- }
}
+exports.getDetails = getDetails;
+//# sourceMappingURL=platform.js.map
-var type = Type$1;
-
-/*eslint-disable max-len*/
-
-
-
-
-
-function compileList(schema, name) {
- var result = [];
+/***/ }),
- schema[name].forEach(function (currentType) {
- var newIndex = result.length;
+/***/ 1847:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- result.forEach(function (previousType, previousIndex) {
- if (previousType.tag === currentType.tag &&
- previousType.kind === currentType.kind &&
- previousType.multi === currentType.multi) {
- newIndex = previousIndex;
- }
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
});
-
- result[newIndex] = currentType;
- });
-
- return result;
-}
-
-
-function compileMap(/* lists... */) {
- var result = {
- scalar: {},
- sequence: {},
- mapping: {},
- fallback: {},
- multi: {
- scalar: [],
- sequence: [],
- mapping: [],
- fallback: []
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
+const os_1 = __nccwpck_require__(857);
+const fs_1 = __nccwpck_require__(9896);
+const { access, appendFile, writeFile } = fs_1.promises;
+exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
+exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
+class Summary {
+ constructor() {
+ this._buffer = '';
+ }
+ /**
+ * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
+ * Also checks r/w permissions.
+ *
+ * @returns step summary file path
+ */
+ filePath() {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._filePath) {
+ return this._filePath;
+ }
+ const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
+ if (!pathFromEnv) {
+ throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
+ }
+ try {
+ yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
+ }
+ catch (_a) {
+ throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
+ }
+ this._filePath = pathFromEnv;
+ return this._filePath;
+ });
+ }
+ /**
+ * Wraps content in an HTML tag, adding any HTML attributes
+ *
+ * @param {string} tag HTML tag to wrap
+ * @param {string | null} content content within the tag
+ * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
+ *
+ * @returns {string} content wrapped in HTML element
+ */
+ wrap(tag, content, attrs = {}) {
+ const htmlAttrs = Object.entries(attrs)
+ .map(([key, value]) => ` ${key}="${value}"`)
+ .join('');
+ if (!content) {
+ return `<${tag}${htmlAttrs}>`;
}
- }, index, length;
-
- function collectType(type) {
- if (type.multi) {
- result.multi[type.kind].push(type);
- result.multi['fallback'].push(type);
- } else {
- result[type.kind][type.tag] = result['fallback'][type.tag] = type;
+ return `<${tag}${htmlAttrs}>${content}${tag}>`;
}
- }
-
- for (index = 0, length = arguments.length; index < length; index += 1) {
- arguments[index].forEach(collectType);
- }
- return result;
-}
-
-
-function Schema$1(definition) {
- return this.extend(definition);
-}
-
-
-Schema$1.prototype.extend = function extend(definition) {
- var implicit = [];
- var explicit = [];
-
- if (definition instanceof type) {
- // Schema.extend(type)
- explicit.push(definition);
-
- } else if (Array.isArray(definition)) {
- // Schema.extend([ type1, type2, ... ])
- explicit = explicit.concat(definition);
-
- } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
- // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
- if (definition.implicit) implicit = implicit.concat(definition.implicit);
- if (definition.explicit) explicit = explicit.concat(definition.explicit);
-
- } else {
- throw new exception('Schema.extend argument should be a Type, [ Type ], ' +
- 'or a schema definition ({ implicit: [...], explicit: [...] })');
- }
-
- implicit.forEach(function (type$1) {
- if (!(type$1 instanceof type)) {
- throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ /**
+ * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
+ *
+ * @param {SummaryWriteOptions} [options] (optional) options for write operation
+ *
+ * @returns {Promise} summary instance
+ */
+ write(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
+ const filePath = yield this.filePath();
+ const writeFunc = overwrite ? writeFile : appendFile;
+ yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
+ return this.emptyBuffer();
+ });
}
-
- if (type$1.loadKind && type$1.loadKind !== 'scalar') {
- throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
+ /**
+ * Clears the summary buffer and wipes the summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ clear() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.emptyBuffer().write({ overwrite: true });
+ });
}
-
- if (type$1.multi) {
- throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
+ /**
+ * Returns the current summary buffer as a string
+ *
+ * @returns {string} string of summary buffer
+ */
+ stringify() {
+ return this._buffer;
}
- });
-
- explicit.forEach(function (type$1) {
- if (!(type$1 instanceof type)) {
- throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ /**
+ * If the summary buffer is empty
+ *
+ * @returns {boolen} true if the buffer is empty
+ */
+ isEmptyBuffer() {
+ return this._buffer.length === 0;
}
- });
-
- var result = Object.create(Schema$1.prototype);
-
- result.implicit = (this.implicit || []).concat(implicit);
- result.explicit = (this.explicit || []).concat(explicit);
-
- result.compiledImplicit = compileList(result, 'implicit');
- result.compiledExplicit = compileList(result, 'explicit');
- result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
-
- return result;
-};
-
-
-var schema = Schema$1;
-
-var str = new type('tag:yaml.org,2002:str', {
- kind: 'scalar',
- construct: function (data) { return data !== null ? data : ''; }
-});
-
-var seq = new type('tag:yaml.org,2002:seq', {
- kind: 'sequence',
- construct: function (data) { return data !== null ? data : []; }
-});
-
-var map = new type('tag:yaml.org,2002:map', {
- kind: 'mapping',
- construct: function (data) { return data !== null ? data : {}; }
-});
-
-var failsafe = new schema({
- explicit: [
- str,
- seq,
- map
- ]
-});
-
-function resolveYamlNull(data) {
- if (data === null) return true;
-
- var max = data.length;
-
- return (max === 1 && data === '~') ||
- (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
-}
-
-function constructYamlNull() {
- return null;
-}
-
-function isNull(object) {
- return object === null;
-}
-
-var _null = new type('tag:yaml.org,2002:null', {
- kind: 'scalar',
- resolve: resolveYamlNull,
- construct: constructYamlNull,
- predicate: isNull,
- represent: {
- canonical: function () { return '~'; },
- lowercase: function () { return 'null'; },
- uppercase: function () { return 'NULL'; },
- camelcase: function () { return 'Null'; },
- empty: function () { return ''; }
- },
- defaultStyle: 'lowercase'
-});
-
-function resolveYamlBoolean(data) {
- if (data === null) return false;
-
- var max = data.length;
-
- return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
- (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
-}
-
-function constructYamlBoolean(data) {
- return data === 'true' ||
- data === 'True' ||
- data === 'TRUE';
-}
-
-function isBoolean(object) {
- return Object.prototype.toString.call(object) === '[object Boolean]';
-}
-
-var bool = new type('tag:yaml.org,2002:bool', {
- kind: 'scalar',
- resolve: resolveYamlBoolean,
- construct: constructYamlBoolean,
- predicate: isBoolean,
- represent: {
- lowercase: function (object) { return object ? 'true' : 'false'; },
- uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
- camelcase: function (object) { return object ? 'True' : 'False'; }
- },
- defaultStyle: 'lowercase'
-});
-
-function isHexCode(c) {
- return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
- ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
- ((0x61/* a */ <= c) && (c <= 0x66/* f */));
-}
-
-function isOctCode(c) {
- return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
-}
-
-function isDecCode(c) {
- return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
-}
-
-function resolveYamlInteger(data) {
- if (data === null) return false;
-
- var max = data.length,
- index = 0,
- hasDigits = false,
- ch;
-
- if (!max) return false;
-
- ch = data[index];
-
- // sign
- if (ch === '-' || ch === '+') {
- ch = data[++index];
- }
-
- if (ch === '0') {
- // 0
- if (index + 1 === max) return true;
- ch = data[++index];
-
- // base 2, base 8, base 16
-
- if (ch === 'b') {
- // base 2
- index++;
-
- for (; index < max; index++) {
- ch = data[index];
- if (ch === '_') continue;
- if (ch !== '0' && ch !== '1') return false;
- hasDigits = true;
- }
- return hasDigits && ch !== '_';
+ /**
+ * Resets the summary buffer without writing to summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ emptyBuffer() {
+ this._buffer = '';
+ return this;
}
-
-
- if (ch === 'x') {
- // base 16
- index++;
-
- for (; index < max; index++) {
- ch = data[index];
- if (ch === '_') continue;
- if (!isHexCode(data.charCodeAt(index))) return false;
- hasDigits = true;
- }
- return hasDigits && ch !== '_';
+ /**
+ * Adds raw text to the summary buffer
+ *
+ * @param {string} text content to add
+ * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addRaw(text, addEOL = false) {
+ this._buffer += text;
+ return addEOL ? this.addEOL() : this;
}
-
-
- if (ch === 'o') {
- // base 8
- index++;
-
- for (; index < max; index++) {
- ch = data[index];
- if (ch === '_') continue;
- if (!isOctCode(data.charCodeAt(index))) return false;
- hasDigits = true;
- }
- return hasDigits && ch !== '_';
+ /**
+ * Adds the operating system-specific end-of-line marker to the buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addEOL() {
+ return this.addRaw(os_1.EOL);
}
- }
-
- // base 10 (except 0)
-
- // value should not start with `_`;
- if (ch === '_') return false;
-
- for (; index < max; index++) {
- ch = data[index];
- if (ch === '_') continue;
- if (!isDecCode(data.charCodeAt(index))) {
- return false;
+ /**
+ * Adds an HTML codeblock to the summary buffer
+ *
+ * @param {string} code content to render within fenced code block
+ * @param {string} lang (optional) language to syntax highlight code
+ *
+ * @returns {Summary} summary instance
+ */
+ addCodeBlock(code, lang) {
+ const attrs = Object.assign({}, (lang && { lang }));
+ const element = this.wrap('pre', this.wrap('code', code), attrs);
+ return this.addRaw(element).addEOL();
}
- hasDigits = true;
- }
-
- // Should have digits and should not end with `_`
- if (!hasDigits || ch === '_') return false;
-
- return true;
-}
-
-function constructYamlInteger(data) {
- var value = data, sign = 1, ch;
-
- if (value.indexOf('_') !== -1) {
- value = value.replace(/_/g, '');
- }
-
- ch = value[0];
-
- if (ch === '-' || ch === '+') {
- if (ch === '-') sign = -1;
- value = value.slice(1);
- ch = value[0];
- }
-
- if (value === '0') return 0;
-
- if (ch === '0') {
- if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
- if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
- if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
- }
-
- return sign * parseInt(value, 10);
-}
-
-function isInteger(object) {
- return (Object.prototype.toString.call(object)) === '[object Number]' &&
- (object % 1 === 0 && !common.isNegativeZero(object));
-}
-
-var js_yaml_int = new type('tag:yaml.org,2002:int', {
- kind: 'scalar',
- resolve: resolveYamlInteger,
- construct: constructYamlInteger,
- predicate: isInteger,
- represent: {
- binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
- octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },
- decimal: function (obj) { return obj.toString(10); },
- /* eslint-disable max-len */
- hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
- },
- defaultStyle: 'decimal',
- styleAliases: {
- binary: [ 2, 'bin' ],
- octal: [ 8, 'oct' ],
- decimal: [ 10, 'dec' ],
- hexadecimal: [ 16, 'hex' ]
- }
-});
-
-var YAML_FLOAT_PATTERN = new RegExp(
- // 2.5e4, 2.5 and integers
- '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
- // .2e4, .2
- // special case, seems not from spec
- '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
- // .inf
- '|[-+]?\\.(?:inf|Inf|INF)' +
- // .nan
- '|\\.(?:nan|NaN|NAN))$');
-
-function resolveYamlFloat(data) {
- if (data === null) return false;
-
- if (!YAML_FLOAT_PATTERN.test(data) ||
- // Quick hack to not allow integers end with `_`
- // Probably should update regexp & check speed
- data[data.length - 1] === '_') {
- return false;
- }
-
- return true;
-}
-
-function constructYamlFloat(data) {
- var value, sign;
-
- value = data.replace(/_/g, '').toLowerCase();
- sign = value[0] === '-' ? -1 : 1;
-
- if ('+-'.indexOf(value[0]) >= 0) {
- value = value.slice(1);
- }
-
- if (value === '.inf') {
- return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
-
- } else if (value === '.nan') {
- return NaN;
- }
- return sign * parseFloat(value, 10);
-}
-
-
-var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
-
-function representYamlFloat(object, style) {
- var res;
-
- if (isNaN(object)) {
- switch (style) {
- case 'lowercase': return '.nan';
- case 'uppercase': return '.NAN';
- case 'camelcase': return '.NaN';
+ /**
+ * Adds an HTML list to the summary buffer
+ *
+ * @param {string[]} items list of items to render
+ * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addList(items, ordered = false) {
+ const tag = ordered ? 'ol' : 'ul';
+ const listItems = items.map(item => this.wrap('li', item)).join('');
+ const element = this.wrap(tag, listItems);
+ return this.addRaw(element).addEOL();
}
- } else if (Number.POSITIVE_INFINITY === object) {
- switch (style) {
- case 'lowercase': return '.inf';
- case 'uppercase': return '.INF';
- case 'camelcase': return '.Inf';
+ /**
+ * Adds an HTML table to the summary buffer
+ *
+ * @param {SummaryTableCell[]} rows table rows
+ *
+ * @returns {Summary} summary instance
+ */
+ addTable(rows) {
+ const tableBody = rows
+ .map(row => {
+ const cells = row
+ .map(cell => {
+ if (typeof cell === 'string') {
+ return this.wrap('td', cell);
+ }
+ const { header, data, colspan, rowspan } = cell;
+ const tag = header ? 'th' : 'td';
+ const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
+ return this.wrap(tag, data, attrs);
+ })
+ .join('');
+ return this.wrap('tr', cells);
+ })
+ .join('');
+ const element = this.wrap('table', tableBody);
+ return this.addRaw(element).addEOL();
}
- } else if (Number.NEGATIVE_INFINITY === object) {
- switch (style) {
- case 'lowercase': return '-.inf';
- case 'uppercase': return '-.INF';
- case 'camelcase': return '-.Inf';
+ /**
+ * Adds a collapsable HTML details element to the summary buffer
+ *
+ * @param {string} label text for the closed state
+ * @param {string} content collapsable content
+ *
+ * @returns {Summary} summary instance
+ */
+ addDetails(label, content) {
+ const element = this.wrap('details', this.wrap('summary', label) + content);
+ return this.addRaw(element).addEOL();
}
- } else if (common.isNegativeZero(object)) {
- return '-0.0';
- }
-
- res = object.toString(10);
-
- // JS stringifier can build scientific format without dots: 5e-100,
- // while YAML requres dot: 5.e-100. Fix it with simple hack
-
- return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
-}
-
-function isFloat(object) {
- return (Object.prototype.toString.call(object) === '[object Number]') &&
- (object % 1 !== 0 || common.isNegativeZero(object));
-}
-
-var js_yaml_float = new type('tag:yaml.org,2002:float', {
- kind: 'scalar',
- resolve: resolveYamlFloat,
- construct: constructYamlFloat,
- predicate: isFloat,
- represent: representYamlFloat,
- defaultStyle: 'lowercase'
-});
-
-var json = failsafe.extend({
- implicit: [
- _null,
- bool,
- js_yaml_int,
- js_yaml_float
- ]
-});
-
-var js_yaml_core = json;
-
-var YAML_DATE_REGEXP = new RegExp(
- '^([0-9][0-9][0-9][0-9])' + // [1] year
- '-([0-9][0-9])' + // [2] month
- '-([0-9][0-9])$'); // [3] day
-
-var YAML_TIMESTAMP_REGEXP = new RegExp(
- '^([0-9][0-9][0-9][0-9])' + // [1] year
- '-([0-9][0-9]?)' + // [2] month
- '-([0-9][0-9]?)' + // [3] day
- '(?:[Tt]|[ \\t]+)' + // ...
- '([0-9][0-9]?)' + // [4] hour
- ':([0-9][0-9])' + // [5] minute
- ':([0-9][0-9])' + // [6] second
- '(?:\\.([0-9]*))?' + // [7] fraction
- '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
- '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
-
-function resolveYamlTimestamp(data) {
- if (data === null) return false;
- if (YAML_DATE_REGEXP.exec(data) !== null) return true;
- if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
- return false;
-}
-
-function constructYamlTimestamp(data) {
- var match, year, month, day, hour, minute, second, fraction = 0,
- delta = null, tz_hour, tz_minute, date;
-
- match = YAML_DATE_REGEXP.exec(data);
- if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
-
- if (match === null) throw new Error('Date resolve error');
-
- // match: [1] year [2] month [3] day
-
- year = +(match[1]);
- month = +(match[2]) - 1; // JS month starts with 0
- day = +(match[3]);
-
- if (!match[4]) { // no hour
- return new Date(Date.UTC(year, month, day));
- }
-
- // match: [4] hour [5] minute [6] second [7] fraction
-
- hour = +(match[4]);
- minute = +(match[5]);
- second = +(match[6]);
-
- if (match[7]) {
- fraction = match[7].slice(0, 3);
- while (fraction.length < 3) { // milli-seconds
- fraction += '0';
+ /**
+ * Adds an HTML image tag to the summary buffer
+ *
+ * @param {string} src path to the image you to embed
+ * @param {string} alt text description of the image
+ * @param {SummaryImageOptions} options (optional) addition image attributes
+ *
+ * @returns {Summary} summary instance
+ */
+ addImage(src, alt, options) {
+ const { width, height } = options || {};
+ const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
+ const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
+ return this.addRaw(element).addEOL();
}
- fraction = +fraction;
- }
-
- // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
-
- if (match[9]) {
- tz_hour = +(match[10]);
- tz_minute = +(match[11] || 0);
- delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
- if (match[9] === '-') delta = -delta;
- }
-
- date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
-
- if (delta) date.setTime(date.getTime() - delta);
-
- return date;
-}
-
-function representYamlTimestamp(object /*, style*/) {
- return object.toISOString();
-}
-
-var timestamp = new type('tag:yaml.org,2002:timestamp', {
- kind: 'scalar',
- resolve: resolveYamlTimestamp,
- construct: constructYamlTimestamp,
- instanceOf: Date,
- represent: representYamlTimestamp
-});
-
-function resolveYamlMerge(data) {
- return data === '<<' || data === null;
-}
-
-var merge = new type('tag:yaml.org,2002:merge', {
- kind: 'scalar',
- resolve: resolveYamlMerge
-});
-
-/*eslint-disable no-bitwise*/
-
-
-
-
-
-// [ 64, 65, 66 ] -> [ padding, CR, LF ]
-var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
-
-
-function resolveYamlBinary(data) {
- if (data === null) return false;
-
- var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
-
- // Convert one by one.
- for (idx = 0; idx < max; idx++) {
- code = map.indexOf(data.charAt(idx));
-
- // Skip CR/LF
- if (code > 64) continue;
-
- // Fail on illegal characters
- if (code < 0) return false;
-
- bitlen += 6;
- }
-
- // If there are any bits left, source was corrupted
- return (bitlen % 8) === 0;
-}
-
-function constructYamlBinary(data) {
- var idx, tailbits,
- input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
- max = input.length,
- map = BASE64_MAP,
- bits = 0,
- result = [];
-
- // Collect by 6*4 bits (3 bytes)
-
- for (idx = 0; idx < max; idx++) {
- if ((idx % 4 === 0) && idx) {
- result.push((bits >> 16) & 0xFF);
- result.push((bits >> 8) & 0xFF);
- result.push(bits & 0xFF);
+ /**
+ * Adds an HTML section heading element
+ *
+ * @param {string} text heading text
+ * @param {number | string} [level=1] (optional) the heading level, default: 1
+ *
+ * @returns {Summary} summary instance
+ */
+ addHeading(text, level) {
+ const tag = `h${level}`;
+ const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
+ ? tag
+ : 'h1';
+ const element = this.wrap(allowedTag, text);
+ return this.addRaw(element).addEOL();
}
-
- bits = (bits << 6) | map.indexOf(input.charAt(idx));
- }
-
- // Dump tail
-
- tailbits = (max % 4) * 6;
-
- if (tailbits === 0) {
- result.push((bits >> 16) & 0xFF);
- result.push((bits >> 8) & 0xFF);
- result.push(bits & 0xFF);
- } else if (tailbits === 18) {
- result.push((bits >> 10) & 0xFF);
- result.push((bits >> 2) & 0xFF);
- } else if (tailbits === 12) {
- result.push((bits >> 4) & 0xFF);
- }
-
- return new Uint8Array(result);
-}
-
-function representYamlBinary(object /*, style*/) {
- var result = '', bits = 0, idx, tail,
- max = object.length,
- map = BASE64_MAP;
-
- // Convert every three bytes to 4 ASCII characters.
-
- for (idx = 0; idx < max; idx++) {
- if ((idx % 3 === 0) && idx) {
- result += map[(bits >> 18) & 0x3F];
- result += map[(bits >> 12) & 0x3F];
- result += map[(bits >> 6) & 0x3F];
- result += map[bits & 0x3F];
+ /**
+ * Adds an HTML thematic break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addSeparator() {
+ const element = this.wrap('hr', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML line break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addBreak() {
+ const element = this.wrap('br', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML blockquote to the summary buffer
+ *
+ * @param {string} text quote text
+ * @param {string} cite (optional) citation url
+ *
+ * @returns {Summary} summary instance
+ */
+ addQuote(text, cite) {
+ const attrs = Object.assign({}, (cite && { cite }));
+ const element = this.wrap('blockquote', text, attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML anchor tag to the summary buffer
+ *
+ * @param {string} text link text/content
+ * @param {string} href hyperlink
+ *
+ * @returns {Summary} summary instance
+ */
+ addLink(text, href) {
+ const element = this.wrap('a', text, { href });
+ return this.addRaw(element).addEOL();
}
-
- bits = (bits << 8) + object[idx];
- }
-
- // Dump tail
-
- tail = max % 3;
-
- if (tail === 0) {
- result += map[(bits >> 18) & 0x3F];
- result += map[(bits >> 12) & 0x3F];
- result += map[(bits >> 6) & 0x3F];
- result += map[bits & 0x3F];
- } else if (tail === 2) {
- result += map[(bits >> 10) & 0x3F];
- result += map[(bits >> 4) & 0x3F];
- result += map[(bits << 2) & 0x3F];
- result += map[64];
- } else if (tail === 1) {
- result += map[(bits >> 2) & 0x3F];
- result += map[(bits << 4) & 0x3F];
- result += map[64];
- result += map[64];
- }
-
- return result;
-}
-
-function isBinary(obj) {
- return Object.prototype.toString.call(obj) === '[object Uint8Array]';
}
+const _summary = new Summary();
+/**
+ * @deprecated use `core.summary`
+ */
+exports.markdownSummary = _summary;
+exports.summary = _summary;
+//# sourceMappingURL=summary.js.map
-var binary = new type('tag:yaml.org,2002:binary', {
- kind: 'scalar',
- resolve: resolveYamlBinary,
- construct: constructYamlBinary,
- predicate: isBinary,
- represent: representYamlBinary
-});
-
-var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
-var _toString$2 = Object.prototype.toString;
-
-function resolveYamlOmap(data) {
- if (data === null) return true;
-
- var objectKeys = [], index, length, pair, pairKey, pairHasKey,
- object = data;
+/***/ }),
- for (index = 0, length = object.length; index < length; index += 1) {
- pair = object[index];
- pairHasKey = false;
+/***/ 302:
+/***/ ((__unused_webpack_module, exports) => {
- if (_toString$2.call(pair) !== '[object Object]') return false;
- for (pairKey in pair) {
- if (_hasOwnProperty$3.call(pair, pairKey)) {
- if (!pairHasKey) pairHasKey = true;
- else return false;
- }
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toCommandProperties = exports.toCommandValue = void 0;
+/**
+ * Sanitizes an input into a string so it can be passed into issueCommand safely
+ * @param input input to sanitize into a string
+ */
+function toCommandValue(input) {
+ if (input === null || input === undefined) {
+ return '';
}
-
- if (!pairHasKey) return false;
-
- if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
- else return false;
- }
-
- return true;
-}
-
-function constructYamlOmap(data) {
- return data !== null ? data : [];
+ else if (typeof input === 'string' || input instanceof String) {
+ return input;
+ }
+ return JSON.stringify(input);
}
-
-var omap = new type('tag:yaml.org,2002:omap', {
- kind: 'sequence',
- resolve: resolveYamlOmap,
- construct: constructYamlOmap
-});
-
-var _toString$1 = Object.prototype.toString;
-
-function resolveYamlPairs(data) {
- if (data === null) return true;
-
- var index, length, pair, keys, result,
- object = data;
-
- result = new Array(object.length);
-
- for (index = 0, length = object.length; index < length; index += 1) {
- pair = object[index];
-
- if (_toString$1.call(pair) !== '[object Object]') return false;
-
- keys = Object.keys(pair);
-
- if (keys.length !== 1) return false;
-
- result[index] = [ keys[0], pair[keys[0]] ];
- }
-
- return true;
+exports.toCommandValue = toCommandValue;
+/**
+ *
+ * @param annotationProperties
+ * @returns The command properties to send with the actual annotation command
+ * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
+ */
+function toCommandProperties(annotationProperties) {
+ if (!Object.keys(annotationProperties).length) {
+ return {};
+ }
+ return {
+ title: annotationProperties.title,
+ file: annotationProperties.file,
+ line: annotationProperties.startLine,
+ endLine: annotationProperties.endLine,
+ col: annotationProperties.startColumn,
+ endColumn: annotationProperties.endColumn
+ };
}
+exports.toCommandProperties = toCommandProperties;
+//# sourceMappingURL=utils.js.map
-function constructYamlPairs(data) {
- if (data === null) return [];
-
- var index, length, pair, keys, result,
- object = data;
-
- result = new Array(object.length);
-
- for (index = 0, length = object.length; index < length; index += 1) {
- pair = object[index];
-
- keys = Object.keys(pair);
+/***/ }),
- result[index] = [ keys[0], pair[keys[0]] ];
- }
+/***/ 5236:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- return result;
-}
-var pairs = new type('tag:yaml.org,2002:pairs', {
- kind: 'sequence',
- resolve: resolveYamlPairs,
- construct: constructYamlPairs
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
});
-
-var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
-
-function resolveYamlSet(data) {
- if (data === null) return true;
-
- var key, object = data;
-
- for (key in object) {
- if (_hasOwnProperty$2.call(object, key)) {
- if (object[key] !== null) return false;
- }
- }
-
- return true;
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getExecOutput = exports.exec = void 0;
+const string_decoder_1 = __nccwpck_require__(3193);
+const tr = __importStar(__nccwpck_require__(6665));
+/**
+ * Exec a command.
+ * Output will be streamed to the live console.
+ * Returns promise with return code
+ *
+ * @param commandLine command to execute (can include additional args). Must be correctly escaped.
+ * @param args optional arguments for tool. Escaping is handled by the lib.
+ * @param options optional exec options. See ExecOptions
+ * @returns Promise exit code
+ */
+function exec(commandLine, args, options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const commandArgs = tr.argStringToArray(commandLine);
+ if (commandArgs.length === 0) {
+ throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
+ }
+ // Path to tool to execute should be first arg
+ const toolPath = commandArgs[0];
+ args = commandArgs.slice(1).concat(args || []);
+ const runner = new tr.ToolRunner(toolPath, args, options);
+ return runner.exec();
+ });
}
-
-function constructYamlSet(data) {
- return data !== null ? data : {};
+exports.exec = exec;
+/**
+ * Exec a command and get the output.
+ * Output will be streamed to the live console.
+ * Returns promise with the exit code and collected stdout and stderr
+ *
+ * @param commandLine command to execute (can include additional args). Must be correctly escaped.
+ * @param args optional arguments for tool. Escaping is handled by the lib.
+ * @param options optional exec options. See ExecOptions
+ * @returns Promise exit code, stdout, and stderr
+ */
+function getExecOutput(commandLine, args, options) {
+ var _a, _b;
+ return __awaiter(this, void 0, void 0, function* () {
+ let stdout = '';
+ let stderr = '';
+ //Using string decoder covers the case where a mult-byte character is split
+ const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
+ const stderrDecoder = new string_decoder_1.StringDecoder('utf8');
+ const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
+ const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
+ const stdErrListener = (data) => {
+ stderr += stderrDecoder.write(data);
+ if (originalStdErrListener) {
+ originalStdErrListener(data);
+ }
+ };
+ const stdOutListener = (data) => {
+ stdout += stdoutDecoder.write(data);
+ if (originalStdoutListener) {
+ originalStdoutListener(data);
+ }
+ };
+ const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });
+ const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));
+ //flush any remaining characters
+ stdout += stdoutDecoder.end();
+ stderr += stderrDecoder.end();
+ return {
+ exitCode,
+ stdout,
+ stderr
+ };
+ });
}
+exports.getExecOutput = getExecOutput;
+//# sourceMappingURL=exec.js.map
-var set = new type('tag:yaml.org,2002:set', {
- kind: 'mapping',
- resolve: resolveYamlSet,
- construct: constructYamlSet
-});
-
-var _default = js_yaml_core.extend({
- implicit: [
- timestamp,
- merge
- ],
- explicit: [
- binary,
- omap,
- pairs,
- set
- ]
-});
+/***/ }),
-/*eslint-disable max-len,no-use-before-define*/
+/***/ 6665:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-
-
-
-
-var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
-
-
-var CONTEXT_FLOW_IN = 1;
-var CONTEXT_FLOW_OUT = 2;
-var CONTEXT_BLOCK_IN = 3;
-var CONTEXT_BLOCK_OUT = 4;
-
-
-var CHOMPING_CLIP = 1;
-var CHOMPING_STRIP = 2;
-var CHOMPING_KEEP = 3;
-
-
-var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
-var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
-var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
-var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
-var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
-
-
-function _class(obj) { return Object.prototype.toString.call(obj); }
-
-function is_EOL(c) {
- return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
-}
-
-function is_WHITE_SPACE(c) {
- return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
-}
-
-function is_WS_OR_EOL(c) {
- return (c === 0x09/* Tab */) ||
- (c === 0x20/* Space */) ||
- (c === 0x0A/* LF */) ||
- (c === 0x0D/* CR */);
-}
-
-function is_FLOW_INDICATOR(c) {
- return c === 0x2C/* , */ ||
- c === 0x5B/* [ */ ||
- c === 0x5D/* ] */ ||
- c === 0x7B/* { */ ||
- c === 0x7D/* } */;
-}
-
-function fromHexCode(c) {
- var lc;
-
- if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
- return c - 0x30;
- }
-
- /*eslint-disable no-bitwise*/
- lc = c | 0x20;
-
- if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
- return lc - 0x61 + 10;
- }
-
- return -1;
-}
-
-function escapedHexLen(c) {
- if (c === 0x78/* x */) { return 2; }
- if (c === 0x75/* u */) { return 4; }
- if (c === 0x55/* U */) { return 8; }
- return 0;
-}
-
-function fromDecimalCode(c) {
- if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
- return c - 0x30;
- }
-
- return -1;
-}
-
-function simpleEscapeSequence(c) {
- /* eslint-disable indent */
- return (c === 0x30/* 0 */) ? '\x00' :
- (c === 0x61/* a */) ? '\x07' :
- (c === 0x62/* b */) ? '\x08' :
- (c === 0x74/* t */) ? '\x09' :
- (c === 0x09/* Tab */) ? '\x09' :
- (c === 0x6E/* n */) ? '\x0A' :
- (c === 0x76/* v */) ? '\x0B' :
- (c === 0x66/* f */) ? '\x0C' :
- (c === 0x72/* r */) ? '\x0D' :
- (c === 0x65/* e */) ? '\x1B' :
- (c === 0x20/* Space */) ? ' ' :
- (c === 0x22/* " */) ? '\x22' :
- (c === 0x2F/* / */) ? '/' :
- (c === 0x5C/* \ */) ? '\x5C' :
- (c === 0x4E/* N */) ? '\x85' :
- (c === 0x5F/* _ */) ? '\xA0' :
- (c === 0x4C/* L */) ? '\u2028' :
- (c === 0x50/* P */) ? '\u2029' : '';
-}
-
-function charFromCodepoint(c) {
- if (c <= 0xFFFF) {
- return String.fromCharCode(c);
- }
- // Encode UTF-16 surrogate pair
- // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
- return String.fromCharCode(
- ((c - 0x010000) >> 10) + 0xD800,
- ((c - 0x010000) & 0x03FF) + 0xDC00
- );
-}
-
-var simpleEscapeCheck = new Array(256); // integer, for fast access
-var simpleEscapeMap = new Array(256);
-for (var i = 0; i < 256; i++) {
- simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
- simpleEscapeMap[i] = simpleEscapeSequence(i);
-}
-
-
-function State$1(input, options) {
- this.input = input;
-
- this.filename = options['filename'] || null;
- this.schema = options['schema'] || _default;
- this.onWarning = options['onWarning'] || null;
- // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
- // if such documents have no explicit %YAML directive
- this.legacy = options['legacy'] || false;
-
- this.json = options['json'] || false;
- this.listener = options['listener'] || null;
-
- this.implicitTypes = this.schema.compiledImplicit;
- this.typeMap = this.schema.compiledTypeMap;
-
- this.length = input.length;
- this.position = 0;
- this.line = 0;
- this.lineStart = 0;
- this.lineIndent = 0;
-
- // position of first leading tab in the current line,
- // used to make sure there are no tabs in the indentation
- this.firstTabInLine = -1;
-
- this.documents = [];
-
- /*
- this.version;
- this.checkLineBreaks;
- this.tagMap;
- this.anchorMap;
- this.tag;
- this.anchor;
- this.kind;
- this.result;*/
-
-}
-
-
-function generateError(state, message) {
- var mark = {
- name: state.filename,
- buffer: state.input.slice(0, -1), // omit trailing \0
- position: state.position,
- line: state.line,
- column: state.position - state.lineStart
- };
-
- mark.snippet = snippet(mark);
-
- return new exception(message, mark);
-}
-
-function throwError(state, message) {
- throw generateError(state, message);
-}
-
-function throwWarning(state, message) {
- if (state.onWarning) {
- state.onWarning.call(null, generateError(state, message));
- }
-}
-
-
-var directiveHandlers = {
-
- YAML: function handleYamlDirective(state, name, args) {
-
- var match, major, minor;
-
- if (state.version !== null) {
- throwError(state, 'duplication of %YAML directive');
- }
-
- if (args.length !== 1) {
- throwError(state, 'YAML directive accepts exactly one argument');
- }
-
- match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
-
- if (match === null) {
- throwError(state, 'ill-formed argument of the YAML directive');
- }
-
- major = parseInt(match[1], 10);
- minor = parseInt(match[2], 10);
-
- if (major !== 1) {
- throwError(state, 'unacceptable YAML version of the document');
- }
-
- state.version = args[0];
- state.checkLineBreaks = (minor < 2);
-
- if (minor !== 1 && minor !== 2) {
- throwWarning(state, 'unsupported YAML version of the document');
- }
- },
-
- TAG: function handleTagDirective(state, name, args) {
-
- var handle, prefix;
-
- if (args.length !== 2) {
- throwError(state, 'TAG directive accepts exactly two arguments');
- }
-
- handle = args[0];
- prefix = args[1];
-
- if (!PATTERN_TAG_HANDLE.test(handle)) {
- throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
- }
-
- if (_hasOwnProperty$1.call(state.tagMap, handle)) {
- throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
- }
-
- if (!PATTERN_TAG_URI.test(prefix)) {
- throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
- }
-
- try {
- prefix = decodeURIComponent(prefix);
- } catch (err) {
- throwError(state, 'tag prefix is malformed: ' + prefix);
- }
-
- state.tagMap[handle] = prefix;
- }
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
};
-
-
-function captureSegment(state, start, end, checkJson) {
- var _position, _length, _character, _result;
-
- if (start < end) {
- _result = state.input.slice(start, end);
-
- if (checkJson) {
- for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
- _character = _result.charCodeAt(_position);
- if (!(_character === 0x09 ||
- (0x20 <= _character && _character <= 0x10FFFF))) {
- throwError(state, 'expected valid JSON character');
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.argStringToArray = exports.ToolRunner = void 0;
+const os = __importStar(__nccwpck_require__(857));
+const events = __importStar(__nccwpck_require__(4434));
+const child = __importStar(__nccwpck_require__(5317));
+const path = __importStar(__nccwpck_require__(6928));
+const io = __importStar(__nccwpck_require__(4994));
+const ioUtil = __importStar(__nccwpck_require__(5207));
+const timers_1 = __nccwpck_require__(3557);
+/* eslint-disable @typescript-eslint/unbound-method */
+const IS_WINDOWS = process.platform === 'win32';
+/*
+ * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
+ */
+class ToolRunner extends events.EventEmitter {
+ constructor(toolPath, args, options) {
+ super();
+ if (!toolPath) {
+ throw new Error("Parameter 'toolPath' cannot be null or empty.");
}
- }
- } else if (PATTERN_NON_PRINTABLE.test(_result)) {
- throwError(state, 'the stream contains non-printable characters');
- }
-
- state.result += _result;
- }
-}
-
-function mergeMappings(state, destination, source, overridableKeys) {
- var sourceKeys, key, index, quantity;
-
- if (!common.isObject(source)) {
- throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
- }
-
- sourceKeys = Object.keys(source);
-
- for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
- key = sourceKeys[index];
-
- if (!_hasOwnProperty$1.call(destination, key)) {
- destination[key] = source[key];
- overridableKeys[key] = true;
- }
- }
-}
-
-function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
- startLine, startLineStart, startPos) {
-
- var index, quantity;
-
- // The output is a plain object here, so keys can only be strings.
- // We need to convert keyNode to a string, but doing so can hang the process
- // (deeply nested arrays that explode exponentially using aliases).
- if (Array.isArray(keyNode)) {
- keyNode = Array.prototype.slice.call(keyNode);
-
- for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
- if (Array.isArray(keyNode[index])) {
- throwError(state, 'nested arrays are not supported inside keys');
- }
-
- if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
- keyNode[index] = '[object Object]';
- }
- }
- }
-
- // Avoid code execution in load() via toString property
- // (still use its own toString for arrays, timestamps,
- // and whatever user schema extensions happen to have @@toStringTag)
- if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
- keyNode = '[object Object]';
- }
-
-
- keyNode = String(keyNode);
-
- if (_result === null) {
- _result = {};
- }
-
- if (keyTag === 'tag:yaml.org,2002:merge') {
- if (Array.isArray(valueNode)) {
- for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
- mergeMappings(state, _result, valueNode[index], overridableKeys);
- }
- } else {
- mergeMappings(state, _result, valueNode, overridableKeys);
- }
- } else {
- if (!state.json &&
- !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
- _hasOwnProperty$1.call(_result, keyNode)) {
- state.line = startLine || state.line;
- state.lineStart = startLineStart || state.lineStart;
- state.position = startPos || state.position;
- throwError(state, 'duplicated mapping key');
- }
-
- // used for this specific key only because Object.defineProperty is slow
- if (keyNode === '__proto__') {
- Object.defineProperty(_result, keyNode, {
- configurable: true,
- enumerable: true,
- writable: true,
- value: valueNode
- });
- } else {
- _result[keyNode] = valueNode;
- }
- delete overridableKeys[keyNode];
- }
-
- return _result;
-}
-
-function readLineBreak(state) {
- var ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch === 0x0A/* LF */) {
- state.position++;
- } else if (ch === 0x0D/* CR */) {
- state.position++;
- if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
- state.position++;
- }
- } else {
- throwError(state, 'a line break is expected');
- }
-
- state.line += 1;
- state.lineStart = state.position;
- state.firstTabInLine = -1;
-}
-
-function skipSeparationSpace(state, allowComments, checkIndent) {
- var lineBreaks = 0,
- ch = state.input.charCodeAt(state.position);
-
- while (ch !== 0) {
- while (is_WHITE_SPACE(ch)) {
- if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
- state.firstTabInLine = state.position;
- }
- ch = state.input.charCodeAt(++state.position);
- }
-
- if (allowComments && ch === 0x23/* # */) {
- do {
- ch = state.input.charCodeAt(++state.position);
- } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
- }
-
- if (is_EOL(ch)) {
- readLineBreak(state);
-
- ch = state.input.charCodeAt(state.position);
- lineBreaks++;
- state.lineIndent = 0;
-
- while (ch === 0x20/* Space */) {
- state.lineIndent++;
- ch = state.input.charCodeAt(++state.position);
- }
- } else {
- break;
- }
- }
-
- if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
- throwWarning(state, 'deficient indentation');
- }
-
- return lineBreaks;
-}
-
-function testDocumentSeparator(state) {
- var _position = state.position,
- ch;
-
- ch = state.input.charCodeAt(_position);
-
- // Condition state.position === state.lineStart is tested
- // in parent on each call, for efficiency. No needs to test here again.
- if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
- ch === state.input.charCodeAt(_position + 1) &&
- ch === state.input.charCodeAt(_position + 2)) {
-
- _position += 3;
-
- ch = state.input.charCodeAt(_position);
-
- if (ch === 0 || is_WS_OR_EOL(ch)) {
- return true;
- }
- }
-
- return false;
-}
-
-function writeFoldedLines(state, count) {
- if (count === 1) {
- state.result += ' ';
- } else if (count > 1) {
- state.result += common.repeat('\n', count - 1);
- }
-}
-
-
-function readPlainScalar(state, nodeIndent, withinFlowCollection) {
- var preceding,
- following,
- captureStart,
- captureEnd,
- hasPendingContent,
- _line,
- _lineStart,
- _lineIndent,
- _kind = state.kind,
- _result = state.result,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (is_WS_OR_EOL(ch) ||
- is_FLOW_INDICATOR(ch) ||
- ch === 0x23/* # */ ||
- ch === 0x26/* & */ ||
- ch === 0x2A/* * */ ||
- ch === 0x21/* ! */ ||
- ch === 0x7C/* | */ ||
- ch === 0x3E/* > */ ||
- ch === 0x27/* ' */ ||
- ch === 0x22/* " */ ||
- ch === 0x25/* % */ ||
- ch === 0x40/* @ */ ||
- ch === 0x60/* ` */) {
- return false;
- }
-
- if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
- following = state.input.charCodeAt(state.position + 1);
-
- if (is_WS_OR_EOL(following) ||
- withinFlowCollection && is_FLOW_INDICATOR(following)) {
- return false;
- }
- }
-
- state.kind = 'scalar';
- state.result = '';
- captureStart = captureEnd = state.position;
- hasPendingContent = false;
-
- while (ch !== 0) {
- if (ch === 0x3A/* : */) {
- following = state.input.charCodeAt(state.position + 1);
-
- if (is_WS_OR_EOL(following) ||
- withinFlowCollection && is_FLOW_INDICATOR(following)) {
- break;
- }
-
- } else if (ch === 0x23/* # */) {
- preceding = state.input.charCodeAt(state.position - 1);
-
- if (is_WS_OR_EOL(preceding)) {
- break;
- }
-
- } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
- withinFlowCollection && is_FLOW_INDICATOR(ch)) {
- break;
-
- } else if (is_EOL(ch)) {
- _line = state.line;
- _lineStart = state.lineStart;
- _lineIndent = state.lineIndent;
- skipSeparationSpace(state, false, -1);
-
- if (state.lineIndent >= nodeIndent) {
- hasPendingContent = true;
- ch = state.input.charCodeAt(state.position);
- continue;
- } else {
- state.position = captureEnd;
- state.line = _line;
- state.lineStart = _lineStart;
- state.lineIndent = _lineIndent;
- break;
- }
- }
-
- if (hasPendingContent) {
- captureSegment(state, captureStart, captureEnd, false);
- writeFoldedLines(state, state.line - _line);
- captureStart = captureEnd = state.position;
- hasPendingContent = false;
- }
-
- if (!is_WHITE_SPACE(ch)) {
- captureEnd = state.position + 1;
- }
-
- ch = state.input.charCodeAt(++state.position);
- }
-
- captureSegment(state, captureStart, captureEnd, false);
-
- if (state.result) {
- return true;
- }
-
- state.kind = _kind;
- state.result = _result;
- return false;
-}
-
-function readSingleQuotedScalar(state, nodeIndent) {
- var ch,
- captureStart, captureEnd;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch !== 0x27/* ' */) {
- return false;
- }
-
- state.kind = 'scalar';
- state.result = '';
- state.position++;
- captureStart = captureEnd = state.position;
-
- while ((ch = state.input.charCodeAt(state.position)) !== 0) {
- if (ch === 0x27/* ' */) {
- captureSegment(state, captureStart, state.position, true);
- ch = state.input.charCodeAt(++state.position);
-
- if (ch === 0x27/* ' */) {
- captureStart = state.position;
- state.position++;
- captureEnd = state.position;
- } else {
- return true;
- }
-
- } else if (is_EOL(ch)) {
- captureSegment(state, captureStart, captureEnd, true);
- writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
- captureStart = captureEnd = state.position;
-
- } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
- throwError(state, 'unexpected end of the document within a single quoted scalar');
-
- } else {
- state.position++;
- captureEnd = state.position;
+ this.toolPath = toolPath;
+ this.args = args || [];
+ this.options = options || {};
}
- }
-
- throwError(state, 'unexpected end of the stream within a single quoted scalar');
-}
-
-function readDoubleQuotedScalar(state, nodeIndent) {
- var captureStart,
- captureEnd,
- hexLength,
- hexResult,
- tmp,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch !== 0x22/* " */) {
- return false;
- }
-
- state.kind = 'scalar';
- state.result = '';
- state.position++;
- captureStart = captureEnd = state.position;
-
- while ((ch = state.input.charCodeAt(state.position)) !== 0) {
- if (ch === 0x22/* " */) {
- captureSegment(state, captureStart, state.position, true);
- state.position++;
- return true;
-
- } else if (ch === 0x5C/* \ */) {
- captureSegment(state, captureStart, state.position, true);
- ch = state.input.charCodeAt(++state.position);
-
- if (is_EOL(ch)) {
- skipSeparationSpace(state, false, nodeIndent);
-
- // TODO: rework to inline fn with no type cast?
- } else if (ch < 256 && simpleEscapeCheck[ch]) {
- state.result += simpleEscapeMap[ch];
- state.position++;
-
- } else if ((tmp = escapedHexLen(ch)) > 0) {
- hexLength = tmp;
- hexResult = 0;
-
- for (; hexLength > 0; hexLength--) {
- ch = state.input.charCodeAt(++state.position);
-
- if ((tmp = fromHexCode(ch)) >= 0) {
- hexResult = (hexResult << 4) + tmp;
-
- } else {
- throwError(state, 'expected hexadecimal character');
- }
+ _debug(message) {
+ if (this.options.listeners && this.options.listeners.debug) {
+ this.options.listeners.debug(message);
}
-
- state.result += charFromCodepoint(hexResult);
-
- state.position++;
-
- } else {
- throwError(state, 'unknown escape sequence');
- }
-
- captureStart = captureEnd = state.position;
-
- } else if (is_EOL(ch)) {
- captureSegment(state, captureStart, captureEnd, true);
- writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
- captureStart = captureEnd = state.position;
-
- } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
- throwError(state, 'unexpected end of the document within a double quoted scalar');
-
- } else {
- state.position++;
- captureEnd = state.position;
- }
- }
-
- throwError(state, 'unexpected end of the stream within a double quoted scalar');
-}
-
-function readFlowCollection(state, nodeIndent) {
- var readNext = true,
- _line,
- _lineStart,
- _pos,
- _tag = state.tag,
- _result,
- _anchor = state.anchor,
- following,
- terminator,
- isPair,
- isExplicitPair,
- isMapping,
- overridableKeys = Object.create(null),
- keyNode,
- keyTag,
- valueNode,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch === 0x5B/* [ */) {
- terminator = 0x5D;/* ] */
- isMapping = false;
- _result = [];
- } else if (ch === 0x7B/* { */) {
- terminator = 0x7D;/* } */
- isMapping = true;
- _result = {};
- } else {
- return false;
- }
-
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = _result;
- }
-
- ch = state.input.charCodeAt(++state.position);
-
- while (ch !== 0) {
- skipSeparationSpace(state, true, nodeIndent);
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch === terminator) {
- state.position++;
- state.tag = _tag;
- state.anchor = _anchor;
- state.kind = isMapping ? 'mapping' : 'sequence';
- state.result = _result;
- return true;
- } else if (!readNext) {
- throwError(state, 'missed comma between flow collection entries');
- } else if (ch === 0x2C/* , */) {
- // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
- throwError(state, "expected the node content, but found ','");
- }
-
- keyTag = keyNode = valueNode = null;
- isPair = isExplicitPair = false;
-
- if (ch === 0x3F/* ? */) {
- following = state.input.charCodeAt(state.position + 1);
-
- if (is_WS_OR_EOL(following)) {
- isPair = isExplicitPair = true;
- state.position++;
- skipSeparationSpace(state, true, nodeIndent);
- }
- }
-
- _line = state.line; // Save the current line.
- _lineStart = state.lineStart;
- _pos = state.position;
- composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
- keyTag = state.tag;
- keyNode = state.result;
- skipSeparationSpace(state, true, nodeIndent);
-
- ch = state.input.charCodeAt(state.position);
-
- if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
- isPair = true;
- ch = state.input.charCodeAt(++state.position);
- skipSeparationSpace(state, true, nodeIndent);
- composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
- valueNode = state.result;
}
-
- if (isMapping) {
- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
- } else if (isPair) {
- _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
- } else {
- _result.push(keyNode);
- }
-
- skipSeparationSpace(state, true, nodeIndent);
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch === 0x2C/* , */) {
- readNext = true;
- ch = state.input.charCodeAt(++state.position);
- } else {
- readNext = false;
- }
- }
-
- throwError(state, 'unexpected end of the stream within a flow collection');
-}
-
-function readBlockScalar(state, nodeIndent) {
- var captureStart,
- folding,
- chomping = CHOMPING_CLIP,
- didReadContent = false,
- detectedIndent = false,
- textIndent = nodeIndent,
- emptyLines = 0,
- atMoreIndented = false,
- tmp,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch === 0x7C/* | */) {
- folding = false;
- } else if (ch === 0x3E/* > */) {
- folding = true;
- } else {
- return false;
- }
-
- state.kind = 'scalar';
- state.result = '';
-
- while (ch !== 0) {
- ch = state.input.charCodeAt(++state.position);
-
- if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
- if (CHOMPING_CLIP === chomping) {
- chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
- } else {
- throwError(state, 'repeat of a chomping mode identifier');
- }
-
- } else if ((tmp = fromDecimalCode(ch)) >= 0) {
- if (tmp === 0) {
- throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
- } else if (!detectedIndent) {
- textIndent = nodeIndent + tmp - 1;
- detectedIndent = true;
- } else {
- throwError(state, 'repeat of an indentation width identifier');
- }
-
- } else {
- break;
- }
- }
-
- if (is_WHITE_SPACE(ch)) {
- do { ch = state.input.charCodeAt(++state.position); }
- while (is_WHITE_SPACE(ch));
-
- if (ch === 0x23/* # */) {
- do { ch = state.input.charCodeAt(++state.position); }
- while (!is_EOL(ch) && (ch !== 0));
- }
- }
-
- while (ch !== 0) {
- readLineBreak(state);
- state.lineIndent = 0;
-
- ch = state.input.charCodeAt(state.position);
-
- while ((!detectedIndent || state.lineIndent < textIndent) &&
- (ch === 0x20/* Space */)) {
- state.lineIndent++;
- ch = state.input.charCodeAt(++state.position);
- }
-
- if (!detectedIndent && state.lineIndent > textIndent) {
- textIndent = state.lineIndent;
- }
-
- if (is_EOL(ch)) {
- emptyLines++;
- continue;
- }
-
- // End of the scalar.
- if (state.lineIndent < textIndent) {
-
- // Perform the chomping.
- if (chomping === CHOMPING_KEEP) {
- state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
- } else if (chomping === CHOMPING_CLIP) {
- if (didReadContent) { // i.e. only if the scalar is not empty.
- state.result += '\n';
+ _getCommandString(options, noPrefix) {
+ const toolPath = this._getSpawnFileName();
+ const args = this._getSpawnArgs(options);
+ let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
+ if (IS_WINDOWS) {
+ // Windows + cmd file
+ if (this._isCmdFile()) {
+ cmd += toolPath;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
+ }
+ // Windows + verbatim
+ else if (options.windowsVerbatimArguments) {
+ cmd += `"${toolPath}"`;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
+ }
+ // Windows (regular)
+ else {
+ cmd += this._windowsQuoteCmdArg(toolPath);
+ for (const a of args) {
+ cmd += ` ${this._windowsQuoteCmdArg(a)}`;
+ }
+ }
}
- }
-
- // Break this `while` cycle and go to the funciton's epilogue.
- break;
- }
-
- // Folded style: use fancy rules to handle line breaks.
- if (folding) {
-
- // Lines starting with white space characters (more-indented lines) are not folded.
- if (is_WHITE_SPACE(ch)) {
- atMoreIndented = true;
- // except for the first content line (cf. Example 8.1)
- state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
-
- // End of more-indented block.
- } else if (atMoreIndented) {
- atMoreIndented = false;
- state.result += common.repeat('\n', emptyLines + 1);
-
- // Just one line break - perceive as the same line.
- } else if (emptyLines === 0) {
- if (didReadContent) { // i.e. only if we have already read some scalar content.
- state.result += ' ';
+ else {
+ // OSX/Linux - this can likely be improved with some form of quoting.
+ // creating processes on Unix is fundamentally different than Windows.
+ // on Unix, execvp() takes an arg array.
+ cmd += toolPath;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
}
-
- // Several line breaks - perceive as different lines.
- } else {
- state.result += common.repeat('\n', emptyLines);
- }
-
- // Literal style: just add exact number of line breaks between content lines.
- } else {
- // Keep all line breaks except the header line break.
- state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
- }
-
- didReadContent = true;
- detectedIndent = true;
- emptyLines = 0;
- captureStart = state.position;
-
- while (!is_EOL(ch) && (ch !== 0)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- captureSegment(state, captureStart, state.position, false);
- }
-
- return true;
-}
-
-function readBlockSequence(state, nodeIndent) {
- var _line,
- _tag = state.tag,
- _anchor = state.anchor,
- _result = [],
- following,
- detected = false,
- ch;
-
- // there is a leading tab before this token, so it can't be a block sequence/mapping;
- // it can still be flow sequence/mapping or a scalar
- if (state.firstTabInLine !== -1) return false;
-
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = _result;
- }
-
- ch = state.input.charCodeAt(state.position);
-
- while (ch !== 0) {
- if (state.firstTabInLine !== -1) {
- state.position = state.firstTabInLine;
- throwError(state, 'tab characters must not be used in indentation');
+ return cmd;
}
-
- if (ch !== 0x2D/* - */) {
- break;
+ _processLineBuffer(data, strBuffer, onLine) {
+ try {
+ let s = strBuffer + data.toString();
+ let n = s.indexOf(os.EOL);
+ while (n > -1) {
+ const line = s.substring(0, n);
+ onLine(line);
+ // the rest of the string ...
+ s = s.substring(n + os.EOL.length);
+ n = s.indexOf(os.EOL);
+ }
+ return s;
+ }
+ catch (err) {
+ // streaming lines to console is best effort. Don't fail a build.
+ this._debug(`error processing line. Failed with error ${err}`);
+ return '';
+ }
}
-
- following = state.input.charCodeAt(state.position + 1);
-
- if (!is_WS_OR_EOL(following)) {
- break;
+ _getSpawnFileName() {
+ if (IS_WINDOWS) {
+ if (this._isCmdFile()) {
+ return process.env['COMSPEC'] || 'cmd.exe';
+ }
+ }
+ return this.toolPath;
}
-
- detected = true;
- state.position++;
-
- if (skipSeparationSpace(state, true, -1)) {
- if (state.lineIndent <= nodeIndent) {
- _result.push(null);
- ch = state.input.charCodeAt(state.position);
- continue;
- }
+ _getSpawnArgs(options) {
+ if (IS_WINDOWS) {
+ if (this._isCmdFile()) {
+ let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
+ for (const a of this.args) {
+ argline += ' ';
+ argline += options.windowsVerbatimArguments
+ ? a
+ : this._windowsQuoteCmdArg(a);
+ }
+ argline += '"';
+ return [argline];
+ }
+ }
+ return this.args;
}
-
- _line = state.line;
- composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
- _result.push(state.result);
- skipSeparationSpace(state, true, -1);
-
- ch = state.input.charCodeAt(state.position);
-
- if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
- throwError(state, 'bad indentation of a sequence entry');
- } else if (state.lineIndent < nodeIndent) {
- break;
+ _endsWith(str, end) {
+ return str.endsWith(end);
}
- }
-
- if (detected) {
- state.tag = _tag;
- state.anchor = _anchor;
- state.kind = 'sequence';
- state.result = _result;
- return true;
- }
- return false;
-}
-
-function readBlockMapping(state, nodeIndent, flowIndent) {
- var following,
- allowCompact,
- _line,
- _keyLine,
- _keyLineStart,
- _keyPos,
- _tag = state.tag,
- _anchor = state.anchor,
- _result = {},
- overridableKeys = Object.create(null),
- keyTag = null,
- keyNode = null,
- valueNode = null,
- atExplicitKey = false,
- detected = false,
- ch;
-
- // there is a leading tab before this token, so it can't be a block sequence/mapping;
- // it can still be flow sequence/mapping or a scalar
- if (state.firstTabInLine !== -1) return false;
-
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = _result;
- }
-
- ch = state.input.charCodeAt(state.position);
-
- while (ch !== 0) {
- if (!atExplicitKey && state.firstTabInLine !== -1) {
- state.position = state.firstTabInLine;
- throwError(state, 'tab characters must not be used in indentation');
+ _isCmdFile() {
+ const upperToolPath = this.toolPath.toUpperCase();
+ return (this._endsWith(upperToolPath, '.CMD') ||
+ this._endsWith(upperToolPath, '.BAT'));
}
-
- following = state.input.charCodeAt(state.position + 1);
- _line = state.line; // Save the current line.
-
- //
- // Explicit notation case. There are two separate blocks:
- // first for the key (denoted by "?") and second for the value (denoted by ":")
- //
- if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
-
- if (ch === 0x3F/* ? */) {
- if (atExplicitKey) {
- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
- keyTag = keyNode = valueNode = null;
- }
-
- detected = true;
- atExplicitKey = true;
- allowCompact = true;
-
- } else if (atExplicitKey) {
- // i.e. 0x3A/* : */ === character after the explicit key.
- atExplicitKey = false;
- allowCompact = true;
-
- } else {
- throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
- }
-
- state.position += 1;
- ch = following;
-
- //
- // Implicit notation case. Flow-style node as the key first, then ":", and the value.
- //
- } else {
- _keyLine = state.line;
- _keyLineStart = state.lineStart;
- _keyPos = state.position;
-
- if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
- // Neither implicit nor explicit notation.
- // Reading is done. Go to the epilogue.
- break;
- }
-
- if (state.line === _line) {
- ch = state.input.charCodeAt(state.position);
-
- while (is_WHITE_SPACE(ch)) {
- ch = state.input.charCodeAt(++state.position);
+ _windowsQuoteCmdArg(arg) {
+ // for .exe, apply the normal quoting rules that libuv applies
+ if (!this._isCmdFile()) {
+ return this._uvQuoteCmdArg(arg);
}
-
- if (ch === 0x3A/* : */) {
- ch = state.input.charCodeAt(++state.position);
-
- if (!is_WS_OR_EOL(ch)) {
- throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
- }
-
- if (atExplicitKey) {
- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
- keyTag = keyNode = valueNode = null;
- }
-
- detected = true;
- atExplicitKey = false;
- allowCompact = false;
- keyTag = state.tag;
- keyNode = state.result;
-
- } else if (detected) {
- throwError(state, 'can not read an implicit mapping pair; a colon is missed');
-
- } else {
- state.tag = _tag;
- state.anchor = _anchor;
- return true; // Keep the result of `composeNode`.
+ // otherwise apply quoting rules specific to the cmd.exe command line parser.
+ // the libuv rules are generic and are not designed specifically for cmd.exe
+ // command line parser.
+ //
+ // for a detailed description of the cmd.exe command line parser, refer to
+ // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
+ // need quotes for empty arg
+ if (!arg) {
+ return '""';
}
-
- } else if (detected) {
- throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
-
- } else {
- state.tag = _tag;
- state.anchor = _anchor;
- return true; // Keep the result of `composeNode`.
- }
- }
-
- //
- // Common reading code for both explicit and implicit notations.
- //
- if (state.line === _line || state.lineIndent > nodeIndent) {
- if (atExplicitKey) {
- _keyLine = state.line;
- _keyLineStart = state.lineStart;
- _keyPos = state.position;
- }
-
- if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
- if (atExplicitKey) {
- keyNode = state.result;
- } else {
- valueNode = state.result;
+ // determine whether the arg needs to be quoted
+ const cmdSpecialChars = [
+ ' ',
+ '\t',
+ '&',
+ '(',
+ ')',
+ '[',
+ ']',
+ '{',
+ '}',
+ '^',
+ '=',
+ ';',
+ '!',
+ "'",
+ '+',
+ ',',
+ '`',
+ '~',
+ '|',
+ '<',
+ '>',
+ '"'
+ ];
+ let needsQuotes = false;
+ for (const char of arg) {
+ if (cmdSpecialChars.some(x => x === char)) {
+ needsQuotes = true;
+ break;
+ }
}
- }
-
- if (!atExplicitKey) {
- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
- keyTag = keyNode = valueNode = null;
- }
-
- skipSeparationSpace(state, true, -1);
- ch = state.input.charCodeAt(state.position);
- }
-
- if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
- throwError(state, 'bad indentation of a mapping entry');
- } else if (state.lineIndent < nodeIndent) {
- break;
- }
- }
-
- //
- // Epilogue.
- //
-
- // Special case: last mapping's node contains only the key in explicit notation.
- if (atExplicitKey) {
- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
- }
-
- // Expose the resulting mapping.
- if (detected) {
- state.tag = _tag;
- state.anchor = _anchor;
- state.kind = 'mapping';
- state.result = _result;
- }
-
- return detected;
-}
-
-function readTagProperty(state) {
- var _position,
- isVerbatim = false,
- isNamed = false,
- tagHandle,
- tagName,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch !== 0x21/* ! */) return false;
-
- if (state.tag !== null) {
- throwError(state, 'duplication of a tag property');
- }
-
- ch = state.input.charCodeAt(++state.position);
-
- if (ch === 0x3C/* < */) {
- isVerbatim = true;
- ch = state.input.charCodeAt(++state.position);
-
- } else if (ch === 0x21/* ! */) {
- isNamed = true;
- tagHandle = '!!';
- ch = state.input.charCodeAt(++state.position);
-
- } else {
- tagHandle = '!';
- }
-
- _position = state.position;
-
- if (isVerbatim) {
- do { ch = state.input.charCodeAt(++state.position); }
- while (ch !== 0 && ch !== 0x3E/* > */);
-
- if (state.position < state.length) {
- tagName = state.input.slice(_position, state.position);
- ch = state.input.charCodeAt(++state.position);
- } else {
- throwError(state, 'unexpected end of the stream within a verbatim tag');
- }
- } else {
- while (ch !== 0 && !is_WS_OR_EOL(ch)) {
-
- if (ch === 0x21/* ! */) {
- if (!isNamed) {
- tagHandle = state.input.slice(_position - 1, state.position + 1);
-
- if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
- throwError(state, 'named tag handle cannot contain such characters');
- }
-
- isNamed = true;
- _position = state.position + 1;
- } else {
- throwError(state, 'tag suffix cannot contain exclamation marks');
+ // short-circuit if quotes not needed
+ if (!needsQuotes) {
+ return arg;
}
- }
-
- ch = state.input.charCodeAt(++state.position);
- }
-
- tagName = state.input.slice(_position, state.position);
-
- if (PATTERN_FLOW_INDICATORS.test(tagName)) {
- throwError(state, 'tag suffix cannot contain flow indicator characters');
- }
- }
-
- if (tagName && !PATTERN_TAG_URI.test(tagName)) {
- throwError(state, 'tag name cannot contain such characters: ' + tagName);
- }
-
- try {
- tagName = decodeURIComponent(tagName);
- } catch (err) {
- throwError(state, 'tag name is malformed: ' + tagName);
- }
-
- if (isVerbatim) {
- state.tag = tagName;
-
- } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
- state.tag = state.tagMap[tagHandle] + tagName;
-
- } else if (tagHandle === '!') {
- state.tag = '!' + tagName;
-
- } else if (tagHandle === '!!') {
- state.tag = 'tag:yaml.org,2002:' + tagName;
-
- } else {
- throwError(state, 'undeclared tag handle "' + tagHandle + '"');
- }
-
- return true;
-}
-
-function readAnchorProperty(state) {
- var _position,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch !== 0x26/* & */) return false;
-
- if (state.anchor !== null) {
- throwError(state, 'duplication of an anchor property');
- }
-
- ch = state.input.charCodeAt(++state.position);
- _position = state.position;
-
- while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- if (state.position === _position) {
- throwError(state, 'name of an anchor node must contain at least one character');
- }
-
- state.anchor = state.input.slice(_position, state.position);
- return true;
-}
-
-function readAlias(state) {
- var _position, alias,
- ch;
-
- ch = state.input.charCodeAt(state.position);
-
- if (ch !== 0x2A/* * */) return false;
-
- ch = state.input.charCodeAt(++state.position);
- _position = state.position;
-
- while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- if (state.position === _position) {
- throwError(state, 'name of an alias node must contain at least one character');
- }
-
- alias = state.input.slice(_position, state.position);
-
- if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
- throwError(state, 'unidentified alias "' + alias + '"');
- }
-
- state.result = state.anchorMap[alias];
- skipSeparationSpace(state, true, -1);
- return true;
-}
-
-function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
- var allowBlockStyles,
- allowBlockScalars,
- allowBlockCollections,
- indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) {
- indentStatus = 1;
- } else if (state.lineIndent === parentIndent) {
- indentStatus = 0;
- } else if (state.lineIndent < parentIndent) {
- indentStatus = -1;
- }
- }
- }
-
- if (indentStatus === 1) {
- while (readTagProperty(state) || readAnchorProperty(state)) {
- if (skipSeparationSpace(state, true, -1)) {
- atNewLine = true;
- allowBlockCollections = allowBlockStyles;
-
- if (state.lineIndent > parentIndent) {
- indentStatus = 1;
- } else if (state.lineIndent === parentIndent) {
- indentStatus = 0;
- } else if (state.lineIndent < parentIndent) {
- indentStatus = -1;
+ // the following quoting rules are very similar to the rules that by libuv applies.
+ //
+ // 1) wrap the string in quotes
+ //
+ // 2) double-up quotes - i.e. " => ""
+ //
+ // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
+ // doesn't work well with a cmd.exe command line.
+ //
+ // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
+ // for example, the command line:
+ // foo.exe "myarg:""my val"""
+ // is parsed by a .NET console app into an arg array:
+ // [ "myarg:\"my val\"" ]
+ // which is the same end result when applying libuv quoting rules. although the actual
+ // command line from libuv quoting rules would look like:
+ // foo.exe "myarg:\"my val\""
+ //
+ // 3) double-up slashes that precede a quote,
+ // e.g. hello \world => "hello \world"
+ // hello\"world => "hello\\""world"
+ // hello\\"world => "hello\\\\""world"
+ // hello world\ => "hello world\\"
+ //
+ // technically this is not required for a cmd.exe command line, or the batch argument parser.
+ // the reasons for including this as a .cmd quoting rule are:
+ //
+ // a) this is optimized for the scenario where the argument is passed from the .cmd file to an
+ // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
+ //
+ // b) it's what we've been doing previously (by deferring to node default behavior) and we
+ // haven't heard any complaints about that aspect.
+ //
+ // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
+ // escaped when used on the command line directly - even though within a .cmd file % can be escaped
+ // by using %%.
+ //
+ // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
+ // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
+ //
+ // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
+ // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
+ // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
+ // to an external program.
+ //
+ // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
+ // % can be escaped within a .cmd file.
+ let reverse = '"';
+ let quoteHit = true;
+ for (let i = arg.length; i > 0; i--) {
+ // walk the string in reverse
+ reverse += arg[i - 1];
+ if (quoteHit && arg[i - 1] === '\\') {
+ reverse += '\\'; // double the slash
+ }
+ else if (arg[i - 1] === '"') {
+ quoteHit = true;
+ reverse += '"'; // double the quote
+ }
+ else {
+ quoteHit = false;
+ }
}
- } else {
- allowBlockCollections = false;
- }
- }
- }
-
- if (allowBlockCollections) {
- allowBlockCollections = atNewLine || allowCompact;
- }
-
- if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
- if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
- flowIndent = parentIndent;
- } else {
- flowIndent = parentIndent + 1;
+ reverse += '"';
+ return reverse
+ .split('')
+ .reverse()
+ .join('');
}
-
- blockIndent = state.position - state.lineStart;
-
- if (indentStatus === 1) {
- if (allowBlockCollections &&
- (readBlockSequence(state, blockIndent) ||
- readBlockMapping(state, blockIndent, flowIndent)) ||
- readFlowCollection(state, flowIndent)) {
- hasContent = true;
- } else {
- if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
- readSingleQuotedScalar(state, flowIndent) ||
- readDoubleQuotedScalar(state, flowIndent)) {
- hasContent = true;
-
- } else if (readAlias(state)) {
- hasContent = true;
-
- if (state.tag !== null || state.anchor !== null) {
- throwError(state, 'alias node should not have any properties');
- }
-
- } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
- hasContent = true;
-
- if (state.tag === null) {
- state.tag = '?';
- }
+ _uvQuoteCmdArg(arg) {
+ // Tool runner wraps child_process.spawn() and needs to apply the same quoting as
+ // Node in certain cases where the undocumented spawn option windowsVerbatimArguments
+ // is used.
+ //
+ // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
+ // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
+ // pasting copyright notice from Node within this function:
+ //
+ // Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ //
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
+ // of this software and associated documentation files (the "Software"), to
+ // deal in the Software without restriction, including without limitation the
+ // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ // sell copies of the Software, and to permit persons to whom the Software is
+ // furnished to do so, subject to the following conditions:
+ //
+ // The above copyright notice and this permission notice shall be included in
+ // all copies or substantial portions of the Software.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ // IN THE SOFTWARE.
+ if (!arg) {
+ // Need double quotation for empty argument
+ return '""';
}
-
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = state.result;
+ if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
+ // No quotation needed
+ return arg;
}
- }
- } else if (indentStatus === 0) {
- // Special case: block sequences are allowed to have same indentation level as the parent.
- // http://www.yaml.org/spec/1.2/spec.html#id2799784
- hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
- }
- }
-
- if (state.tag === null) {
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = state.result;
- }
-
- } else if (state.tag === '?') {
- // Implicit resolving is not allowed for non-scalar types, and '?'
- // non-specific tag is only automatically assigned to plain scalars.
- //
- // We only need to check kind conformity in case user explicitly assigns '?'
- // tag, for example like this: "!> [0]"
- //
- if (state.result !== null && state.kind !== 'scalar') {
- throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
- }
-
- for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
- type = state.implicitTypes[typeIndex];
-
- if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
- state.result = type.construct(state.result);
- state.tag = type.tag;
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = state.result;
+ if (!arg.includes('"') && !arg.includes('\\')) {
+ // No embedded double quotes or backslashes, so I can just wrap
+ // quote marks around the whole thing.
+ return `"${arg}"`;
}
- break;
- }
- }
- } else if (state.tag !== '!') {
- if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
- type = state.typeMap[state.kind || 'fallback'][state.tag];
- } else {
- // looking for multi type
- type = null;
- typeList = state.typeMap.multi[state.kind || 'fallback'];
-
- for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
- if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
- type = typeList[typeIndex];
- break;
+ // Expected input/output:
+ // input : hello"world
+ // output: "hello\"world"
+ // input : hello""world
+ // output: "hello\"\"world"
+ // input : hello\world
+ // output: hello\world
+ // input : hello\\world
+ // output: hello\\world
+ // input : hello\"world
+ // output: "hello\\\"world"
+ // input : hello\\"world
+ // output: "hello\\\\\"world"
+ // input : hello world\
+ // output: "hello world\\" - note the comment in libuv actually reads "hello world\"
+ // but it appears the comment is wrong, it should be "hello world\\"
+ let reverse = '"';
+ let quoteHit = true;
+ for (let i = arg.length; i > 0; i--) {
+ // walk the string in reverse
+ reverse += arg[i - 1];
+ if (quoteHit && arg[i - 1] === '\\') {
+ reverse += '\\';
+ }
+ else if (arg[i - 1] === '"') {
+ quoteHit = true;
+ reverse += '\\';
+ }
+ else {
+ quoteHit = false;
+ }
}
- }
+ reverse += '"';
+ return reverse
+ .split('')
+ .reverse()
+ .join('');
}
-
- if (!type) {
- throwError(state, 'unknown tag !<' + state.tag + '>');
+ _cloneExecOptions(options) {
+ options = options || {};
+ const result = {
+ cwd: options.cwd || process.cwd(),
+ env: options.env || process.env,
+ silent: options.silent || false,
+ windowsVerbatimArguments: options.windowsVerbatimArguments || false,
+ failOnStdErr: options.failOnStdErr || false,
+ ignoreReturnCode: options.ignoreReturnCode || false,
+ delay: options.delay || 10000
+ };
+ result.outStream = options.outStream || process.stdout;
+ result.errStream = options.errStream || process.stderr;
+ return result;
}
-
- if (state.result !== null && type.kind !== state.kind) {
- throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
+ _getSpawnOptions(options, toolPath) {
+ options = options || {};
+ const result = {};
+ result.cwd = options.cwd;
+ result.env = options.env;
+ result['windowsVerbatimArguments'] =
+ options.windowsVerbatimArguments || this._isCmdFile();
+ if (options.windowsVerbatimArguments) {
+ result.argv0 = `"${toolPath}"`;
+ }
+ return result;
}
-
- if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
- throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
- } else {
- state.result = type.construct(state.result, state.tag);
- if (state.anchor !== null) {
- state.anchorMap[state.anchor] = state.result;
- }
+ /**
+ * Exec a tool.
+ * Output will be streamed to the live console.
+ * Returns promise with return code
+ *
+ * @param tool path to tool to exec
+ * @param options optional exec options. See ExecOptions
+ * @returns number
+ */
+ exec() {
+ return __awaiter(this, void 0, void 0, function* () {
+ // root the tool path if it is unrooted and contains relative pathing
+ if (!ioUtil.isRooted(this.toolPath) &&
+ (this.toolPath.includes('/') ||
+ (IS_WINDOWS && this.toolPath.includes('\\')))) {
+ // prefer options.cwd if it is specified, however options.cwd may also need to be rooted
+ this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
+ }
+ // if the tool is only a file name, then resolve it from the PATH
+ // otherwise verify it exists (add extension on Windows if necessary)
+ this.toolPath = yield io.which(this.toolPath, true);
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
+ this._debug(`exec tool: ${this.toolPath}`);
+ this._debug('arguments:');
+ for (const arg of this.args) {
+ this._debug(` ${arg}`);
+ }
+ const optionsNonNull = this._cloneExecOptions(this.options);
+ if (!optionsNonNull.silent && optionsNonNull.outStream) {
+ optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
+ }
+ const state = new ExecState(optionsNonNull, this.toolPath);
+ state.on('debug', (message) => {
+ this._debug(message);
+ });
+ if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) {
+ return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
+ }
+ const fileName = this._getSpawnFileName();
+ const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
+ let stdbuffer = '';
+ if (cp.stdout) {
+ cp.stdout.on('data', (data) => {
+ if (this.options.listeners && this.options.listeners.stdout) {
+ this.options.listeners.stdout(data);
+ }
+ if (!optionsNonNull.silent && optionsNonNull.outStream) {
+ optionsNonNull.outStream.write(data);
+ }
+ stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
+ if (this.options.listeners && this.options.listeners.stdline) {
+ this.options.listeners.stdline(line);
+ }
+ });
+ });
+ }
+ let errbuffer = '';
+ if (cp.stderr) {
+ cp.stderr.on('data', (data) => {
+ state.processStderr = true;
+ if (this.options.listeners && this.options.listeners.stderr) {
+ this.options.listeners.stderr(data);
+ }
+ if (!optionsNonNull.silent &&
+ optionsNonNull.errStream &&
+ optionsNonNull.outStream) {
+ const s = optionsNonNull.failOnStdErr
+ ? optionsNonNull.errStream
+ : optionsNonNull.outStream;
+ s.write(data);
+ }
+ errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
+ if (this.options.listeners && this.options.listeners.errline) {
+ this.options.listeners.errline(line);
+ }
+ });
+ });
+ }
+ cp.on('error', (err) => {
+ state.processError = err.message;
+ state.processExited = true;
+ state.processClosed = true;
+ state.CheckComplete();
+ });
+ cp.on('exit', (code) => {
+ state.processExitCode = code;
+ state.processExited = true;
+ this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
+ state.CheckComplete();
+ });
+ cp.on('close', (code) => {
+ state.processExitCode = code;
+ state.processExited = true;
+ state.processClosed = true;
+ this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
+ state.CheckComplete();
+ });
+ state.on('done', (error, exitCode) => {
+ if (stdbuffer.length > 0) {
+ this.emit('stdline', stdbuffer);
+ }
+ if (errbuffer.length > 0) {
+ this.emit('errline', errbuffer);
+ }
+ cp.removeAllListeners();
+ if (error) {
+ reject(error);
+ }
+ else {
+ resolve(exitCode);
+ }
+ });
+ if (this.options.input) {
+ if (!cp.stdin) {
+ throw new Error('child process missing stdin');
+ }
+ cp.stdin.end(this.options.input);
+ }
+ }));
+ });
}
- }
-
- if (state.listener !== null) {
- state.listener('close', state);
- }
- return state.tag !== null || state.anchor !== null || hasContent;
}
-
-function readDocument(state) {
- var documentStart = state.position,
- _position,
- directiveName,
- directiveArgs,
- hasDirectives = false,
- ch;
-
- state.version = null;
- state.checkLineBreaks = state.legacy;
- state.tagMap = Object.create(null);
- state.anchorMap = Object.create(null);
-
- while ((ch = state.input.charCodeAt(state.position)) !== 0) {
- skipSeparationSpace(state, true, -1);
-
- ch = state.input.charCodeAt(state.position);
-
- if (state.lineIndent > 0 || ch !== 0x25/* % */) {
- break;
+exports.ToolRunner = ToolRunner;
+/**
+ * Convert an arg string to an array of args. Handles escaping
+ *
+ * @param argString string of arguments
+ * @returns string[] array of arguments
+ */
+function argStringToArray(argString) {
+ const args = [];
+ let inQuotes = false;
+ let escaped = false;
+ let arg = '';
+ function append(c) {
+ // we only escape double quotes.
+ if (escaped && c !== '"') {
+ arg += '\\';
+ }
+ arg += c;
+ escaped = false;
}
-
- hasDirectives = true;
- ch = state.input.charCodeAt(++state.position);
- _position = state.position;
-
- while (ch !== 0 && !is_WS_OR_EOL(ch)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- directiveName = state.input.slice(_position, state.position);
- directiveArgs = [];
-
- if (directiveName.length < 1) {
- throwError(state, 'directive name must not be less than one character in length');
- }
-
- while (ch !== 0) {
- while (is_WHITE_SPACE(ch)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- if (ch === 0x23/* # */) {
- do { ch = state.input.charCodeAt(++state.position); }
- while (ch !== 0 && !is_EOL(ch));
- break;
- }
-
- if (is_EOL(ch)) break;
-
- _position = state.position;
-
- while (ch !== 0 && !is_WS_OR_EOL(ch)) {
- ch = state.input.charCodeAt(++state.position);
- }
-
- directiveArgs.push(state.input.slice(_position, state.position));
- }
-
- if (ch !== 0) readLineBreak(state);
-
- if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
- directiveHandlers[directiveName](state, directiveName, directiveArgs);
- } else {
- throwWarning(state, 'unknown document directive "' + directiveName + '"');
- }
- }
-
- skipSeparationSpace(state, true, -1);
-
- if (state.lineIndent === 0 &&
- state.input.charCodeAt(state.position) === 0x2D/* - */ &&
- state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
- state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
- state.position += 3;
- skipSeparationSpace(state, true, -1);
-
- } else if (hasDirectives) {
- throwError(state, 'directives end mark is expected');
- }
-
- composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
- skipSeparationSpace(state, true, -1);
-
- if (state.checkLineBreaks &&
- PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
- throwWarning(state, 'non-ASCII line breaks are interpreted as content');
- }
-
- state.documents.push(state.result);
-
- if (state.position === state.lineStart && testDocumentSeparator(state)) {
-
- if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
- state.position += 3;
- skipSeparationSpace(state, true, -1);
- }
- return;
- }
-
- if (state.position < (state.length - 1)) {
- throwError(state, 'end of the stream or a document separator is expected');
- } else {
- return;
- }
-}
-
-
-function loadDocuments(input, options) {
- input = String(input);
- options = options || {};
-
- if (input.length !== 0) {
-
- // Add tailing `\n` if not exists
- if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
- input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
- input += '\n';
- }
-
- // Strip BOM
- if (input.charCodeAt(0) === 0xFEFF) {
- input = input.slice(1);
- }
- }
-
- var state = new State$1(input, options);
-
- var nullpos = input.indexOf('\0');
-
- if (nullpos !== -1) {
- state.position = nullpos;
- throwError(state, 'null byte is not allowed in input');
- }
-
- // Use 0 as string terminator. That significantly simplifies bounds check.
- state.input += '\0';
-
- while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
- state.lineIndent += 1;
- state.position += 1;
- }
-
- while (state.position < (state.length - 1)) {
- readDocument(state);
- }
-
- return state.documents;
-}
-
-
-function loadAll$1(input, iterator, options) {
- if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
- options = iterator;
- iterator = null;
- }
-
- var documents = loadDocuments(input, options);
-
- if (typeof iterator !== 'function') {
- return documents;
- }
-
- for (var index = 0, length = documents.length; index < length; index += 1) {
- iterator(documents[index]);
- }
-}
-
-
-function load$1(input, options) {
- var documents = loadDocuments(input, options);
-
- if (documents.length === 0) {
- /*eslint-disable no-undefined*/
- return undefined;
- } else if (documents.length === 1) {
- return documents[0];
- }
- throw new exception('expected a single document in the stream, but found more');
-}
-
-
-var loadAll_1 = loadAll$1;
-var load_1 = load$1;
-
-var loader = {
- loadAll: loadAll_1,
- load: load_1
-};
-
-/*eslint-disable no-use-before-define*/
-
-
-
-
-
-var _toString = Object.prototype.toString;
-var _hasOwnProperty = Object.prototype.hasOwnProperty;
-
-var CHAR_BOM = 0xFEFF;
-var CHAR_TAB = 0x09; /* Tab */
-var CHAR_LINE_FEED = 0x0A; /* LF */
-var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
-var CHAR_SPACE = 0x20; /* Space */
-var CHAR_EXCLAMATION = 0x21; /* ! */
-var CHAR_DOUBLE_QUOTE = 0x22; /* " */
-var CHAR_SHARP = 0x23; /* # */
-var CHAR_PERCENT = 0x25; /* % */
-var CHAR_AMPERSAND = 0x26; /* & */
-var CHAR_SINGLE_QUOTE = 0x27; /* ' */
-var CHAR_ASTERISK = 0x2A; /* * */
-var CHAR_COMMA = 0x2C; /* , */
-var CHAR_MINUS = 0x2D; /* - */
-var CHAR_COLON = 0x3A; /* : */
-var CHAR_EQUALS = 0x3D; /* = */
-var CHAR_GREATER_THAN = 0x3E; /* > */
-var CHAR_QUESTION = 0x3F; /* ? */
-var CHAR_COMMERCIAL_AT = 0x40; /* @ */
-var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
-var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
-var CHAR_GRAVE_ACCENT = 0x60; /* ` */
-var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
-var CHAR_VERTICAL_LINE = 0x7C; /* | */
-var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
-
-var ESCAPE_SEQUENCES = {};
-
-ESCAPE_SEQUENCES[0x00] = '\\0';
-ESCAPE_SEQUENCES[0x07] = '\\a';
-ESCAPE_SEQUENCES[0x08] = '\\b';
-ESCAPE_SEQUENCES[0x09] = '\\t';
-ESCAPE_SEQUENCES[0x0A] = '\\n';
-ESCAPE_SEQUENCES[0x0B] = '\\v';
-ESCAPE_SEQUENCES[0x0C] = '\\f';
-ESCAPE_SEQUENCES[0x0D] = '\\r';
-ESCAPE_SEQUENCES[0x1B] = '\\e';
-ESCAPE_SEQUENCES[0x22] = '\\"';
-ESCAPE_SEQUENCES[0x5C] = '\\\\';
-ESCAPE_SEQUENCES[0x85] = '\\N';
-ESCAPE_SEQUENCES[0xA0] = '\\_';
-ESCAPE_SEQUENCES[0x2028] = '\\L';
-ESCAPE_SEQUENCES[0x2029] = '\\P';
-
-var DEPRECATED_BOOLEANS_SYNTAX = [
- 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
- 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
-];
-
-var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
-
-function compileStyleMap(schema, map) {
- var result, keys, index, length, tag, style, type;
-
- if (map === null) return {};
-
- result = {};
- keys = Object.keys(map);
-
- for (index = 0, length = keys.length; index < length; index += 1) {
- tag = keys[index];
- style = String(map[tag]);
-
- if (tag.slice(0, 2) === '!!') {
- tag = 'tag:yaml.org,2002:' + tag.slice(2);
- }
- type = schema.compiledTypeMap['fallback'][tag];
-
- if (type && _hasOwnProperty.call(type.styleAliases, style)) {
- style = type.styleAliases[style];
- }
-
- result[tag] = style;
- }
-
- return result;
-}
-
-function encodeHex(character) {
- var string, handle, length;
-
- string = character.toString(16).toUpperCase();
-
- if (character <= 0xFF) {
- handle = 'x';
- length = 2;
- } else if (character <= 0xFFFF) {
- handle = 'u';
- length = 4;
- } else if (character <= 0xFFFFFFFF) {
- handle = 'U';
- length = 8;
- } else {
- throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
- }
-
- return '\\' + handle + common.repeat('0', length - string.length) + string;
-}
-
-
-var QUOTING_TYPE_SINGLE = 1,
- QUOTING_TYPE_DOUBLE = 2;
-
-function State(options) {
- this.schema = options['schema'] || _default;
- this.indent = Math.max(1, (options['indent'] || 2));
- this.noArrayIndent = options['noArrayIndent'] || false;
- this.skipInvalid = options['skipInvalid'] || false;
- this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
- this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
- this.sortKeys = options['sortKeys'] || false;
- this.lineWidth = options['lineWidth'] || 80;
- this.noRefs = options['noRefs'] || false;
- this.noCompatMode = options['noCompatMode'] || false;
- this.condenseFlow = options['condenseFlow'] || false;
- this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
- this.forceQuotes = options['forceQuotes'] || false;
- this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;
-
- this.implicitTypes = this.schema.compiledImplicit;
- this.explicitTypes = this.schema.compiledExplicit;
-
- this.tag = null;
- this.result = '';
-
- this.duplicates = [];
- this.usedDuplicates = null;
-}
-
-// Indents every line in a string. Empty lines (\n only) are not indented.
-function indentString(string, spaces) {
- var ind = common.repeat(' ', spaces),
- position = 0,
- next = -1,
- result = '',
- line,
- length = string.length;
-
- while (position < length) {
- next = string.indexOf('\n', position);
- if (next === -1) {
- line = string.slice(position);
- position = length;
- } else {
- line = string.slice(position, next + 1);
- position = next + 1;
- }
-
- if (line.length && line !== '\n') result += ind;
-
- result += line;
- }
-
- return result;
-}
-
-function generateNextLine(state, level) {
- return '\n' + common.repeat(' ', state.indent * level);
-}
-
-function testImplicitResolving(state, str) {
- var index, length, type;
-
- for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
- type = state.implicitTypes[index];
-
- if (type.resolve(str)) {
- return true;
- }
- }
-
- return false;
-}
-
-// [33] s-white ::= s-space | s-tab
-function isWhitespace(c) {
- return c === CHAR_SPACE || c === CHAR_TAB;
-}
-
-// Returns true if the character can be printed without escaping.
-// From YAML 1.2: "any allowed characters known to be non-printable
-// should also be escaped. [However,] This isn’t mandatory"
-// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
-function isPrintable(c) {
- return (0x00020 <= c && c <= 0x00007E)
- || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
- || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
- || (0x10000 <= c && c <= 0x10FFFF);
-}
-
-// [34] ns-char ::= nb-char - s-white
-// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
-// [26] b-char ::= b-line-feed | b-carriage-return
-// Including s-white (for some reason, examples doesn't match specs in this aspect)
-// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
-function isNsCharOrWhitespace(c) {
- return isPrintable(c)
- && c !== CHAR_BOM
- // - b-char
- && c !== CHAR_CARRIAGE_RETURN
- && c !== CHAR_LINE_FEED;
-}
-
-// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
-// c = flow-in ⇒ ns-plain-safe-in
-// c = block-key ⇒ ns-plain-safe-out
-// c = flow-key ⇒ ns-plain-safe-in
-// [128] ns-plain-safe-out ::= ns-char
-// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
-// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
-// | ( /* An ns-char preceding */ “#” )
-// | ( “:” /* Followed by an ns-plain-safe(c) */ )
-function isPlainSafe(c, prev, inblock) {
- var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
- var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
- return (
- // ns-plain-safe
- inblock ? // c = flow-in
- cIsNsCharOrWhitespace
- : cIsNsCharOrWhitespace
- // - c-flow-indicator
- && c !== CHAR_COMMA
- && c !== CHAR_LEFT_SQUARE_BRACKET
- && c !== CHAR_RIGHT_SQUARE_BRACKET
- && c !== CHAR_LEFT_CURLY_BRACKET
- && c !== CHAR_RIGHT_CURLY_BRACKET
- )
- // ns-plain-char
- && c !== CHAR_SHARP // false on '#'
- && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
- || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
- || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
-}
-
-// Simplified test for values allowed as the first character in plain style.
-function isPlainSafeFirst(c) {
- // Uses a subset of ns-char - c-indicator
- // where ns-char = nb-char - s-white.
- // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
- return isPrintable(c) && c !== CHAR_BOM
- && !isWhitespace(c) // - s-white
- // - (c-indicator ::=
- // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
- && c !== CHAR_MINUS
- && c !== CHAR_QUESTION
- && c !== CHAR_COLON
- && c !== CHAR_COMMA
- && c !== CHAR_LEFT_SQUARE_BRACKET
- && c !== CHAR_RIGHT_SQUARE_BRACKET
- && c !== CHAR_LEFT_CURLY_BRACKET
- && c !== CHAR_RIGHT_CURLY_BRACKET
- // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
- && c !== CHAR_SHARP
- && c !== CHAR_AMPERSAND
- && c !== CHAR_ASTERISK
- && c !== CHAR_EXCLAMATION
- && c !== CHAR_VERTICAL_LINE
- && c !== CHAR_EQUALS
- && c !== CHAR_GREATER_THAN
- && c !== CHAR_SINGLE_QUOTE
- && c !== CHAR_DOUBLE_QUOTE
- // | “%” | “@” | “`”)
- && c !== CHAR_PERCENT
- && c !== CHAR_COMMERCIAL_AT
- && c !== CHAR_GRAVE_ACCENT;
-}
-
-// Simplified test for values allowed as the last character in plain style.
-function isPlainSafeLast(c) {
- // just not whitespace or colon, it will be checked to be plain character later
- return !isWhitespace(c) && c !== CHAR_COLON;
-}
-
-// Same as 'string'.codePointAt(pos), but works in older browsers.
-function codePointAt(string, pos) {
- var first = string.charCodeAt(pos), second;
- if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
- second = string.charCodeAt(pos + 1);
- if (second >= 0xDC00 && second <= 0xDFFF) {
- // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
- return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
- }
- }
- return first;
-}
-
-// Determines whether block indentation indicator is required.
-function needIndentIndicator(string) {
- var leadingSpaceRe = /^\n* /;
- return leadingSpaceRe.test(string);
-}
-
-var STYLE_PLAIN = 1,
- STYLE_SINGLE = 2,
- STYLE_LITERAL = 3,
- STYLE_FOLDED = 4,
- STYLE_DOUBLE = 5;
-
-// Determines which scalar styles are possible and returns the preferred style.
-// lineWidth = -1 => no limit.
-// Pre-conditions: str.length > 0.
-// Post-conditions:
-// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
-// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
-// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
-function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
- testAmbiguousType, quotingType, forceQuotes, inblock) {
-
- var i;
- var char = 0;
- var prevChar = null;
- var hasLineBreak = false;
- var hasFoldableLine = false; // only checked if shouldTrackWidth
- var shouldTrackWidth = lineWidth !== -1;
- var previousLineBreak = -1; // count the first line correctly
- var plain = isPlainSafeFirst(codePointAt(string, 0))
- && isPlainSafeLast(codePointAt(string, string.length - 1));
-
- if (singleLineOnly || forceQuotes) {
- // Case: no block styles.
- // Check for disallowed characters to rule out plain and single.
- for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
- char = codePointAt(string, i);
- if (!isPrintable(char)) {
- return STYLE_DOUBLE;
- }
- plain = plain && isPlainSafe(char, prevChar, inblock);
- prevChar = char;
- }
- } else {
- // Case: block styles permitted.
- for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
- char = codePointAt(string, i);
- if (char === CHAR_LINE_FEED) {
- hasLineBreak = true;
- // Check if any line can be folded.
- if (shouldTrackWidth) {
- hasFoldableLine = hasFoldableLine ||
- // Foldable line = too long, and not more-indented.
- (i - previousLineBreak - 1 > lineWidth &&
- string[previousLineBreak + 1] !== ' ');
- previousLineBreak = i;
+ for (let i = 0; i < argString.length; i++) {
+ const c = argString.charAt(i);
+ if (c === '"') {
+ if (!escaped) {
+ inQuotes = !inQuotes;
+ }
+ else {
+ append(c);
+ }
+ continue;
}
- } else if (!isPrintable(char)) {
- return STYLE_DOUBLE;
- }
- plain = plain && isPlainSafe(char, prevChar, inblock);
- prevChar = char;
- }
- // in case the end is missing a \n
- hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
- (i - previousLineBreak - 1 > lineWidth &&
- string[previousLineBreak + 1] !== ' '));
- }
- // Although every style can represent \n without escaping, prefer block styles
- // for multiline, since they're more readable and they don't add empty lines.
- // Also prefer folding a super-long line.
- if (!hasLineBreak && !hasFoldableLine) {
- // Strings interpretable as another type have to be quoted;
- // e.g. the string 'true' vs. the boolean true.
- if (plain && !forceQuotes && !testAmbiguousType(string)) {
- return STYLE_PLAIN;
- }
- return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
- }
- // Edge case: block indentation indicator can only have one digit.
- if (indentPerLevel > 9 && needIndentIndicator(string)) {
- return STYLE_DOUBLE;
- }
- // At this point we know block styles are valid.
- // Prefer literal style unless we want to fold.
- if (!forceQuotes) {
- return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
- }
- return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
-}
-
-// Note: line breaking/folding is implemented for only the folded style.
-// NB. We drop the last trailing newline (if any) of a returned block scalar
-// since the dumper adds its own newline. This always works:
-// • No ending newline => unaffected; already using strip "-" chomping.
-// • Ending newline => removed then restored.
-// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
-function writeScalar(state, string, level, iskey, inblock) {
- state.dump = (function () {
- if (string.length === 0) {
- return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
- }
- if (!state.noCompatMode) {
- if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
- return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
- }
- }
-
- var indent = state.indent * Math.max(1, level); // no 0-indent scalars
- // As indentation gets deeper, let the width decrease monotonically
- // to the lower bound min(state.lineWidth, 40).
- // Note that this implies
- // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
- // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
- // This behaves better than a constant minimum width which disallows narrower options,
- // or an indent threshold which causes the width to suddenly increase.
- var lineWidth = state.lineWidth === -1
- ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
-
- // Without knowing if keys are implicit/explicit, assume implicit for safety.
- var singleLineOnly = iskey
- // No block styles in flow mode.
- || (state.flowLevel > -1 && level >= state.flowLevel);
- function testAmbiguity(string) {
- return testImplicitResolving(state, string);
- }
-
- switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
- testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
-
- case STYLE_PLAIN:
- return string;
- case STYLE_SINGLE:
- return "'" + string.replace(/'/g, "''") + "'";
- case STYLE_LITERAL:
- return '|' + blockHeader(string, state.indent)
- + dropEndingNewline(indentString(string, indent));
- case STYLE_FOLDED:
- return '>' + blockHeader(string, state.indent)
- + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
- case STYLE_DOUBLE:
- return '"' + escapeString(string) + '"';
- default:
- throw new exception('impossible error: invalid scalar style');
- }
- }());
-}
-
-// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
-function blockHeader(string, indentPerLevel) {
- var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
-
- // note the special case: the string '\n' counts as a "trailing" empty line.
- var clip = string[string.length - 1] === '\n';
- var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
- var chomp = keep ? '+' : (clip ? '' : '-');
-
- return indentIndicator + chomp + '\n';
-}
-
-// (See the note for writeScalar.)
-function dropEndingNewline(string) {
- return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
-}
-
-// Note: a long line without a suitable break point will exceed the width limit.
-// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
-function foldString(string, width) {
- // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
- // unless they're before or after a more-indented line, or at the very
- // beginning or end, in which case $k$ maps to $k$.
- // Therefore, parse each chunk as newline(s) followed by a content line.
- var lineRe = /(\n+)([^\n]*)/g;
-
- // first line (possibly an empty line)
- var result = (function () {
- var nextLF = string.indexOf('\n');
- nextLF = nextLF !== -1 ? nextLF : string.length;
- lineRe.lastIndex = nextLF;
- return foldLine(string.slice(0, nextLF), width);
- }());
- // If we haven't reached the first content line yet, don't add an extra \n.
- var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
- var moreIndented;
-
- // rest of the lines
- var match;
- while ((match = lineRe.exec(string))) {
- var prefix = match[1], line = match[2];
- moreIndented = (line[0] === ' ');
- result += prefix
- + (!prevMoreIndented && !moreIndented && line !== ''
- ? '\n' : '')
- + foldLine(line, width);
- prevMoreIndented = moreIndented;
- }
-
- return result;
-}
-
-// Greedy line breaking.
-// Picks the longest line under the limit each time,
-// otherwise settles for the shortest line over the limit.
-// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
-function foldLine(line, width) {
- if (line === '' || line[0] === ' ') return line;
-
- // Since a more-indented line adds a \n, breaks can't be followed by a space.
- var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
- var match;
- // start is an inclusive index. end, curr, and next are exclusive.
- var start = 0, end, curr = 0, next = 0;
- var result = '';
-
- // Invariants: 0 <= start <= length-1.
- // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
- // Inside the loop:
- // A match implies length >= 2, so curr and next are <= length-2.
- while ((match = breakRe.exec(line))) {
- next = match.index;
- // maintain invariant: curr - start <= width
- if (next - start > width) {
- end = (curr > start) ? curr : next; // derive end <= length-2
- result += '\n' + line.slice(start, end);
- // skip the space that was output as \n
- start = end + 1; // derive start <= length-1
- }
- curr = next;
- }
-
- // By the invariants, start <= length-1, so there is something left over.
- // It is either the whole string or a part starting from non-whitespace.
- result += '\n';
- // Insert a break if the remainder is too long and there is a break available.
- if (line.length - start > width && curr > start) {
- result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
- } else {
- result += line.slice(start);
- }
-
- return result.slice(1); // drop extra \n joiner
-}
-
-// Escapes a double-quoted string.
-function escapeString(string) {
- var result = '';
- var char = 0;
- var escapeSeq;
-
- for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
- char = codePointAt(string, i);
- escapeSeq = ESCAPE_SEQUENCES[char];
-
- if (!escapeSeq && isPrintable(char)) {
- result += string[i];
- if (char >= 0x10000) result += string[i + 1];
- } else {
- result += escapeSeq || encodeHex(char);
- }
- }
-
- return result;
-}
-
-function writeFlowSequence(state, level, object) {
- var _result = '',
- _tag = state.tag,
- index,
- length,
- value;
-
- for (index = 0, length = object.length; index < length; index += 1) {
- value = object[index];
-
- if (state.replacer) {
- value = state.replacer.call(object, String(index), value);
- }
-
- // Write only valid elements, put null instead of invalid elements.
- if (writeNode(state, level, value, false, false) ||
- (typeof value === 'undefined' &&
- writeNode(state, level, null, false, false))) {
-
- if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
- _result += state.dump;
- }
- }
-
- state.tag = _tag;
- state.dump = '[' + _result + ']';
-}
-
-function writeBlockSequence(state, level, object, compact) {
- var _result = '',
- _tag = state.tag,
- index,
- length,
- value;
-
- for (index = 0, length = object.length; index < length; index += 1) {
- value = object[index];
-
- if (state.replacer) {
- value = state.replacer.call(object, String(index), value);
- }
-
- // Write only valid elements, put null instead of invalid elements.
- if (writeNode(state, level + 1, value, true, true, false, true) ||
- (typeof value === 'undefined' &&
- writeNode(state, level + 1, null, true, true, false, true))) {
-
- if (!compact || _result !== '') {
- _result += generateNextLine(state, level);
- }
-
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
- _result += '-';
- } else {
- _result += '- ';
- }
-
- _result += state.dump;
- }
- }
-
- state.tag = _tag;
- state.dump = _result || '[]'; // Empty sequence if no valid values.
-}
-
-function writeFlowMapping(state, level, object) {
- var _result = '',
- _tag = state.tag,
- objectKeyList = Object.keys(object),
- index,
- length,
- objectKey,
- objectValue,
- pairBuffer;
-
- for (index = 0, length = objectKeyList.length; index < length; index += 1) {
-
- pairBuffer = '';
- if (_result !== '') pairBuffer += ', ';
-
- if (state.condenseFlow) pairBuffer += '"';
-
- objectKey = objectKeyList[index];
- objectValue = object[objectKey];
-
- if (state.replacer) {
- objectValue = state.replacer.call(object, objectKey, objectValue);
- }
-
- if (!writeNode(state, level, objectKey, false, false)) {
- continue; // Skip this pair because of invalid key;
- }
-
- if (state.dump.length > 1024) pairBuffer += '? ';
-
- pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
-
- if (!writeNode(state, level, objectValue, false, false)) {
- continue; // Skip this pair because of invalid value.
- }
-
- pairBuffer += state.dump;
-
- // Both key and value are valid.
- _result += pairBuffer;
- }
-
- state.tag = _tag;
- state.dump = '{' + _result + '}';
-}
-
-function writeBlockMapping(state, level, object, compact) {
- var _result = '',
- _tag = state.tag,
- objectKeyList = Object.keys(object),
- index,
- length,
- objectKey,
- objectValue,
- explicitPair,
- pairBuffer;
-
- // Allow sorting keys so that the output file is deterministic
- if (state.sortKeys === true) {
- // Default sorting
- objectKeyList.sort();
- } else if (typeof state.sortKeys === 'function') {
- // Custom sort function
- objectKeyList.sort(state.sortKeys);
- } else if (state.sortKeys) {
- // Something is wrong
- throw new exception('sortKeys must be a boolean or a function');
- }
-
- for (index = 0, length = objectKeyList.length; index < length; index += 1) {
- pairBuffer = '';
-
- if (!compact || _result !== '') {
- pairBuffer += generateNextLine(state, level);
- }
-
- objectKey = objectKeyList[index];
- objectValue = object[objectKey];
-
- if (state.replacer) {
- objectValue = state.replacer.call(object, objectKey, objectValue);
- }
-
- if (!writeNode(state, level + 1, objectKey, true, true, true)) {
- continue; // Skip this pair because of invalid key.
- }
-
- explicitPair = (state.tag !== null && state.tag !== '?') ||
- (state.dump && state.dump.length > 1024);
-
- if (explicitPair) {
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
- pairBuffer += '?';
- } else {
- pairBuffer += '? ';
- }
- }
-
- pairBuffer += state.dump;
-
- if (explicitPair) {
- pairBuffer += generateNextLine(state, level);
- }
-
- if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
- continue; // Skip this pair because of invalid value.
+ if (c === '\\' && escaped) {
+ append(c);
+ continue;
+ }
+ if (c === '\\' && inQuotes) {
+ escaped = true;
+ continue;
+ }
+ if (c === ' ' && !inQuotes) {
+ if (arg.length > 0) {
+ args.push(arg);
+ arg = '';
+ }
+ continue;
+ }
+ append(c);
}
-
- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
- pairBuffer += ':';
- } else {
- pairBuffer += ': ';
+ if (arg.length > 0) {
+ args.push(arg.trim());
}
-
- pairBuffer += state.dump;
-
- // Both key and value are valid.
- _result += pairBuffer;
- }
-
- state.tag = _tag;
- state.dump = _result || '{}'; // Empty mapping if no valid pairs.
+ return args;
}
-
-function detectType(state, object, explicit) {
- var _result, typeList, index, length, type, style;
-
- typeList = explicit ? state.explicitTypes : state.implicitTypes;
-
- for (index = 0, length = typeList.length; index < length; index += 1) {
- type = typeList[index];
-
- if ((type.instanceOf || type.predicate) &&
- (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
- (!type.predicate || type.predicate(object))) {
-
- if (explicit) {
- if (type.multi && type.representName) {
- state.tag = type.representName(object);
- } else {
- state.tag = type.tag;
+exports.argStringToArray = argStringToArray;
+class ExecState extends events.EventEmitter {
+ constructor(options, toolPath) {
+ super();
+ this.processClosed = false; // tracks whether the process has exited and stdio is closed
+ this.processError = '';
+ this.processExitCode = 0;
+ this.processExited = false; // tracks whether the process has exited
+ this.processStderr = false; // tracks whether stderr was written to
+ this.delay = 10000; // 10 seconds
+ this.done = false;
+ this.timeout = null;
+ if (!toolPath) {
+ throw new Error('toolPath must not be empty');
}
- } else {
- state.tag = '?';
- }
-
- if (type.represent) {
- style = state.styleMap[type.tag] || type.defaultStyle;
-
- if (_toString.call(type.represent) === '[object Function]') {
- _result = type.represent(object, style);
- } else if (_hasOwnProperty.call(type.represent, style)) {
- _result = type.represent[style](object, style);
- } else {
- throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
+ this.options = options;
+ this.toolPath = toolPath;
+ if (options.delay) {
+ this.delay = options.delay;
}
-
- state.dump = _result;
- }
-
- return true;
}
- }
-
- return false;
-}
-
-// Serializes `object` and writes it to global `result`.
-// Returns true on success, or false on invalid object.
-//
-function writeNode(state, level, object, block, compact, iskey, isblockseq) {
- state.tag = null;
- state.dump = object;
-
- if (!detectType(state, object, false)) {
- detectType(state, object, true);
- }
-
- var type = _toString.call(state.dump);
- var inblock = block;
- var tagStr;
-
- if (block) {
- block = (state.flowLevel < 0 || state.flowLevel > level);
- }
-
- var objectOrArray = type === '[object Object]' || type === '[object Array]',
- duplicateIndex,
- duplicate;
-
- if (objectOrArray) {
- duplicateIndex = state.duplicates.indexOf(object);
- duplicate = duplicateIndex !== -1;
- }
-
- if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
- compact = false;
- }
-
- if (duplicate && state.usedDuplicates[duplicateIndex]) {
- state.dump = '*ref_' + duplicateIndex;
- } else {
- if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
- state.usedDuplicates[duplicateIndex] = true;
- }
- if (type === '[object Object]') {
- if (block && (Object.keys(state.dump).length !== 0)) {
- writeBlockMapping(state, level, state.dump, compact);
- if (duplicate) {
- state.dump = '&ref_' + duplicateIndex + state.dump;
+ CheckComplete() {
+ if (this.done) {
+ return;
}
- } else {
- writeFlowMapping(state, level, state.dump);
- if (duplicate) {
- state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ if (this.processClosed) {
+ this._setResult();
}
- }
- } else if (type === '[object Array]') {
- if (block && (state.dump.length !== 0)) {
- if (state.noArrayIndent && !isblockseq && level > 0) {
- writeBlockSequence(state, level - 1, state.dump, compact);
- } else {
- writeBlockSequence(state, level, state.dump, compact);
+ else if (this.processExited) {
+ this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this);
}
- if (duplicate) {
- state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ _debug(message) {
+ this.emit('debug', message);
+ }
+ _setResult() {
+ // determine whether there is an error
+ let error;
+ if (this.processExited) {
+ if (this.processError) {
+ error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
+ }
+ else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
+ error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
+ }
+ else if (this.processStderr && this.options.failOnStdErr) {
+ error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
+ }
}
- } else {
- writeFlowSequence(state, level, state.dump);
- if (duplicate) {
- state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ // clear the timeout
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
}
- }
- } else if (type === '[object String]') {
- if (state.tag !== '?') {
- writeScalar(state, state.dump, level, iskey, inblock);
- }
- } else if (type === '[object Undefined]') {
- return false;
- } else {
- if (state.skipInvalid) return false;
- throw new exception('unacceptable kind of an object to dump ' + type);
- }
-
- if (state.tag !== null && state.tag !== '?') {
- // Need to encode all characters except those allowed by the spec:
- //
- // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
- // [36] ns-hex-digit ::= ns-dec-digit
- // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
- // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
- // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
- // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
- // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
- // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
- //
- // Also need to encode '!' because it has special meaning (end of tag prefix).
- //
- tagStr = encodeURI(
- state.tag[0] === '!' ? state.tag.slice(1) : state.tag
- ).replace(/!/g, '%21');
-
- if (state.tag[0] === '!') {
- tagStr = '!' + tagStr;
- } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
- tagStr = '!!' + tagStr.slice(18);
- } else {
- tagStr = '!<' + tagStr + '>';
- }
-
- state.dump = tagStr + ' ' + state.dump;
+ this.done = true;
+ this.emit('done', error, this.processExitCode);
}
- }
-
- return true;
-}
-
-function getDuplicateReferences(object, state) {
- var objects = [],
- duplicatesIndexes = [],
- index,
- length;
-
- inspectNode(object, objects, duplicatesIndexes);
-
- for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
- state.duplicates.push(objects[duplicatesIndexes[index]]);
- }
- state.usedDuplicates = new Array(length);
-}
-
-function inspectNode(object, objects, duplicatesIndexes) {
- var objectKeyList,
- index,
- length;
-
- if (object !== null && typeof object === 'object') {
- index = objects.indexOf(object);
- if (index !== -1) {
- if (duplicatesIndexes.indexOf(index) === -1) {
- duplicatesIndexes.push(index);
- }
- } else {
- objects.push(object);
-
- if (Array.isArray(object)) {
- for (index = 0, length = object.length; index < length; index += 1) {
- inspectNode(object[index], objects, duplicatesIndexes);
+ static HandleTimeout(state) {
+ if (state.done) {
+ return;
}
- } else {
- objectKeyList = Object.keys(object);
-
- for (index = 0, length = objectKeyList.length; index < length; index += 1) {
- inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
+ if (!state.processClosed && state.processExited) {
+ const message = `The STDIO streams did not close within ${state.delay /
+ 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
+ state._debug(message);
}
- }
+ state._setResult();
}
- }
-}
-
-function dump$1(input, options) {
- options = options || {};
-
- var state = new State(options);
-
- if (!state.noRefs) getDuplicateReferences(input, state);
-
- var value = input;
-
- if (state.replacer) {
- value = state.replacer.call({ '': value }, '', value);
- }
-
- if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
-
- return '';
}
+//# sourceMappingURL=toolrunner.js.map
-var dump_1 = dump$1;
+/***/ }),
-var dumper = {
- dump: dump_1
-};
+/***/ 4552:
+/***/ (function(__unused_webpack_module, exports) {
-function renamed(from, to) {
- return function () {
- throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
- 'Use yaml.' + to + ' instead, which is now safe by default.');
- };
-}
-
-
-var Type = type;
-var Schema = schema;
-var FAILSAFE_SCHEMA = failsafe;
-var JSON_SCHEMA = json;
-var CORE_SCHEMA = js_yaml_core;
-var DEFAULT_SCHEMA = _default;
-var load = loader.load;
-var loadAll = loader.loadAll;
-var dump = dumper.dump;
-var YAMLException = exception;
-
-// Re-export all types in case user wants to create custom schema
-var types = {
- binary: binary,
- float: js_yaml_float,
- map: map,
- null: _null,
- pairs: pairs,
- set: set,
- timestamp: timestamp,
- bool: bool,
- int: js_yaml_int,
- merge: merge,
- omap: omap,
- seq: seq,
- str: str
-};
-// Removed functions from JS-YAML 3.0.x
-var safeLoad = renamed('safeLoad', 'load');
-var safeLoadAll = renamed('safeLoadAll', 'loadAll');
-var safeDump = renamed('safeDump', 'dump');
-
-var jsYaml = {
- Type: Type,
- Schema: Schema,
- FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
- JSON_SCHEMA: JSON_SCHEMA,
- CORE_SCHEMA: CORE_SCHEMA,
- DEFAULT_SCHEMA: DEFAULT_SCHEMA,
- load: load,
- loadAll: loadAll,
- dump: dump,
- YAMLException: YAMLException,
- types: types,
- safeLoad: safeLoad,
- safeLoadAll: safeLoadAll,
- safeDump: safeDump
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
};
-
-/* harmony default export */ const js_yaml = (jsYaml);
-
-
-// EXTERNAL MODULE: external "path"
-var external_path_ = __nccwpck_require__(71017);
-// EXTERNAL MODULE: external "util"
-var external_util_ = __nccwpck_require__(73837);
-;// CONCATENATED MODULE: ./lib/readConfig.js
-
-
-
-
-
-
-/**
- * Reads configuration from the provided config file path.
- * If a configuration is also present in the workspace directory,
- * the function merges the two configurations, with the workspace
- * configuration taking precedence.
- *
- * @param config - Path to the configuration file.
- * @param workspace - Path to the workspace directory.
- * @returns A merged configuration object, or an empty object if no configuration is found.
- */
-function readJSONSync(path) {
- const data = external_fs_.readFileSync(path, 'utf-8');
- const ext = path.split('.').pop()?.toLowerCase();
- if (ext === 'json') {
- return JSON.parse(data);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;
+class BasicCredentialHandler {
+ constructor(username, password) {
+ this.username = username;
+ this.password = password;
}
- else if (ext === 'yaml' || ext === 'yml') {
- return js_yaml.load(data);
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
}
- else {
- throw new Error(`Unsupported file extension: ${ext}`);
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
}
}
-/**
- * Custom array merge function to remove duplicates.
- *
- * @param source - Source array.
- * @param target - Target array.
- * @returns Merged array with duplicates removed.
- */
-function arrayMergeDedupe(source, target) {
- return Array.from(new Set([...source, ...target]));
-}
-function readConfig(defaultOptions, mainConfigPath, workspace, defaultConfigName) {
- const configFile = (0,external_path_.resolve)(mainConfigPath || defaultConfigName);
- const configFilename = configFile.split('/').pop();
- const workspaceConfig = (0,external_path_.resolve)(workspace, configFilename || defaultConfigName);
- const configExists = external_fs_.existsSync(configFile);
- const workspaceConfigExists = workspaceConfig !== configFile && external_fs_.existsSync(workspaceConfig);
- let resultData = defaultOptions || {};
- if (configExists) {
- resultData = cjs_default()(resultData, readJSONSync(configFile), { arrayMerge: arrayMergeDedupe });
+exports.BasicCredentialHandler = BasicCredentialHandler;
+class BearerCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Bearer ${this.token}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
}
- if (workspaceConfigExists) {
- resultData = cjs_default()(resultData, readJSONSync(workspaceConfig), { arrayMerge: arrayMergeDedupe });
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
}
- core.startGroup('🔎 Dotnet Format Config');
- core.info(`${(0,external_util_.inspect)(resultData)}`);
- core.endGroup();
- return resultData;
}
-
-
-/***/ }),
-
-/***/ 52605:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-var __webpack_unused_export__;
-
-__webpack_unused_export__ = ({ value: true });
-exports.U = void 0;
-const artifact_client_1 = __nccwpck_require__(48802);
-/**
- * Constructs an ArtifactClient
- */
-function create() {
- return artifact_client_1.DefaultArtifactClient.create();
+exports.BearerCredentialHandler = BearerCredentialHandler;
+class PersonalAccessTokenCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
}
-exports.U = create;
-//# sourceMappingURL=artifact-client.js.map
+exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
+//# sourceMappingURL=auth.js.map
/***/ }),
-/***/ 48802:
+/***/ 4844:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-"use strict";
+/* eslint-disable @typescript-eslint/no-explicit-any */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -4950,1222 +1965,725 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DefaultArtifactClient = void 0;
-const core = __importStar(__nccwpck_require__(42186));
-const upload_specification_1 = __nccwpck_require__(10183);
-const upload_http_client_1 = __nccwpck_require__(74354);
-const utils_1 = __nccwpck_require__(36327);
-const path_and_artifact_name_validation_1 = __nccwpck_require__(87398);
-const download_http_client_1 = __nccwpck_require__(8538);
-const download_specification_1 = __nccwpck_require__(95686);
-const config_variables_1 = __nccwpck_require__(42222);
-const path_1 = __nccwpck_require__(71017);
-class DefaultArtifactClient {
- /**
- * Constructs a DefaultArtifactClient
- */
- static create() {
- return new DefaultArtifactClient();
- }
- /**
- * Uploads an artifact
- */
- uploadArtifact(name, files, rootDirectory, options) {
- return __awaiter(this, void 0, void 0, function* () {
- core.info(`Starting artifact upload
-For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`);
- (0, path_and_artifact_name_validation_1.checkArtifactName)(name);
- // Get specification for the files being uploaded
- const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files);
- const uploadResponse = {
- artifactName: name,
- artifactItems: [],
- size: 0,
- failedItems: []
- };
- const uploadHttpClient = new upload_http_client_1.UploadHttpClient();
- if (uploadSpecification.length === 0) {
- core.warning(`No files found that can be uploaded`);
- }
- else {
- // Create an entry for the artifact in the file container
- const response = yield uploadHttpClient.createArtifactInFileContainer(name, options);
- if (!response.fileContainerResourceUrl) {
- core.debug(response.toString());
- throw new Error('No URL provided by the Artifact Service to upload an artifact to');
- }
- core.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`);
- core.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`);
- // Upload each of the files that were found concurrently
- const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options);
- // Update the size of the artifact to indicate we are done uploading
- // The uncompressed size is used for display when downloading a zip of the artifact from the UI
- core.info(`File upload process has finished. Finalizing the artifact upload`);
- yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name);
- if (uploadResult.failedItems.length > 0) {
- core.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`);
- }
- else {
- core.info(`Artifact has been finalized. All files have been successfully uploaded!`);
- }
- core.info(`
-The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes
-The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage
-
-Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r\n`);
- uploadResponse.artifactItems = uploadSpecification.map(item => item.absoluteFilePath);
- uploadResponse.size = uploadResult.uploadSize;
- uploadResponse.failedItems = uploadResult.failedItems;
- }
- return uploadResponse;
- });
- }
- downloadArtifact(name, path, options) {
- return __awaiter(this, void 0, void 0, function* () {
- const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
- const artifacts = yield downloadHttpClient.listArtifacts();
- if (artifacts.count === 0) {
- throw new Error(`Unable to find any artifacts for the associated workflow`);
- }
- const artifactToDownload = artifacts.value.find(artifact => {
- return artifact.name === name;
- });
- if (!artifactToDownload) {
- throw new Error(`Unable to find an artifact with the name: ${name}`);
- }
- const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl);
- if (!path) {
- path = (0, config_variables_1.getWorkSpaceDirectory)();
- }
- path = (0, path_1.normalize)(path);
- path = (0, path_1.resolve)(path);
- // During upload, empty directories are rejected by the remote server so there should be no artifacts that consist of only empty directories
- const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false);
- if (downloadSpecification.filesToDownload.length === 0) {
- core.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`);
- }
- else {
- // Create all necessary directories recursively before starting any download
- yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
- core.info('Directory structure has been set up for the artifact');
- yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
- yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
- }
- return {
- artifactName: name,
- downloadPath: downloadSpecification.rootDownloadLocation
- };
- });
- }
- downloadAllArtifacts(path) {
- return __awaiter(this, void 0, void 0, function* () {
- const downloadHttpClient = new download_http_client_1.DownloadHttpClient();
- const response = [];
- const artifacts = yield downloadHttpClient.listArtifacts();
- if (artifacts.count === 0) {
- core.info('Unable to find any artifacts for the associated workflow');
- return response;
- }
- if (!path) {
- path = (0, config_variables_1.getWorkSpaceDirectory)();
- }
- path = (0, path_1.normalize)(path);
- path = (0, path_1.resolve)(path);
- let downloadedArtifacts = 0;
- while (downloadedArtifacts < artifacts.count) {
- const currentArtifactToDownload = artifacts.value[downloadedArtifacts];
- downloadedArtifacts += 1;
- core.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`);
- // Get container entries for the specific artifact
- const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl);
- const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path, true);
- if (downloadSpecification.filesToDownload.length === 0) {
- core.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`);
- }
- else {
- yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure);
- yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate);
- yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload);
- }
- response.push({
- artifactName: currentArtifactToDownload.name,
- downloadPath: downloadSpecification.rootDownloadLocation
- });
- }
- return response;
- });
- }
-}
-exports.DefaultArtifactClient = DefaultArtifactClient;
-//# sourceMappingURL=artifact-client.js.map
-
-/***/ }),
-
-/***/ 42222:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isGhes = exports.getRetentionDays = exports.getWorkSpaceDirectory = exports.getWorkFlowRunId = exports.getRuntimeUrl = exports.getRuntimeToken = exports.getDownloadFileConcurrency = exports.getInitialRetryIntervalInMilliseconds = exports.getRetryMultiplier = exports.getRetryLimit = exports.getUploadChunkSize = exports.getUploadFileConcurrency = void 0;
-// The number of concurrent uploads that happens at the same time
-function getUploadFileConcurrency() {
- return 2;
-}
-exports.getUploadFileConcurrency = getUploadFileConcurrency;
-// When uploading large files that can't be uploaded with a single http call, this controls
-// the chunk size that is used during upload
-function getUploadChunkSize() {
- return 8 * 1024 * 1024; // 8 MB Chunks
-}
-exports.getUploadChunkSize = getUploadChunkSize;
-// The maximum number of retries that can be attempted before an upload or download fails
-function getRetryLimit() {
- return 5;
-}
-exports.getRetryLimit = getRetryLimit;
-// With exponential backoff, the larger the retry count, the larger the wait time before another attempt
-// The retry multiplier controls by how much the backOff time increases depending on the number of retries
-function getRetryMultiplier() {
- return 1.5;
-}
-exports.getRetryMultiplier = getRetryMultiplier;
-// The initial wait time if an upload or download fails and a retry is being attempted for the first time
-function getInitialRetryIntervalInMilliseconds() {
- return 3000;
-}
-exports.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds;
-// The number of concurrent downloads that happens at the same time
-function getDownloadFileConcurrency() {
- return 2;
-}
-exports.getDownloadFileConcurrency = getDownloadFileConcurrency;
-function getRuntimeToken() {
- const token = process.env['ACTIONS_RUNTIME_TOKEN'];
- if (!token) {
- throw new Error('Unable to get ACTIONS_RUNTIME_TOKEN env variable');
- }
- return token;
-}
-exports.getRuntimeToken = getRuntimeToken;
-function getRuntimeUrl() {
- const runtimeUrl = process.env['ACTIONS_RUNTIME_URL'];
- if (!runtimeUrl) {
- throw new Error('Unable to get ACTIONS_RUNTIME_URL env variable');
- }
- return runtimeUrl;
-}
-exports.getRuntimeUrl = getRuntimeUrl;
-function getWorkFlowRunId() {
- const workFlowRunId = process.env['GITHUB_RUN_ID'];
- if (!workFlowRunId) {
- throw new Error('Unable to get GITHUB_RUN_ID env variable');
- }
- return workFlowRunId;
-}
-exports.getWorkFlowRunId = getWorkFlowRunId;
-function getWorkSpaceDirectory() {
- const workspaceDirectory = process.env['GITHUB_WORKSPACE'];
- if (!workspaceDirectory) {
- throw new Error('Unable to get GITHUB_WORKSPACE env variable');
- }
- return workspaceDirectory;
-}
-exports.getWorkSpaceDirectory = getWorkSpaceDirectory;
-function getRetentionDays() {
- return process.env['GITHUB_RETENTION_DAYS'];
-}
-exports.getRetentionDays = getRetentionDays;
-function isGhes() {
- const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
- return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM';
-}
-exports.isGhes = isGhes;
-//# sourceMappingURL=config-variables.js.map
-
-/***/ }),
-
-/***/ 23549:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
+exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
+const http = __importStar(__nccwpck_require__(8611));
+const https = __importStar(__nccwpck_require__(5692));
+const pm = __importStar(__nccwpck_require__(4988));
+const tunnel = __importStar(__nccwpck_require__(770));
+const undici_1 = __nccwpck_require__(6752);
+var HttpCodes;
+(function (HttpCodes) {
+ HttpCodes[HttpCodes["OK"] = 200] = "OK";
+ HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
+ HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
+ HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
+ HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
+ HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
+ HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
+ HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
+ HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+ HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
+ HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
+ HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
+ HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
+ HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
+ HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
+ HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+ HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
+ HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+ HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
+ HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
+ HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
+ HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
+ HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
+ HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
+ HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
+ HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+ HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
+})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));
+var Headers;
+(function (Headers) {
+ Headers["Accept"] = "accept";
+ Headers["ContentType"] = "content-type";
+})(Headers || (exports.Headers = Headers = {}));
+var MediaTypes;
+(function (MediaTypes) {
+ MediaTypes["ApplicationJson"] = "application/json";
+})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));
/**
- * CRC64: cyclic redundancy check, 64-bits
- *
- * In order to validate that artifacts are not being corrupted over the wire, this redundancy check allows us to
- * validate that there was no corruption during transmission. The implementation here is based on Go's hash/crc64 pkg,
- * but without the slicing-by-8 optimization: https://cs.opensource.google/go/go/+/master:src/hash/crc64/crc64.go
- *
- * This implementation uses a pregenerated table based on 0x9A6C9329AC4BC9B5 as the polynomial, the same polynomial that
- * is used for Azure Storage: https://github.com/Azure/azure-storage-net/blob/cbe605f9faa01bfc3003d75fc5a16b2eaccfe102/Lib/Common/Core/Util/Crc64.cs#L27
+ * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-// when transpile target is >= ES2020 (after dropping node 12) these can be changed to bigint literals - ts(2737)
-const PREGEN_POLY_TABLE = [
- BigInt('0x0000000000000000'),
- BigInt('0x7F6EF0C830358979'),
- BigInt('0xFEDDE190606B12F2'),
- BigInt('0x81B31158505E9B8B'),
- BigInt('0xC962E5739841B68F'),
- BigInt('0xB60C15BBA8743FF6'),
- BigInt('0x37BF04E3F82AA47D'),
- BigInt('0x48D1F42BC81F2D04'),
- BigInt('0xA61CECB46814FE75'),
- BigInt('0xD9721C7C5821770C'),
- BigInt('0x58C10D24087FEC87'),
- BigInt('0x27AFFDEC384A65FE'),
- BigInt('0x6F7E09C7F05548FA'),
- BigInt('0x1010F90FC060C183'),
- BigInt('0x91A3E857903E5A08'),
- BigInt('0xEECD189FA00BD371'),
- BigInt('0x78E0FF3B88BE6F81'),
- BigInt('0x078E0FF3B88BE6F8'),
- BigInt('0x863D1EABE8D57D73'),
- BigInt('0xF953EE63D8E0F40A'),
- BigInt('0xB1821A4810FFD90E'),
- BigInt('0xCEECEA8020CA5077'),
- BigInt('0x4F5FFBD87094CBFC'),
- BigInt('0x30310B1040A14285'),
- BigInt('0xDEFC138FE0AA91F4'),
- BigInt('0xA192E347D09F188D'),
- BigInt('0x2021F21F80C18306'),
- BigInt('0x5F4F02D7B0F40A7F'),
- BigInt('0x179EF6FC78EB277B'),
- BigInt('0x68F0063448DEAE02'),
- BigInt('0xE943176C18803589'),
- BigInt('0x962DE7A428B5BCF0'),
- BigInt('0xF1C1FE77117CDF02'),
- BigInt('0x8EAF0EBF2149567B'),
- BigInt('0x0F1C1FE77117CDF0'),
- BigInt('0x7072EF2F41224489'),
- BigInt('0x38A31B04893D698D'),
- BigInt('0x47CDEBCCB908E0F4'),
- BigInt('0xC67EFA94E9567B7F'),
- BigInt('0xB9100A5CD963F206'),
- BigInt('0x57DD12C379682177'),
- BigInt('0x28B3E20B495DA80E'),
- BigInt('0xA900F35319033385'),
- BigInt('0xD66E039B2936BAFC'),
- BigInt('0x9EBFF7B0E12997F8'),
- BigInt('0xE1D10778D11C1E81'),
- BigInt('0x606216208142850A'),
- BigInt('0x1F0CE6E8B1770C73'),
- BigInt('0x8921014C99C2B083'),
- BigInt('0xF64FF184A9F739FA'),
- BigInt('0x77FCE0DCF9A9A271'),
- BigInt('0x08921014C99C2B08'),
- BigInt('0x4043E43F0183060C'),
- BigInt('0x3F2D14F731B68F75'),
- BigInt('0xBE9E05AF61E814FE'),
- BigInt('0xC1F0F56751DD9D87'),
- BigInt('0x2F3DEDF8F1D64EF6'),
- BigInt('0x50531D30C1E3C78F'),
- BigInt('0xD1E00C6891BD5C04'),
- BigInt('0xAE8EFCA0A188D57D'),
- BigInt('0xE65F088B6997F879'),
- BigInt('0x9931F84359A27100'),
- BigInt('0x1882E91B09FCEA8B'),
- BigInt('0x67EC19D339C963F2'),
- BigInt('0xD75ADABD7A6E2D6F'),
- BigInt('0xA8342A754A5BA416'),
- BigInt('0x29873B2D1A053F9D'),
- BigInt('0x56E9CBE52A30B6E4'),
- BigInt('0x1E383FCEE22F9BE0'),
- BigInt('0x6156CF06D21A1299'),
- BigInt('0xE0E5DE5E82448912'),
- BigInt('0x9F8B2E96B271006B'),
- BigInt('0x71463609127AD31A'),
- BigInt('0x0E28C6C1224F5A63'),
- BigInt('0x8F9BD7997211C1E8'),
- BigInt('0xF0F5275142244891'),
- BigInt('0xB824D37A8A3B6595'),
- BigInt('0xC74A23B2BA0EECEC'),
- BigInt('0x46F932EAEA507767'),
- BigInt('0x3997C222DA65FE1E'),
- BigInt('0xAFBA2586F2D042EE'),
- BigInt('0xD0D4D54EC2E5CB97'),
- BigInt('0x5167C41692BB501C'),
- BigInt('0x2E0934DEA28ED965'),
- BigInt('0x66D8C0F56A91F461'),
- BigInt('0x19B6303D5AA47D18'),
- BigInt('0x980521650AFAE693'),
- BigInt('0xE76BD1AD3ACF6FEA'),
- BigInt('0x09A6C9329AC4BC9B'),
- BigInt('0x76C839FAAAF135E2'),
- BigInt('0xF77B28A2FAAFAE69'),
- BigInt('0x8815D86ACA9A2710'),
- BigInt('0xC0C42C4102850A14'),
- BigInt('0xBFAADC8932B0836D'),
- BigInt('0x3E19CDD162EE18E6'),
- BigInt('0x41773D1952DB919F'),
- BigInt('0x269B24CA6B12F26D'),
- BigInt('0x59F5D4025B277B14'),
- BigInt('0xD846C55A0B79E09F'),
- BigInt('0xA72835923B4C69E6'),
- BigInt('0xEFF9C1B9F35344E2'),
- BigInt('0x90973171C366CD9B'),
- BigInt('0x1124202993385610'),
- BigInt('0x6E4AD0E1A30DDF69'),
- BigInt('0x8087C87E03060C18'),
- BigInt('0xFFE938B633338561'),
- BigInt('0x7E5A29EE636D1EEA'),
- BigInt('0x0134D92653589793'),
- BigInt('0x49E52D0D9B47BA97'),
- BigInt('0x368BDDC5AB7233EE'),
- BigInt('0xB738CC9DFB2CA865'),
- BigInt('0xC8563C55CB19211C'),
- BigInt('0x5E7BDBF1E3AC9DEC'),
- BigInt('0x21152B39D3991495'),
- BigInt('0xA0A63A6183C78F1E'),
- BigInt('0xDFC8CAA9B3F20667'),
- BigInt('0x97193E827BED2B63'),
- BigInt('0xE877CE4A4BD8A21A'),
- BigInt('0x69C4DF121B863991'),
- BigInt('0x16AA2FDA2BB3B0E8'),
- BigInt('0xF86737458BB86399'),
- BigInt('0x8709C78DBB8DEAE0'),
- BigInt('0x06BAD6D5EBD3716B'),
- BigInt('0x79D4261DDBE6F812'),
- BigInt('0x3105D23613F9D516'),
- BigInt('0x4E6B22FE23CC5C6F'),
- BigInt('0xCFD833A67392C7E4'),
- BigInt('0xB0B6C36E43A74E9D'),
- BigInt('0x9A6C9329AC4BC9B5'),
- BigInt('0xE50263E19C7E40CC'),
- BigInt('0x64B172B9CC20DB47'),
- BigInt('0x1BDF8271FC15523E'),
- BigInt('0x530E765A340A7F3A'),
- BigInt('0x2C608692043FF643'),
- BigInt('0xADD397CA54616DC8'),
- BigInt('0xD2BD67026454E4B1'),
- BigInt('0x3C707F9DC45F37C0'),
- BigInt('0x431E8F55F46ABEB9'),
- BigInt('0xC2AD9E0DA4342532'),
- BigInt('0xBDC36EC59401AC4B'),
- BigInt('0xF5129AEE5C1E814F'),
- BigInt('0x8A7C6A266C2B0836'),
- BigInt('0x0BCF7B7E3C7593BD'),
- BigInt('0x74A18BB60C401AC4'),
- BigInt('0xE28C6C1224F5A634'),
- BigInt('0x9DE29CDA14C02F4D'),
- BigInt('0x1C518D82449EB4C6'),
- BigInt('0x633F7D4A74AB3DBF'),
- BigInt('0x2BEE8961BCB410BB'),
- BigInt('0x548079A98C8199C2'),
- BigInt('0xD53368F1DCDF0249'),
- BigInt('0xAA5D9839ECEA8B30'),
- BigInt('0x449080A64CE15841'),
- BigInt('0x3BFE706E7CD4D138'),
- BigInt('0xBA4D61362C8A4AB3'),
- BigInt('0xC52391FE1CBFC3CA'),
- BigInt('0x8DF265D5D4A0EECE'),
- BigInt('0xF29C951DE49567B7'),
- BigInt('0x732F8445B4CBFC3C'),
- BigInt('0x0C41748D84FE7545'),
- BigInt('0x6BAD6D5EBD3716B7'),
- BigInt('0x14C39D968D029FCE'),
- BigInt('0x95708CCEDD5C0445'),
- BigInt('0xEA1E7C06ED698D3C'),
- BigInt('0xA2CF882D2576A038'),
- BigInt('0xDDA178E515432941'),
- BigInt('0x5C1269BD451DB2CA'),
- BigInt('0x237C997575283BB3'),
- BigInt('0xCDB181EAD523E8C2'),
- BigInt('0xB2DF7122E51661BB'),
- BigInt('0x336C607AB548FA30'),
- BigInt('0x4C0290B2857D7349'),
- BigInt('0x04D364994D625E4D'),
- BigInt('0x7BBD94517D57D734'),
- BigInt('0xFA0E85092D094CBF'),
- BigInt('0x856075C11D3CC5C6'),
- BigInt('0x134D926535897936'),
- BigInt('0x6C2362AD05BCF04F'),
- BigInt('0xED9073F555E26BC4'),
- BigInt('0x92FE833D65D7E2BD'),
- BigInt('0xDA2F7716ADC8CFB9'),
- BigInt('0xA54187DE9DFD46C0'),
- BigInt('0x24F29686CDA3DD4B'),
- BigInt('0x5B9C664EFD965432'),
- BigInt('0xB5517ED15D9D8743'),
- BigInt('0xCA3F8E196DA80E3A'),
- BigInt('0x4B8C9F413DF695B1'),
- BigInt('0x34E26F890DC31CC8'),
- BigInt('0x7C339BA2C5DC31CC'),
- BigInt('0x035D6B6AF5E9B8B5'),
- BigInt('0x82EE7A32A5B7233E'),
- BigInt('0xFD808AFA9582AA47'),
- BigInt('0x4D364994D625E4DA'),
- BigInt('0x3258B95CE6106DA3'),
- BigInt('0xB3EBA804B64EF628'),
- BigInt('0xCC8558CC867B7F51'),
- BigInt('0x8454ACE74E645255'),
- BigInt('0xFB3A5C2F7E51DB2C'),
- BigInt('0x7A894D772E0F40A7'),
- BigInt('0x05E7BDBF1E3AC9DE'),
- BigInt('0xEB2AA520BE311AAF'),
- BigInt('0x944455E88E0493D6'),
- BigInt('0x15F744B0DE5A085D'),
- BigInt('0x6A99B478EE6F8124'),
- BigInt('0x224840532670AC20'),
- BigInt('0x5D26B09B16452559'),
- BigInt('0xDC95A1C3461BBED2'),
- BigInt('0xA3FB510B762E37AB'),
- BigInt('0x35D6B6AF5E9B8B5B'),
- BigInt('0x4AB846676EAE0222'),
- BigInt('0xCB0B573F3EF099A9'),
- BigInt('0xB465A7F70EC510D0'),
- BigInt('0xFCB453DCC6DA3DD4'),
- BigInt('0x83DAA314F6EFB4AD'),
- BigInt('0x0269B24CA6B12F26'),
- BigInt('0x7D0742849684A65F'),
- BigInt('0x93CA5A1B368F752E'),
- BigInt('0xECA4AAD306BAFC57'),
- BigInt('0x6D17BB8B56E467DC'),
- BigInt('0x12794B4366D1EEA5'),
- BigInt('0x5AA8BF68AECEC3A1'),
- BigInt('0x25C64FA09EFB4AD8'),
- BigInt('0xA4755EF8CEA5D153'),
- BigInt('0xDB1BAE30FE90582A'),
- BigInt('0xBCF7B7E3C7593BD8'),
- BigInt('0xC399472BF76CB2A1'),
- BigInt('0x422A5673A732292A'),
- BigInt('0x3D44A6BB9707A053'),
- BigInt('0x759552905F188D57'),
- BigInt('0x0AFBA2586F2D042E'),
- BigInt('0x8B48B3003F739FA5'),
- BigInt('0xF42643C80F4616DC'),
- BigInt('0x1AEB5B57AF4DC5AD'),
- BigInt('0x6585AB9F9F784CD4'),
- BigInt('0xE436BAC7CF26D75F'),
- BigInt('0x9B584A0FFF135E26'),
- BigInt('0xD389BE24370C7322'),
- BigInt('0xACE74EEC0739FA5B'),
- BigInt('0x2D545FB4576761D0'),
- BigInt('0x523AAF7C6752E8A9'),
- BigInt('0xC41748D84FE75459'),
- BigInt('0xBB79B8107FD2DD20'),
- BigInt('0x3ACAA9482F8C46AB'),
- BigInt('0x45A459801FB9CFD2'),
- BigInt('0x0D75ADABD7A6E2D6'),
- BigInt('0x721B5D63E7936BAF'),
- BigInt('0xF3A84C3BB7CDF024'),
- BigInt('0x8CC6BCF387F8795D'),
- BigInt('0x620BA46C27F3AA2C'),
- BigInt('0x1D6554A417C62355'),
- BigInt('0x9CD645FC4798B8DE'),
- BigInt('0xE3B8B53477AD31A7'),
- BigInt('0xAB69411FBFB21CA3'),
- BigInt('0xD407B1D78F8795DA'),
- BigInt('0x55B4A08FDFD90E51'),
- BigInt('0x2ADA5047EFEC8728')
+function getProxyUrl(serverUrl) {
+ const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+ return proxyUrl ? proxyUrl.href : '';
+}
+exports.getProxyUrl = getProxyUrl;
+const HttpRedirectCodes = [
+ HttpCodes.MovedPermanently,
+ HttpCodes.ResourceMoved,
+ HttpCodes.SeeOther,
+ HttpCodes.TemporaryRedirect,
+ HttpCodes.PermanentRedirect
];
-class CRC64 {
- constructor() {
- this._crc = BigInt(0);
- }
- update(data) {
- const buffer = typeof data === 'string' ? Buffer.from(data) : data;
- let crc = CRC64.flip64Bits(this._crc);
- for (const dataByte of buffer) {
- const crcByte = Number(crc & BigInt(0xff));
- crc = PREGEN_POLY_TABLE[crcByte ^ dataByte] ^ (crc >> BigInt(8));
- }
- this._crc = CRC64.flip64Bits(crc);
- }
- digest(encoding) {
- switch (encoding) {
- case 'hex':
- return this._crc.toString(16).toUpperCase();
- case 'base64':
- return this.toBuffer().toString('base64');
- default:
- return this.toBuffer();
- }
+const HttpResponseRetryCodes = [
+ HttpCodes.BadGateway,
+ HttpCodes.ServiceUnavailable,
+ HttpCodes.GatewayTimeout
+];
+const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
+const ExponentialBackoffCeiling = 10;
+const ExponentialBackoffTimeSlice = 5;
+class HttpClientError extends Error {
+ constructor(message, statusCode) {
+ super(message);
+ this.name = 'HttpClientError';
+ this.statusCode = statusCode;
+ Object.setPrototypeOf(this, HttpClientError.prototype);
}
- toBuffer() {
- return Buffer.from([0, 8, 16, 24, 32, 40, 48, 56].map(s => Number((this._crc >> BigInt(s)) & BigInt(0xff))));
+}
+exports.HttpClientError = HttpClientError;
+class HttpClientResponse {
+ constructor(message) {
+ this.message = message;
+ }
+ readBody() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ let output = Buffer.alloc(0);
+ this.message.on('data', (chunk) => {
+ output = Buffer.concat([output, chunk]);
+ });
+ this.message.on('end', () => {
+ resolve(output.toString());
+ });
+ }));
+ });
}
- static flip64Bits(n) {
- return (BigInt(1) << BigInt(64)) - BigInt(1) - n;
+ readBodyBuffer() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ const chunks = [];
+ this.message.on('data', (chunk) => {
+ chunks.push(chunk);
+ });
+ this.message.on('end', () => {
+ resolve(Buffer.concat(chunks));
+ });
+ }));
+ });
}
}
-exports["default"] = CRC64;
-//# sourceMappingURL=crc64.js.map
-
-/***/ }),
-
-/***/ 8538:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+exports.HttpClientResponse = HttpClientResponse;
+function isHttps(requestUrl) {
+ const parsedUrl = new URL(requestUrl);
+ return parsedUrl.protocol === 'https:';
+}
+exports.isHttps = isHttps;
+class HttpClient {
+ constructor(userAgent, handlers, requestOptions) {
+ this._ignoreSslError = false;
+ this._allowRedirects = true;
+ this._allowRedirectDowngrade = false;
+ this._maxRedirects = 50;
+ this._allowRetries = false;
+ this._maxRetries = 1;
+ this._keepAlive = false;
+ this._disposed = false;
+ this.userAgent = userAgent;
+ this.handlers = handlers || [];
+ this.requestOptions = requestOptions;
+ if (requestOptions) {
+ if (requestOptions.ignoreSslError != null) {
+ this._ignoreSslError = requestOptions.ignoreSslError;
+ }
+ this._socketTimeout = requestOptions.socketTimeout;
+ if (requestOptions.allowRedirects != null) {
+ this._allowRedirects = requestOptions.allowRedirects;
+ }
+ if (requestOptions.allowRedirectDowngrade != null) {
+ this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+ }
+ if (requestOptions.maxRedirects != null) {
+ this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+ }
+ if (requestOptions.keepAlive != null) {
+ this._keepAlive = requestOptions.keepAlive;
+ }
+ if (requestOptions.allowRetries != null) {
+ this._allowRetries = requestOptions.allowRetries;
+ }
+ if (requestOptions.maxRetries != null) {
+ this._maxRetries = requestOptions.maxRetries;
+ }
+ }
}
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DownloadHttpClient = void 0;
-const fs = __importStar(__nccwpck_require__(57147));
-const core = __importStar(__nccwpck_require__(42186));
-const zlib = __importStar(__nccwpck_require__(59796));
-const utils_1 = __nccwpck_require__(36327);
-const url_1 = __nccwpck_require__(57310);
-const status_reporter_1 = __nccwpck_require__(39081);
-const perf_hooks_1 = __nccwpck_require__(4074);
-const http_manager_1 = __nccwpck_require__(16527);
-const config_variables_1 = __nccwpck_require__(42222);
-const requestUtils_1 = __nccwpck_require__(90755);
-class DownloadHttpClient {
- constructor() {
- this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), '@actions/artifact-download');
- // downloads are usually significantly faster than uploads so display status information every second
- this.statusReporter = new status_reporter_1.StatusReporter(1000);
+ options(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
+ });
}
- /**
- * Gets a list of all artifacts that are in a specific container
- */
- listArtifacts() {
+ get(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('GET', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ del(requestUrl, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
- const artifactUrl = (0, utils_1.getArtifactUrl)();
- // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately
- const client = this.downloadHttpManager.getClient(0);
- const headers = (0, utils_1.getDownloadHeaders)('application/json');
- const response = yield (0, requestUtils_1.retryHttpClientRequest)('List Artifacts', () => __awaiter(this, void 0, void 0, function* () { return client.get(artifactUrl, headers); }));
- const body = yield response.readBody();
- return JSON.parse(body);
+ return this.request('DELETE', requestUrl, null, additionalHeaders || {});
});
}
- /**
- * Fetches a set of container items that describe the contents of an artifact
- * @param artifactName the name of the artifact
- * @param containerUrl the artifact container URL for the run
- */
- getContainerItems(artifactName, containerUrl) {
+ post(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('POST', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ patch(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PATCH', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ put(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PUT', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ head(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('HEAD', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ sendStream(verb, requestUrl, stream, additionalHeaders) {
return __awaiter(this, void 0, void 0, function* () {
- // the itemPath search parameter controls which containers will be returned
- const resourceUrl = new url_1.URL(containerUrl);
- resourceUrl.searchParams.append('itemPath', artifactName);
- // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately
- const client = this.downloadHttpManager.getClient(0);
- const headers = (0, utils_1.getDownloadHeaders)('application/json');
- const response = yield (0, requestUtils_1.retryHttpClientRequest)('Get Container Items', () => __awaiter(this, void 0, void 0, function* () { return client.get(resourceUrl.toString(), headers); }));
- const body = yield response.readBody();
- return JSON.parse(body);
+ return this.request(verb, requestUrl, stream, additionalHeaders);
});
}
/**
- * Concurrently downloads all the files that are part of an artifact
- * @param downloadItems information about what items to download and where to save them
+ * Gets a typed object from an endpoint
+ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
- downloadSingleArtifact(downloadItems) {
+ getJson(requestUrl, additionalHeaders = {}) {
return __awaiter(this, void 0, void 0, function* () {
- const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)();
- // limit the number of files downloaded at a single time
- core.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`);
- const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()];
- let currentFile = 0;
- let downloadedFiles = 0;
- core.info(`Total number of files that will be downloaded: ${downloadItems.length}`);
- this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length);
- this.statusReporter.start();
- yield Promise.all(parallelDownloads.map((index) => __awaiter(this, void 0, void 0, function* () {
- while (currentFile < downloadItems.length) {
- const currentFileToDownload = downloadItems[currentFile];
- currentFile += 1;
- const startTime = perf_hooks_1.performance.now();
- yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath);
- if (core.isDebug()) {
- core.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`);
- }
- this.statusReporter.incrementProcessedCount();
- }
- })))
- .catch(error => {
- throw new Error(`Unable to download the artifact: ${error}`);
- })
- .finally(() => {
- this.statusReporter.stop();
- // safety dispose all connections
- this.downloadHttpManager.disposeAndReplaceAllClients();
- });
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ const res = yield this.get(requestUrl, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ postJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.post(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ putJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.put(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ patchJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.patch(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
});
}
/**
- * Downloads an individual file
- * @param httpClientIndex the index of the http client that is used to make all of the calls
- * @param artifactLocation origin location where a file will be downloaded from
- * @param downloadPath destination location for the file being downloaded
+ * Makes a raw http request.
+ * All other methods such as get, post, patch, and request ultimately call this.
+ * Prefer get, del, post and patch
*/
- downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) {
+ request(verb, requestUrl, data, headers) {
return __awaiter(this, void 0, void 0, function* () {
- let retryCount = 0;
- const retryLimit = (0, config_variables_1.getRetryLimit)();
- let destinationStream = fs.createWriteStream(downloadPath);
- const headers = (0, utils_1.getDownloadHeaders)('application/json', true, true);
- // a single GET request is used to download a file
- const makeDownloadRequest = () => __awaiter(this, void 0, void 0, function* () {
- const client = this.downloadHttpManager.getClient(httpClientIndex);
- return yield client.get(artifactLocation, headers);
- });
- // check the response headers to determine if the file was compressed using gzip
- const isGzip = (incomingHeaders) => {
- return ('content-encoding' in incomingHeaders &&
- incomingHeaders['content-encoding'] === 'gzip');
- };
- // Increments the current retry count and then checks if the retry limit has been reached
- // If there have been too many retries, fail so the download stops. If there is a retryAfterValue value provided,
- // it will be used
- const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () {
- retryCount++;
- if (retryCount > retryLimit) {
- return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`));
- }
- else {
- this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex);
- if (retryAfterValue) {
- // Back off by waiting the specified time denoted by the retry-after header
- core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`);
- yield (0, utils_1.sleep)(retryAfterValue);
+ if (this._disposed) {
+ throw new Error('Client has already been disposed.');
+ }
+ const parsedUrl = new URL(requestUrl);
+ let info = this._prepareRequest(verb, parsedUrl, headers);
+ // Only perform retries on reads since writes may not be idempotent.
+ const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
+ ? this._maxRetries + 1
+ : 1;
+ let numTries = 0;
+ let response;
+ do {
+ response = yield this.requestRaw(info, data);
+ // Check if it's an authentication challenge
+ if (response &&
+ response.message &&
+ response.message.statusCode === HttpCodes.Unauthorized) {
+ let authenticationHandler;
+ for (const handler of this.handlers) {
+ if (handler.canHandleAuthentication(response)) {
+ authenticationHandler = handler;
+ break;
+ }
+ }
+ if (authenticationHandler) {
+ return authenticationHandler.handleAuthentication(this, info, data);
}
else {
- // Back off using an exponential value that depends on the retry count
- const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
- core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`);
- yield (0, utils_1.sleep)(backoffTime);
+ // We have received an unauthorized response but have no handlers to handle it.
+ // Let the response return to the caller.
+ return response;
}
- core.info(`Finished backoff for retry #${retryCount}, continuing with download`);
}
- });
- const isAllBytesReceived = (expected, received) => {
- // be lenient, if any input is missing, assume success, i.e. not truncated
- if (!expected ||
- !received ||
- process.env['ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION']) {
- core.info('Skipping download validation.');
- return true;
- }
- return parseInt(expected) === received;
- };
- const resetDestinationStream = (fileDownloadPath) => __awaiter(this, void 0, void 0, function* () {
- destinationStream.close();
- // await until file is created at downloadpath; node15 and up fs.createWriteStream had not created a file yet
- yield new Promise(resolve => {
- destinationStream.on('close', resolve);
- if (destinationStream.writableFinished) {
- resolve();
+ let redirectsRemaining = this._maxRedirects;
+ while (response.message.statusCode &&
+ HttpRedirectCodes.includes(response.message.statusCode) &&
+ this._allowRedirects &&
+ redirectsRemaining > 0) {
+ const redirectUrl = response.message.headers['location'];
+ if (!redirectUrl) {
+ // if there's no location to redirect to, we won't
+ break;
}
- });
- yield (0, utils_1.rmFile)(fileDownloadPath);
- destinationStream = fs.createWriteStream(fileDownloadPath);
- });
- // keep trying to download a file until a retry limit has been reached
- while (retryCount <= retryLimit) {
- let response;
- try {
- response = yield makeDownloadRequest();
- }
- catch (error) {
- // if an error is caught, it is usually indicative of a timeout so retry the download
- core.info('An error occurred while attempting to download a file');
- // eslint-disable-next-line no-console
- console.log(error);
- // increment the retryCount and use exponential backoff to wait before making the next request
- yield backOff();
- continue;
- }
- let forceRetry = false;
- if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
- // The body contains the contents of the file however calling response.readBody() causes all the content to be converted to a string
- // which can cause some gzip encoded data to be lost
- // Instead of using response.readBody(), response.message is a readableStream that can be directly used to get the raw body contents
- try {
- const isGzipped = isGzip(response.message.headers);
- yield this.pipeResponseToFile(response, destinationStream, isGzipped);
- if (isGzipped ||
- isAllBytesReceived(response.message.headers['content-length'], yield (0, utils_1.getFileSize)(downloadPath))) {
- return;
- }
- else {
- forceRetry = true;
- }
+ const parsedRedirectUrl = new URL(redirectUrl);
+ if (parsedUrl.protocol === 'https:' &&
+ parsedUrl.protocol !== parsedRedirectUrl.protocol &&
+ !this._allowRedirectDowngrade) {
+ throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
}
- catch (error) {
- // retry on error, most likely streams were corrupted
- forceRetry = true;
+ // we need to finish reading the response before reassigning response
+ // which will leak the open socket.
+ yield response.readBody();
+ // strip authorization header if redirected to a different hostname
+ if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+ for (const header in headers) {
+ // header names are case insensitive
+ if (header.toLowerCase() === 'authorization') {
+ delete headers[header];
+ }
+ }
}
+ // let's make the request with the new redirectUrl
+ info = this._prepareRequest(verb, parsedRedirectUrl, headers);
+ response = yield this.requestRaw(info, data);
+ redirectsRemaining--;
}
- if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
- core.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`);
- resetDestinationStream(downloadPath);
- // if a throttled status code is received, try to get the retryAfter header value, else differ to standard exponential backoff
- (0, utils_1.isThrottledStatusCode)(response.message.statusCode)
- ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers))
- : yield backOff();
+ if (!response.message.statusCode ||
+ !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+ // If not a retry code, return immediately instead of retrying
+ return response;
}
- else {
- // Some unexpected response code, fail immediately and stop the download
- (0, utils_1.displayHttpDiagnostics)(response);
- return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`));
+ numTries += 1;
+ if (numTries < maxTries) {
+ yield response.readBody();
+ yield this._performExponentialBackoff(numTries);
}
- }
+ } while (numTries < maxTries);
+ return response;
});
}
/**
- * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary
- * @param response the http response received when downloading a file
- * @param destinationStream the stream where the file should be written to
- * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it
+ * Needs to be called if keepAlive is set to true in request options.
+ */
+ dispose() {
+ if (this._agent) {
+ this._agent.destroy();
+ }
+ this._disposed = true;
+ }
+ /**
+ * Raw request.
+ * @param info
+ * @param data
*/
- pipeResponseToFile(response, destinationStream, isGzip) {
+ requestRaw(info, data) {
return __awaiter(this, void 0, void 0, function* () {
- yield new Promise((resolve, reject) => {
- if (isGzip) {
- const gunzip = zlib.createGunzip();
- response.message
- .on('error', error => {
- core.info(`An error occurred while attempting to read the response stream`);
- gunzip.close();
- destinationStream.close();
- reject(error);
- })
- .pipe(gunzip)
- .on('error', error => {
- core.info(`An error occurred while attempting to decompress the response stream`);
- destinationStream.close();
- reject(error);
- })
- .pipe(destinationStream)
- .on('close', () => {
- resolve();
- })
- .on('error', error => {
- core.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
- reject(error);
- });
- }
- else {
- response.message
- .on('error', error => {
- core.info(`An error occurred while attempting to read the response stream`);
- destinationStream.close();
- reject(error);
- })
- .pipe(destinationStream)
- .on('close', () => {
- resolve();
- })
- .on('error', error => {
- core.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`);
- reject(error);
- });
+ return new Promise((resolve, reject) => {
+ function callbackForResult(err, res) {
+ if (err) {
+ reject(err);
+ }
+ else if (!res) {
+ // If `err` is not passed, then `res` must be passed.
+ reject(new Error('Unknown error'));
+ }
+ else {
+ resolve(res);
+ }
}
+ this.requestRawWithCallback(info, data, callbackForResult);
});
- return;
});
}
-}
-exports.DownloadHttpClient = DownloadHttpClient;
-//# sourceMappingURL=download-http-client.js.map
-
-/***/ }),
-
-/***/ 95686:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getDownloadSpecification = void 0;
-const path = __importStar(__nccwpck_require__(71017));
-/**
- * Creates a specification for a set of files that will be downloaded
- * @param artifactName the name of the artifact
- * @param artifactEntries a set of container entries that describe that files that make up an artifact
- * @param downloadPath the path where the artifact will be downloaded to
- * @param includeRootDirectory specifies if there should be an extra directory (denoted by the artifact name) where the artifact files should be downloaded to
- */
-function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) {
- // use a set for the directory paths so that there are no duplicates
- const directories = new Set();
- const specifications = {
- rootDownloadLocation: includeRootDirectory
- ? path.join(downloadPath, artifactName)
- : downloadPath,
- directoryStructure: [],
- emptyFilesToCreate: [],
- filesToDownload: []
- };
- for (const entry of artifactEntries) {
- // Ignore artifacts in the container that don't begin with the same name
- if (entry.path.startsWith(`${artifactName}/`) ||
- entry.path.startsWith(`${artifactName}\\`)) {
- // normalize all separators to the local OS
- const normalizedPathEntry = path.normalize(entry.path);
- // entry.path always starts with the artifact name, if includeRootDirectory is false, remove the name from the beginning of the path
- const filePath = path.join(downloadPath, includeRootDirectory
- ? normalizedPathEntry
- : normalizedPathEntry.replace(artifactName, ''));
- // Case insensitive folder structure maintained in the backend, not every folder is created so the 'folder'
- // itemType cannot be relied upon. The file must be used to determine the directory structure
- if (entry.itemType === 'file') {
- // Get the directories that we need to create from the filePath for each individual file
- directories.add(path.dirname(filePath));
- if (entry.fileLength === 0) {
- // An empty file was uploaded, create the empty files locally so that no extra http calls are made
- specifications.emptyFilesToCreate.push(filePath);
- }
- else {
- specifications.filesToDownload.push({
- sourceLocation: entry.contentLocation,
- targetPath: filePath
- });
- }
+ /**
+ * Raw request with callback.
+ * @param info
+ * @param data
+ * @param onResult
+ */
+ requestRawWithCallback(info, data, onResult) {
+ if (typeof data === 'string') {
+ if (!info.options.headers) {
+ info.options.headers = {};
}
+ info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
- }
- specifications.directoryStructure = Array.from(directories);
- return specifications;
-}
-exports.getDownloadSpecification = getDownloadSpecification;
-//# sourceMappingURL=download-specification.js.map
-
-/***/ }),
-
-/***/ 16527:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpManager = void 0;
-const utils_1 = __nccwpck_require__(36327);
-/**
- * Used for managing http clients during either upload or download
- */
-class HttpManager {
- constructor(clientCount, userAgent) {
- if (clientCount < 1) {
- throw new Error('There must be at least one client');
+ let callbackCalled = false;
+ function handleResult(err, res) {
+ if (!callbackCalled) {
+ callbackCalled = true;
+ onResult(err, res);
+ }
}
- this.userAgent = userAgent;
- this.clients = new Array(clientCount).fill((0, utils_1.createHttpClient)(userAgent));
- }
- getClient(index) {
- return this.clients[index];
- }
- // client disposal is necessary if a keep-alive connection is used to properly close the connection
- // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292
- disposeAndReplaceClient(index) {
- this.clients[index].dispose();
- this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent);
- }
- disposeAndReplaceAllClients() {
- for (const [index] of this.clients.entries()) {
- this.disposeAndReplaceClient(index);
+ const req = info.httpModule.request(info.options, (msg) => {
+ const res = new HttpClientResponse(msg);
+ handleResult(undefined, res);
+ });
+ let socket;
+ req.on('socket', sock => {
+ socket = sock;
+ });
+ // If we ever get disconnected, we want the socket to timeout eventually
+ req.setTimeout(this._socketTimeout || 3 * 60000, () => {
+ if (socket) {
+ socket.end();
+ }
+ handleResult(new Error(`Request timeout: ${info.options.path}`));
+ });
+ req.on('error', function (err) {
+ // err has statusCode property
+ // res should have headers
+ handleResult(err);
+ });
+ if (data && typeof data === 'string') {
+ req.write(data, 'utf8');
+ }
+ if (data && typeof data !== 'string') {
+ data.on('close', function () {
+ req.end();
+ });
+ data.pipe(req);
+ }
+ else {
+ req.end();
}
}
-}
-exports.HttpManager = HttpManager;
-//# sourceMappingURL=http-manager.js.map
-
-/***/ }),
-
-/***/ 87398:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.checkArtifactFilePath = exports.checkArtifactName = void 0;
-const core_1 = __nccwpck_require__(42186);
-/**
- * Invalid characters that cannot be in the artifact name or an uploaded file. Will be rejected
- * from the server if attempted to be sent over. These characters are not allowed due to limitations with certain
- * file systems such as NTFS. To maintain platform-agnostic behavior, all characters that are not supported by an
- * individual filesystem/platform will not be supported on all fileSystems/platforms
- *
- * FilePaths can include characters such as \ and / which are not permitted in the artifact name alone
- */
-const invalidArtifactFilePathCharacters = new Map([
- ['"', ' Double quote "'],
- [':', ' Colon :'],
- ['<', ' Less than <'],
- ['>', ' Greater than >'],
- ['|', ' Vertical bar |'],
- ['*', ' Asterisk *'],
- ['?', ' Question mark ?'],
- ['\r', ' Carriage return \\r'],
- ['\n', ' Line feed \\n']
-]);
-const invalidArtifactNameCharacters = new Map([
- ...invalidArtifactFilePathCharacters,
- ['\\', ' Backslash \\'],
- ['/', ' Forward slash /']
-]);
-/**
- * Scans the name of the artifact to make sure there are no illegal characters
- */
-function checkArtifactName(name) {
- if (!name) {
- throw new Error(`Artifact name: ${name}, is incorrectly provided`);
- }
- for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) {
- if (name.includes(invalidCharacterKey)) {
- throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter}
-
-Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()}
-
-These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`);
+ /**
+ * Gets an http agent. This function is useful when you need an http agent that handles
+ * routing through a proxy server - depending upon the url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+ getAgent(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ return this._getAgent(parsedUrl);
+ }
+ getAgentDispatcher(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ const proxyUrl = pm.getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (!useProxy) {
+ return;
}
+ return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
}
- (0, core_1.info)(`Artifact name is valid!`);
-}
-exports.checkArtifactName = checkArtifactName;
-/**
- * Scans the name of the filePath used to make sure there are no illegal characters
- */
-function checkArtifactFilePath(path) {
- if (!path) {
- throw new Error(`Artifact path: ${path}, is incorrectly provided`);
- }
- for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) {
- if (path.includes(invalidCharacterKey)) {
- throw new Error(`Artifact path is not valid: ${path}. Contains the following character: ${errorMessageForCharacter}
-
-Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()}
-
-The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.
- `);
+ _prepareRequest(method, requestUrl, headers) {
+ const info = {};
+ info.parsedUrl = requestUrl;
+ const usingSsl = info.parsedUrl.protocol === 'https:';
+ info.httpModule = usingSsl ? https : http;
+ const defaultPort = usingSsl ? 443 : 80;
+ info.options = {};
+ info.options.host = info.parsedUrl.hostname;
+ info.options.port = info.parsedUrl.port
+ ? parseInt(info.parsedUrl.port)
+ : defaultPort;
+ info.options.path =
+ (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
+ info.options.method = method;
+ info.options.headers = this._mergeHeaders(headers);
+ if (this.userAgent != null) {
+ info.options.headers['user-agent'] = this.userAgent;
}
+ info.options.agent = this._getAgent(info.parsedUrl);
+ // gives handlers an opportunity to participate
+ if (this.handlers) {
+ for (const handler of this.handlers) {
+ handler.prepareRequest(info.options);
+ }
+ }
+ return info;
}
-}
-exports.checkArtifactFilePath = checkArtifactFilePath;
-//# sourceMappingURL=path-and-artifact-name-validation.js.map
-
-/***/ }),
-
-/***/ 90755:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+ _mergeHeaders(headers) {
+ if (this.requestOptions && this.requestOptions.headers) {
+ return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+ }
+ return lowercaseKeys(headers || {});
}
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.retryHttpClientRequest = exports.retry = void 0;
-const utils_1 = __nccwpck_require__(36327);
-const core = __importStar(__nccwpck_require__(42186));
-const config_variables_1 = __nccwpck_require__(42222);
-function retry(name, operation, customErrorMessages, maxAttempts) {
- return __awaiter(this, void 0, void 0, function* () {
- let response = undefined;
- let statusCode = undefined;
- let isRetryable = false;
- let errorMessage = '';
- let customErrorInformation = undefined;
- let attempt = 1;
- while (attempt <= maxAttempts) {
- try {
- response = yield operation();
- statusCode = response.message.statusCode;
- if ((0, utils_1.isSuccessStatusCode)(statusCode)) {
- return response;
- }
- // Extra error information that we want to display if a particular response code is hit
- if (statusCode) {
- customErrorInformation = customErrorMessages.get(statusCode);
- }
- isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode);
- errorMessage = `Artifact service responded with ${statusCode}`;
- }
- catch (error) {
- isRetryable = true;
- errorMessage = error.message;
+ _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
+ let clientHeader;
+ if (this.requestOptions && this.requestOptions.headers) {
+ clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+ }
+ return additionalHeaders[header] || clientHeader || _default;
+ }
+ _getAgent(parsedUrl) {
+ let agent;
+ const proxyUrl = pm.getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (this._keepAlive && useProxy) {
+ agent = this._proxyAgent;
+ }
+ if (this._keepAlive && !useProxy) {
+ agent = this._agent;
+ }
+ // if agent is already assigned use that agent.
+ if (agent) {
+ return agent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ let maxSockets = 100;
+ if (this.requestOptions) {
+ maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+ }
+ // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
+ if (proxyUrl && proxyUrl.hostname) {
+ const agentOptions = {
+ maxSockets,
+ keepAlive: this._keepAlive,
+ proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
+ proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+ })), { host: proxyUrl.hostname, port: proxyUrl.port })
+ };
+ let tunnelAgent;
+ const overHttps = proxyUrl.protocol === 'https:';
+ if (usingSsl) {
+ tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
- if (!isRetryable) {
- core.info(`${name} - Error is not retryable`);
- if (response) {
- (0, utils_1.displayHttpDiagnostics)(response);
- }
- break;
+ else {
+ tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
- core.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
- yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt));
- attempt++;
+ agent = tunnelAgent(agentOptions);
+ this._proxyAgent = agent;
}
- if (response) {
- (0, utils_1.displayHttpDiagnostics)(response);
+ // if reusing agent across request and tunneling agent isn't assigned create a new agent
+ if (this._keepAlive && !agent) {
+ const options = { keepAlive: this._keepAlive, maxSockets };
+ agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
+ this._agent = agent;
}
- if (customErrorInformation) {
- throw Error(`${name} failed: ${customErrorInformation}`);
+ // if not using private agent and tunnel agent isn't setup then use global agent
+ if (!agent) {
+ agent = usingSsl ? https.globalAgent : http.globalAgent;
}
- throw Error(`${name} failed: ${errorMessage}`);
- });
-}
-exports.retry = retry;
-function retryHttpClientRequest(name, method, customErrorMessages = new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) {
- return __awaiter(this, void 0, void 0, function* () {
- return yield retry(name, method, customErrorMessages, maxAttempts);
- });
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ agent.options = Object.assign(agent.options || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return agent;
+ }
+ _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+ let proxyAgent;
+ if (this._keepAlive) {
+ proxyAgent = this._proxyAgentDispatcher;
+ }
+ // if agent is already assigned use that agent.
+ if (proxyAgent) {
+ return proxyAgent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
+ token: `${proxyUrl.username}:${proxyUrl.password}`
+ })));
+ this._proxyAgentDispatcher = proxyAgent;
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return proxyAgent;
+ }
+ _performExponentialBackoff(retryNumber) {
+ return __awaiter(this, void 0, void 0, function* () {
+ retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+ const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+ return new Promise(resolve => setTimeout(() => resolve(), ms));
+ });
+ }
+ _processResponse(res, options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
+ const statusCode = res.message.statusCode || 0;
+ const response = {
+ statusCode,
+ result: null,
+ headers: {}
+ };
+ // not found leads to null obj returned
+ if (statusCode === HttpCodes.NotFound) {
+ resolve(response);
+ }
+ // get the result from the body
+ function dateTimeDeserializer(key, value) {
+ if (typeof value === 'string') {
+ const a = new Date(value);
+ if (!isNaN(a.valueOf())) {
+ return a;
+ }
+ }
+ return value;
+ }
+ let obj;
+ let contents;
+ try {
+ contents = yield res.readBody();
+ if (contents && contents.length > 0) {
+ if (options && options.deserializeDates) {
+ obj = JSON.parse(contents, dateTimeDeserializer);
+ }
+ else {
+ obj = JSON.parse(contents);
+ }
+ response.result = obj;
+ }
+ response.headers = res.message.headers;
+ }
+ catch (err) {
+ // Invalid resource (contents not json); leaving result obj null
+ }
+ // note that 3xx redirects are handled by the http layer.
+ if (statusCode > 299) {
+ let msg;
+ // if exception/error in body, attempt to get better error
+ if (obj && obj.message) {
+ msg = obj.message;
+ }
+ else if (contents && contents.length > 0) {
+ // it may be the case that the exception is in the body message as string
+ msg = contents;
+ }
+ else {
+ msg = `Failed request: (${statusCode})`;
+ }
+ const err = new HttpClientError(msg, statusCode);
+ err.result = response.result;
+ reject(err);
+ }
+ else {
+ resolve(response);
+ }
+ }));
+ });
+ }
}
-exports.retryHttpClientRequest = retryHttpClientRequest;
-//# sourceMappingURL=requestUtils.js.map
+exports.HttpClient = HttpClient;
+const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 39081:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 4988:
+/***/ ((__unused_webpack_module, exports) => {
-"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.StatusReporter = void 0;
-const core_1 = __nccwpck_require__(42186);
-/**
- * Status Reporter that displays information about the progress/status of an artifact that is being uploaded or downloaded
- *
- * Variable display time that can be adjusted using the displayFrequencyInMilliseconds variable
- * The total status of the upload/download gets displayed according to this value
- * If there is a large file that is being uploaded, extra information about the individual status can also be displayed using the updateLargeFileStatus function
- */
-class StatusReporter {
- constructor(displayFrequencyInMilliseconds) {
- this.totalNumberOfFilesToProcess = 0;
- this.processedCount = 0;
- this.largeFiles = new Map();
- this.totalFileStatus = undefined;
- this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds;
- }
- setTotalNumberOfFilesToProcess(fileTotal) {
- this.totalNumberOfFilesToProcess = fileTotal;
- this.processedCount = 0;
- }
- start() {
- // displays information about the total upload/download status
- this.totalFileStatus = setInterval(() => {
- // display 1 decimal place without any rounding
- const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess);
- (0, core_1.info)(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`);
- }, this.displayFrequencyInMilliseconds);
- }
- // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload
- updateLargeFileStatus(fileName, chunkStartIndex, chunkEndIndex, totalUploadFileSize) {
- // display 1 decimal place without any rounding
- const percentage = this.formatPercentage(chunkEndIndex, totalUploadFileSize);
- (0, core_1.info)(`Uploaded ${fileName} (${percentage.slice(0, percentage.indexOf('.') + 2)}%) bytes ${chunkStartIndex}:${chunkEndIndex}`);
- }
- stop() {
- if (this.totalFileStatus) {
- clearInterval(this.totalFileStatus);
+exports.checkBypass = exports.getProxyUrl = void 0;
+function getProxyUrl(reqUrl) {
+ const usingSsl = reqUrl.protocol === 'https:';
+ if (checkBypass(reqUrl)) {
+ return undefined;
+ }
+ const proxyVar = (() => {
+ if (usingSsl) {
+ return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
+ }
+ else {
+ return process.env['http_proxy'] || process.env['HTTP_PROXY'];
+ }
+ })();
+ if (proxyVar) {
+ try {
+ return new URL(proxyVar);
+ }
+ catch (_a) {
+ if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
+ return new URL(`http://${proxyVar}`);
}
}
- incrementProcessedCount() {
- this.processedCount++;
+ else {
+ return undefined;
+ }
+}
+exports.getProxyUrl = getProxyUrl;
+function checkBypass(reqUrl) {
+ if (!reqUrl.hostname) {
+ return false;
+ }
+ const reqHost = reqUrl.hostname;
+ if (isLoopbackAddress(reqHost)) {
+ return true;
+ }
+ const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
+ if (!noProxy) {
+ return false;
+ }
+ // Determine the request port
+ let reqPort;
+ if (reqUrl.port) {
+ reqPort = Number(reqUrl.port);
+ }
+ else if (reqUrl.protocol === 'http:') {
+ reqPort = 80;
+ }
+ else if (reqUrl.protocol === 'https:') {
+ reqPort = 443;
+ }
+ // Format the request hostname and hostname with port
+ const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+ if (typeof reqPort === 'number') {
+ upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
- formatPercentage(numerator, denominator) {
- // toFixed() rounds, so use extra precision to display accurate information even though 4 decimal places are not displayed
- return ((numerator / denominator) * 100).toFixed(4).toString();
+ // Compare request host against noproxy
+ for (const upperNoProxyItem of noProxy
+ .split(',')
+ .map(x => x.trim().toUpperCase())
+ .filter(x => x)) {
+ if (upperNoProxyItem === '*' ||
+ upperReqHosts.some(x => x === upperNoProxyItem ||
+ x.endsWith(`.${upperNoProxyItem}`) ||
+ (upperNoProxyItem.startsWith('.') &&
+ x.endsWith(`${upperNoProxyItem}`)))) {
+ return true;
+ }
}
+ return false;
}
-exports.StatusReporter = StatusReporter;
-//# sourceMappingURL=status-reporter.js.map
+exports.checkBypass = checkBypass;
+function isLoopbackAddress(host) {
+ const hostLower = host.toLowerCase();
+ return (hostLower === 'localhost' ||
+ hostLower.startsWith('127.') ||
+ hostLower.startsWith('[::1]') ||
+ hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
+}
+//# sourceMappingURL=proxy.js.map
/***/ }),
-/***/ 40606:
+/***/ 5207:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -6178,7 +2696,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
@@ -6191,135 +2709,170 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __asyncValues = (this && this.__asyncValues) || function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-};
+var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createGZipFileInBuffer = exports.createGZipFileOnDisk = void 0;
-const fs = __importStar(__nccwpck_require__(57147));
-const zlib = __importStar(__nccwpck_require__(59796));
-const util_1 = __nccwpck_require__(73837);
-const stat = (0, util_1.promisify)(fs.stat);
-/**
- * GZipping certain files that are already compressed will likely not yield further size reductions. Creating large temporary gzip
- * files then will just waste a lot of time before ultimately being discarded (especially for very large files).
- * If any of these types of files are encountered then on-disk gzip creation will be skipped and the original file will be uploaded as-is
- */
-const gzipExemptFileExtensions = [
- '.gz',
- '.gzip',
- '.tgz',
- '.taz',
- '.Z',
- '.taZ',
- '.bz2',
- '.tbz',
- '.tbz2',
- '.tz2',
- '.lz',
- '.lzma',
- '.tlz',
- '.lzo',
- '.xz',
- '.txz',
- '.zst',
- '.zstd',
- '.tzst',
- '.zip',
- '.7z' // 7ZIP
-];
-/**
- * Creates a Gzip compressed file of an original file at the provided temporary filepath location
- * @param {string} originalFilePath filepath of whatever will be compressed. The original file will be unmodified
- * @param {string} tempFilePath the location of where the Gzip file will be created
- * @returns the size of gzip file that gets created
- */
-function createGZipFileOnDisk(originalFilePath, tempFilePath) {
+exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;
+const fs = __importStar(__nccwpck_require__(9896));
+const path = __importStar(__nccwpck_require__(6928));
+_a = fs.promises
+// export const {open} = 'fs'
+, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
+// export const {open} = 'fs'
+exports.IS_WINDOWS = process.platform === 'win32';
+// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691
+exports.UV_FS_O_EXLOCK = 0x10000000;
+exports.READONLY = fs.constants.O_RDONLY;
+function exists(fsPath) {
return __awaiter(this, void 0, void 0, function* () {
- for (const gzipExemptExtension of gzipExemptFileExtensions) {
- if (originalFilePath.endsWith(gzipExemptExtension)) {
- // return a really large number so that the original file gets uploaded
- return Number.MAX_SAFE_INTEGER;
+ try {
+ yield exports.stat(fsPath);
+ }
+ catch (err) {
+ if (err.code === 'ENOENT') {
+ return false;
}
+ throw err;
}
- return new Promise((resolve, reject) => {
- const inputStream = fs.createReadStream(originalFilePath);
- const gzip = zlib.createGzip();
- const outputStream = fs.createWriteStream(tempFilePath);
- inputStream.pipe(gzip).pipe(outputStream);
- outputStream.on('finish', () => __awaiter(this, void 0, void 0, function* () {
- // wait for stream to finish before calculating the size which is needed as part of the Content-Length header when starting an upload
- const size = (yield stat(tempFilePath)).size;
- resolve(size);
- }));
- outputStream.on('error', error => {
- // eslint-disable-next-line no-console
- console.log(error);
- reject(error);
- });
- });
+ return true;
+ });
+}
+exports.exists = exists;
+function isDirectory(fsPath, useStat = false) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
+ return stats.isDirectory();
});
}
-exports.createGZipFileOnDisk = createGZipFileOnDisk;
+exports.isDirectory = isDirectory;
+/**
+ * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
+ * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
+ */
+function isRooted(p) {
+ p = normalizeSeparators(p);
+ if (!p) {
+ throw new Error('isRooted() parameter "p" cannot be empty');
+ }
+ if (exports.IS_WINDOWS) {
+ return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
+ ); // e.g. C: or C:\hello
+ }
+ return p.startsWith('/');
+}
+exports.isRooted = isRooted;
/**
- * Creates a GZip file in memory using a buffer. Should be used for smaller files to reduce disk I/O
- * @param originalFilePath the path to the original file that is being GZipped
- * @returns a buffer with the GZip file
+ * Best effort attempt to determine whether a file exists and is executable.
+ * @param filePath file path to check
+ * @param extensions additional file extensions to try
+ * @return if file exists and is executable, returns the file path. otherwise empty string.
*/
-function createGZipFileInBuffer(originalFilePath) {
+function tryGetExecutablePath(filePath, extensions) {
return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
- var _a, e_1, _b, _c;
- const inputStream = fs.createReadStream(originalFilePath);
- const gzip = zlib.createGzip();
- inputStream.pipe(gzip);
- // read stream into buffer, using experimental async iterators see https://github.com/nodejs/readable-stream/issues/403#issuecomment-479069043
- const chunks = [];
+ let stats = undefined;
+ try {
+ // test file exists
+ stats = yield exports.stat(filePath);
+ }
+ catch (err) {
+ if (err.code !== 'ENOENT') {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
+ }
+ }
+ if (stats && stats.isFile()) {
+ if (exports.IS_WINDOWS) {
+ // on Windows, test for valid extension
+ const upperExt = path.extname(filePath).toUpperCase();
+ if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
+ return filePath;
+ }
+ }
+ else {
+ if (isUnixExecutable(stats)) {
+ return filePath;
+ }
+ }
+ }
+ // try each extension
+ const originalFilePath = filePath;
+ for (const extension of extensions) {
+ filePath = originalFilePath + extension;
+ stats = undefined;
try {
- for (var _d = true, gzip_1 = __asyncValues(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a;) {
- _c = gzip_1_1.value;
- _d = false;
+ stats = yield exports.stat(filePath);
+ }
+ catch (err) {
+ if (err.code !== 'ENOENT') {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
+ }
+ }
+ if (stats && stats.isFile()) {
+ if (exports.IS_WINDOWS) {
+ // preserve the case of the actual file (since an extension was appended)
try {
- const chunk = _c;
- chunks.push(chunk);
+ const directory = path.dirname(filePath);
+ const upperName = path.basename(filePath).toUpperCase();
+ for (const actualName of yield exports.readdir(directory)) {
+ if (upperName === actualName.toUpperCase()) {
+ filePath = path.join(directory, actualName);
+ break;
+ }
+ }
}
- finally {
- _d = true;
+ catch (err) {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
}
+ return filePath;
}
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1);
+ else {
+ if (isUnixExecutable(stats)) {
+ return filePath;
+ }
}
- finally { if (e_1) throw e_1.error; }
}
- resolve(Buffer.concat(chunks));
- }));
+ }
+ return '';
});
}
-exports.createGZipFileInBuffer = createGZipFileInBuffer;
-//# sourceMappingURL=upload-gzip.js.map
+exports.tryGetExecutablePath = tryGetExecutablePath;
+function normalizeSeparators(p) {
+ p = p || '';
+ if (exports.IS_WINDOWS) {
+ // convert slashes on Windows
+ p = p.replace(/\//g, '\\');
+ // remove redundant slashes
+ return p.replace(/\\\\+/g, '\\');
+ }
+ // remove redundant slashes
+ return p.replace(/\/\/+/g, '/');
+}
+// on Mac/Linux, test the execute bit
+// R W X R W X R W X
+// 256 128 64 32 16 8 4 2 1
+function isUnixExecutable(stats) {
+ return ((stats.mode & 1) > 0 ||
+ ((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
+ ((stats.mode & 64) > 0 && stats.uid === process.getuid()));
+}
+// Get the path of cmd.exe in windows
+function getCmdPath() {
+ var _a;
+ return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
+}
+exports.getCmdPath = getCmdPath;
+//# sourceMappingURL=io-util.js.map
/***/ }),
-/***/ 74354:
+/***/ 4994:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -6332,7 +2885,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
@@ -6346,122751 +2899,23690 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.UploadHttpClient = void 0;
-const fs = __importStar(__nccwpck_require__(57147));
-const core = __importStar(__nccwpck_require__(42186));
-const tmp = __importStar(__nccwpck_require__(68065));
-const stream = __importStar(__nccwpck_require__(12781));
-const utils_1 = __nccwpck_require__(36327);
-const config_variables_1 = __nccwpck_require__(42222);
-const util_1 = __nccwpck_require__(73837);
-const url_1 = __nccwpck_require__(57310);
-const perf_hooks_1 = __nccwpck_require__(4074);
-const status_reporter_1 = __nccwpck_require__(39081);
-const http_client_1 = __nccwpck_require__(96255);
-const http_manager_1 = __nccwpck_require__(16527);
-const upload_gzip_1 = __nccwpck_require__(40606);
-const requestUtils_1 = __nccwpck_require__(90755);
-const stat = (0, util_1.promisify)(fs.stat);
-class UploadHttpClient {
- constructor() {
- this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), '@actions/artifact-upload');
- this.statusReporter = new status_reporter_1.StatusReporter(10000);
- }
- /**
- * Creates a file container for the new artifact in the remote blob storage/file service
- * @param {string} artifactName Name of the artifact being created
- * @returns The response from the Artifact Service if the file container was successfully created
- */
- createArtifactInFileContainer(artifactName, options) {
- return __awaiter(this, void 0, void 0, function* () {
- const parameters = {
- Type: 'actions_storage',
- Name: artifactName
- };
- // calculate retention period
- if (options && options.retentionDays) {
- const maxRetentionStr = (0, config_variables_1.getRetentionDays)();
- parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr);
- }
- const data = JSON.stringify(parameters, null, 2);
- const artifactUrl = (0, utils_1.getArtifactUrl)();
- // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately
- const client = this.uploadHttpManager.getClient(0);
- const headers = (0, utils_1.getUploadHeaders)('application/json', false);
- // Extra information to display when a particular HTTP code is returned
- // If a 403 is returned when trying to create a file container, the customer has exceeded
- // their storage quota so no new artifact containers can be created
- const customErrorMessages = new Map([
- [
- http_client_1.HttpCodes.Forbidden,
- (0, config_variables_1.isGhes)()
- ? 'Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly.'
- : 'Artifact storage quota has been hit. Unable to upload any new artifacts'
- ],
- [
- http_client_1.HttpCodes.BadRequest,
- `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}`
- ]
- ]);
- const response = yield (0, requestUtils_1.retryHttpClientRequest)('Create Artifact Container', () => __awaiter(this, void 0, void 0, function* () { return client.post(artifactUrl, data, headers); }), customErrorMessages);
- const body = yield response.readBody();
- return JSON.parse(body);
- });
- }
- /**
- * Concurrently upload all of the files in chunks
- * @param {string} uploadUrl Base Url for the artifact that was created
- * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded
- * @returns The size of all the files uploaded in bytes
- */
- uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) {
- return __awaiter(this, void 0, void 0, function* () {
- const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)();
- const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)();
- core.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`);
- const parameters = [];
- // by default, file uploads will continue if there is an error unless specified differently in the options
- let continueOnError = true;
- if (options) {
- if (options.continueOnError === false) {
- continueOnError = false;
- }
+exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0;
+const assert_1 = __nccwpck_require__(2613);
+const path = __importStar(__nccwpck_require__(6928));
+const ioUtil = __importStar(__nccwpck_require__(5207));
+/**
+ * Copies a file or folder.
+ * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
+ *
+ * @param source source path
+ * @param dest destination path
+ * @param options optional. See CopyOptions.
+ */
+function cp(source, dest, options = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const { force, recursive, copySourceDirectory } = readCopyOptions(options);
+ const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
+ // Dest is an existing file, but not forcing
+ if (destStat && destStat.isFile() && !force) {
+ return;
+ }
+ // If dest is an existing directory, should copy inside.
+ const newDest = destStat && destStat.isDirectory() && copySourceDirectory
+ ? path.join(dest, path.basename(source))
+ : dest;
+ if (!(yield ioUtil.exists(source))) {
+ throw new Error(`no such file or directory: ${source}`);
+ }
+ const sourceStat = yield ioUtil.stat(source);
+ if (sourceStat.isDirectory()) {
+ if (!recursive) {
+ throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
}
- // prepare the necessary parameters to upload all the files
- for (const file of filesToUpload) {
- const resourceUrl = new url_1.URL(uploadUrl);
- resourceUrl.searchParams.append('itemPath', file.uploadFilePath);
- parameters.push({
- file: file.absoluteFilePath,
- resourceUrl: resourceUrl.toString(),
- maxChunkSize: MAX_CHUNK_SIZE,
- continueOnError
- });
+ else {
+ yield cpDirRecursive(source, newDest, 0, force);
}
- const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()];
- const failedItemsToReport = [];
- let currentFile = 0;
- let completedFiles = 0;
- let uploadFileSize = 0;
- let totalFileSize = 0;
- let abortPendingFileUploads = false;
- this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length);
- this.statusReporter.start();
- // only allow a certain amount of files to be uploaded at once, this is done to reduce potential errors
- yield Promise.all(parallelUploads.map((index) => __awaiter(this, void 0, void 0, function* () {
- while (currentFile < filesToUpload.length) {
- const currentFileParameters = parameters[currentFile];
- currentFile += 1;
- if (abortPendingFileUploads) {
- failedItemsToReport.push(currentFileParameters.file);
- continue;
- }
- const startTime = perf_hooks_1.performance.now();
- const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters);
- if (core.isDebug()) {
- core.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`);
- }
- uploadFileSize += uploadFileResult.successfulUploadSize;
- totalFileSize += uploadFileResult.totalSize;
- if (uploadFileResult.isSuccess === false) {
- failedItemsToReport.push(currentFileParameters.file);
- if (!continueOnError) {
- // fail fast
- core.error(`aborting artifact upload`);
- abortPendingFileUploads = true;
- }
- }
- this.statusReporter.incrementProcessedCount();
- }
- })));
- this.statusReporter.stop();
- // done uploading, safety dispose all connections
- this.uploadHttpManager.disposeAndReplaceAllClients();
- core.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`);
- return {
- uploadSize: uploadFileSize,
- totalSize: totalFileSize,
- failedItems: failedItemsToReport
- };
- });
- }
- /**
- * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space.
- * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls
- * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls
- * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded
- * @returns The size of the file that was uploaded in bytes along with any failed uploads
- */
- uploadFileAsync(httpClientIndex, parameters) {
- return __awaiter(this, void 0, void 0, function* () {
- const fileStat = yield stat(parameters.file);
- const totalFileSize = fileStat.size;
- const isFIFO = fileStat.isFIFO();
- let offset = 0;
- let isUploadSuccessful = true;
- let failedChunkSizes = 0;
- let uploadFileSize = 0;
- let isGzip = true;
- // the file that is being uploaded is less than 64k in size to increase throughput and to minimize disk I/O
- // for creating a new GZip file, an in-memory buffer is used for compression
- // with named pipes the file size is reported as zero in that case don't read the file in memory
- if (!isFIFO && totalFileSize < 65536) {
- core.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`);
- const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file);
- // An open stream is needed in the event of a failure and we need to retry. If a NodeJS.ReadableStream is directly passed in,
- // it will not properly get reset to the start of the stream if a chunk upload needs to be retried
- let openUploadStream;
- if (totalFileSize < buffer.byteLength) {
- // compression did not help with reducing the size, use a readable stream from the original file for upload
- core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
- openUploadStream = () => fs.createReadStream(parameters.file);
- isGzip = false;
- uploadFileSize = totalFileSize;
- }
- else {
- // create a readable stream using a PassThrough stream that is both readable and writable
- core.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`);
- openUploadStream = () => {
- const passThrough = new stream.PassThrough();
- passThrough.end(buffer);
- return passThrough;
- };
- uploadFileSize = buffer.byteLength;
- }
- const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize);
- if (!result) {
- // chunk failed to upload
- isUploadSuccessful = false;
- failedChunkSizes += uploadFileSize;
- core.warning(`Aborting upload for ${parameters.file} due to failure`);
- }
- return {
- isSuccess: isUploadSuccessful,
- successfulUploadSize: uploadFileSize - failedChunkSizes,
- totalSize: totalFileSize
- };
+ }
+ else {
+ if (path.relative(source, newDest) === '') {
+ // a file cannot be copied to itself
+ throw new Error(`'${newDest}' and '${source}' are the same file`);
}
- else {
- // the file that is being uploaded is greater than 64k in size, a temporary file gets created on disk using the
- // npm tmp-promise package and this file gets used to create a GZipped file
- const tempFile = yield tmp.file();
- core.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`);
- // create a GZip file of the original file being uploaded, the original file should not be modified in any way
- uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path);
- let uploadFilePath = tempFile.path;
- // compression did not help with size reduction, use the original file for upload and delete the temp GZip file
- // for named pipes totalFileSize is zero, this assumes compression did help
- if (!isFIFO && totalFileSize < uploadFileSize) {
- core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`);
- uploadFileSize = totalFileSize;
- uploadFilePath = parameters.file;
- isGzip = false;
- }
- else {
- core.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`);
- }
- let abortFileUpload = false;
- // upload only a single chunk at a time
- while (offset < uploadFileSize) {
- const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize);
- const startChunkIndex = offset;
- const endChunkIndex = offset + chunkSize - 1;
- offset += parameters.maxChunkSize;
- if (abortFileUpload) {
- // if we don't want to continue in the event of an error, any pending upload chunks will be marked as failed
- failedChunkSizes += chunkSize;
- continue;
- }
- const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs.createReadStream(uploadFilePath, {
- start: startChunkIndex,
- end: endChunkIndex,
- autoClose: false
- }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize);
- if (!result) {
- // Chunk failed to upload, report as failed and do not continue uploading any more chunks for the file. It is possible that part of a chunk was
- // successfully uploaded so the server may report a different size for what was uploaded
- isUploadSuccessful = false;
- failedChunkSizes += chunkSize;
- core.warning(`Aborting upload for ${parameters.file} due to failure`);
- abortFileUpload = true;
- }
- else {
- // if an individual file is greater than 8MB (1024*1024*8) in size, display extra information about the upload status
- if (uploadFileSize > 8388608) {
- this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize);
- }
- }
- }
- // Delete the temporary file that was created as part of the upload. If the temp file does not get manually deleted by
- // calling cleanup, it gets removed when the node process exits. For more info see: https://www.npmjs.com/package/tmp-promise#about
- core.debug(`deleting temporary gzip file ${tempFile.path}`);
- yield tempFile.cleanup();
- return {
- isSuccess: isUploadSuccessful,
- successfulUploadSize: uploadFileSize - failedChunkSizes,
- totalSize: totalFileSize
- };
+ yield copyFile(source, newDest, force);
+ }
+ });
+}
+exports.cp = cp;
+/**
+ * Moves a path.
+ *
+ * @param source source path
+ * @param dest destination path
+ * @param options optional. See MoveOptions.
+ */
+function mv(source, dest, options = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (yield ioUtil.exists(dest)) {
+ let destExists = true;
+ if (yield ioUtil.isDirectory(dest)) {
+ // If dest is directory copy src into dest
+ dest = path.join(dest, path.basename(source));
+ destExists = yield ioUtil.exists(dest);
}
- });
- }
- /**
- * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code
- * indicates a retryable status, we try to upload the chunk as well
- * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls
- * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to
- * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded
- * @param {number} start Starting byte index of file that the chunk belongs to
- * @param {number} end Ending byte index of file that the chunk belongs to
- * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded
- * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream
- * @param {number} totalFileSize Original total size of the file that is being uploaded
- * @returns if the chunk was successfully uploaded
- */
- uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) {
- return __awaiter(this, void 0, void 0, function* () {
- // open a new stream and read it to compute the digest
- const digest = yield (0, utils_1.digestForStream)(openStream());
- // prepare all the necessary headers before making any http call
- const headers = (0, utils_1.getUploadHeaders)('application/octet-stream', true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest);
- const uploadChunkRequest = () => __awaiter(this, void 0, void 0, function* () {
- const client = this.uploadHttpManager.getClient(httpClientIndex);
- return yield client.sendStream('PUT', resourceUrl, openStream(), headers);
- });
- let retryCount = 0;
- const retryLimit = (0, config_variables_1.getRetryLimit)();
- // Increments the current retry count and then checks if the retry limit has been reached
- // If there have been too many retries, fail so the download stops
- const incrementAndCheckRetryLimit = (response) => {
- retryCount++;
- if (retryCount > retryLimit) {
- if (response) {
- (0, utils_1.displayHttpDiagnostics)(response);
- }
- core.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`);
- return true;
- }
- return false;
- };
- const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () {
- this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex);
- if (retryAfterValue) {
- core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`);
- yield (0, utils_1.sleep)(retryAfterValue);
- }
- else {
- const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount);
- core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`);
- yield (0, utils_1.sleep)(backoffTime);
- }
- core.info(`Finished backoff for retry #${retryCount}, continuing with upload`);
- return;
- });
- // allow for failed chunks to be retried multiple times
- while (retryCount <= retryLimit) {
- let response;
- try {
- response = yield uploadChunkRequest();
- }
- catch (error) {
- // if an error is caught, it is usually indicative of a timeout so retry the upload
- core.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`);
- // eslint-disable-next-line no-console
- console.log(error);
- if (incrementAndCheckRetryLimit()) {
- return false;
- }
- yield backOff();
- continue;
- }
- // Always read the body of the response. There is potential for a resource leak if the body is not read which will
- // result in the connection remaining open along with unintended consequences when trying to dispose of the client
- yield response.readBody();
- if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) {
- return true;
- }
- else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) {
- core.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`);
- if (incrementAndCheckRetryLimit(response)) {
- return false;
- }
- (0, utils_1.isThrottledStatusCode)(response.message.statusCode)
- ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers))
- : yield backOff();
+ if (destExists) {
+ if (options.force == null || options.force) {
+ yield rmRF(dest);
}
else {
- core.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`);
- (0, utils_1.displayHttpDiagnostics)(response);
- return false;
+ throw new Error('Destination already exists');
}
}
- return false;
- });
- }
- /**
- * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact.
- * Updating the size indicates that we are done uploading all the contents of the artifact
- */
- patchArtifactSize(size, artifactName) {
- return __awaiter(this, void 0, void 0, function* () {
- const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)());
- resourceUrl.searchParams.append('artifactName', artifactName);
- const parameters = { Size: size };
- const data = JSON.stringify(parameters, null, 2);
- core.debug(`URL is ${resourceUrl.toString()}`);
- // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately
- const client = this.uploadHttpManager.getClient(0);
- const headers = (0, utils_1.getUploadHeaders)('application/json', false);
- // Extra information to display when a particular HTTP code is returned
- const customErrorMessages = new Map([
- [
- http_client_1.HttpCodes.NotFound,
- `An Artifact with the name ${artifactName} was not found`
- ]
- ]);
- // TODO retry for all possible response codes, the artifact upload is pretty much complete so it at all costs we should try to finish this
- const response = yield (0, requestUtils_1.retryHttpClientRequest)('Finalize artifact upload', () => __awaiter(this, void 0, void 0, function* () { return client.patch(resourceUrl.toString(), data, headers); }), customErrorMessages);
- yield response.readBody();
- core.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`);
- });
- }
+ }
+ yield mkdirP(path.dirname(dest));
+ yield ioUtil.rename(source, dest);
+ });
}
-exports.UploadHttpClient = UploadHttpClient;
-//# sourceMappingURL=upload-http-client.js.map
-
-/***/ }),
-
-/***/ 10183:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getUploadSpecification = void 0;
-const fs = __importStar(__nccwpck_require__(57147));
-const core_1 = __nccwpck_require__(42186);
-const path_1 = __nccwpck_require__(71017);
-const path_and_artifact_name_validation_1 = __nccwpck_require__(87398);
+exports.mv = mv;
/**
- * Creates a specification that describes how each file that is part of the artifact will be uploaded
- * @param artifactName the name of the artifact being uploaded. Used during upload to denote where the artifact is stored on the server
- * @param rootDirectory an absolute file path that denotes the path that should be removed from the beginning of each artifact file
- * @param artifactFiles a list of absolute file paths that denote what should be uploaded as part of the artifact
+ * Remove a path recursively with force
+ *
+ * @param inputPath path to remove
*/
-function getUploadSpecification(artifactName, rootDirectory, artifactFiles) {
- // artifact name was checked earlier on, no need to check again
- const specifications = [];
- if (!fs.existsSync(rootDirectory)) {
- throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`);
- }
- if (!fs.statSync(rootDirectory).isDirectory()) {
- throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`);
- }
- // Normalize and resolve, this allows for either absolute or relative paths to be used
- rootDirectory = (0, path_1.normalize)(rootDirectory);
- rootDirectory = (0, path_1.resolve)(rootDirectory);
- /*
- Example to demonstrate behavior
-
- Input:
- artifactName: my-artifact
- rootDirectory: '/home/user/files/plz-upload'
- artifactFiles: [
- '/home/user/files/plz-upload/file1.txt',
- '/home/user/files/plz-upload/file2.txt',
- '/home/user/files/plz-upload/dir/file3.txt'
- ]
-
- Output:
- specifications: [
- ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file1.txt'],
- ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'],
- ['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt']
- ]
- */
- for (let file of artifactFiles) {
- if (!fs.existsSync(file)) {
- throw new Error(`File ${file} does not exist`);
- }
- if (!fs.statSync(file).isDirectory()) {
- // Normalize and resolve, this allows for either absolute or relative paths to be used
- file = (0, path_1.normalize)(file);
- file = (0, path_1.resolve)(file);
- if (!file.startsWith(rootDirectory)) {
- throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`);
+function rmRF(inputPath) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (ioUtil.IS_WINDOWS) {
+ // Check for invalid characters
+ // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
+ if (/[*"<>|]/.test(inputPath)) {
+ throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
}
- // Check for forbidden characters in file paths that will be rejected during upload
- const uploadPath = file.replace(rootDirectory, '');
- (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath);
- /*
- uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all
- be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts
-
- path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt
- join('artifact-name/', 'file-to-upload.txt')
- join('artifact-name/', '/file-to-upload.txt')
- join('artifact-name', 'file-to-upload.txt')
- join('artifact-name', '/file-to-upload.txt')
- */
- specifications.push({
- absoluteFilePath: file,
- uploadFilePath: (0, path_1.join)(artifactName, uploadPath)
+ }
+ try {
+ // note if path does not exist, error is silent
+ yield ioUtil.rm(inputPath, {
+ force: true,
+ maxRetries: 3,
+ recursive: true,
+ retryDelay: 300
});
}
- else {
- // Directories are rejected by the server during upload
- (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`);
+ catch (err) {
+ throw new Error(`File was unable to be removed ${err}`);
}
- }
- return specifications;
-}
-exports.getUploadSpecification = getUploadSpecification;
-//# sourceMappingURL=upload-specification.js.map
-
-/***/ }),
-
-/***/ 36327:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
});
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.digestForStream = exports.sleep = exports.getProperRetention = exports.rmFile = exports.getFileSize = exports.createEmptyFilesForArtifact = exports.createDirectoriesForArtifact = exports.displayHttpDiagnostics = exports.getArtifactUrl = exports.createHttpClient = exports.getUploadHeaders = exports.getDownloadHeaders = exports.getContentRange = exports.tryGetRetryAfterValueTimeInMilliseconds = exports.isThrottledStatusCode = exports.isRetryableStatusCode = exports.isForbiddenStatusCode = exports.isSuccessStatusCode = exports.getApiVersion = exports.parseEnvNumber = exports.getExponentialRetryTimeInMilliseconds = void 0;
-const crypto_1 = __importDefault(__nccwpck_require__(6113));
-const fs_1 = __nccwpck_require__(57147);
-const core_1 = __nccwpck_require__(42186);
-const http_client_1 = __nccwpck_require__(96255);
-const auth_1 = __nccwpck_require__(35526);
-const config_variables_1 = __nccwpck_require__(42222);
-const crc64_1 = __importDefault(__nccwpck_require__(23549));
-/**
- * Returns a retry time in milliseconds that exponentially gets larger
- * depending on the amount of retries that have been attempted
- */
-function getExponentialRetryTimeInMilliseconds(retryCount) {
- if (retryCount < 0) {
- throw new Error('RetryCount should not be negative');
- }
- else if (retryCount === 0) {
- return (0, config_variables_1.getInitialRetryIntervalInMilliseconds)();
- }
- const minTime = (0, config_variables_1.getInitialRetryIntervalInMilliseconds)() * (0, config_variables_1.getRetryMultiplier)() * retryCount;
- const maxTime = minTime * (0, config_variables_1.getRetryMultiplier)();
- // returns a random number between the minTime (inclusive) and the maxTime (exclusive)
- return Math.trunc(Math.random() * (maxTime - minTime) + minTime);
-}
-exports.getExponentialRetryTimeInMilliseconds = getExponentialRetryTimeInMilliseconds;
-/**
- * Parses a env variable that is a number
- */
-function parseEnvNumber(key) {
- const value = Number(process.env[key]);
- if (Number.isNaN(value) || value < 0) {
- return undefined;
- }
- return value;
}
-exports.parseEnvNumber = parseEnvNumber;
+exports.rmRF = rmRF;
/**
- * Various utility functions to help with the necessary API calls
+ * Make a directory. Creates the full path with folders in between
+ * Will throw if it fails
+ *
+ * @param fsPath path to create
+ * @returns Promise
*/
-function getApiVersion() {
- return '6.0-preview';
-}
-exports.getApiVersion = getApiVersion;
-function isSuccessStatusCode(statusCode) {
- if (!statusCode) {
- return false;
- }
- return statusCode >= 200 && statusCode < 300;
-}
-exports.isSuccessStatusCode = isSuccessStatusCode;
-function isForbiddenStatusCode(statusCode) {
- if (!statusCode) {
- return false;
- }
- return statusCode === http_client_1.HttpCodes.Forbidden;
-}
-exports.isForbiddenStatusCode = isForbiddenStatusCode;
-function isRetryableStatusCode(statusCode) {
- if (!statusCode) {
- return false;
- }
- const retryableStatusCodes = [
- http_client_1.HttpCodes.BadGateway,
- http_client_1.HttpCodes.GatewayTimeout,
- http_client_1.HttpCodes.InternalServerError,
- http_client_1.HttpCodes.ServiceUnavailable,
- http_client_1.HttpCodes.TooManyRequests,
- 413 // Payload Too Large
- ];
- return retryableStatusCodes.includes(statusCode);
-}
-exports.isRetryableStatusCode = isRetryableStatusCode;
-function isThrottledStatusCode(statusCode) {
- if (!statusCode) {
- return false;
- }
- return statusCode === http_client_1.HttpCodes.TooManyRequests;
+function mkdirP(fsPath) {
+ return __awaiter(this, void 0, void 0, function* () {
+ assert_1.ok(fsPath, 'a path argument must be provided');
+ yield ioUtil.mkdir(fsPath, { recursive: true });
+ });
}
-exports.isThrottledStatusCode = isThrottledStatusCode;
+exports.mkdirP = mkdirP;
/**
- * Attempts to get the retry-after value from a set of http headers. The retry time
- * is originally denoted in seconds, so if present, it is converted to milliseconds
- * @param headers all the headers received when making an http call
+ * Returns path of a tool had the tool actually been invoked. Resolves via paths.
+ * If you check and the tool does not exist, it will throw.
+ *
+ * @param tool name of the tool
+ * @param check whether to check if tool exists
+ * @returns Promise path to tool
*/
-function tryGetRetryAfterValueTimeInMilliseconds(headers) {
- if (headers['retry-after']) {
- const retryTime = Number(headers['retry-after']);
- if (!isNaN(retryTime)) {
- (0, core_1.info)(`Retry-After header is present with a value of ${retryTime}`);
- return retryTime * 1000;
+function which(tool, check) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (!tool) {
+ throw new Error("parameter 'tool' is required");
}
- (0, core_1.info)(`Returned retry-after header value: ${retryTime} is non-numeric and cannot be used`);
- return undefined;
- }
- (0, core_1.info)(`No retry-after header was found. Dumping all headers for diagnostic purposes`);
- // eslint-disable-next-line no-console
- console.log(headers);
- return undefined;
-}
-exports.tryGetRetryAfterValueTimeInMilliseconds = tryGetRetryAfterValueTimeInMilliseconds;
-function getContentRange(start, end, total) {
- // Format: `bytes start-end/fileSize
- // start and end are inclusive
- // For a 200 byte chunk starting at byte 0:
- // Content-Range: bytes 0-199/200
- return `bytes ${start}-${end}/${total}`;
-}
-exports.getContentRange = getContentRange;
-/**
- * Sets all the necessary headers when downloading an artifact
- * @param {string} contentType the type of content being uploaded
- * @param {boolean} isKeepAlive is the same connection being used to make multiple calls
- * @param {boolean} acceptGzip can we accept a gzip encoded response
- * @param {string} acceptType the type of content that we can accept
- * @returns appropriate headers to make a specific http call during artifact download
- */
-function getDownloadHeaders(contentType, isKeepAlive, acceptGzip) {
- const requestOptions = {};
- if (contentType) {
- requestOptions['Content-Type'] = contentType;
- }
- if (isKeepAlive) {
- requestOptions['Connection'] = 'Keep-Alive';
- // keep alive for at least 10 seconds before closing the connection
- requestOptions['Keep-Alive'] = '10';
- }
- if (acceptGzip) {
- // if we are expecting a response with gzip encoding, it should be using an octet-stream in the accept header
- requestOptions['Accept-Encoding'] = 'gzip';
- requestOptions['Accept'] = `application/octet-stream;api-version=${getApiVersion()}`;
- }
- else {
- // default to application/json if we are not working with gzip content
- requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`;
- }
- return requestOptions;
+ // recursive when check=true
+ if (check) {
+ const result = yield which(tool, false);
+ if (!result) {
+ if (ioUtil.IS_WINDOWS) {
+ throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
+ }
+ else {
+ throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
+ }
+ }
+ return result;
+ }
+ const matches = yield findInPath(tool);
+ if (matches && matches.length > 0) {
+ return matches[0];
+ }
+ return '';
+ });
}
-exports.getDownloadHeaders = getDownloadHeaders;
-/**
- * Sets all the necessary headers when uploading an artifact
- * @param {string} contentType the type of content being uploaded
- * @param {boolean} isKeepAlive is the same connection being used to make multiple calls
- * @param {boolean} isGzip is the connection being used to upload GZip compressed content
- * @param {number} uncompressedLength the original size of the content if something is being uploaded that has been compressed
- * @param {number} contentLength the length of the content that is being uploaded
- * @param {string} contentRange the range of the content that is being uploaded
- * @returns appropriate headers to make a specific http call during artifact upload
- */
-function getUploadHeaders(contentType, isKeepAlive, isGzip, uncompressedLength, contentLength, contentRange, digest) {
- const requestOptions = {};
- requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`;
- if (contentType) {
- requestOptions['Content-Type'] = contentType;
- }
- if (isKeepAlive) {
- requestOptions['Connection'] = 'Keep-Alive';
- // keep alive for at least 10 seconds before closing the connection
- requestOptions['Keep-Alive'] = '10';
- }
- if (isGzip) {
- requestOptions['Content-Encoding'] = 'gzip';
- requestOptions['x-tfs-filelength'] = uncompressedLength;
- }
- if (contentLength) {
- requestOptions['Content-Length'] = contentLength;
- }
- if (contentRange) {
- requestOptions['Content-Range'] = contentRange;
- }
- if (digest) {
- requestOptions['x-actions-results-crc64'] = digest.crc64;
- requestOptions['x-actions-results-md5'] = digest.md5;
- }
- return requestOptions;
-}
-exports.getUploadHeaders = getUploadHeaders;
-function createHttpClient(userAgent) {
- return new http_client_1.HttpClient(userAgent, [
- new auth_1.BearerCredentialHandler((0, config_variables_1.getRuntimeToken)())
- ]);
-}
-exports.createHttpClient = createHttpClient;
-function getArtifactUrl() {
- const artifactUrl = `${(0, config_variables_1.getRuntimeUrl)()}_apis/pipelines/workflows/${(0, config_variables_1.getWorkFlowRunId)()}/artifacts?api-version=${getApiVersion()}`;
- (0, core_1.debug)(`Artifact Url: ${artifactUrl}`);
- return artifactUrl;
-}
-exports.getArtifactUrl = getArtifactUrl;
+exports.which = which;
/**
- * Uh oh! Something might have gone wrong during either upload or download. The IHtttpClientResponse object contains information
- * about the http call that was made by the actions http client. This information might be useful to display for diagnostic purposes, but
- * this entire object is really big and most of the information is not really useful. This function takes the response object and displays only
- * the information that we want.
+ * Returns a list of all occurrences of the given tool on the system path.
*
- * Certain information such as the TLSSocket and the Readable state are not really useful for diagnostic purposes so they can be avoided.
- * Other information such as the headers, the response code and message might be useful, so this is displayed.
+ * @returns Promise the paths of the tool
*/
-function displayHttpDiagnostics(response) {
- (0, core_1.info)(`##### Begin Diagnostic HTTP information #####
-Status Code: ${response.message.statusCode}
-Status Message: ${response.message.statusMessage}
-Header Information: ${JSON.stringify(response.message.headers, undefined, 2)}
-###### End Diagnostic HTTP information ######`);
-}
-exports.displayHttpDiagnostics = displayHttpDiagnostics;
-function createDirectoriesForArtifact(directories) {
+function findInPath(tool) {
return __awaiter(this, void 0, void 0, function* () {
- for (const directory of directories) {
- yield fs_1.promises.mkdir(directory, {
- recursive: true
- });
+ if (!tool) {
+ throw new Error("parameter 'tool' is required");
}
- });
-}
-exports.createDirectoriesForArtifact = createDirectoriesForArtifact;
-function createEmptyFilesForArtifact(emptyFilesToCreate) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const filePath of emptyFilesToCreate) {
- yield (yield fs_1.promises.open(filePath, 'w')).close();
+ // build the list of extensions to try
+ const extensions = [];
+ if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) {
+ for (const extension of process.env['PATHEXT'].split(path.delimiter)) {
+ if (extension) {
+ extensions.push(extension);
+ }
+ }
+ }
+ // if it's rooted, return it if exists. otherwise return empty.
+ if (ioUtil.isRooted(tool)) {
+ const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
+ if (filePath) {
+ return [filePath];
+ }
+ return [];
+ }
+ // if any path separators, return empty
+ if (tool.includes(path.sep)) {
+ return [];
+ }
+ // build the list of directories
+ //
+ // Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
+ // it feels like we should not do this. Checking the current directory seems like more of a use
+ // case of a shell, and the which() function exposed by the toolkit should strive for consistency
+ // across platforms.
+ const directories = [];
+ if (process.env.PATH) {
+ for (const p of process.env.PATH.split(path.delimiter)) {
+ if (p) {
+ directories.push(p);
+ }
+ }
+ }
+ // find all matches
+ const matches = [];
+ for (const directory of directories) {
+ const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions);
+ if (filePath) {
+ matches.push(filePath);
+ }
}
+ return matches;
});
}
-exports.createEmptyFilesForArtifact = createEmptyFilesForArtifact;
-function getFileSize(filePath) {
- return __awaiter(this, void 0, void 0, function* () {
- const stats = yield fs_1.promises.stat(filePath);
- (0, core_1.debug)(`${filePath} size:(${stats.size}) blksize:(${stats.blksize}) blocks:(${stats.blocks})`);
- return stats.size;
- });
+exports.findInPath = findInPath;
+function readCopyOptions(options) {
+ const force = options.force == null ? true : options.force;
+ const recursive = Boolean(options.recursive);
+ const copySourceDirectory = options.copySourceDirectory == null
+ ? true
+ : Boolean(options.copySourceDirectory);
+ return { force, recursive, copySourceDirectory };
}
-exports.getFileSize = getFileSize;
-function rmFile(filePath) {
+function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
return __awaiter(this, void 0, void 0, function* () {
- yield fs_1.promises.unlink(filePath);
- });
-}
-exports.rmFile = rmFile;
-function getProperRetention(retentionInput, retentionSetting) {
- if (retentionInput < 0) {
- throw new Error('Invalid retention, minimum value is 1.');
- }
- let retention = retentionInput;
- if (retentionSetting) {
- const maxRetention = parseInt(retentionSetting);
- if (!isNaN(maxRetention) && maxRetention < retention) {
- (0, core_1.warning)(`Retention days is greater than the max value allowed by the repository setting, reduce retention to ${maxRetention} days`);
- retention = maxRetention;
+ // Ensure there is not a run away recursive copy
+ if (currentDepth >= 255)
+ return;
+ currentDepth++;
+ yield mkdirP(destDir);
+ const files = yield ioUtil.readdir(sourceDir);
+ for (const fileName of files) {
+ const srcFile = `${sourceDir}/${fileName}`;
+ const destFile = `${destDir}/${fileName}`;
+ const srcFileStat = yield ioUtil.lstat(srcFile);
+ if (srcFileStat.isDirectory()) {
+ // Recurse
+ yield cpDirRecursive(srcFile, destFile, currentDepth, force);
+ }
+ else {
+ yield copyFile(srcFile, destFile, force);
+ }
}
- }
- return retention;
-}
-exports.getProperRetention = getProperRetention;
-function sleep(milliseconds) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise(resolve => setTimeout(resolve, milliseconds));
+ // Change the mode for the newly created directory
+ yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
});
}
-exports.sleep = sleep;
-function digestForStream(stream) {
+// Buffered file copy
+function copyFile(srcFile, destFile, force) {
return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve, reject) => {
- const crc64 = new crc64_1.default();
- const md5 = crypto_1.default.createHash('md5');
- stream
- .on('data', data => {
- crc64.update(data);
- md5.update(data);
- })
- .on('end', () => resolve({
- crc64: crc64.digest('base64'),
- md5: md5.digest('base64')
- }))
- .on('error', reject);
- });
+ if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
+ // unlink/re-link it
+ try {
+ yield ioUtil.lstat(destFile);
+ yield ioUtil.unlink(destFile);
+ }
+ catch (e) {
+ // Try to override file permission
+ if (e.code === 'EPERM') {
+ yield ioUtil.chmod(destFile, '0666');
+ yield ioUtil.unlink(destFile);
+ }
+ // other errors = it doesn't exist, no work to do
+ }
+ // Copy over symlink
+ const symlinkFull = yield ioUtil.readlink(srcFile);
+ yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
+ }
+ else if (!(yield ioUtil.exists(destFile)) || force) {
+ yield ioUtil.copyFile(srcFile, destFile);
+ }
});
}
-exports.digestForStream = digestForStream;
-//# sourceMappingURL=utils.js.map
+//# sourceMappingURL=io.js.map
/***/ }),
-/***/ 87351:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 1715:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.issue = exports.issueCommand = void 0;
-const os = __importStar(__nccwpck_require__(22037));
-const utils_1 = __nccwpck_require__(5278);
-/**
- * Commands
- *
- * Command Format:
- * ::name key=value,key=value::message
- *
- * Examples:
- * ::warning::This is the message
- * ::set-env name=MY_VAR::some value
- */
-function issueCommand(command, properties, message) {
- const cmd = new Command(command, properties, message);
- process.stdout.write(cmd.toString() + os.EOL);
-}
-exports.issueCommand = issueCommand;
-function issue(name, message = '') {
- issueCommand(name, {}, message);
-}
-exports.issue = issue;
-const CMD_STRING = '::';
-class Command {
- constructor(command, properties, message) {
- if (!command) {
- command = 'missing.command';
- }
- this.command = command;
- this.properties = properties;
- this.message = message;
- }
- toString() {
- let cmdStr = CMD_STRING + this.command;
- if (this.properties && Object.keys(this.properties).length > 0) {
- cmdStr += ' ';
- let first = true;
- for (const key in this.properties) {
- if (this.properties.hasOwnProperty(key)) {
- const val = this.properties[key];
- if (val) {
- if (first) {
- first = false;
- }
- else {
- cmdStr += ',';
- }
- cmdStr += `${key}=${escapeProperty(val)}`;
- }
- }
- }
- }
- cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
- return cmdStr;
- }
-}
-function escapeData(s) {
- return utils_1.toCommandValue(s)
- .replace(/%/g, '%25')
- .replace(/\r/g, '%0D')
- .replace(/\n/g, '%0A');
-}
-function escapeProperty(s) {
- return utils_1.toCommandValue(s)
- .replace(/%/g, '%25')
- .replace(/\r/g, '%0D')
- .replace(/\n/g, '%0A')
- .replace(/:/g, '%3A')
- .replace(/,/g, '%2C');
-}
-//# sourceMappingURL=command.js.map
-/***/ }),
+const WritableStream = (__nccwpck_require__(7075).Writable)
+const inherits = (__nccwpck_require__(7975).inherits)
-/***/ 42186:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+const StreamSearch = __nccwpck_require__(1601)
-"use strict";
+const PartStream = __nccwpck_require__(1403)
+const HeaderParser = __nccwpck_require__(6604)
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
-const command_1 = __nccwpck_require__(87351);
-const file_command_1 = __nccwpck_require__(717);
-const utils_1 = __nccwpck_require__(5278);
-const os = __importStar(__nccwpck_require__(22037));
-const path = __importStar(__nccwpck_require__(71017));
-const oidc_utils_1 = __nccwpck_require__(98041);
-/**
- * The code to exit an action
- */
-var ExitCode;
-(function (ExitCode) {
- /**
- * A code indicating that the action was successful
- */
- ExitCode[ExitCode["Success"] = 0] = "Success";
- /**
- * A code indicating that the action was a failure
- */
- ExitCode[ExitCode["Failure"] = 1] = "Failure";
-})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
-//-----------------------------------------------------------------------
-// Variables
-//-----------------------------------------------------------------------
-/**
- * Sets env variable for this action and future actions in the job
- * @param name the name of the variable to set
- * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function exportVariable(name, val) {
- const convertedVal = utils_1.toCommandValue(val);
- process.env[name] = convertedVal;
- const filePath = process.env['GITHUB_ENV'] || '';
- if (filePath) {
- return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));
+const DASH = 45
+const B_ONEDASH = Buffer.from('-')
+const B_CRLF = Buffer.from('\r\n')
+const EMPTY_FN = function () {}
+
+function Dicer (cfg) {
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
+ WritableStream.call(this, cfg)
+
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
+
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
+
+ this._headerFirst = cfg.headerFirst
+
+ this._dashes = 0
+ this._parts = 0
+ this._finished = false
+ this._realFinish = false
+ this._isPreamble = true
+ this._justMatched = false
+ this._firstWrite = true
+ this._inHeader = true
+ this._part = undefined
+ this._cb = undefined
+ this._ignoreData = false
+ this._partOpts = { highWaterMark: cfg.partHwm }
+ this._pause = false
+
+ const self = this
+ this._hparser = new HeaderParser(cfg)
+ this._hparser.on('header', function (header) {
+ self._inHeader = false
+ self._part.emit('header', header)
+ })
+}
+inherits(Dicer, WritableStream)
+
+Dicer.prototype.emit = function (ev) {
+ if (ev === 'finish' && !this._realFinish) {
+ if (!this._finished) {
+ const self = this
+ process.nextTick(function () {
+ self.emit('error', new Error('Unexpected end of multipart data'))
+ if (self._part && !self._ignoreData) {
+ const type = (self._isPreamble ? 'Preamble' : 'Part')
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
+ self._part.push(null)
+ process.nextTick(function () {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ return
+ }
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
}
- command_1.issueCommand('set-env', { name }, convertedVal);
+ } else { WritableStream.prototype.emit.apply(this, arguments) }
}
-exports.exportVariable = exportVariable;
-/**
- * Registers a secret which will get masked from logs
- * @param secret value of the secret
- */
-function setSecret(secret) {
- command_1.issueCommand('add-mask', {}, secret);
+
+Dicer.prototype._write = function (data, encoding, cb) {
+ // ignore unexpected data (e.g. extra trailer data after finished)
+ if (!this._hparser && !this._bparser) { return cb() }
+
+ if (this._headerFirst && this._isPreamble) {
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }
+ }
+ const r = this._hparser.push(data)
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ }
+
+ // allows for "easier" testing
+ if (this._firstWrite) {
+ this._bparser.push(B_CRLF)
+ this._firstWrite = false
+ }
+
+ this._bparser.push(data)
+
+ if (this._pause) { this._cb = cb } else { cb() }
}
-exports.setSecret = setSecret;
-/**
- * Prepends inputPath to the PATH (for this action and future actions)
- * @param inputPath
- */
-function addPath(inputPath) {
- const filePath = process.env['GITHUB_PATH'] || '';
- if (filePath) {
- file_command_1.issueFileCommand('PATH', inputPath);
+
+Dicer.prototype.reset = function () {
+ this._part = undefined
+ this._bparser = undefined
+ this._hparser = undefined
+}
+
+Dicer.prototype.setBoundary = function (boundary) {
+ const self = this
+ this._bparser = new StreamSearch('\r\n--' + boundary)
+ this._bparser.on('info', function (isMatch, data, start, end) {
+ self._oninfo(isMatch, data, start, end)
+ })
+}
+
+Dicer.prototype._ignore = function () {
+ if (this._part && !this._ignoreData) {
+ this._ignoreData = true
+ this._part.on('error', EMPTY_FN)
+ // we must perform some kind of read on the stream even though we are
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
+ // after pushing null to the stream
+ this._part.resume()
+ }
+}
+
+Dicer.prototype._oninfo = function (isMatch, data, start, end) {
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+
+ if (!this._part && this._justMatched && data) {
+ while (this._dashes < 2 && (start + i) < end) {
+ if (data[start + i] === DASH) {
+ ++i
+ ++this._dashes
+ } else {
+ if (this._dashes) { buf = B_ONEDASH }
+ this._dashes = 0
+ break
+ }
}
- else {
- command_1.issueCommand('add-path', {}, inputPath);
+ if (this._dashes === 2) {
+ if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }
+ this.reset()
+ this._finished = true
+ // no more parts will be added
+ if (self._parts === 0) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ }
}
- process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
-}
-exports.addPath = addPath;
-/**
- * Gets the value of an input.
- * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
- * Returns an empty string if the value is not defined.
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns string
- */
-function getInput(name, options) {
- const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
- if (options && options.required && !val) {
- throw new Error(`Input required and not supplied: ${name}`);
+ if (this._dashes) { return }
+ }
+ if (this._justMatched) { this._justMatched = false }
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ this._part._read = function (n) {
+ self._unpause()
}
- if (options && options.trimWhitespace === false) {
- return val;
+ if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part) } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part) } else { this._ignore() }
+ if (!this._isPreamble) { this._inHeader = true }
+ }
+ if (data && start < end && !this._ignoreData) {
+ if (this._isPreamble || !this._inHeader) {
+ if (buf) { shouldWriteMore = this._part.push(buf) }
+ shouldWriteMore = this._part.push(data.slice(start, end))
+ if (!shouldWriteMore) { this._pause = true }
+ } else if (!this._isPreamble && this._inHeader) {
+ if (buf) { this._hparser.push(buf) }
+ r = this._hparser.push(data.slice(start, end))
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
}
- return val.trim();
-}
-exports.getInput = getInput;
-/**
- * Gets the values of an multiline input. Each value is also trimmed.
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns string[]
- *
- */
-function getMultilineInput(name, options) {
- const inputs = getInput(name, options)
- .split('\n')
- .filter(x => x !== '');
- if (options && options.trimWhitespace === false) {
- return inputs;
+ }
+ if (isMatch) {
+ this._hparser.reset()
+ if (this._isPreamble) { this._isPreamble = false } else {
+ if (start !== end) {
+ ++this._parts
+ this._part.on('end', function () {
+ if (--self._parts === 0) {
+ if (self._finished) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ } else {
+ self._unpause()
+ }
+ }
+ })
+ }
}
- return inputs.map(input => input.trim());
+ this._part.push(null)
+ this._part = undefined
+ this._ignoreData = false
+ this._justMatched = true
+ this._dashes = 0
+ }
}
-exports.getMultilineInput = getMultilineInput;
-/**
- * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
- * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
- * The return value is also in boolean type.
- * ref: https://yaml.org/spec/1.2/spec.html#id2804923
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns boolean
- */
-function getBooleanInput(name, options) {
- const trueValue = ['true', 'True', 'TRUE'];
- const falseValue = ['false', 'False', 'FALSE'];
- const val = getInput(name, options);
- if (trueValue.includes(val))
- return true;
- if (falseValue.includes(val))
- return false;
- throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
- `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
+
+Dicer.prototype._unpause = function () {
+ if (!this._pause) { return }
+
+ this._pause = false
+ if (this._cb) {
+ const cb = this._cb
+ this._cb = undefined
+ cb()
+ }
}
-exports.getBooleanInput = getBooleanInput;
-/**
- * Sets the value of an output.
- *
- * @param name name of the output to set
- * @param value value to store. Non-string values will be converted to a string via JSON.stringify
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function setOutput(name, value) {
- const filePath = process.env['GITHUB_OUTPUT'] || '';
- if (filePath) {
- return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));
+
+module.exports = Dicer
+
+
+/***/ }),
+
+/***/ 6604:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const EventEmitter = (__nccwpck_require__(8474).EventEmitter)
+const inherits = (__nccwpck_require__(7975).inherits)
+const getLimit = __nccwpck_require__(6424)
+
+const StreamSearch = __nccwpck_require__(1601)
+
+const B_DCRLF = Buffer.from('\r\n\r\n')
+const RE_CRLF = /\r\n/g
+const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
+
+function HeaderParser (cfg) {
+ EventEmitter.call(this)
+
+ cfg = cfg || {}
+ const self = this
+ this.nread = 0
+ this.maxed = false
+ this.npairs = 0
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
+ this.buffer = ''
+ this.header = {}
+ this.finished = false
+ this.ss = new StreamSearch(B_DCRLF)
+ this.ss.on('info', function (isMatch, data, start, end) {
+ if (data && !self.maxed) {
+ if (self.nread + end - start >= self.maxHeaderSize) {
+ end = self.maxHeaderSize - self.nread + start
+ self.nread = self.maxHeaderSize
+ self.maxed = true
+ } else { self.nread += (end - start) }
+
+ self.buffer += data.toString('binary', start, end)
}
- process.stdout.write(os.EOL);
- command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));
-}
-exports.setOutput = setOutput;
-/**
- * Enables or disables the echoing of commands into stdout for the rest of the step.
- * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
- *
- */
-function setCommandEcho(enabled) {
- command_1.issue('echo', enabled ? 'on' : 'off');
-}
-exports.setCommandEcho = setCommandEcho;
-//-----------------------------------------------------------------------
-// Results
-//-----------------------------------------------------------------------
-/**
- * Sets the action status to failed.
- * When the action exits it will be with an exit code of 1
- * @param message add error issue message
- */
-function setFailed(message) {
- process.exitCode = ExitCode.Failure;
- error(message);
-}
-exports.setFailed = setFailed;
-//-----------------------------------------------------------------------
-// Logging Commands
-//-----------------------------------------------------------------------
-/**
- * Gets whether Actions Step Debug is on or not
- */
-function isDebug() {
- return process.env['RUNNER_DEBUG'] === '1';
+ if (isMatch) { self._finish() }
+ })
}
-exports.isDebug = isDebug;
-/**
- * Writes debug message to user log
- * @param message debug message
- */
-function debug(message) {
- command_1.issueCommand('debug', {}, message);
+inherits(HeaderParser, EventEmitter)
+
+HeaderParser.prototype.push = function (data) {
+ const r = this.ss.push(data)
+ if (this.finished) { return r }
}
-exports.debug = debug;
-/**
- * Adds an error issue
- * @param message error issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function error(message, properties = {}) {
- command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+
+HeaderParser.prototype.reset = function () {
+ this.finished = false
+ this.buffer = ''
+ this.header = {}
+ this.ss.reset()
}
-exports.error = error;
-/**
- * Adds a warning issue
- * @param message warning issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function warning(message, properties = {}) {
- command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+
+HeaderParser.prototype._finish = function () {
+ if (this.buffer) { this._parseHeader() }
+ this.ss.matches = this.ss.maxMatches
+ const header = this.header
+ this.header = {}
+ this.buffer = ''
+ this.finished = true
+ this.nread = this.npairs = 0
+ this.maxed = false
+ this.emit('header', header)
}
-exports.warning = warning;
-/**
- * Adds a notice issue
- * @param message notice issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function notice(message, properties = {}) {
- command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+
+HeaderParser.prototype._parseHeader = function () {
+ if (this.npairs === this.maxHeaderPairs) { return }
+
+ const lines = this.buffer.split(RE_CRLF)
+ const len = lines.length
+ let m, h
+
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (lines[i].length === 0) { continue }
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
+ // folded header content
+ // RFC2822 says to just remove the CRLF and not the whitespace following
+ // it, so we follow the RFC and include the leading whitespace ...
+ if (h) {
+ this.header[h][this.header[h].length - 1] += lines[i]
+ continue
+ }
+ }
+
+ const posColon = lines[i].indexOf(':')
+ if (
+ posColon === -1 ||
+ posColon === 0
+ ) {
+ return
+ }
+ m = RE_HDR.exec(lines[i])
+ h = m[1].toLowerCase()
+ this.header[h] = this.header[h] || []
+ this.header[h].push((m[2] || ''))
+ if (++this.npairs === this.maxHeaderPairs) { break }
+ }
}
-exports.notice = notice;
-/**
- * Writes info to log with console.log.
- * @param message info message
- */
-function info(message) {
- process.stdout.write(message + os.EOL);
+
+module.exports = HeaderParser
+
+
+/***/ }),
+
+/***/ 1403:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const inherits = (__nccwpck_require__(7975).inherits)
+const ReadableStream = (__nccwpck_require__(7075).Readable)
+
+function PartStream (opts) {
+ ReadableStream.call(this, opts)
}
-exports.info = info;
+inherits(PartStream, ReadableStream)
+
+PartStream.prototype._read = function (n) {}
+
+module.exports = PartStream
+
+
+/***/ }),
+
+/***/ 1601:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
/**
- * Begin an output group.
+ * Copyright Brian White. All rights reserved.
*
- * Output until the next `groupEnd` will be foldable in this group
+ * @see https://github.com/mscdex/streamsearch
*
- * @param name The name of the output group
- */
-function startGroup(name) {
- command_1.issue('group', name);
-}
-exports.startGroup = startGroup;
-/**
- * End an output group.
- */
-function endGroup() {
- command_1.issue('endgroup');
-}
-exports.endGroup = endGroup;
-/**
- * Wrap an asynchronous function call in a group.
+ * 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:
*
- * Returns the same type as the function itself.
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
*
- * @param name The name of the group
- * @param fn The function to wrap in the group
- */
-function group(name, fn) {
- return __awaiter(this, void 0, void 0, function* () {
- startGroup(name);
- let result;
- try {
- result = yield fn();
- }
- finally {
- endGroup();
- }
- return result;
- });
-}
-exports.group = group;
-//-----------------------------------------------------------------------
-// Wrapper action state
-//-----------------------------------------------------------------------
-/**
- * Saves state for current action, the state can only be retrieved by this action's post job execution.
+ * 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.
*
- * @param name name of the state to store
- * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function saveState(name, value) {
- const filePath = process.env['GITHUB_STATE'] || '';
- if (filePath) {
- return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));
- }
- command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));
+const EventEmitter = (__nccwpck_require__(8474).EventEmitter)
+const inherits = (__nccwpck_require__(7975).inherits)
+
+function SBMH (needle) {
+ if (typeof needle === 'string') {
+ needle = Buffer.from(needle)
+ }
+
+ if (!Buffer.isBuffer(needle)) {
+ throw new TypeError('The needle has to be a String or a Buffer.')
+ }
+
+ const needleLength = needle.length
+
+ if (needleLength === 0) {
+ throw new Error('The needle cannot be an empty String/Buffer.')
+ }
+
+ if (needleLength > 256) {
+ throw new Error('The needle cannot have a length bigger than 256.')
+ }
+
+ this.maxMatches = Infinity
+ this.matches = 0
+
+ this._occ = new Array(256)
+ .fill(needleLength) // Initialize occurrence table.
+ this._lookbehind_size = 0
+ this._needle = needle
+ this._bufpos = 0
+
+ this._lookbehind = Buffer.alloc(needleLength)
+
+ // Populate occurrence table with analysis of the needle,
+ // ignoring last letter.
+ for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
+ this._occ[needle[i]] = needleLength - 1 - i
+ }
}
-exports.saveState = saveState;
-/**
- * Gets the value of an state set by this action's main execution.
- *
- * @param name name of the state to get
- * @returns string
- */
-function getState(name) {
- return process.env[`STATE_${name}`] || '';
+inherits(SBMH, EventEmitter)
+
+SBMH.prototype.reset = function () {
+ this._lookbehind_size = 0
+ this.matches = 0
+ this._bufpos = 0
}
-exports.getState = getState;
-function getIDToken(aud) {
- return __awaiter(this, void 0, void 0, function* () {
- return yield oidc_utils_1.OidcClient.getIDToken(aud);
- });
+
+SBMH.prototype.push = function (chunk, pos) {
+ if (!Buffer.isBuffer(chunk)) {
+ chunk = Buffer.from(chunk, 'binary')
+ }
+ const chlen = chunk.length
+ this._bufpos = pos || 0
+ let r
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
+ return r
}
-exports.getIDToken = getIDToken;
-/**
- * Summary exports
- */
-var summary_1 = __nccwpck_require__(81327);
-Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } }));
-/**
- * @deprecated use core.summary
- */
-var summary_2 = __nccwpck_require__(81327);
-Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } }));
-/**
- * Path exports
- */
-var path_utils_1 = __nccwpck_require__(2981);
-Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } }));
-Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } }));
-Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }));
-//# sourceMappingURL=core.js.map
-/***/ }),
+SBMH.prototype._sbmh_feed = function (data) {
+ const len = data.length
+ const needle = this._needle
+ const needleLength = needle.length
+ const lastNeedleChar = needle[needleLength - 1]
-/***/ 717:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ // Positive: points to a position in `data`
+ // pos == 3 points to data[3]
+ // Negative: points to a position in the lookbehind buffer
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
+ let pos = -this._lookbehind_size
+ let ch
-"use strict";
+ if (pos < 0) {
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
+ // search with character lookup code that considers both the
+ // lookbehind buffer and the current round's haystack data.
+ //
+ // Loop until
+ // there is a match.
+ // or until
+ // we've moved past the position that requires the
+ // lookbehind buffer. In this case we switch to the
+ // optimized loop.
+ // or until
+ // the character to look at lies outside the haystack.
+ while (pos < 0 && pos <= len - needleLength) {
+ ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
-// For internal use, subject to change.
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
-// We use any as a valid input type
-/* eslint-disable @typescript-eslint/no-explicit-any */
-const fs = __importStar(__nccwpck_require__(57147));
-const os = __importStar(__nccwpck_require__(22037));
-const uuid_1 = __nccwpck_require__(75840);
-const utils_1 = __nccwpck_require__(5278);
-function issueFileCommand(command, message) {
- const filePath = process.env[`GITHUB_${command}`];
- if (!filePath) {
- throw new Error(`Unable to find environment variable for file command ${command}`);
- }
- if (!fs.existsSync(filePath)) {
- throw new Error(`Missing file at path: ${filePath}`);
- }
- fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
- encoding: 'utf8'
- });
-}
-exports.issueFileCommand = issueFileCommand;
-function prepareKeyValueMessage(key, value) {
- const delimiter = `ghadelimiter_${uuid_1.v4()}`;
- const convertedValue = utils_1.toCommandValue(value);
- // These should realistically never happen, but just in case someone finds a
- // way to exploit uuid generation let's not allow keys or values that contain
- // the delimiter.
- if (key.includes(delimiter)) {
- throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
+ if (
+ ch === lastNeedleChar &&
+ this._sbmh_memcmp(data, pos, needleLength - 1)
+ ) {
+ this._lookbehind_size = 0
+ ++this.matches
+ this.emit('info', true)
+
+ return (this._bufpos = pos + needleLength)
+ }
+ pos += this._occ[ch]
}
- if (convertedValue.includes(delimiter)) {
- throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
+
+ // No match.
+
+ if (pos < 0) {
+ // There's too few data for Boyer-Moore-Horspool to run,
+ // so let's use a different algorithm to skip as much as
+ // we can.
+ // Forward pos until
+ // the trailing part of lookbehind + data
+ // looks like the beginning of the needle
+ // or until
+ // pos == 0
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
- return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
-}
-exports.prepareKeyValueMessage = prepareKeyValueMessage;
-//# sourceMappingURL=file-command.js.map
-/***/ }),
+ if (pos >= 0) {
+ // Discard lookbehind buffer.
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
+ this._lookbehind_size = 0
+ } else {
+ // Cut off part of the lookbehind buffer that has
+ // been processed and append the entire haystack
+ // into it.
+ const bytesToCutOff = this._lookbehind_size + pos
+ if (bytesToCutOff > 0) {
+ // The cut off data is guaranteed not to contain the needle.
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
+ }
-/***/ 98041:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
+ this._lookbehind_size - bytesToCutOff)
+ this._lookbehind_size -= bytesToCutOff
-"use strict";
+ data.copy(this._lookbehind, this._lookbehind_size)
+ this._lookbehind_size += len
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.OidcClient = void 0;
-const http_client_1 = __nccwpck_require__(96255);
-const auth_1 = __nccwpck_require__(35526);
-const core_1 = __nccwpck_require__(42186);
-class OidcClient {
- static createHttpClient(allowRetry = true, maxRetry = 10) {
- const requestOptions = {
- allowRetries: allowRetry,
- maxRetries: maxRetry
- };
- return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
- }
- static getRequestToken() {
- const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
- if (!token) {
- throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
- }
- return token;
- }
- static getIDTokenUrl() {
- const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
- if (!runtimeUrl) {
- throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
- }
- return runtimeUrl;
- }
- static getCall(id_token_url) {
- var _a;
- return __awaiter(this, void 0, void 0, function* () {
- const httpclient = OidcClient.createHttpClient();
- const res = yield httpclient
- .getJson(id_token_url)
- .catch(error => {
- throw new Error(`Failed to get ID Token. \n
- Error Code : ${error.statusCode}\n
- Error Message: ${error.message}`);
- });
- const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
- if (!id_token) {
- throw new Error('Response json body do not have ID Token field');
- }
- return id_token;
- });
- }
- static getIDToken(audience) {
- return __awaiter(this, void 0, void 0, function* () {
- try {
- // New ID Token is requested from action service
- let id_token_url = OidcClient.getIDTokenUrl();
- if (audience) {
- const encodedAudience = encodeURIComponent(audience);
- id_token_url = `${id_token_url}&audience=${encodedAudience}`;
- }
- core_1.debug(`ID token url is ${id_token_url}`);
- const id_token = yield OidcClient.getCall(id_token_url);
- core_1.setSecret(id_token);
- return id_token;
- }
- catch (error) {
- throw new Error(`Error message: ${error.message}`);
- }
- });
+ this._bufpos = len
+ return len
}
+ }
+
+ pos += (pos >= 0) * this._bufpos
+
+ // Lookbehind buffer is now empty. We only need to check if the
+ // needle is in the haystack.
+ if (data.indexOf(needle, pos) !== -1) {
+ pos = data.indexOf(needle, pos)
+ ++this.matches
+ if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+
+ return (this._bufpos = pos + needleLength)
+ } else {
+ pos = len - needleLength
+ }
+
+ // There was no match. If there's trailing haystack data that we cannot
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
+ // data is less than the needle size) then match using a modified
+ // algorithm that starts matching from the beginning instead of the end.
+ // Whatever trailing data is left after running this algorithm is added to
+ // the lookbehind buffer.
+ while (
+ pos < len &&
+ (
+ data[pos] !== needle[0] ||
+ (
+ (Buffer.compare(
+ data.subarray(pos, pos + len - pos),
+ needle.subarray(0, len - pos)
+ ) !== 0)
+ )
+ )
+ ) {
+ ++pos
+ }
+ if (pos < len) {
+ data.copy(this._lookbehind, 0, pos, pos + (len - pos))
+ this._lookbehind_size = len - pos
+ }
+
+ // Everything until pos is guaranteed not to contain needle data.
+ if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
+
+ this._bufpos = len
+ return len
}
-exports.OidcClient = OidcClient;
-//# sourceMappingURL=oidc-utils.js.map
+
+SBMH.prototype._sbmh_lookup_char = function (data, pos) {
+ return (pos < 0)
+ ? this._lookbehind[this._lookbehind_size + pos]
+ : data[pos]
+}
+
+SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
+ }
+ return true
+}
+
+module.exports = SBMH
+
/***/ }),
-/***/ 2981:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 4652:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
-const path = __importStar(__nccwpck_require__(71017));
-/**
- * toPosixPath converts the given path to the posix form. On Windows, \\ will be
- * replaced with /.
- *
- * @param pth. Path to transform.
- * @return string Posix path.
- */
-function toPosixPath(pth) {
- return pth.replace(/[\\]/g, '/');
+
+const WritableStream = (__nccwpck_require__(7075).Writable)
+const { inherits } = __nccwpck_require__(7975)
+const Dicer = __nccwpck_require__(1715)
+
+const MultipartParser = __nccwpck_require__(6419)
+const UrlencodedParser = __nccwpck_require__(5670)
+const parseParams = __nccwpck_require__(8106)
+
+function Busboy (opts) {
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
+
+ if (typeof opts !== 'object') {
+ throw new TypeError('Busboy expected an options-Object.')
+ }
+ if (typeof opts.headers !== 'object') {
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ }
+ if (typeof opts.headers['content-type'] !== 'string') {
+ throw new TypeError('Missing Content-Type-header.')
+ }
+
+ const {
+ headers,
+ ...streamOptions
+ } = opts
+
+ this.opts = {
+ autoDestroy: false,
+ ...streamOptions
+ }
+ WritableStream.call(this, this.opts)
+
+ this._done = false
+ this._parser = this.getParserByHeaders(headers)
+ this._finished = false
}
-exports.toPosixPath = toPosixPath;
-/**
- * toWin32Path converts the given path to the win32 form. On Linux, / will be
- * replaced with \\.
- *
- * @param pth. Path to transform.
- * @return string Win32 path.
- */
-function toWin32Path(pth) {
- return pth.replace(/[/]/g, '\\');
+inherits(Busboy, WritableStream)
+
+Busboy.prototype.emit = function (ev) {
+ if (ev === 'finish') {
+ if (!this._done) {
+ this._parser?.end()
+ return
+ } else if (this._finished) {
+ return
+ }
+ this._finished = true
+ }
+ WritableStream.prototype.emit.apply(this, arguments)
}
-exports.toWin32Path = toWin32Path;
-/**
- * toPlatformPath converts the given path to a platform-specific path. It does
- * this by replacing instances of / and \ with the platform-specific path
- * separator.
- *
- * @param pth The path to platformize.
- * @return string The platform-specific path.
- */
-function toPlatformPath(pth) {
- return pth.replace(/[/\\]/g, path.sep);
+
+Busboy.prototype.getParserByHeaders = function (headers) {
+ const parsed = parseParams(headers['content-type'])
+
+ const cfg = {
+ defCharset: this.opts.defCharset,
+ fileHwm: this.opts.fileHwm,
+ headers,
+ highWaterMark: this.opts.highWaterMark,
+ isPartAFile: this.opts.isPartAFile,
+ limits: this.opts.limits,
+ parsedConType: parsed,
+ preservePath: this.opts.preservePath
+ }
+
+ if (MultipartParser.detect.test(parsed[0])) {
+ return new MultipartParser(this, cfg)
+ }
+ if (UrlencodedParser.detect.test(parsed[0])) {
+ return new UrlencodedParser(this, cfg)
+ }
+ throw new Error('Unsupported Content-Type.')
}
-exports.toPlatformPath = toPlatformPath;
-//# sourceMappingURL=path-utils.js.map
+
+Busboy.prototype._write = function (chunk, encoding, cb) {
+ this._parser.write(chunk, cb)
+}
+
+module.exports = Busboy
+module.exports["default"] = Busboy
+module.exports.Busboy = Busboy
+
+module.exports.Dicer = Dicer
+
/***/ }),
-/***/ 81327:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 6419:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
-const os_1 = __nccwpck_require__(22037);
-const fs_1 = __nccwpck_require__(57147);
-const { access, appendFile, writeFile } = fs_1.promises;
-exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
-exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
-class Summary {
- constructor() {
- this._buffer = '';
- }
- /**
- * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
- * Also checks r/w permissions.
- *
- * @returns step summary file path
- */
- filePath() {
- return __awaiter(this, void 0, void 0, function* () {
- if (this._filePath) {
- return this._filePath;
- }
- const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
- if (!pathFromEnv) {
- throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
- }
- try {
- yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
- }
- catch (_a) {
- throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
- }
- this._filePath = pathFromEnv;
- return this._filePath;
- });
- }
- /**
- * Wraps content in an HTML tag, adding any HTML attributes
- *
- * @param {string} tag HTML tag to wrap
- * @param {string | null} content content within the tag
- * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
- *
- * @returns {string} content wrapped in HTML element
- */
- wrap(tag, content, attrs = {}) {
- const htmlAttrs = Object.entries(attrs)
- .map(([key, value]) => ` ${key}="${value}"`)
- .join('');
- if (!content) {
- return `<${tag}${htmlAttrs}>`;
- }
- return `<${tag}${htmlAttrs}>${content}${tag}>`;
- }
- /**
- * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
- *
- * @param {SummaryWriteOptions} [options] (optional) options for write operation
- *
- * @returns {Promise} summary instance
- */
- write(options) {
- return __awaiter(this, void 0, void 0, function* () {
- const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
- const filePath = yield this.filePath();
- const writeFunc = overwrite ? writeFile : appendFile;
- yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
- return this.emptyBuffer();
- });
- }
- /**
- * Clears the summary buffer and wipes the summary file
- *
- * @returns {Summary} summary instance
- */
- clear() {
- return __awaiter(this, void 0, void 0, function* () {
- return this.emptyBuffer().write({ overwrite: true });
- });
- }
- /**
- * Returns the current summary buffer as a string
- *
- * @returns {string} string of summary buffer
- */
- stringify() {
- return this._buffer;
- }
- /**
- * If the summary buffer is empty
- *
- * @returns {boolen} true if the buffer is empty
- */
- isEmptyBuffer() {
- return this._buffer.length === 0;
- }
- /**
- * Resets the summary buffer without writing to summary file
- *
- * @returns {Summary} summary instance
- */
- emptyBuffer() {
- this._buffer = '';
- return this;
- }
- /**
- * Adds raw text to the summary buffer
- *
- * @param {string} text content to add
- * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
- *
- * @returns {Summary} summary instance
- */
- addRaw(text, addEOL = false) {
- this._buffer += text;
- return addEOL ? this.addEOL() : this;
- }
- /**
- * Adds the operating system-specific end-of-line marker to the buffer
- *
- * @returns {Summary} summary instance
- */
- addEOL() {
- return this.addRaw(os_1.EOL);
- }
- /**
- * Adds an HTML codeblock to the summary buffer
- *
- * @param {string} code content to render within fenced code block
- * @param {string} lang (optional) language to syntax highlight code
- *
- * @returns {Summary} summary instance
- */
- addCodeBlock(code, lang) {
- const attrs = Object.assign({}, (lang && { lang }));
- const element = this.wrap('pre', this.wrap('code', code), attrs);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML list to the summary buffer
- *
- * @param {string[]} items list of items to render
- * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
- *
- * @returns {Summary} summary instance
- */
- addList(items, ordered = false) {
- const tag = ordered ? 'ol' : 'ul';
- const listItems = items.map(item => this.wrap('li', item)).join('');
- const element = this.wrap(tag, listItems);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML table to the summary buffer
- *
- * @param {SummaryTableCell[]} rows table rows
- *
- * @returns {Summary} summary instance
- */
- addTable(rows) {
- const tableBody = rows
- .map(row => {
- const cells = row
- .map(cell => {
- if (typeof cell === 'string') {
- return this.wrap('td', cell);
- }
- const { header, data, colspan, rowspan } = cell;
- const tag = header ? 'th' : 'td';
- const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
- return this.wrap(tag, data, attrs);
- })
- .join('');
- return this.wrap('tr', cells);
- })
- .join('');
- const element = this.wrap('table', tableBody);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds a collapsable HTML details element to the summary buffer
- *
- * @param {string} label text for the closed state
- * @param {string} content collapsable content
- *
- * @returns {Summary} summary instance
- */
- addDetails(label, content) {
- const element = this.wrap('details', this.wrap('summary', label) + content);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML image tag to the summary buffer
- *
- * @param {string} src path to the image you to embed
- * @param {string} alt text description of the image
- * @param {SummaryImageOptions} options (optional) addition image attributes
- *
- * @returns {Summary} summary instance
- */
- addImage(src, alt, options) {
- const { width, height } = options || {};
- const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
- const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML section heading element
- *
- * @param {string} text heading text
- * @param {number | string} [level=1] (optional) the heading level, default: 1
- *
- * @returns {Summary} summary instance
- */
- addHeading(text, level) {
- const tag = `h${level}`;
- const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
- ? tag
- : 'h1';
- const element = this.wrap(allowedTag, text);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML thematic break (
) to the summary buffer
- *
- * @returns {Summary} summary instance
- */
- addSeparator() {
- const element = this.wrap('hr', null);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML line break (
) to the summary buffer
- *
- * @returns {Summary} summary instance
- */
- addBreak() {
- const element = this.wrap('br', null);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML blockquote to the summary buffer
- *
- * @param {string} text quote text
- * @param {string} cite (optional) citation url
- *
- * @returns {Summary} summary instance
- */
- addQuote(text, cite) {
- const attrs = Object.assign({}, (cite && { cite }));
- const element = this.wrap('blockquote', text, attrs);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML anchor tag to the summary buffer
- *
- * @param {string} text link text/content
- * @param {string} href hyperlink
- *
- * @returns {Summary} summary instance
- */
- addLink(text, href) {
- const element = this.wrap('a', text, { href });
- return this.addRaw(element).addEOL();
- }
-}
-const _summary = new Summary();
-/**
- * @deprecated use `core.summary`
- */
-exports.markdownSummary = _summary;
-exports.summary = _summary;
-//# sourceMappingURL=summary.js.map
-/***/ }),
+// TODO:
+// * support 1 nested multipart level
+// (see second multipart example here:
+// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
+// * support limits.fieldNameSize
+// -- this will require modifications to utils.parseParams
-/***/ 5278:
-/***/ ((__unused_webpack_module, exports) => {
+const { Readable } = __nccwpck_require__(7075)
+const { inherits } = __nccwpck_require__(7975)
-"use strict";
+const Dicer = __nccwpck_require__(1715)
-// We use any as a valid input type
-/* eslint-disable @typescript-eslint/no-explicit-any */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toCommandProperties = exports.toCommandValue = void 0;
-/**
- * Sanitizes an input into a string so it can be passed into issueCommand safely
- * @param input input to sanitize into a string
- */
-function toCommandValue(input) {
- if (input === null || input === undefined) {
- return '';
- }
- else if (typeof input === 'string' || input instanceof String) {
- return input;
+const parseParams = __nccwpck_require__(8106)
+const decodeText = __nccwpck_require__(5422)
+const basename = __nccwpck_require__(4045)
+const getLimit = __nccwpck_require__(6424)
+
+const RE_BOUNDARY = /^boundary$/i
+const RE_FIELD = /^form-data$/i
+const RE_CHARSET = /^charset$/i
+const RE_FILENAME = /^filename$/i
+const RE_NAME = /^name$/i
+
+Multipart.detect = /^multipart\/form-data/i
+function Multipart (boy, cfg) {
+ let i
+ let len
+ const self = this
+ let boundary
+ const limits = cfg.limits
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
+ const parsedConType = cfg.parsedConType || []
+ const defCharset = cfg.defCharset || 'utf8'
+ const preservePath = cfg.preservePath
+ const fileOpts = { highWaterMark: cfg.fileHwm }
+
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
+ if (Array.isArray(parsedConType[i]) &&
+ RE_BOUNDARY.test(parsedConType[i][0])) {
+ boundary = parsedConType[i][1]
+ break
}
- return JSON.stringify(input);
-}
-exports.toCommandValue = toCommandValue;
-/**
- *
- * @param annotationProperties
- * @returns The command properties to send with the actual annotation command
- * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
- */
-function toCommandProperties(annotationProperties) {
- if (!Object.keys(annotationProperties).length) {
- return {};
+ }
+
+ function checkFinished () {
+ if (nends === 0 && finished && !boy._done) {
+ finished = false
+ self.end()
}
- return {
- title: annotationProperties.title,
- file: annotationProperties.file,
- line: annotationProperties.startLine,
- endLine: annotationProperties.endLine,
- col: annotationProperties.startColumn,
- endColumn: annotationProperties.endColumn
- };
-}
-exports.toCommandProperties = toCommandProperties;
-//# sourceMappingURL=utils.js.map
+ }
-/***/ }),
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
-/***/ 71514:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
+ const filesLimit = getLimit(limits, 'files', Infinity)
+ const fieldsLimit = getLimit(limits, 'fields', Infinity)
+ const partsLimit = getLimit(limits, 'parts', Infinity)
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
-"use strict";
+ let nfiles = 0
+ let nfields = 0
+ let nends = 0
+ let curFile
+ let curField
+ let finished = false
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getExecOutput = exports.exec = void 0;
-const string_decoder_1 = __nccwpck_require__(71576);
-const tr = __importStar(__nccwpck_require__(88159));
-/**
- * Exec a command.
- * Output will be streamed to the live console.
- * Returns promise with return code
- *
- * @param commandLine command to execute (can include additional args). Must be correctly escaped.
- * @param args optional arguments for tool. Escaping is handled by the lib.
- * @param options optional exec options. See ExecOptions
- * @returns Promise exit code
- */
-function exec(commandLine, args, options) {
- return __awaiter(this, void 0, void 0, function* () {
- const commandArgs = tr.argStringToArray(commandLine);
- if (commandArgs.length === 0) {
- throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
- }
- // Path to tool to execute should be first arg
- const toolPath = commandArgs[0];
- args = commandArgs.slice(1).concat(args || []);
- const runner = new tr.ToolRunner(toolPath, args, options);
- return runner.exec();
- });
-}
-exports.exec = exec;
-/**
- * Exec a command and get the output.
- * Output will be streamed to the live console.
- * Returns promise with the exit code and collected stdout and stderr
- *
- * @param commandLine command to execute (can include additional args). Must be correctly escaped.
- * @param args optional arguments for tool. Escaping is handled by the lib.
- * @param options optional exec options. See ExecOptions
- * @returns Promise exit code, stdout, and stderr
- */
-function getExecOutput(commandLine, args, options) {
- var _a, _b;
- return __awaiter(this, void 0, void 0, function* () {
- let stdout = '';
- let stderr = '';
- //Using string decoder covers the case where a mult-byte character is split
- const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
- const stderrDecoder = new string_decoder_1.StringDecoder('utf8');
- const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
- const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
- const stdErrListener = (data) => {
- stderr += stderrDecoder.write(data);
- if (originalStdErrListener) {
- originalStdErrListener(data);
- }
- };
- const stdOutListener = (data) => {
- stdout += stdoutDecoder.write(data);
- if (originalStdoutListener) {
- originalStdoutListener(data);
- }
- };
- const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });
- const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));
- //flush any remaining characters
- stdout += stdoutDecoder.end();
- stderr += stderrDecoder.end();
- return {
- exitCode,
- stdout,
- stderr
- };
- });
-}
-exports.getExecOutput = getExecOutput;
-//# sourceMappingURL=exec.js.map
+ this._needDrain = false
+ this._pause = false
+ this._cb = undefined
+ this._nparts = 0
+ this._boy = boy
-/***/ }),
+ const parserCfg = {
+ boundary,
+ maxHeaderPairs: headerPairsLimit,
+ maxHeaderSize: headerSizeLimit,
+ partHwm: fileOpts.highWaterMark,
+ highWaterMark: cfg.highWaterMark
+ }
-/***/ 88159:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ this.parser = new Dicer(parserCfg)
+ this.parser.on('drain', function () {
+ self._needDrain = false
+ if (self._cb && !self._pause) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }).on('part', function onPart (part) {
+ if (++self._nparts > partsLimit) {
+ self.parser.removeListener('part', onPart)
+ self.parser.on('part', skipPart)
+ boy.hitPartsLimit = true
+ boy.emit('partsLimit')
+ return skipPart(part)
+ }
-"use strict";
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
+ // us emit 'end' early since we know the part has ended if we are already
+ // seeing the next part
+ if (curField) {
+ const field = curField
+ field.emit('end')
+ field.removeAllListeners('end')
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.argStringToArray = exports.ToolRunner = void 0;
-const os = __importStar(__nccwpck_require__(22037));
-const events = __importStar(__nccwpck_require__(82361));
-const child = __importStar(__nccwpck_require__(32081));
-const path = __importStar(__nccwpck_require__(71017));
-const io = __importStar(__nccwpck_require__(47351));
-const ioUtil = __importStar(__nccwpck_require__(81962));
-const timers_1 = __nccwpck_require__(39512);
-/* eslint-disable @typescript-eslint/unbound-method */
-const IS_WINDOWS = process.platform === 'win32';
-/*
- * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
- */
-class ToolRunner extends events.EventEmitter {
- constructor(toolPath, args, options) {
- super();
- if (!toolPath) {
- throw new Error("Parameter 'toolPath' cannot be null or empty.");
+ part.on('header', function (header) {
+ let contype
+ let fieldname
+ let parsed
+ let charset
+ let encoding
+ let filename
+ let nsize = 0
+
+ if (header['content-type']) {
+ parsed = parseParams(header['content-type'][0])
+ if (parsed[0]) {
+ contype = parsed[0].toLowerCase()
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_CHARSET.test(parsed[i][0])) {
+ charset = parsed[i][1].toLowerCase()
+ break
+ }
+ }
}
- this.toolPath = toolPath;
- this.args = args || [];
- this.options = options || {};
- }
- _debug(message) {
- if (this.options.listeners && this.options.listeners.debug) {
- this.options.listeners.debug(message);
+ }
+
+ if (contype === undefined) { contype = 'text/plain' }
+ if (charset === undefined) { charset = defCharset }
+
+ if (header['content-disposition']) {
+ parsed = parseParams(header['content-disposition'][0])
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_NAME.test(parsed[i][0])) {
+ fieldname = parsed[i][1]
+ } else if (RE_FILENAME.test(parsed[i][0])) {
+ filename = parsed[i][1]
+ if (!preservePath) { filename = basename(filename) }
+ }
}
- }
- _getCommandString(options, noPrefix) {
- const toolPath = this._getSpawnFileName();
- const args = this._getSpawnArgs(options);
- let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
- if (IS_WINDOWS) {
- // Windows + cmd file
- if (this._isCmdFile()) {
- cmd += toolPath;
- for (const a of args) {
- cmd += ` ${a}`;
- }
- }
- // Windows + verbatim
- else if (options.windowsVerbatimArguments) {
- cmd += `"${toolPath}"`;
- for (const a of args) {
- cmd += ` ${a}`;
- }
- }
- // Windows (regular)
- else {
- cmd += this._windowsQuoteCmdArg(toolPath);
- for (const a of args) {
- cmd += ` ${this._windowsQuoteCmdArg(a)}`;
- }
- }
+ } else { return skipPart(part) }
+
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
+
+ let onData,
+ onEnd
+
+ if (isPartAFile(fieldname, contype, filename)) {
+ // file/binary field
+ if (nfiles === filesLimit) {
+ if (!boy.hitFilesLimit) {
+ boy.hitFilesLimit = true
+ boy.emit('filesLimit')
+ }
+ return skipPart(part)
}
- else {
- // OSX/Linux - this can likely be improved with some form of quoting.
- // creating processes on Unix is fundamentally different than Windows.
- // on Unix, execvp() takes an arg array.
- cmd += toolPath;
- for (const a of args) {
- cmd += ` ${a}`;
- }
+
+ ++nfiles
+
+ if (!boy._events.file) {
+ self.parser._ignore()
+ return
}
- return cmd;
- }
- _processLineBuffer(data, strBuffer, onLine) {
- try {
- let s = strBuffer + data.toString();
- let n = s.indexOf(os.EOL);
- while (n > -1) {
- const line = s.substring(0, n);
- onLine(line);
- // the rest of the string ...
- s = s.substring(n + os.EOL.length);
- n = s.indexOf(os.EOL);
- }
- return s;
+
+ ++nends
+ const file = new FileStream(fileOpts)
+ curFile = file
+ file.on('end', function () {
+ --nends
+ self._pause = false
+ checkFinished()
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ })
+ file._read = function (n) {
+ if (!self._pause) { return }
+ self._pause = false
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
}
- catch (err) {
- // streaming lines to console is best effort. Don't fail a build.
- this._debug(`error processing line. Failed with error ${err}`);
- return '';
+ boy.emit('file', fieldname, file, filename, encoding, contype)
+
+ onData = function (data) {
+ if ((nsize += data.length) > fileSizeLimit) {
+ const extralen = fileSizeLimit - nsize + data.length
+ if (extralen > 0) { file.push(data.slice(0, extralen)) }
+ file.truncated = true
+ file.bytesRead = fileSizeLimit
+ part.removeAllListeners('data')
+ file.emit('limit')
+ return
+ } else if (!file.push(data)) { self._pause = true }
+
+ file.bytesRead = nsize
}
- }
- _getSpawnFileName() {
- if (IS_WINDOWS) {
- if (this._isCmdFile()) {
- return process.env['COMSPEC'] || 'cmd.exe';
- }
+
+ onEnd = function () {
+ curFile = undefined
+ file.push(null)
}
- return this.toolPath;
- }
- _getSpawnArgs(options) {
- if (IS_WINDOWS) {
- if (this._isCmdFile()) {
- let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
- for (const a of this.args) {
- argline += ' ';
- argline += options.windowsVerbatimArguments
- ? a
- : this._windowsQuoteCmdArg(a);
- }
- argline += '"';
- return [argline];
- }
+ } else {
+ // non-file field
+ if (nfields === fieldsLimit) {
+ if (!boy.hitFieldsLimit) {
+ boy.hitFieldsLimit = true
+ boy.emit('fieldsLimit')
+ }
+ return skipPart(part)
}
- return this.args;
- }
- _endsWith(str, end) {
- return str.endsWith(end);
+
+ ++nfields
+ ++nends
+ let buffer = ''
+ let truncated = false
+ curField = part
+
+ onData = function (data) {
+ if ((nsize += data.length) > fieldSizeLimit) {
+ const extralen = (fieldSizeLimit - (nsize - data.length))
+ buffer += data.toString('binary', 0, extralen)
+ truncated = true
+ part.removeAllListeners('data')
+ } else { buffer += data.toString('binary') }
+ }
+
+ onEnd = function () {
+ curField = undefined
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
+ --nends
+ checkFinished()
+ }
+ }
+
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
+ broken. Streams2/streams3 is a huge black box of confusion, but
+ somehow overriding the sync state seems to fix things again (and still
+ seems to work for previous node versions).
+ */
+ part._readableState.sync = false
+
+ part.on('data', onData)
+ part.on('end', onEnd)
+ }).on('error', function (err) {
+ if (curFile) { curFile.emit('error', err) }
+ })
+ }).on('error', function (err) {
+ boy.emit('error', err)
+ }).on('finish', function () {
+ finished = true
+ checkFinished()
+ })
+}
+
+Multipart.prototype.write = function (chunk, cb) {
+ const r = this.parser.write(chunk)
+ if (r && !this._pause) {
+ cb()
+ } else {
+ this._needDrain = !r
+ this._cb = cb
+ }
+}
+
+Multipart.prototype.end = function () {
+ const self = this
+
+ if (self.parser.writable) {
+ self.parser.end()
+ } else if (!self._boy._done) {
+ process.nextTick(function () {
+ self._boy._done = true
+ self._boy.emit('finish')
+ })
+ }
+}
+
+function skipPart (part) {
+ part.resume()
+}
+
+function FileStream (opts) {
+ Readable.call(this, opts)
+
+ this.bytesRead = 0
+
+ this.truncated = false
+}
+
+inherits(FileStream, Readable)
+
+FileStream.prototype._read = function (n) {}
+
+module.exports = Multipart
+
+
+/***/ }),
+
+/***/ 5670:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Decoder = __nccwpck_require__(7259)
+const decodeText = __nccwpck_require__(5422)
+const getLimit = __nccwpck_require__(6424)
+
+const RE_CHARSET = /^charset$/i
+
+UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
+function UrlEncoded (boy, cfg) {
+ const limits = cfg.limits
+ const parsedConType = cfg.parsedConType
+ this.boy = boy
+
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+
+ let charset
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
+ if (Array.isArray(parsedConType[i]) &&
+ RE_CHARSET.test(parsedConType[i][0])) {
+ charset = parsedConType[i][1].toLowerCase()
+ break
}
- _isCmdFile() {
- const upperToolPath = this.toolPath.toUpperCase();
- return (this._endsWith(upperToolPath, '.CMD') ||
- this._endsWith(upperToolPath, '.BAT'));
+ }
+
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
+
+ this.decoder = new Decoder()
+ this.charset = charset
+ this._fields = 0
+ this._state = 'key'
+ this._checkingBytes = true
+ this._bytesKey = 0
+ this._bytesVal = 0
+ this._key = ''
+ this._val = ''
+ this._keyTrunc = false
+ this._valTrunc = false
+ this._hitLimit = false
+}
+
+UrlEncoded.prototype.write = function (data, cb) {
+ if (this._fields === this.fieldsLimit) {
+ if (!this.boy.hitFieldsLimit) {
+ this.boy.hitFieldsLimit = true
+ this.boy.emit('fieldsLimit')
}
- _windowsQuoteCmdArg(arg) {
- // for .exe, apply the normal quoting rules that libuv applies
- if (!this._isCmdFile()) {
- return this._uvQuoteCmdArg(arg);
+ return cb()
+ }
+
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length
+
+ while (p < len) {
+ if (this._state === 'key') {
+ idxeq = idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x3D/* = */) {
+ idxeq = i
+ break
+ } else if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
}
- // otherwise apply quoting rules specific to the cmd.exe command line parser.
- // the libuv rules are generic and are not designed specifically for cmd.exe
- // command line parser.
- //
- // for a detailed description of the cmd.exe command line parser, refer to
- // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
- // need quotes for empty arg
- if (!arg) {
- return '""';
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesKey }
+ }
+
+ if (idxeq !== undefined) {
+ // key with assignment
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
+ this._state = 'val'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._val = ''
+ this._bytesVal = 0
+ this._valTrunc = false
+ this.decoder.reset()
+
+ p = idxeq + 1
+ } else if (idxamp !== undefined) {
+ // key with no assignment
+ ++this._fields
+ let key; const keyTrunc = this._keyTrunc
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ if (key.length) {
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
+ '',
+ keyTrunc,
+ false)
}
- // determine whether the arg needs to be quoted
- const cmdSpecialChars = [
- ' ',
- '\t',
- '&',
- '(',
- ')',
- '[',
- ']',
- '{',
- '}',
- '^',
- '=',
- ';',
- '!',
- "'",
- '+',
- ',',
- '`',
- '~',
- '|',
- '<',
- '>',
- '"'
- ];
- let needsQuotes = false;
- for (const char of arg) {
- if (cmdSpecialChars.some(x => x === char)) {
- needsQuotes = true;
- break;
- }
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._keyTrunc = true
}
- // short-circuit if quotes not needed
- if (!needsQuotes) {
- return arg;
+ } else {
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
+ } else {
+ idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
}
- // the following quoting rules are very similar to the rules that by libuv applies.
- //
- // 1) wrap the string in quotes
- //
- // 2) double-up quotes - i.e. " => ""
- //
- // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
- // doesn't work well with a cmd.exe command line.
- //
- // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
- // for example, the command line:
- // foo.exe "myarg:""my val"""
- // is parsed by a .NET console app into an arg array:
- // [ "myarg:\"my val\"" ]
- // which is the same end result when applying libuv quoting rules. although the actual
- // command line from libuv quoting rules would look like:
- // foo.exe "myarg:\"my val\""
- //
- // 3) double-up slashes that precede a quote,
- // e.g. hello \world => "hello \world"
- // hello\"world => "hello\\""world"
- // hello\\"world => "hello\\\\""world"
- // hello world\ => "hello world\\"
- //
- // technically this is not required for a cmd.exe command line, or the batch argument parser.
- // the reasons for including this as a .cmd quoting rule are:
- //
- // a) this is optimized for the scenario where the argument is passed from the .cmd file to an
- // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
- //
- // b) it's what we've been doing previously (by deferring to node default behavior) and we
- // haven't heard any complaints about that aspect.
- //
- // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
- // escaped when used on the command line directly - even though within a .cmd file % can be escaped
- // by using %%.
- //
- // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
- // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
- //
- // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
- // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
- // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
- // to an external program.
- //
- // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
- // % can be escaped within a .cmd file.
- let reverse = '"';
- let quoteHit = true;
- for (let i = arg.length; i > 0; i--) {
- // walk the string in reverse
- reverse += arg[i - 1];
- if (quoteHit && arg[i - 1] === '\\') {
- reverse += '\\'; // double the slash
- }
- else if (arg[i - 1] === '"') {
- quoteHit = true;
- reverse += '"'; // double the quote
- }
- else {
- quoteHit = false;
- }
- }
- reverse += '"';
- return reverse
- .split('')
- .reverse()
- .join('');
- }
- _uvQuoteCmdArg(arg) {
- // Tool runner wraps child_process.spawn() and needs to apply the same quoting as
- // Node in certain cases where the undocumented spawn option windowsVerbatimArguments
- // is used.
- //
- // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
- // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
- // pasting copyright notice from Node within this function:
- //
- // Copyright Joyent, Inc. and other Node contributors. All rights reserved.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to
- // deal in the Software without restriction, including without limitation the
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- // sell copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- // IN THE SOFTWARE.
- if (!arg) {
- // Need double quotation for empty argument
- return '""';
- }
- if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
- // No quotation needed
- return arg;
- }
- if (!arg.includes('"') && !arg.includes('\\')) {
- // No embedded double quotes or backslashes, so I can just wrap
- // quote marks around the whole thing.
- return `"${arg}"`;
- }
- // Expected input/output:
- // input : hello"world
- // output: "hello\"world"
- // input : hello""world
- // output: "hello\"\"world"
- // input : hello\world
- // output: hello\world
- // input : hello\\world
- // output: hello\\world
- // input : hello\"world
- // output: "hello\\\"world"
- // input : hello\\"world
- // output: "hello\\\\\"world"
- // input : hello world\
- // output: "hello world\\" - note the comment in libuv actually reads "hello world\"
- // but it appears the comment is wrong, it should be "hello world\\"
- let reverse = '"';
- let quoteHit = true;
- for (let i = arg.length; i > 0; i--) {
- // walk the string in reverse
- reverse += arg[i - 1];
- if (quoteHit && arg[i - 1] === '\\') {
- reverse += '\\';
- }
- else if (arg[i - 1] === '"') {
- quoteHit = true;
- reverse += '\\';
- }
- else {
- quoteHit = false;
- }
- }
- reverse += '"';
- return reverse
- .split('')
- .reverse()
- .join('');
- }
- _cloneExecOptions(options) {
- options = options || {};
- const result = {
- cwd: options.cwd || process.cwd(),
- env: options.env || process.env,
- silent: options.silent || false,
- windowsVerbatimArguments: options.windowsVerbatimArguments || false,
- failOnStdErr: options.failOnStdErr || false,
- ignoreReturnCode: options.ignoreReturnCode || false,
- delay: options.delay || 10000
- };
- result.outStream = options.outStream || process.stdout;
- result.errStream = options.errStream || process.stderr;
- return result;
- }
- _getSpawnOptions(options, toolPath) {
- options = options || {};
- const result = {};
- result.cwd = options.cwd;
- result.env = options.env;
- result['windowsVerbatimArguments'] =
- options.windowsVerbatimArguments || this._isCmdFile();
- if (options.windowsVerbatimArguments) {
- result.argv0 = `"${toolPath}"`;
- }
- return result;
- }
- /**
- * Exec a tool.
- * Output will be streamed to the live console.
- * Returns promise with return code
- *
- * @param tool path to tool to exec
- * @param options optional exec options. See ExecOptions
- * @returns number
- */
- exec() {
- return __awaiter(this, void 0, void 0, function* () {
- // root the tool path if it is unrooted and contains relative pathing
- if (!ioUtil.isRooted(this.toolPath) &&
- (this.toolPath.includes('/') ||
- (IS_WINDOWS && this.toolPath.includes('\\')))) {
- // prefer options.cwd if it is specified, however options.cwd may also need to be rooted
- this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
- }
- // if the tool is only a file name, then resolve it from the PATH
- // otherwise verify it exists (add extension on Windows if necessary)
- this.toolPath = yield io.which(this.toolPath, true);
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
- this._debug(`exec tool: ${this.toolPath}`);
- this._debug('arguments:');
- for (const arg of this.args) {
- this._debug(` ${arg}`);
- }
- const optionsNonNull = this._cloneExecOptions(this.options);
- if (!optionsNonNull.silent && optionsNonNull.outStream) {
- optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
- }
- const state = new ExecState(optionsNonNull, this.toolPath);
- state.on('debug', (message) => {
- this._debug(message);
- });
- if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) {
- return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
- }
- const fileName = this._getSpawnFileName();
- const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
- let stdbuffer = '';
- if (cp.stdout) {
- cp.stdout.on('data', (data) => {
- if (this.options.listeners && this.options.listeners.stdout) {
- this.options.listeners.stdout(data);
- }
- if (!optionsNonNull.silent && optionsNonNull.outStream) {
- optionsNonNull.outStream.write(data);
- }
- stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
- if (this.options.listeners && this.options.listeners.stdline) {
- this.options.listeners.stdline(line);
- }
- });
- });
- }
- let errbuffer = '';
- if (cp.stderr) {
- cp.stderr.on('data', (data) => {
- state.processStderr = true;
- if (this.options.listeners && this.options.listeners.stderr) {
- this.options.listeners.stderr(data);
- }
- if (!optionsNonNull.silent &&
- optionsNonNull.errStream &&
- optionsNonNull.outStream) {
- const s = optionsNonNull.failOnStdErr
- ? optionsNonNull.errStream
- : optionsNonNull.outStream;
- s.write(data);
- }
- errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
- if (this.options.listeners && this.options.listeners.errline) {
- this.options.listeners.errline(line);
- }
- });
- });
- }
- cp.on('error', (err) => {
- state.processError = err.message;
- state.processExited = true;
- state.processClosed = true;
- state.CheckComplete();
- });
- cp.on('exit', (code) => {
- state.processExitCode = code;
- state.processExited = true;
- this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
- state.CheckComplete();
- });
- cp.on('close', (code) => {
- state.processExitCode = code;
- state.processExited = true;
- state.processClosed = true;
- this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
- state.CheckComplete();
- });
- state.on('done', (error, exitCode) => {
- if (stdbuffer.length > 0) {
- this.emit('stdline', stdbuffer);
- }
- if (errbuffer.length > 0) {
- this.emit('errline', errbuffer);
- }
- cp.removeAllListeners();
- if (error) {
- reject(error);
- }
- else {
- resolve(exitCode);
- }
- });
- if (this.options.input) {
- if (!cp.stdin) {
- throw new Error('child process missing stdin');
- }
- cp.stdin.end(this.options.input);
- }
- }));
- });
- }
-}
-exports.ToolRunner = ToolRunner;
-/**
- * Convert an arg string to an array of args. Handles escaping
- *
- * @param argString string of arguments
- * @returns string[] array of arguments
- */
-function argStringToArray(argString) {
- const args = [];
- let inQuotes = false;
- let escaped = false;
- let arg = '';
- function append(c) {
- // we only escape double quotes.
- if (escaped && c !== '"') {
- arg += '\\';
- }
- arg += c;
- escaped = false;
- }
- for (let i = 0; i < argString.length; i++) {
- const c = argString.charAt(i);
- if (c === '"') {
- if (!escaped) {
- inQuotes = !inQuotes;
- }
- else {
- append(c);
- }
- continue;
- }
- if (c === '\\' && escaped) {
- append(c);
- continue;
- }
- if (c === '\\' && inQuotes) {
- escaped = true;
- continue;
- }
- if (c === ' ' && !inQuotes) {
- if (arg.length > 0) {
- args.push(arg);
- arg = '';
- }
- continue;
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesVal }
+ }
+
+ if (idxamp !== undefined) {
+ ++this._fields
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ this._state = 'key'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._valTrunc = true
}
- append(c);
- }
- if (arg.length > 0) {
- args.push(arg.trim());
+ } else {
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
}
- return args;
+ }
+ cb()
}
-exports.argStringToArray = argStringToArray;
-class ExecState extends events.EventEmitter {
- constructor(options, toolPath) {
- super();
- this.processClosed = false; // tracks whether the process has exited and stdio is closed
- this.processError = '';
- this.processExitCode = 0;
- this.processExited = false; // tracks whether the process has exited
- this.processStderr = false; // tracks whether stderr was written to
- this.delay = 10000; // 10 seconds
- this.done = false;
- this.timeout = null;
- if (!toolPath) {
- throw new Error('toolPath must not be empty');
- }
- this.options = options;
- this.toolPath = toolPath;
- if (options.delay) {
- this.delay = options.delay;
- }
- }
- CheckComplete() {
- if (this.done) {
- return;
- }
- if (this.processClosed) {
- this._setResult();
- }
- else if (this.processExited) {
- this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this);
- }
- }
- _debug(message) {
- this.emit('debug', message);
- }
- _setResult() {
- // determine whether there is an error
- let error;
- if (this.processExited) {
- if (this.processError) {
- error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
- }
- else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
- error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
- }
- else if (this.processStderr && this.options.failOnStdErr) {
- error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
- }
- }
- // clear the timeout
- if (this.timeout) {
- clearTimeout(this.timeout);
- this.timeout = null;
- }
- this.done = true;
- this.emit('done', error, this.processExitCode);
- }
- static HandleTimeout(state) {
- if (state.done) {
- return;
- }
- if (!state.processClosed && state.processExited) {
- const message = `The STDIO streams did not close within ${state.delay /
- 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
- state._debug(message);
- }
- state._setResult();
- }
+
+UrlEncoded.prototype.end = function () {
+ if (this.boy._done) { return }
+
+ if (this._state === 'key' && this._key.length > 0) {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ '',
+ this._keyTrunc,
+ false)
+ } else if (this._state === 'val') {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ }
+ this.boy._done = true
+ this.boy.emit('finish')
}
-//# sourceMappingURL=toolrunner.js.map
+
+module.exports = UrlEncoded
+
/***/ }),
-/***/ 74087:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 7259:
+/***/ ((module) => {
-"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Context = void 0;
-const fs_1 = __nccwpck_require__(57147);
-const os_1 = __nccwpck_require__(22037);
-class Context {
- /**
- * Hydrate the context from the environment
- */
- constructor() {
- var _a, _b, _c;
- this.payload = {};
- if (process.env.GITHUB_EVENT_PATH) {
- if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) {
- this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));
- }
- else {
- const path = process.env.GITHUB_EVENT_PATH;
- process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);
- }
- }
- this.eventName = process.env.GITHUB_EVENT_NAME;
- this.sha = process.env.GITHUB_SHA;
- this.ref = process.env.GITHUB_REF;
- this.workflow = process.env.GITHUB_WORKFLOW;
- this.action = process.env.GITHUB_ACTION;
- this.actor = process.env.GITHUB_ACTOR;
- this.job = process.env.GITHUB_JOB;
- this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);
- this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);
- this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`;
- this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`;
- this.graphqlUrl =
- (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`;
- }
- get issue() {
- const payload = this.payload;
- return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });
- }
- get repo() {
- if (process.env.GITHUB_REPOSITORY) {
- const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');
- return { owner, repo };
- }
- if (this.payload.repository) {
- return {
- owner: this.payload.repository.owner.login,
- repo: this.payload.repository.name
- };
+
+const RE_PLUS = /\+/g
+
+const HEX = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+]
+
+function Decoder () {
+ this.buffer = undefined
+}
+Decoder.prototype.write = function (str) {
+ // Replace '+' with ' ' before decoding
+ str = str.replace(RE_PLUS, ' ')
+ let res = ''
+ let i = 0; let p = 0; const len = str.length
+ for (; i < len; ++i) {
+ if (this.buffer !== undefined) {
+ if (!HEX[str.charCodeAt(i)]) {
+ res += '%' + this.buffer
+ this.buffer = undefined
+ --i // retry character
+ } else {
+ this.buffer += str[i]
+ ++p
+ if (this.buffer.length === 2) {
+ res += String.fromCharCode(parseInt(this.buffer, 16))
+ this.buffer = undefined
}
- throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'");
+ }
+ } else if (str[i] === '%') {
+ if (i > p) {
+ res += str.substring(p, i)
+ p = i
+ }
+ this.buffer = ''
+ ++p
}
+ }
+ if (p < len && this.buffer === undefined) { res += str.substring(p) }
+ return res
+}
+Decoder.prototype.reset = function () {
+ this.buffer = undefined
}
-exports.Context = Context;
-//# sourceMappingURL=context.js.map
+
+module.exports = Decoder
+
/***/ }),
-/***/ 95438:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 4045:
+/***/ ((module) => {
-"use strict";
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getOctokit = exports.context = void 0;
-const Context = __importStar(__nccwpck_require__(74087));
-const utils_1 = __nccwpck_require__(73030);
-exports.context = new Context.Context();
-/**
- * Returns a hydrated octokit ready to use for GitHub Actions
- *
- * @param token the repo PAT or GITHUB_TOKEN
- * @param options other options to set
- */
-function getOctokit(token, options, ...additionalPlugins) {
- const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins);
- return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options));
-}
-exports.getOctokit = getOctokit;
-//# sourceMappingURL=github.js.map
-
-/***/ }),
-/***/ 47914:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+module.exports = function basename (path) {
+ if (typeof path !== 'string') { return '' }
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
+ switch (path.charCodeAt(i)) {
+ case 0x2F: // '/'
+ case 0x5C: // '\'
+ path = path.slice(i + 1)
+ return (path === '..' || path === '.' ? '' : path)
}
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0;
-const httpClient = __importStar(__nccwpck_require__(96255));
-const undici_1 = __nccwpck_require__(41773);
-function getAuthString(token, options) {
- if (!token && !options.auth) {
- throw new Error('Parameter token or opts.auth is required');
- }
- else if (token && options.auth) {
- throw new Error('Parameters token and opts.auth may not both be specified');
- }
- return typeof options.auth === 'string' ? options.auth : `token ${token}`;
-}
-exports.getAuthString = getAuthString;
-function getProxyAgent(destinationUrl) {
- const hc = new httpClient.HttpClient();
- return hc.getAgent(destinationUrl);
-}
-exports.getProxyAgent = getProxyAgent;
-function getProxyAgentDispatcher(destinationUrl) {
- const hc = new httpClient.HttpClient();
- return hc.getAgentDispatcher(destinationUrl);
-}
-exports.getProxyAgentDispatcher = getProxyAgentDispatcher;
-function getProxyFetch(destinationUrl) {
- const httpDispatcher = getProxyAgentDispatcher(destinationUrl);
- const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () {
- return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));
- });
- return proxyFetch;
-}
-exports.getProxyFetch = getProxyFetch;
-function getApiBaseUrl() {
- return process.env['GITHUB_API_URL'] || 'https://api.github.com';
+ }
+ return (path === '..' || path === '.' ? '' : path)
}
-exports.getApiBaseUrl = getApiBaseUrl;
-//# sourceMappingURL=utils.js.map
-/***/ }),
-
-/***/ 73030:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0;
-const Context = __importStar(__nccwpck_require__(74087));
-const Utils = __importStar(__nccwpck_require__(47914));
-// octokit + plugins
-const core_1 = __nccwpck_require__(18525);
-const plugin_rest_endpoint_methods_1 = __nccwpck_require__(94045);
-const plugin_paginate_rest_1 = __nccwpck_require__(48945);
-exports.context = new Context.Context();
-const baseUrl = Utils.getApiBaseUrl();
-exports.defaults = {
- baseUrl,
- request: {
- agent: Utils.getProxyAgent(baseUrl),
- fetch: Utils.getProxyFetch(baseUrl)
- }
-};
-exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults);
-/**
- * Convience function to correctly format Octokit Options to pass into the constructor.
- *
- * @param token the repo PAT or GITHUB_TOKEN
- * @param options other options to set
- */
-function getOctokitOptions(token, options) {
- const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller
- // Auth
- const auth = Utils.getAuthString(token, opts);
- if (auth) {
- opts.auth = auth;
- }
- return opts;
-}
-exports.getOctokitOptions = getOctokitOptions;
-//# sourceMappingURL=utils.js.map
/***/ }),
-/***/ 40673:
+/***/ 5422:
/***/ ((module) => {
-"use strict";
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- createTokenAuth: () => createTokenAuth
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/auth.js
-var REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
-var REGEX_IS_INSTALLATION = /^ghs_/;
-var REGEX_IS_USER_TO_SERVER = /^ghu_/;
-async function auth(token) {
- const isApp = token.split(/\./).length === 3;
- const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
- const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
- const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
- return {
- type: "token",
- token,
- tokenType
- };
-}
+// Node has always utf-8
+const utf8Decoder = new TextDecoder('utf-8')
+const textDecoders = new Map([
+ ['utf-8', utf8Decoder],
+ ['utf8', utf8Decoder]
+])
-// pkg/dist-src/with-authorization-prefix.js
-function withAuthorizationPrefix(token) {
- if (token.split(/\./).length === 3) {
- return `bearer ${token}`;
+function decodeText (text, textEncoding, destEncoding) {
+ if (text) {
+ if (textDecoders.has(destEncoding)) {
+ try {
+ return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
+ } catch (e) { }
+ } else {
+ try {
+ textDecoders.set(destEncoding, new TextDecoder(destEncoding))
+ return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
+ } catch (e) { }
+ }
}
- return `token ${token}`;
-}
-
-// pkg/dist-src/hook.js
-async function hook(token, request, route, parameters) {
- const endpoint = request.endpoint.merge(
- route,
- parameters
- );
- endpoint.headers.authorization = withAuthorizationPrefix(token);
- return request(endpoint);
+ return text
}
-// pkg/dist-src/index.js
-var createTokenAuth = function createTokenAuth2(token) {
- if (!token) {
- throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
- }
- if (typeof token !== "string") {
- throw new Error(
- "[@octokit/auth-token] Token passed to createTokenAuth is not a string"
- );
- }
- token = token.replace(/^(token|bearer) +/i, "");
- return Object.assign(auth.bind(null, token), {
- hook: hook.bind(null, token)
- });
-};
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+module.exports = decodeText
/***/ }),
-/***/ 18525:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+/***/ 6424:
+/***/ ((module) => {
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- Octokit: () => Octokit
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_universal_user_agent = __nccwpck_require__(45030);
-var import_before_after_hook = __nccwpck_require__(83682);
-var import_request = __nccwpck_require__(89353);
-var import_graphql = __nccwpck_require__(86422);
-var import_auth_token = __nccwpck_require__(40673);
-
-// pkg/dist-src/version.js
-var VERSION = "5.0.1";
-
-// pkg/dist-src/index.js
-var Octokit = class {
- static {
- this.VERSION = VERSION;
- }
- static defaults(defaults) {
- const OctokitWithDefaults = class extends this {
- constructor(...args) {
- const options = args[0] || {};
- if (typeof defaults === "function") {
- super(defaults(options));
- return;
- }
- super(
- Object.assign(
- {},
- defaults,
- options,
- options.userAgent && defaults.userAgent ? {
- userAgent: `${options.userAgent} ${defaults.userAgent}`
- } : null
- )
- );
- }
- };
- return OctokitWithDefaults;
- }
- static {
- this.plugins = [];
- }
- /**
- * Attach a plugin (or many) to your Octokit instance.
- *
- * @example
- * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
- */
- static plugin(...newPlugins) {
- const currentPlugins = this.plugins;
- const NewOctokit = class extends this {
- static {
- this.plugins = currentPlugins.concat(
- newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
- );
- }
- };
- return NewOctokit;
- }
- constructor(options = {}) {
- const hook = new import_before_after_hook.Collection();
- const requestDefaults = {
- baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl,
- headers: {},
- request: Object.assign({}, options.request, {
- // @ts-ignore internal usage only, no need to type
- hook: hook.bind(null, "request")
- }),
- mediaType: {
- previews: [],
- format: ""
- }
- };
- requestDefaults.headers["user-agent"] = [
- options.userAgent,
- `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
- ].filter(Boolean).join(" ");
- if (options.baseUrl) {
- requestDefaults.baseUrl = options.baseUrl;
- }
- if (options.previews) {
- requestDefaults.mediaType.previews = options.previews;
- }
- if (options.timeZone) {
- requestDefaults.headers["time-zone"] = options.timeZone;
- }
- this.request = import_request.request.defaults(requestDefaults);
- this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults);
- this.log = Object.assign(
- {
- debug: () => {
- },
- info: () => {
- },
- warn: console.warn.bind(console),
- error: console.error.bind(console)
- },
- options.log
- );
- this.hook = hook;
- if (!options.authStrategy) {
- if (!options.auth) {
- this.auth = async () => ({
- type: "unauthenticated"
- });
- } else {
- const auth = (0, import_auth_token.createTokenAuth)(options.auth);
- hook.wrap("request", auth.hook);
- this.auth = auth;
- }
- } else {
- const { authStrategy, ...otherOptions } = options;
- const auth = authStrategy(
- Object.assign(
- {
- request: this.request,
- log: this.log,
- // we pass the current octokit instance as well as its constructor options
- // to allow for authentication strategies that return a new octokit instance
- // that shares the same internal state as the current one. The original
- // requirement for this was the "event-octokit" authentication strategy
- // of https://github.com/probot/octokit-auth-probot.
- octokit: this,
- octokitOptions: otherOptions
- },
- options.auth
- )
- );
- hook.wrap("request", auth.hook);
- this.auth = auth;
- }
- const classConstructor = this.constructor;
- classConstructor.plugins.forEach((plugin) => {
- Object.assign(this, plugin(this, options));
- });
- }
-};
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+module.exports = function getLimit (limits, name, defaultLimit) {
+ if (
+ !limits ||
+ limits[name] === undefined ||
+ limits[name] === null
+ ) { return defaultLimit }
-/***/ }),
+ if (
+ typeof limits[name] !== 'number' ||
+ isNaN(limits[name])
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
-/***/ 38713:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return limits[name]
+}
-"use strict";
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+/***/ }),
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- endpoint: () => endpoint
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/defaults.js
-var import_universal_user_agent = __nccwpck_require__(45030);
-
-// pkg/dist-src/version.js
-var VERSION = "9.0.1";
-
-// pkg/dist-src/defaults.js
-var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
-var DEFAULTS = {
- method: "GET",
- baseUrl: "https://api.github.com",
- headers: {
- accept: "application/vnd.github.v3+json",
- "user-agent": userAgent
- },
- mediaType: {
- format: ""
- }
-};
+/***/ 8106:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// pkg/dist-src/util/lowercase-keys.js
-function lowercaseKeys(object) {
- if (!object) {
- return {};
- }
- return Object.keys(object).reduce((newObj, key) => {
- newObj[key.toLowerCase()] = object[key];
- return newObj;
- }, {});
-}
-
-// pkg/dist-src/util/merge-deep.js
-var import_is_plain_object = __nccwpck_require__(63287);
-function mergeDeep(defaults, options) {
- const result = Object.assign({}, defaults);
- Object.keys(options).forEach((key) => {
- if ((0, import_is_plain_object.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;
-}
-// pkg/dist-src/util/remove-undefined-properties.js
-function removeUndefinedProperties(obj) {
- for (const key in obj) {
- if (obj[key] === void 0) {
- delete obj[key];
- }
- }
- return obj;
-}
-// pkg/dist-src/merge.js
-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 = Object.assign({}, route);
- }
- options.headers = lowercaseKeys(options.headers);
- removeUndefinedProperties(options);
- removeUndefinedProperties(options.headers);
- const mergedOptions = mergeDeep(defaults || {}, options);
- if (options.url === "/graphql") {
- 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;
-}
+const decodeText = __nccwpck_require__(5422)
-// pkg/dist-src/util/add-query-parameters.js
-function addQueryParameters(url, parameters) {
- const separator = /\?/.test(url) ? "&" : "?";
- const names = Object.keys(parameters);
- if (names.length === 0) {
- return url;
- }
- return url + separator + names.map((name) => {
- if (name === "q") {
- return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
- }
- return `${name}=${encodeURIComponent(parameters[name])}`;
- }).join("&");
-}
+const RE_ENCODED = /%([a-fA-F0-9]{2})/g
-// pkg/dist-src/util/extract-url-variable-names.js
-var urlVariableRegex = /\{[^}]+\}/g;
-function removeNonChars(variableName) {
- return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
-}
-function extractUrlVariableNames(url) {
- const matches = url.match(urlVariableRegex);
- if (!matches) {
- return [];
- }
- return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+function encodedReplacer (match, byte) {
+ return String.fromCharCode(parseInt(byte, 16))
}
-// pkg/dist-src/util/omit.js
-function omit(object, keysToOmit) {
- return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => {
- obj[key] = object[key];
- return obj;
- }, {});
-}
+function parseParams (str) {
+ const res = []
+ let state = 'key'
+ let charset = ''
+ let inquote = false
+ let escaping = false
+ let p = 0
+ let tmp = ''
-// pkg/dist-src/util/url-template.js
-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 !== void 0 && 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));
+ for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var
+ const char = str[i]
+ if (char === '\\' && inquote) {
+ if (escaping) { escaping = false } else {
+ escaping = true
+ continue
}
- result.push(
- encodeValue(operator, value, isKeyOperator(operator) ? key : "")
- );
+ } else if (char === '"') {
+ if (!escaping) {
+ if (inquote) {
+ inquote = false
+ state = 'key'
+ } else { inquote = true }
+ continue
+ } else { escaping = false }
} else {
- if (modifier === "*") {
- if (Array.isArray(value)) {
- value.filter(isDefined).forEach(function(value2) {
- result.push(
- encodeValue(operator, value2, 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(value2) {
- tmp.push(encodeValue(operator, value2));
- });
- } 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;
+ if (escaping && inquote) { tmp += '\\' }
+ escaping = false
+ if ((state === 'charset' || state === 'lang') && char === "'") {
+ if (state === 'charset') {
+ state = 'lang'
+ charset = tmp.substring(1)
+ } else { state = 'value' }
+ tmp = ''
+ continue
+ } else if (state === 'key' &&
+ (char === '*' || char === '=') &&
+ res.length) {
+ if (char === '*') { state = 'charset' } else { state = 'value' }
+ res[p] = [tmp, undefined]
+ tmp = ''
+ continue
+ } else if (!inquote && char === ';') {
+ state = 'key'
+ if (charset) {
+ if (tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
}
- return (values.length !== 0 ? operator : "") + values.join(separator);
- } else {
- return values.join(",");
+ charset = ''
+ } else if (tmp.length) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
}
- } else {
- return encodeReserved(literal);
- }
- }
- );
-}
-
-// pkg/dist-src/parse.js
-function parse(options) {
- let method = options.method.toUpperCase();
- let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
- let headers = Object.assign({}, options.headers);
- let body;
- let parameters = omit(options, [
- "method",
- "baseUrl",
- "url",
- "headers",
- "request",
- "mediaType"
- ]);
- const urlVariableNames = extractUrlVariableNames(url);
- url = parseUrl(url).expand(parameters);
- if (!/^http/.test(url)) {
- url = options.baseUrl + url;
- }
- const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
- const remainingParameters = omit(parameters, omittedParameters);
- const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
- if (!isBinaryRequest) {
- if (options.mediaType.format) {
- headers.accept = headers.accept.split(/,/).map(
- (format) => format.replace(
- /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
- `application/vnd$1$2.${options.mediaType.format}`
- )
- ).join(",");
- }
- if (url.endsWith("/graphql")) {
- if (options.mediaType.previews?.length) {
- const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
- headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
- const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
- return `application/vnd.github.${preview}-preview${format}`;
- }).join(",");
- }
- }
- }
- if (["GET", "HEAD"].includes(method)) {
- url = addQueryParameters(url, remainingParameters);
- } else {
- if ("data" in remainingParameters) {
- body = remainingParameters.data;
- } else {
- if (Object.keys(remainingParameters).length) {
- body = remainingParameters;
- }
+ if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+ tmp = ''
+ ++p
+ continue
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
}
+ tmp += char
}
- if (!headers["content-type"] && typeof body !== "undefined") {
- headers["content-type"] = "application/json; charset=utf-8";
- }
- if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
- body = "";
+ if (charset && tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ } else if (tmp) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
}
- return Object.assign(
- { method, url, headers },
- typeof body !== "undefined" ? { body } : null,
- options.request ? { request: options.request } : null
- );
-}
-// pkg/dist-src/endpoint-with-defaults.js
-function endpointWithDefaults(defaults, route, options) {
- return parse(merge(defaults, route, options));
-}
+ if (res[p] === undefined) {
+ if (tmp) { res[p] = tmp }
+ } else { res[p][1] = tmp }
-// pkg/dist-src/with-defaults.js
-function withDefaults(oldDefaults, newDefaults) {
- const DEFAULTS2 = merge(oldDefaults, newDefaults);
- const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
- return Object.assign(endpoint2, {
- DEFAULTS: DEFAULTS2,
- defaults: withDefaults.bind(null, DEFAULTS2),
- merge: merge.bind(null, DEFAULTS2),
- parse
- });
+ return res
}
-// pkg/dist-src/index.js
-var endpoint = withDefaults(null, DEFAULTS);
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+module.exports = parseParams
/***/ }),
-/***/ 86422:
+/***/ 770:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
+module.exports = __nccwpck_require__(218);
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- GraphqlResponseError: () => GraphqlResponseError,
- graphql: () => graphql2,
- withCustomRequest: () => withCustomRequest
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_request3 = __nccwpck_require__(89353);
-var import_universal_user_agent = __nccwpck_require__(45030);
-// pkg/dist-src/version.js
-var VERSION = "7.0.2";
+/***/ }),
-// pkg/dist-src/with-defaults.js
-var import_request2 = __nccwpck_require__(89353);
+/***/ 218:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// pkg/dist-src/graphql.js
-var import_request = __nccwpck_require__(89353);
-// pkg/dist-src/error.js
-function _buildMessageForResponseErrors(data) {
- return `Request failed due to following response errors:
-` + data.errors.map((e) => ` - ${e.message}`).join("\n");
-}
-var GraphqlResponseError = class extends Error {
- constructor(request2, headers, response) {
- super(_buildMessageForResponseErrors(response));
- this.request = request2;
- this.headers = headers;
- this.response = response;
- this.name = "GraphqlResponseError";
- this.errors = response.errors;
- this.data = response.data;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
- }
-};
-// pkg/dist-src/graphql.js
-var NON_VARIABLE_OPTIONS = [
- "method",
- "baseUrl",
- "url",
- "headers",
- "request",
- "query",
- "mediaType"
-];
-var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
-var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
-function graphql(request2, query, options) {
- if (options) {
- if (typeof query === "string" && "query" in options) {
- return Promise.reject(
- new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
- );
- }
- for (const key in options) {
- if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
- continue;
- return Promise.reject(
- new Error(
- `[@octokit/graphql] "${key}" cannot be used as variable name`
- )
- );
- }
- }
- const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
- const requestOptions = Object.keys(
- parsedOptions
- ).reduce((result, key) => {
- if (NON_VARIABLE_OPTIONS.includes(key)) {
- result[key] = parsedOptions[key];
- return result;
- }
- if (!result.variables) {
- result.variables = {};
- }
- result.variables[key] = parsedOptions[key];
- return result;
- }, {});
- const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
- if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
- requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
- }
- return request2(requestOptions).then((response) => {
- if (response.data.errors) {
- const headers = {};
- for (const key of Object.keys(response.headers)) {
- headers[key] = response.headers[key];
- }
- throw new GraphqlResponseError(
- requestOptions,
- headers,
- response.data
- );
- }
- return response.data.data;
- });
-}
+var net = __nccwpck_require__(9278);
+var tls = __nccwpck_require__(4756);
+var http = __nccwpck_require__(8611);
+var https = __nccwpck_require__(5692);
+var events = __nccwpck_require__(4434);
+var assert = __nccwpck_require__(2613);
+var util = __nccwpck_require__(9023);
-// pkg/dist-src/with-defaults.js
-function withDefaults(request2, newDefaults) {
- const newRequest = request2.defaults(newDefaults);
- const newApi = (query, options) => {
- return graphql(newRequest, query, options);
- };
- return Object.assign(newApi, {
- defaults: withDefaults.bind(null, newRequest),
- endpoint: newRequest.endpoint
- });
-}
-// pkg/dist-src/index.js
-var graphql2 = withDefaults(import_request3.request, {
- headers: {
- "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
- },
- method: "POST",
- url: "/graphql"
-});
-function withCustomRequest(customRequest) {
- return withDefaults(customRequest, {
- method: "POST",
- url: "/graphql"
- });
-}
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+exports.httpOverHttp = httpOverHttp;
+exports.httpsOverHttp = httpsOverHttp;
+exports.httpOverHttps = httpOverHttps;
+exports.httpsOverHttps = httpsOverHttps;
-/***/ }),
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
+}
-/***/ 48945:
-/***/ ((module) => {
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
-"use strict";
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
+}
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- composePaginateRest: () => composePaginateRest,
- isPaginatingEndpoint: () => isPaginatingEndpoint,
- paginateRest: () => paginateRest,
- paginatingEndpoints: () => paginatingEndpoints
-});
-module.exports = __toCommonJS(dist_src_exports);
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
-// pkg/dist-src/version.js
-var VERSION = "9.0.0";
-// pkg/dist-src/normalize-paginated-list-response.js
-function normalizePaginatedListResponse(response) {
- if (!response.data) {
- return {
- ...response,
- data: []
- };
- }
- const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
- if (!responseNeedsNormalization)
- return response;
- const incompleteResults = response.data.incomplete_results;
- const repositorySelection = response.data.repository_selection;
- const totalCount = response.data.total_count;
- delete response.data.incomplete_results;
- delete response.data.repository_selection;
- delete response.data.total_count;
- const namespaceKey = Object.keys(response.data)[0];
- const data = response.data[namespaceKey];
- response.data = data;
- if (typeof incompleteResults !== "undefined") {
- response.data.incomplete_results = incompleteResults;
- }
- if (typeof repositorySelection !== "undefined") {
- response.data.repository_selection = repositorySelection;
- }
- response.data.total_count = totalCount;
- return response;
-}
-
-// pkg/dist-src/iterator.js
-function iterator(octokit, route, parameters) {
- const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
- const requestMethod = typeof route === "function" ? route : octokit.request;
- const method = options.method;
- const headers = options.headers;
- let url = options.url;
- return {
- [Symbol.asyncIterator]: () => ({
- async next() {
- if (!url)
- return { done: true };
- try {
- const response = await requestMethod({ method, url, headers });
- const normalizedResponse = normalizePaginatedListResponse(response);
- url = ((normalizedResponse.headers.link || "").match(
- /<([^>]+)>;\s*rel="next"/
- ) || [])[1];
- return { value: normalizedResponse };
- } catch (error) {
- if (error.status !== 409)
- throw error;
- url = "";
- return {
- value: {
- status: 200,
- headers: {},
- data: []
- }
- };
- }
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
+
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
}
- })
- };
-}
-
-// pkg/dist-src/paginate.js
-function paginate(octokit, route, parameters, mapFn) {
- if (typeof parameters === "function") {
- mapFn = parameters;
- parameters = void 0;
- }
- return gather(
- octokit,
- [],
- iterator(octokit, route, parameters)[Symbol.asyncIterator](),
- mapFn
- );
-}
-function gather(octokit, results, iterator2, mapFn) {
- return iterator2.next().then((result) => {
- if (result.done) {
- return results;
- }
- let earlyExit = false;
- function done() {
- earlyExit = true;
- }
- results = results.concat(
- mapFn ? mapFn(result.value, done) : result.value.data
- );
- if (earlyExit) {
- return results;
- }
- return gather(octokit, results, iterator2, mapFn);
+ }
+ socket.destroy();
+ self.removeSocket(socket);
});
}
+util.inherits(TunnelingAgent, events.EventEmitter);
-// pkg/dist-src/compose-paginate.js
-var composePaginateRest = Object.assign(paginate, {
- iterator
-});
-
-// pkg/dist-src/generated/paginating-endpoints.js
-var paginatingEndpoints = [
- "GET /advisories",
- "GET /app/hook/deliveries",
- "GET /app/installation-requests",
- "GET /app/installations",
- "GET /assignments/{assignment_id}/accepted_assignments",
- "GET /classrooms",
- "GET /classrooms/{classroom_id}/assignments",
- "GET /enterprises/{enterprise}/dependabot/alerts",
- "GET /enterprises/{enterprise}/secret-scanning/alerts",
- "GET /events",
- "GET /gists",
- "GET /gists/public",
- "GET /gists/starred",
- "GET /gists/{gist_id}/comments",
- "GET /gists/{gist_id}/commits",
- "GET /gists/{gist_id}/forks",
- "GET /installation/repositories",
- "GET /issues",
- "GET /licenses",
- "GET /marketplace_listing/plans",
- "GET /marketplace_listing/plans/{plan_id}/accounts",
- "GET /marketplace_listing/stubbed/plans",
- "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
- "GET /networks/{owner}/{repo}/events",
- "GET /notifications",
- "GET /organizations",
- "GET /orgs/{org}/actions/cache/usage-by-repository",
- "GET /orgs/{org}/actions/permissions/repositories",
- "GET /orgs/{org}/actions/runners",
- "GET /orgs/{org}/actions/secrets",
- "GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
- "GET /orgs/{org}/actions/variables",
- "GET /orgs/{org}/actions/variables/{name}/repositories",
- "GET /orgs/{org}/blocks",
- "GET /orgs/{org}/code-scanning/alerts",
- "GET /orgs/{org}/codespaces",
- "GET /orgs/{org}/codespaces/secrets",
- "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories",
- "GET /orgs/{org}/copilot/billing/seats",
- "GET /orgs/{org}/dependabot/alerts",
- "GET /orgs/{org}/dependabot/secrets",
- "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
- "GET /orgs/{org}/events",
- "GET /orgs/{org}/failed_invitations",
- "GET /orgs/{org}/hooks",
- "GET /orgs/{org}/hooks/{hook_id}/deliveries",
- "GET /orgs/{org}/installations",
- "GET /orgs/{org}/invitations",
- "GET /orgs/{org}/invitations/{invitation_id}/teams",
- "GET /orgs/{org}/issues",
- "GET /orgs/{org}/members",
- "GET /orgs/{org}/members/{username}/codespaces",
- "GET /orgs/{org}/migrations",
- "GET /orgs/{org}/migrations/{migration_id}/repositories",
- "GET /orgs/{org}/outside_collaborators",
- "GET /orgs/{org}/packages",
- "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
- "GET /orgs/{org}/personal-access-token-requests",
- "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories",
- "GET /orgs/{org}/personal-access-tokens",
- "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories",
- "GET /orgs/{org}/projects",
- "GET /orgs/{org}/public_members",
- "GET /orgs/{org}/repos",
- "GET /orgs/{org}/rulesets",
- "GET /orgs/{org}/secret-scanning/alerts",
- "GET /orgs/{org}/security-advisories",
- "GET /orgs/{org}/teams",
- "GET /orgs/{org}/teams/{team_slug}/discussions",
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
- "GET /orgs/{org}/teams/{team_slug}/invitations",
- "GET /orgs/{org}/teams/{team_slug}/members",
- "GET /orgs/{org}/teams/{team_slug}/projects",
- "GET /orgs/{org}/teams/{team_slug}/repos",
- "GET /orgs/{org}/teams/{team_slug}/teams",
- "GET /projects/columns/{column_id}/cards",
- "GET /projects/{project_id}/collaborators",
- "GET /projects/{project_id}/columns",
- "GET /repos/{owner}/{repo}/actions/artifacts",
- "GET /repos/{owner}/{repo}/actions/caches",
- "GET /repos/{owner}/{repo}/actions/organization-secrets",
- "GET /repos/{owner}/{repo}/actions/organization-variables",
- "GET /repos/{owner}/{repo}/actions/runners",
- "GET /repos/{owner}/{repo}/actions/runs",
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
- "GET /repos/{owner}/{repo}/actions/secrets",
- "GET /repos/{owner}/{repo}/actions/variables",
- "GET /repos/{owner}/{repo}/actions/workflows",
- "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
- "GET /repos/{owner}/{repo}/activity",
- "GET /repos/{owner}/{repo}/assignees",
- "GET /repos/{owner}/{repo}/branches",
- "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
- "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
- "GET /repos/{owner}/{repo}/code-scanning/alerts",
- "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
- "GET /repos/{owner}/{repo}/code-scanning/analyses",
- "GET /repos/{owner}/{repo}/codespaces",
- "GET /repos/{owner}/{repo}/codespaces/devcontainers",
- "GET /repos/{owner}/{repo}/codespaces/secrets",
- "GET /repos/{owner}/{repo}/collaborators",
- "GET /repos/{owner}/{repo}/comments",
- "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
- "GET /repos/{owner}/{repo}/commits",
- "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
- "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
- "GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
- "GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
- "GET /repos/{owner}/{repo}/commits/{ref}/status",
- "GET /repos/{owner}/{repo}/commits/{ref}/statuses",
- "GET /repos/{owner}/{repo}/contributors",
- "GET /repos/{owner}/{repo}/dependabot/alerts",
- "GET /repos/{owner}/{repo}/dependabot/secrets",
- "GET /repos/{owner}/{repo}/deployments",
- "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
- "GET /repos/{owner}/{repo}/environments",
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies",
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps",
- "GET /repos/{owner}/{repo}/events",
- "GET /repos/{owner}/{repo}/forks",
- "GET /repos/{owner}/{repo}/hooks",
- "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
- "GET /repos/{owner}/{repo}/invitations",
- "GET /repos/{owner}/{repo}/issues",
- "GET /repos/{owner}/{repo}/issues/comments",
- "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
- "GET /repos/{owner}/{repo}/issues/events",
- "GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
- "GET /repos/{owner}/{repo}/issues/{issue_number}/events",
- "GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
- "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
- "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
- "GET /repos/{owner}/{repo}/keys",
- "GET /repos/{owner}/{repo}/labels",
- "GET /repos/{owner}/{repo}/milestones",
- "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
- "GET /repos/{owner}/{repo}/notifications",
- "GET /repos/{owner}/{repo}/pages/builds",
- "GET /repos/{owner}/{repo}/projects",
- "GET /repos/{owner}/{repo}/pulls",
- "GET /repos/{owner}/{repo}/pulls/comments",
- "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
- "GET /repos/{owner}/{repo}/releases",
- "GET /repos/{owner}/{repo}/releases/{release_id}/assets",
- "GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
- "GET /repos/{owner}/{repo}/rules/branches/{branch}",
- "GET /repos/{owner}/{repo}/rulesets",
- "GET /repos/{owner}/{repo}/secret-scanning/alerts",
- "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
- "GET /repos/{owner}/{repo}/security-advisories",
- "GET /repos/{owner}/{repo}/stargazers",
- "GET /repos/{owner}/{repo}/subscribers",
- "GET /repos/{owner}/{repo}/tags",
- "GET /repos/{owner}/{repo}/teams",
- "GET /repos/{owner}/{repo}/topics",
- "GET /repositories",
- "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
- "GET /repositories/{repository_id}/environments/{environment_name}/variables",
- "GET /search/code",
- "GET /search/commits",
- "GET /search/issues",
- "GET /search/labels",
- "GET /search/repositories",
- "GET /search/topics",
- "GET /search/users",
- "GET /teams/{team_id}/discussions",
- "GET /teams/{team_id}/discussions/{discussion_number}/comments",
- "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
- "GET /teams/{team_id}/discussions/{discussion_number}/reactions",
- "GET /teams/{team_id}/invitations",
- "GET /teams/{team_id}/members",
- "GET /teams/{team_id}/projects",
- "GET /teams/{team_id}/repos",
- "GET /teams/{team_id}/teams",
- "GET /user/blocks",
- "GET /user/codespaces",
- "GET /user/codespaces/secrets",
- "GET /user/emails",
- "GET /user/followers",
- "GET /user/following",
- "GET /user/gpg_keys",
- "GET /user/installations",
- "GET /user/installations/{installation_id}/repositories",
- "GET /user/issues",
- "GET /user/keys",
- "GET /user/marketplace_purchases",
- "GET /user/marketplace_purchases/stubbed",
- "GET /user/memberships/orgs",
- "GET /user/migrations",
- "GET /user/migrations/{migration_id}/repositories",
- "GET /user/orgs",
- "GET /user/packages",
- "GET /user/packages/{package_type}/{package_name}/versions",
- "GET /user/public_emails",
- "GET /user/repos",
- "GET /user/repository_invitations",
- "GET /user/social_accounts",
- "GET /user/ssh_signing_keys",
- "GET /user/starred",
- "GET /user/subscriptions",
- "GET /user/teams",
- "GET /users",
- "GET /users/{username}/events",
- "GET /users/{username}/events/orgs/{org}",
- "GET /users/{username}/events/public",
- "GET /users/{username}/followers",
- "GET /users/{username}/following",
- "GET /users/{username}/gists",
- "GET /users/{username}/gpg_keys",
- "GET /users/{username}/keys",
- "GET /users/{username}/orgs",
- "GET /users/{username}/packages",
- "GET /users/{username}/projects",
- "GET /users/{username}/received_events",
- "GET /users/{username}/received_events/public",
- "GET /users/{username}/repos",
- "GET /users/{username}/social_accounts",
- "GET /users/{username}/ssh_signing_keys",
- "GET /users/{username}/starred",
- "GET /users/{username}/subscriptions"
-];
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
-// pkg/dist-src/paginating-endpoints.js
-function isPaginatingEndpoint(arg) {
- if (typeof arg === "string") {
- return paginatingEndpoints.includes(arg);
- } else {
- return false;
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
}
-}
-// pkg/dist-src/index.js
-function paginateRest(octokit) {
- return {
- paginate: Object.assign(paginate.bind(null, octokit), {
- iterator: iterator.bind(null, octokit)
- })
- };
-}
-paginateRest.VERSION = VERSION;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
+ function onFree() {
+ self.emit('free', socket, options);
+ }
-/***/ }),
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
-/***/ 94045:
-/***/ ((module) => {
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
-"use strict";
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
+ }
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
+
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
}
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- legacyRestEndpointMethods: () => legacyRestEndpointMethods,
- restEndpointMethods: () => restEndpointMethods
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/version.js
-var VERSION = "10.0.0";
-
-// pkg/dist-src/generated/endpoints.js
-var Endpoints = {
- actions: {
- addCustomLabelsToSelfHostedRunnerForOrg: [
- "POST /orgs/{org}/actions/runners/{runner_id}/labels"
- ],
- addCustomLabelsToSelfHostedRunnerForRepo: [
- "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
- ],
- addSelectedRepoToOrgSecret: [
- "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"
- ],
- addSelectedRepoToOrgVariable: [
- "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"
- ],
- approveWorkflowRun: [
- "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"
- ],
- cancelWorkflowRun: [
- "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"
- ],
- createEnvironmentVariable: [
- "POST /repositories/{repository_id}/environments/{environment_name}/variables"
- ],
- createOrUpdateEnvironmentSecret: [
- "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"
- ],
- createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
- createOrUpdateRepoSecret: [
- "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"
- ],
- createOrgVariable: ["POST /orgs/{org}/actions/variables"],
- createRegistrationTokenForOrg: [
- "POST /orgs/{org}/actions/runners/registration-token"
- ],
- createRegistrationTokenForRepo: [
- "POST /repos/{owner}/{repo}/actions/runners/registration-token"
- ],
- createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
- createRemoveTokenForRepo: [
- "POST /repos/{owner}/{repo}/actions/runners/remove-token"
- ],
- createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"],
- createWorkflowDispatch: [
- "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"
- ],
- deleteActionsCacheById: [
- "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"
- ],
- deleteActionsCacheByKey: [
- "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"
- ],
- deleteArtifact: [
- "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"
- ],
- deleteEnvironmentSecret: [
- "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"
- ],
- deleteEnvironmentVariable: [
- "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}"
- ],
- deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
- deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"],
- deleteRepoSecret: [
- "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"
- ],
- deleteRepoVariable: [
- "DELETE /repos/{owner}/{repo}/actions/variables/{name}"
- ],
- deleteSelfHostedRunnerFromOrg: [
- "DELETE /orgs/{org}/actions/runners/{runner_id}"
- ],
- deleteSelfHostedRunnerFromRepo: [
- "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"
- ],
- deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
- deleteWorkflowRunLogs: [
- "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"
- ],
- disableSelectedRepositoryGithubActionsOrganization: [
- "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"
- ],
- disableWorkflow: [
- "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"
- ],
- downloadArtifact: [
- "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"
- ],
- downloadJobLogsForWorkflowRun: [
- "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"
- ],
- downloadWorkflowRunAttemptLogs: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"
- ],
- downloadWorkflowRunLogs: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"
- ],
- enableSelectedRepositoryGithubActionsOrganization: [
- "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"
- ],
- enableWorkflow: [
- "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"
- ],
- generateRunnerJitconfigForOrg: [
- "POST /orgs/{org}/actions/runners/generate-jitconfig"
- ],
- generateRunnerJitconfigForRepo: [
- "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"
- ],
- getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"],
- getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"],
- getActionsCacheUsageByRepoForOrg: [
- "GET /orgs/{org}/actions/cache/usage-by-repository"
- ],
- getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"],
- getAllowedActionsOrganization: [
- "GET /orgs/{org}/actions/permissions/selected-actions"
- ],
- getAllowedActionsRepository: [
- "GET /repos/{owner}/{repo}/actions/permissions/selected-actions"
- ],
- getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
- getEnvironmentPublicKey: [
- "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"
- ],
- getEnvironmentSecret: [
- "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"
- ],
- getEnvironmentVariable: [
- "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}"
- ],
- getGithubActionsDefaultWorkflowPermissionsOrganization: [
- "GET /orgs/{org}/actions/permissions/workflow"
- ],
- getGithubActionsDefaultWorkflowPermissionsRepository: [
- "GET /repos/{owner}/{repo}/actions/permissions/workflow"
- ],
- getGithubActionsPermissionsOrganization: [
- "GET /orgs/{org}/actions/permissions"
- ],
- getGithubActionsPermissionsRepository: [
- "GET /repos/{owner}/{repo}/actions/permissions"
- ],
- getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
- getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
- getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
- getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"],
- getPendingDeploymentsForRun: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"
- ],
- getRepoPermissions: [
- "GET /repos/{owner}/{repo}/actions/permissions",
- {},
- { renamed: ["actions", "getGithubActionsPermissionsRepository"] }
- ],
- getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
- getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
- getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"],
- getReviewsForRun: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"
- ],
- getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
- getSelfHostedRunnerForRepo: [
- "GET /repos/{owner}/{repo}/actions/runners/{runner_id}"
- ],
- getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
- getWorkflowAccessToRepository: [
- "GET /repos/{owner}/{repo}/actions/permissions/access"
- ],
- getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
- getWorkflowRunAttempt: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"
- ],
- getWorkflowRunUsage: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"
- ],
- getWorkflowUsage: [
- "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"
- ],
- listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
- listEnvironmentSecrets: [
- "GET /repositories/{repository_id}/environments/{environment_name}/secrets"
- ],
- listEnvironmentVariables: [
- "GET /repositories/{repository_id}/environments/{environment_name}/variables"
- ],
- listJobsForWorkflowRun: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"
- ],
- listJobsForWorkflowRunAttempt: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"
- ],
- listLabelsForSelfHostedRunnerForOrg: [
- "GET /orgs/{org}/actions/runners/{runner_id}/labels"
- ],
- listLabelsForSelfHostedRunnerForRepo: [
- "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
- ],
- listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
- listOrgVariables: ["GET /orgs/{org}/actions/variables"],
- listRepoOrganizationSecrets: [
- "GET /repos/{owner}/{repo}/actions/organization-secrets"
- ],
- listRepoOrganizationVariables: [
- "GET /repos/{owner}/{repo}/actions/organization-variables"
- ],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
- listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"],
- listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
- listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
- listRunnerApplicationsForRepo: [
- "GET /repos/{owner}/{repo}/actions/runners/downloads"
- ],
- listSelectedReposForOrgSecret: [
- "GET /orgs/{org}/actions/secrets/{secret_name}/repositories"
- ],
- listSelectedReposForOrgVariable: [
- "GET /orgs/{org}/actions/variables/{name}/repositories"
- ],
- listSelectedRepositoriesEnabledGithubActionsOrganization: [
- "GET /orgs/{org}/actions/permissions/repositories"
- ],
- listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
- listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
- listWorkflowRunArtifacts: [
- "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"
- ],
- listWorkflowRuns: [
- "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"
- ],
- listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
- reRunJobForWorkflowRun: [
- "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"
- ],
- reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
- reRunWorkflowFailedJobs: [
- "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"
- ],
- removeAllCustomLabelsFromSelfHostedRunnerForOrg: [
- "DELETE /orgs/{org}/actions/runners/{runner_id}/labels"
- ],
- removeAllCustomLabelsFromSelfHostedRunnerForRepo: [
- "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
- ],
- removeCustomLabelFromSelfHostedRunnerForOrg: [
- "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"
- ],
- removeCustomLabelFromSelfHostedRunnerForRepo: [
- "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"
- ],
- removeSelectedRepoFromOrgSecret: [
- "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"
- ],
- removeSelectedRepoFromOrgVariable: [
- "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"
- ],
- reviewCustomGatesForRun: [
- "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"
- ],
- reviewPendingDeploymentsForRun: [
- "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"
- ],
- setAllowedActionsOrganization: [
- "PUT /orgs/{org}/actions/permissions/selected-actions"
- ],
- setAllowedActionsRepository: [
- "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"
- ],
- setCustomLabelsForSelfHostedRunnerForOrg: [
- "PUT /orgs/{org}/actions/runners/{runner_id}/labels"
- ],
- setCustomLabelsForSelfHostedRunnerForRepo: [
- "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
- ],
- setGithubActionsDefaultWorkflowPermissionsOrganization: [
- "PUT /orgs/{org}/actions/permissions/workflow"
- ],
- setGithubActionsDefaultWorkflowPermissionsRepository: [
- "PUT /repos/{owner}/{repo}/actions/permissions/workflow"
- ],
- setGithubActionsPermissionsOrganization: [
- "PUT /orgs/{org}/actions/permissions"
- ],
- setGithubActionsPermissionsRepository: [
- "PUT /repos/{owner}/{repo}/actions/permissions"
- ],
- setSelectedReposForOrgSecret: [
- "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"
- ],
- setSelectedReposForOrgVariable: [
- "PUT /orgs/{org}/actions/variables/{name}/repositories"
- ],
- setSelectedRepositoriesEnabledGithubActionsOrganization: [
- "PUT /orgs/{org}/actions/permissions/repositories"
- ],
- setWorkflowAccessToRepository: [
- "PUT /repos/{owner}/{repo}/actions/permissions/access"
- ],
- updateEnvironmentVariable: [
- "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}"
- ],
- updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"],
- updateRepoVariable: [
- "PATCH /repos/{owner}/{repo}/actions/variables/{name}"
- ]
- },
- activity: {
- checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
- deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
- deleteThreadSubscription: [
- "DELETE /notifications/threads/{thread_id}/subscription"
- ],
- getFeeds: ["GET /feeds"],
- getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
- getThread: ["GET /notifications/threads/{thread_id}"],
- getThreadSubscriptionForAuthenticatedUser: [
- "GET /notifications/threads/{thread_id}/subscription"
- ],
- listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
- listNotificationsForAuthenticatedUser: ["GET /notifications"],
- listOrgEventsForAuthenticatedUser: [
- "GET /users/{username}/events/orgs/{org}"
- ],
- listPublicEvents: ["GET /events"],
- listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
- listPublicEventsForUser: ["GET /users/{username}/events/public"],
- listPublicOrgEvents: ["GET /orgs/{org}/events"],
- listReceivedEventsForUser: ["GET /users/{username}/received_events"],
- listReceivedPublicEventsForUser: [
- "GET /users/{username}/received_events/public"
- ],
- listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
- listRepoNotificationsForAuthenticatedUser: [
- "GET /repos/{owner}/{repo}/notifications"
- ],
- listReposStarredByAuthenticatedUser: ["GET /user/starred"],
- listReposStarredByUser: ["GET /users/{username}/starred"],
- listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
- listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
- listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
- listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
- markNotificationsAsRead: ["PUT /notifications"],
- markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
- markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
- setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
- setThreadSubscription: [
- "PUT /notifications/threads/{thread_id}/subscription"
- ],
- starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
- unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
- },
- apps: {
- addRepoToInstallation: [
- "PUT /user/installations/{installation_id}/repositories/{repository_id}",
- {},
- { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] }
- ],
- addRepoToInstallationForAuthenticatedUser: [
- "PUT /user/installations/{installation_id}/repositories/{repository_id}"
- ],
- checkToken: ["POST /applications/{client_id}/token"],
- createFromManifest: ["POST /app-manifests/{code}/conversions"],
- createInstallationAccessToken: [
- "POST /app/installations/{installation_id}/access_tokens"
- ],
- deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
- deleteInstallation: ["DELETE /app/installations/{installation_id}"],
- deleteToken: ["DELETE /applications/{client_id}/token"],
- getAuthenticated: ["GET /app"],
- getBySlug: ["GET /apps/{app_slug}"],
- getInstallation: ["GET /app/installations/{installation_id}"],
- getOrgInstallation: ["GET /orgs/{org}/installation"],
- getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
- getSubscriptionPlanForAccount: [
- "GET /marketplace_listing/accounts/{account_id}"
- ],
- getSubscriptionPlanForAccountStubbed: [
- "GET /marketplace_listing/stubbed/accounts/{account_id}"
- ],
- getUserInstallation: ["GET /users/{username}/installation"],
- getWebhookConfigForApp: ["GET /app/hook/config"],
- getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
- listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
- listAccountsForPlanStubbed: [
- "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"
- ],
- listInstallationReposForAuthenticatedUser: [
- "GET /user/installations/{installation_id}/repositories"
- ],
- listInstallationRequestsForAuthenticatedApp: [
- "GET /app/installation-requests"
- ],
- listInstallations: ["GET /app/installations"],
- listInstallationsForAuthenticatedUser: ["GET /user/installations"],
- listPlans: ["GET /marketplace_listing/plans"],
- listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
- listReposAccessibleToInstallation: ["GET /installation/repositories"],
- listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
- listSubscriptionsForAuthenticatedUserStubbed: [
- "GET /user/marketplace_purchases/stubbed"
- ],
- listWebhookDeliveries: ["GET /app/hook/deliveries"],
- redeliverWebhookDelivery: [
- "POST /app/hook/deliveries/{delivery_id}/attempts"
- ],
- removeRepoFromInstallation: [
- "DELETE /user/installations/{installation_id}/repositories/{repository_id}",
- {},
- { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] }
- ],
- removeRepoFromInstallationForAuthenticatedUser: [
- "DELETE /user/installations/{installation_id}/repositories/{repository_id}"
- ],
- resetToken: ["PATCH /applications/{client_id}/token"],
- revokeInstallationAccessToken: ["DELETE /installation/token"],
- scopeToken: ["POST /applications/{client_id}/token/scoped"],
- suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
- unsuspendInstallation: [
- "DELETE /app/installations/{installation_id}/suspended"
- ],
- updateWebhookConfigForApp: ["PATCH /app/hook/config"]
- },
- billing: {
- getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
- getGithubActionsBillingUser: [
- "GET /users/{username}/settings/billing/actions"
- ],
- getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
- getGithubPackagesBillingUser: [
- "GET /users/{username}/settings/billing/packages"
- ],
- getSharedStorageBillingOrg: [
- "GET /orgs/{org}/settings/billing/shared-storage"
- ],
- getSharedStorageBillingUser: [
- "GET /users/{username}/settings/billing/shared-storage"
- ]
- },
- checks: {
- create: ["POST /repos/{owner}/{repo}/check-runs"],
- createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
- get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
- getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
- listAnnotations: [
- "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"
- ],
- listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
- listForSuite: [
- "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"
- ],
- listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
- rerequestRun: [
- "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"
- ],
- rerequestSuite: [
- "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"
- ],
- setSuitesPreferences: [
- "PATCH /repos/{owner}/{repo}/check-suites/preferences"
- ],
- update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
- },
- codeScanning: {
- deleteAnalysis: [
- "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"
- ],
- getAlert: [
- "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",
- {},
- { renamedParameters: { alert_id: "alert_number" } }
- ],
- getAnalysis: [
- "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"
- ],
- getCodeqlDatabase: [
- "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"
- ],
- getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"],
- getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
- listAlertInstances: [
- "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"
- ],
- listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"],
- listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
- listAlertsInstances: [
- "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
- {},
- { renamed: ["codeScanning", "listAlertInstances"] }
- ],
- listCodeqlDatabases: [
- "GET /repos/{owner}/{repo}/code-scanning/codeql/databases"
- ],
- listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
- updateAlert: [
- "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"
- ],
- updateDefaultSetup: [
- "PATCH /repos/{owner}/{repo}/code-scanning/default-setup"
- ],
- uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
- },
- codesOfConduct: {
- getAllCodesOfConduct: ["GET /codes_of_conduct"],
- getConductCode: ["GET /codes_of_conduct/{key}"]
- },
- codespaces: {
- addRepositoryForSecretForAuthenticatedUser: [
- "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"
- ],
- addSelectedRepoToOrgSecret: [
- "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"
- ],
- codespaceMachinesForAuthenticatedUser: [
- "GET /user/codespaces/{codespace_name}/machines"
- ],
- createForAuthenticatedUser: ["POST /user/codespaces"],
- createOrUpdateOrgSecret: [
- "PUT /orgs/{org}/codespaces/secrets/{secret_name}"
- ],
- createOrUpdateRepoSecret: [
- "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
- ],
- createOrUpdateSecretForAuthenticatedUser: [
- "PUT /user/codespaces/secrets/{secret_name}"
- ],
- createWithPrForAuthenticatedUser: [
- "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"
- ],
- createWithRepoForAuthenticatedUser: [
- "POST /repos/{owner}/{repo}/codespaces"
- ],
- deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"],
- deleteFromOrganization: [
- "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"
- ],
- deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],
- deleteRepoSecret: [
- "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
- ],
- deleteSecretForAuthenticatedUser: [
- "DELETE /user/codespaces/secrets/{secret_name}"
- ],
- exportForAuthenticatedUser: [
- "POST /user/codespaces/{codespace_name}/exports"
- ],
- getCodespacesForUserInOrg: [
- "GET /orgs/{org}/members/{username}/codespaces"
- ],
- getExportDetailsForAuthenticatedUser: [
- "GET /user/codespaces/{codespace_name}/exports/{export_id}"
- ],
- getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"],
- getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"],
- getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"],
- getPublicKeyForAuthenticatedUser: [
- "GET /user/codespaces/secrets/public-key"
- ],
- getRepoPublicKey: [
- "GET /repos/{owner}/{repo}/codespaces/secrets/public-key"
- ],
- getRepoSecret: [
- "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
- ],
- getSecretForAuthenticatedUser: [
- "GET /user/codespaces/secrets/{secret_name}"
- ],
- listDevcontainersInRepositoryForAuthenticatedUser: [
- "GET /repos/{owner}/{repo}/codespaces/devcontainers"
- ],
- listForAuthenticatedUser: ["GET /user/codespaces"],
- listInOrganization: [
- "GET /orgs/{org}/codespaces",
- {},
- { renamedParameters: { org_id: "org" } }
- ],
- listInRepositoryForAuthenticatedUser: [
- "GET /repos/{owner}/{repo}/codespaces"
- ],
- listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"],
- listRepositoriesForSecretForAuthenticatedUser: [
- "GET /user/codespaces/secrets/{secret_name}/repositories"
- ],
- listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"],
- listSelectedReposForOrgSecret: [
- "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"
- ],
- preFlightWithRepoForAuthenticatedUser: [
- "GET /repos/{owner}/{repo}/codespaces/new"
- ],
- publishForAuthenticatedUser: [
- "POST /user/codespaces/{codespace_name}/publish"
- ],
- removeRepositoryForSecretForAuthenticatedUser: [
- "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"
- ],
- removeSelectedRepoFromOrgSecret: [
- "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"
- ],
- repoMachinesForAuthenticatedUser: [
- "GET /repos/{owner}/{repo}/codespaces/machines"
- ],
- setRepositoriesForSecretForAuthenticatedUser: [
- "PUT /user/codespaces/secrets/{secret_name}/repositories"
- ],
- setSelectedReposForOrgSecret: [
- "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"
- ],
- startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"],
- stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"],
- stopInOrganization: [
- "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"
- ],
- updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"]
- },
- copilot: {
- addCopilotForBusinessSeatsForTeams: [
- "POST /orgs/{org}/copilot/billing/selected_teams"
- ],
- addCopilotForBusinessSeatsForUsers: [
- "POST /orgs/{org}/copilot/billing/selected_users"
- ],
- cancelCopilotSeatAssignmentForTeams: [
- "DELETE /orgs/{org}/copilot/billing/selected_teams"
- ],
- cancelCopilotSeatAssignmentForUsers: [
- "DELETE /orgs/{org}/copilot/billing/selected_users"
- ],
- getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"],
- getCopilotSeatAssignmentDetailsForUser: [
- "GET /orgs/{org}/members/{username}/copilot"
- ],
- listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"]
- },
- dependabot: {
- addSelectedRepoToOrgSecret: [
- "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"
- ],
- createOrUpdateOrgSecret: [
- "PUT /orgs/{org}/dependabot/secrets/{secret_name}"
- ],
- createOrUpdateRepoSecret: [
- "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
- ],
- deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],
- deleteRepoSecret: [
- "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
- ],
- getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],
- getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"],
- getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"],
- getRepoPublicKey: [
- "GET /repos/{owner}/{repo}/dependabot/secrets/public-key"
- ],
- getRepoSecret: [
- "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
- ],
- listAlertsForEnterprise: [
- "GET /enterprises/{enterprise}/dependabot/alerts"
- ],
- listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"],
- listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"],
- listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"],
- listSelectedReposForOrgSecret: [
- "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"
- ],
- removeSelectedRepoFromOrgSecret: [
- "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"
- ],
- setSelectedReposForOrgSecret: [
- "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"
- ],
- updateAlert: [
- "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"
- ]
- },
- dependencyGraph: {
- createRepositorySnapshot: [
- "POST /repos/{owner}/{repo}/dependency-graph/snapshots"
- ],
- diffRange: [
- "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"
- ],
- exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"]
- },
- emojis: { get: ["GET /emojis"] },
- gists: {
- checkIsStarred: ["GET /gists/{gist_id}/star"],
- create: ["POST /gists"],
- createComment: ["POST /gists/{gist_id}/comments"],
- delete: ["DELETE /gists/{gist_id}"],
- deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
- fork: ["POST /gists/{gist_id}/forks"],
- get: ["GET /gists/{gist_id}"],
- getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
- getRevision: ["GET /gists/{gist_id}/{sha}"],
- list: ["GET /gists"],
- listComments: ["GET /gists/{gist_id}/comments"],
- listCommits: ["GET /gists/{gist_id}/commits"],
- listForUser: ["GET /users/{username}/gists"],
- listForks: ["GET /gists/{gist_id}/forks"],
- listPublic: ["GET /gists/public"],
- listStarred: ["GET /gists/starred"],
- star: ["PUT /gists/{gist_id}/star"],
- unstar: ["DELETE /gists/{gist_id}/star"],
- update: ["PATCH /gists/{gist_id}"],
- updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
- },
- git: {
- createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
- createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
- createRef: ["POST /repos/{owner}/{repo}/git/refs"],
- createTag: ["POST /repos/{owner}/{repo}/git/tags"],
- createTree: ["POST /repos/{owner}/{repo}/git/trees"],
- deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
- getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
- getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
- getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
- getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
- getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
- listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
- updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
- },
- gitignore: {
- getAllTemplates: ["GET /gitignore/templates"],
- getTemplate: ["GET /gitignore/templates/{name}"]
- },
- interactions: {
- getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
- getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
- getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
- getRestrictionsForYourPublicRepos: [
- "GET /user/interaction-limits",
- {},
- { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] }
- ],
- removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
- removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
- removeRestrictionsForRepo: [
- "DELETE /repos/{owner}/{repo}/interaction-limits"
- ],
- removeRestrictionsForYourPublicRepos: [
- "DELETE /user/interaction-limits",
- {},
- { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] }
- ],
- setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
- setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
- setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
- setRestrictionsForYourPublicRepos: [
- "PUT /user/interaction-limits",
- {},
- { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] }
- ]
- },
- issues: {
- addAssignees: [
- "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"
- ],
- addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
- checkUserCanBeAssignedToIssue: [
- "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"
- ],
- create: ["POST /repos/{owner}/{repo}/issues"],
- createComment: [
- "POST /repos/{owner}/{repo}/issues/{issue_number}/comments"
- ],
- createLabel: ["POST /repos/{owner}/{repo}/labels"],
- createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
- deleteComment: [
- "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"
- ],
- deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
- deleteMilestone: [
- "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"
- ],
- get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
- getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
- getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
- getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
- getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
- list: ["GET /issues"],
- listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
- listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
- listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
- listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
- listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
- listEventsForTimeline: [
- "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"
- ],
- listForAuthenticatedUser: ["GET /user/issues"],
- listForOrg: ["GET /orgs/{org}/issues"],
- listForRepo: ["GET /repos/{owner}/{repo}/issues"],
- listLabelsForMilestone: [
- "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"
- ],
- listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
- listLabelsOnIssue: [
- "GET /repos/{owner}/{repo}/issues/{issue_number}/labels"
- ],
- listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
- lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
- removeAllLabels: [
- "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"
- ],
- removeAssignees: [
- "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"
- ],
- removeLabel: [
- "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"
- ],
- setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
- update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
- updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
- updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
- updateMilestone: [
- "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"
- ]
- },
- licenses: {
- get: ["GET /licenses/{license}"],
- getAllCommonlyUsed: ["GET /licenses"],
- getForRepo: ["GET /repos/{owner}/{repo}/license"]
- },
- markdown: {
- render: ["POST /markdown"],
- renderRaw: [
- "POST /markdown/raw",
- { headers: { "content-type": "text/plain; charset=utf-8" } }
- ]
- },
- meta: {
- get: ["GET /meta"],
- getAllVersions: ["GET /versions"],
- getOctocat: ["GET /octocat"],
- getZen: ["GET /zen"],
- root: ["GET /"]
- },
- migrations: {
- cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
- deleteArchiveForAuthenticatedUser: [
- "DELETE /user/migrations/{migration_id}/archive"
- ],
- deleteArchiveForOrg: [
- "DELETE /orgs/{org}/migrations/{migration_id}/archive"
- ],
- downloadArchiveForOrg: [
- "GET /orgs/{org}/migrations/{migration_id}/archive"
- ],
- getArchiveForAuthenticatedUser: [
- "GET /user/migrations/{migration_id}/archive"
- ],
- getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
- getImportStatus: ["GET /repos/{owner}/{repo}/import"],
- getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
- getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
- getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
- listForAuthenticatedUser: ["GET /user/migrations"],
- listForOrg: ["GET /orgs/{org}/migrations"],
- listReposForAuthenticatedUser: [
- "GET /user/migrations/{migration_id}/repositories"
- ],
- listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
- listReposForUser: [
- "GET /user/migrations/{migration_id}/repositories",
- {},
- { renamed: ["migrations", "listReposForAuthenticatedUser"] }
- ],
- mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
- setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
- startForAuthenticatedUser: ["POST /user/migrations"],
- startForOrg: ["POST /orgs/{org}/migrations"],
- startImport: ["PUT /repos/{owner}/{repo}/import"],
- unlockRepoForAuthenticatedUser: [
- "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"
- ],
- unlockRepoForOrg: [
- "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"
- ],
- updateImport: ["PATCH /repos/{owner}/{repo}/import"]
- },
- orgs: {
- addSecurityManagerTeam: [
- "PUT /orgs/{org}/security-managers/teams/{team_slug}"
- ],
- blockUser: ["PUT /orgs/{org}/blocks/{username}"],
- cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
- checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
- checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
- checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
- convertMemberToOutsideCollaborator: [
- "PUT /orgs/{org}/outside_collaborators/{username}"
- ],
- createInvitation: ["POST /orgs/{org}/invitations"],
- createWebhook: ["POST /orgs/{org}/hooks"],
- delete: ["DELETE /orgs/{org}"],
- deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
- enableOrDisableSecurityProductOnAllOrgRepos: [
- "POST /orgs/{org}/{security_product}/{enablement}"
- ],
- get: ["GET /orgs/{org}"],
- getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
- getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
- getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
- getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
- getWebhookDelivery: [
- "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"
- ],
- list: ["GET /organizations"],
- listAppInstallations: ["GET /orgs/{org}/installations"],
- listBlockedUsers: ["GET /orgs/{org}/blocks"],
- listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
- listForAuthenticatedUser: ["GET /user/orgs"],
- listForUser: ["GET /users/{username}/orgs"],
- listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
- listMembers: ["GET /orgs/{org}/members"],
- listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
- listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
- listPatGrantRepositories: [
- "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"
- ],
- listPatGrantRequestRepositories: [
- "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"
- ],
- listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"],
- listPatGrants: ["GET /orgs/{org}/personal-access-tokens"],
- listPendingInvitations: ["GET /orgs/{org}/invitations"],
- listPublicMembers: ["GET /orgs/{org}/public_members"],
- listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"],
- listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
- listWebhooks: ["GET /orgs/{org}/hooks"],
- pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
- redeliverWebhookDelivery: [
- "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"
- ],
- removeMember: ["DELETE /orgs/{org}/members/{username}"],
- removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
- removeOutsideCollaborator: [
- "DELETE /orgs/{org}/outside_collaborators/{username}"
- ],
- removePublicMembershipForAuthenticatedUser: [
- "DELETE /orgs/{org}/public_members/{username}"
- ],
- removeSecurityManagerTeam: [
- "DELETE /orgs/{org}/security-managers/teams/{team_slug}"
- ],
- reviewPatGrantRequest: [
- "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"
- ],
- reviewPatGrantRequestsInBulk: [
- "POST /orgs/{org}/personal-access-token-requests"
- ],
- setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
- setPublicMembershipForAuthenticatedUser: [
- "PUT /orgs/{org}/public_members/{username}"
- ],
- unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
- update: ["PATCH /orgs/{org}"],
- updateMembershipForAuthenticatedUser: [
- "PATCH /user/memberships/orgs/{org}"
- ],
- updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"],
- updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"],
- updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
- updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
- },
- packages: {
- deletePackageForAuthenticatedUser: [
- "DELETE /user/packages/{package_type}/{package_name}"
- ],
- deletePackageForOrg: [
- "DELETE /orgs/{org}/packages/{package_type}/{package_name}"
- ],
- deletePackageForUser: [
- "DELETE /users/{username}/packages/{package_type}/{package_name}"
- ],
- deletePackageVersionForAuthenticatedUser: [
- "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- deletePackageVersionForOrg: [
- "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- deletePackageVersionForUser: [
- "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- getAllPackageVersionsForAPackageOwnedByAnOrg: [
- "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
- {},
- { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] }
- ],
- getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [
- "GET /user/packages/{package_type}/{package_name}/versions",
- {},
- {
- renamed: [
- "packages",
- "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"
- ]
- }
- ],
- getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [
- "GET /user/packages/{package_type}/{package_name}/versions"
- ],
- getAllPackageVersionsForPackageOwnedByOrg: [
- "GET /orgs/{org}/packages/{package_type}/{package_name}/versions"
- ],
- getAllPackageVersionsForPackageOwnedByUser: [
- "GET /users/{username}/packages/{package_type}/{package_name}/versions"
- ],
- getPackageForAuthenticatedUser: [
- "GET /user/packages/{package_type}/{package_name}"
- ],
- getPackageForOrganization: [
- "GET /orgs/{org}/packages/{package_type}/{package_name}"
- ],
- getPackageForUser: [
- "GET /users/{username}/packages/{package_type}/{package_name}"
- ],
- getPackageVersionForAuthenticatedUser: [
- "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- getPackageVersionForOrganization: [
- "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- getPackageVersionForUser: [
- "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"
- ],
- listDockerMigrationConflictingPackagesForAuthenticatedUser: [
- "GET /user/docker/conflicts"
- ],
- listDockerMigrationConflictingPackagesForOrganization: [
- "GET /orgs/{org}/docker/conflicts"
- ],
- listDockerMigrationConflictingPackagesForUser: [
- "GET /users/{username}/docker/conflicts"
- ],
- listPackagesForAuthenticatedUser: ["GET /user/packages"],
- listPackagesForOrganization: ["GET /orgs/{org}/packages"],
- listPackagesForUser: ["GET /users/{username}/packages"],
- restorePackageForAuthenticatedUser: [
- "POST /user/packages/{package_type}/{package_name}/restore{?token}"
- ],
- restorePackageForOrg: [
- "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"
- ],
- restorePackageForUser: [
- "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"
- ],
- restorePackageVersionForAuthenticatedUser: [
- "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
- ],
- restorePackageVersionForOrg: [
- "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
- ],
- restorePackageVersionForUser: [
- "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
- ]
- },
- projects: {
- addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
- createCard: ["POST /projects/columns/{column_id}/cards"],
- createColumn: ["POST /projects/{project_id}/columns"],
- createForAuthenticatedUser: ["POST /user/projects"],
- createForOrg: ["POST /orgs/{org}/projects"],
- createForRepo: ["POST /repos/{owner}/{repo}/projects"],
- delete: ["DELETE /projects/{project_id}"],
- deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
- deleteColumn: ["DELETE /projects/columns/{column_id}"],
- get: ["GET /projects/{project_id}"],
- getCard: ["GET /projects/columns/cards/{card_id}"],
- getColumn: ["GET /projects/columns/{column_id}"],
- getPermissionForUser: [
- "GET /projects/{project_id}/collaborators/{username}/permission"
- ],
- listCards: ["GET /projects/columns/{column_id}/cards"],
- listCollaborators: ["GET /projects/{project_id}/collaborators"],
- listColumns: ["GET /projects/{project_id}/columns"],
- listForOrg: ["GET /orgs/{org}/projects"],
- listForRepo: ["GET /repos/{owner}/{repo}/projects"],
- listForUser: ["GET /users/{username}/projects"],
- moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
- moveColumn: ["POST /projects/columns/{column_id}/moves"],
- removeCollaborator: [
- "DELETE /projects/{project_id}/collaborators/{username}"
- ],
- update: ["PATCH /projects/{project_id}"],
- updateCard: ["PATCH /projects/columns/cards/{card_id}"],
- updateColumn: ["PATCH /projects/columns/{column_id}"]
- },
- pulls: {
- checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
- create: ["POST /repos/{owner}/{repo}/pulls"],
- createReplyForReviewComment: [
- "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"
- ],
- createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
- createReviewComment: [
- "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"
- ],
- deletePendingReview: [
- "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
- ],
- deleteReviewComment: [
- "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"
- ],
- dismissReview: [
- "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"
- ],
- get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
- getReview: [
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
- ],
- getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
- list: ["GET /repos/{owner}/{repo}/pulls"],
- listCommentsForReview: [
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"
- ],
- listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
- listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
- listRequestedReviewers: [
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
- ],
- listReviewComments: [
- "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"
- ],
- listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
- listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
- merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
- removeRequestedReviewers: [
- "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
- ],
- requestReviewers: [
- "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
- ],
- submitReview: [
- "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"
- ],
- update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
- updateBranch: [
- "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"
- ],
- updateReview: [
- "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
- ],
- updateReviewComment: [
- "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"
- ]
- },
- rateLimit: { get: ["GET /rate_limit"] },
- reactions: {
- createForCommitComment: [
- "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"
- ],
- createForIssue: [
- "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"
- ],
- createForIssueComment: [
- "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"
- ],
- createForPullRequestReviewComment: [
- "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"
- ],
- createForRelease: [
- "POST /repos/{owner}/{repo}/releases/{release_id}/reactions"
- ],
- createForTeamDiscussionCommentInOrg: [
- "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"
- ],
- createForTeamDiscussionInOrg: [
- "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"
- ],
- deleteForCommitComment: [
- "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"
- ],
- deleteForIssue: [
- "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"
- ],
- deleteForIssueComment: [
- "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"
- ],
- deleteForPullRequestComment: [
- "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"
- ],
- deleteForRelease: [
- "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"
- ],
- deleteForTeamDiscussion: [
- "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"
- ],
- deleteForTeamDiscussionComment: [
- "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"
- ],
- listForCommitComment: [
- "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"
- ],
- listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
- listForIssueComment: [
- "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"
- ],
- listForPullRequestReviewComment: [
- "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"
- ],
- listForRelease: [
- "GET /repos/{owner}/{repo}/releases/{release_id}/reactions"
- ],
- listForTeamDiscussionCommentInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"
- ],
- listForTeamDiscussionInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"
- ]
- },
- repos: {
- acceptInvitation: [
- "PATCH /user/repository_invitations/{invitation_id}",
- {},
- { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] }
- ],
- acceptInvitationForAuthenticatedUser: [
- "PATCH /user/repository_invitations/{invitation_id}"
- ],
- addAppAccessRestrictions: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
- {},
- { mapToData: "apps" }
- ],
- addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
- addStatusCheckContexts: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
- {},
- { mapToData: "contexts" }
- ],
- addTeamAccessRestrictions: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
- {},
- { mapToData: "teams" }
- ],
- addUserAccessRestrictions: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
- {},
- { mapToData: "users" }
- ],
- checkAutomatedSecurityFixes: [
- "GET /repos/{owner}/{repo}/automated-security-fixes"
- ],
- checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
- checkVulnerabilityAlerts: [
- "GET /repos/{owner}/{repo}/vulnerability-alerts"
- ],
- codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"],
- compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
- compareCommitsWithBasehead: [
- "GET /repos/{owner}/{repo}/compare/{basehead}"
- ],
- createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
- createCommitComment: [
- "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"
- ],
- createCommitSignatureProtection: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
- ],
- createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
- createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
- createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
- createDeploymentBranchPolicy: [
- "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"
- ],
- createDeploymentProtectionRule: [
- "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"
- ],
- createDeploymentStatus: [
- "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"
- ],
- createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
- createForAuthenticatedUser: ["POST /user/repos"],
- createFork: ["POST /repos/{owner}/{repo}/forks"],
- createInOrg: ["POST /orgs/{org}/repos"],
- createOrUpdateEnvironment: [
- "PUT /repos/{owner}/{repo}/environments/{environment_name}"
- ],
- createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
- createOrgRuleset: ["POST /orgs/{org}/rulesets"],
- createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployment"],
- createPagesSite: ["POST /repos/{owner}/{repo}/pages"],
- createRelease: ["POST /repos/{owner}/{repo}/releases"],
- createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"],
- createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"],
- createUsingTemplate: [
- "POST /repos/{template_owner}/{template_repo}/generate"
- ],
- createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
- declineInvitation: [
- "DELETE /user/repository_invitations/{invitation_id}",
- {},
- { renamed: ["repos", "declineInvitationForAuthenticatedUser"] }
- ],
- declineInvitationForAuthenticatedUser: [
- "DELETE /user/repository_invitations/{invitation_id}"
- ],
- delete: ["DELETE /repos/{owner}/{repo}"],
- deleteAccessRestrictions: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"
- ],
- deleteAdminBranchProtection: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
- ],
- deleteAnEnvironment: [
- "DELETE /repos/{owner}/{repo}/environments/{environment_name}"
- ],
- deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
- deleteBranchProtection: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection"
- ],
- deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
- deleteCommitSignatureProtection: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
- ],
- deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
- deleteDeployment: [
- "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"
- ],
- deleteDeploymentBranchPolicy: [
- "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
- ],
- deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
- deleteInvitation: [
- "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"
- ],
- deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"],
- deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"],
- deletePullRequestReviewProtection: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
- ],
- deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
- deleteReleaseAsset: [
- "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"
- ],
- deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
- deleteTagProtection: [
- "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}"
- ],
- deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
- disableAutomatedSecurityFixes: [
- "DELETE /repos/{owner}/{repo}/automated-security-fixes"
- ],
- disableDeploymentProtectionRule: [
- "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"
- ],
- disablePrivateVulnerabilityReporting: [
- "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"
- ],
- disableVulnerabilityAlerts: [
- "DELETE /repos/{owner}/{repo}/vulnerability-alerts"
- ],
- downloadArchive: [
- "GET /repos/{owner}/{repo}/zipball/{ref}",
- {},
- { renamed: ["repos", "downloadZipballArchive"] }
- ],
- downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
- downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
- enableAutomatedSecurityFixes: [
- "PUT /repos/{owner}/{repo}/automated-security-fixes"
- ],
- enablePrivateVulnerabilityReporting: [
- "PUT /repos/{owner}/{repo}/private-vulnerability-reporting"
- ],
- enableVulnerabilityAlerts: [
- "PUT /repos/{owner}/{repo}/vulnerability-alerts"
- ],
- generateReleaseNotes: [
- "POST /repos/{owner}/{repo}/releases/generate-notes"
- ],
- get: ["GET /repos/{owner}/{repo}"],
- getAccessRestrictions: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"
- ],
- getAdminBranchProtection: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
- ],
- getAllDeploymentProtectionRules: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"
- ],
- getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
- getAllStatusCheckContexts: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"
- ],
- getAllTopics: ["GET /repos/{owner}/{repo}/topics"],
- getAppsWithAccessToProtectedBranch: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"
- ],
- getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
- getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
- getBranchProtection: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection"
- ],
- getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"],
- getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
- getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
- getCollaboratorPermissionLevel: [
- "GET /repos/{owner}/{repo}/collaborators/{username}/permission"
- ],
- getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
- getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
- getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
- getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
- getCommitSignatureProtection: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
- ],
- getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
- getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
- getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
- getCustomDeploymentProtectionRule: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"
- ],
- getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
- getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
- getDeploymentBranchPolicy: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
- ],
- getDeploymentStatus: [
- "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"
- ],
- getEnvironment: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}"
- ],
- getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
- getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
- getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"],
- getOrgRulesets: ["GET /orgs/{org}/rulesets"],
- getPages: ["GET /repos/{owner}/{repo}/pages"],
- getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
- getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
- getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
- getPullRequestReviewProtection: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
- ],
- getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
- getReadme: ["GET /repos/{owner}/{repo}/readme"],
- getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
- getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
- getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
- getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
- getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
- getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"],
- getStatusChecksProtection: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
- ],
- getTeamsWithAccessToProtectedBranch: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"
- ],
- getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
- getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
- getUsersWithAccessToProtectedBranch: [
- "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"
- ],
- getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
- getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
- getWebhookConfigForRepo: [
- "GET /repos/{owner}/{repo}/hooks/{hook_id}/config"
- ],
- getWebhookDelivery: [
- "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"
- ],
- listActivities: ["GET /repos/{owner}/{repo}/activity"],
- listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
- listBranches: ["GET /repos/{owner}/{repo}/branches"],
- listBranchesForHeadCommit: [
- "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"
- ],
- listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
- listCommentsForCommit: [
- "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"
- ],
- listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
- listCommitStatusesForRef: [
- "GET /repos/{owner}/{repo}/commits/{ref}/statuses"
- ],
- listCommits: ["GET /repos/{owner}/{repo}/commits"],
- listContributors: ["GET /repos/{owner}/{repo}/contributors"],
- listCustomDeploymentRuleIntegrations: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"
- ],
- listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
- listDeploymentBranchPolicies: [
- "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"
- ],
- listDeploymentStatuses: [
- "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"
- ],
- listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
- listForAuthenticatedUser: ["GET /user/repos"],
- listForOrg: ["GET /orgs/{org}/repos"],
- listForUser: ["GET /users/{username}/repos"],
- listForks: ["GET /repos/{owner}/{repo}/forks"],
- listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
- listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
- listLanguages: ["GET /repos/{owner}/{repo}/languages"],
- listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
- listPublic: ["GET /repositories"],
- listPullRequestsAssociatedWithCommit: [
- "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"
- ],
- listReleaseAssets: [
- "GET /repos/{owner}/{repo}/releases/{release_id}/assets"
- ],
- listReleases: ["GET /repos/{owner}/{repo}/releases"],
- listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"],
- listTags: ["GET /repos/{owner}/{repo}/tags"],
- listTeams: ["GET /repos/{owner}/{repo}/teams"],
- listWebhookDeliveries: [
- "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"
- ],
- listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
- merge: ["POST /repos/{owner}/{repo}/merges"],
- mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
- pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
- redeliverWebhookDelivery: [
- "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"
- ],
- removeAppAccessRestrictions: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
- {},
- { mapToData: "apps" }
- ],
- removeCollaborator: [
- "DELETE /repos/{owner}/{repo}/collaborators/{username}"
- ],
- removeStatusCheckContexts: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
- {},
- { mapToData: "contexts" }
- ],
- removeStatusCheckProtection: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
- ],
- removeTeamAccessRestrictions: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
- {},
- { mapToData: "teams" }
- ],
- removeUserAccessRestrictions: [
- "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
- {},
- { mapToData: "users" }
- ],
- renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
- replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"],
- requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
- setAdminBranchProtection: [
- "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
- ],
- setAppAccessRestrictions: [
- "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
- {},
- { mapToData: "apps" }
- ],
- setStatusCheckContexts: [
- "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
- {},
- { mapToData: "contexts" }
- ],
- setTeamAccessRestrictions: [
- "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
- {},
- { mapToData: "teams" }
- ],
- setUserAccessRestrictions: [
- "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
- {},
- { mapToData: "users" }
- ],
- testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
- transfer: ["POST /repos/{owner}/{repo}/transfer"],
- update: ["PATCH /repos/{owner}/{repo}"],
- updateBranchProtection: [
- "PUT /repos/{owner}/{repo}/branches/{branch}/protection"
- ],
- updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
- updateDeploymentBranchPolicy: [
- "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
- ],
- updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
- updateInvitation: [
- "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"
- ],
- updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"],
- updatePullRequestReviewProtection: [
- "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
- ],
- updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
- updateReleaseAsset: [
- "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"
- ],
- updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
- updateStatusCheckPotection: [
- "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",
- {},
- { renamed: ["repos", "updateStatusCheckProtection"] }
- ],
- updateStatusCheckProtection: [
- "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
- ],
- updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
- updateWebhookConfigForRepo: [
- "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"
- ],
- uploadReleaseAsset: [
- "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",
- { baseUrl: "https://uploads.github.com" }
- ]
- },
- search: {
- code: ["GET /search/code"],
- commits: ["GET /search/commits"],
- issuesAndPullRequests: ["GET /search/issues"],
- labels: ["GET /search/labels"],
- repos: ["GET /search/repositories"],
- topics: ["GET /search/topics"],
- users: ["GET /search/users"]
- },
- secretScanning: {
- getAlert: [
- "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"
- ],
- listAlertsForEnterprise: [
- "GET /enterprises/{enterprise}/secret-scanning/alerts"
- ],
- listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
- listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
- listLocationsForAlert: [
- "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"
- ],
- updateAlert: [
- "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"
- ]
- },
- securityAdvisories: {
- createPrivateVulnerabilityReport: [
- "POST /repos/{owner}/{repo}/security-advisories/reports"
- ],
- createRepositoryAdvisory: [
- "POST /repos/{owner}/{repo}/security-advisories"
- ],
- createRepositoryAdvisoryCveRequest: [
- "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"
- ],
- getGlobalAdvisory: ["GET /advisories/{ghsa_id}"],
- getRepositoryAdvisory: [
- "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"
- ],
- listGlobalAdvisories: ["GET /advisories"],
- listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"],
- listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"],
- updateRepositoryAdvisory: [
- "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"
- ]
- },
- teams: {
- addOrUpdateMembershipForUserInOrg: [
- "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"
- ],
- addOrUpdateProjectPermissionsInOrg: [
- "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"
- ],
- addOrUpdateRepoPermissionsInOrg: [
- "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
- ],
- checkPermissionsForProjectInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"
- ],
- checkPermissionsForRepoInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
- ],
- create: ["POST /orgs/{org}/teams"],
- createDiscussionCommentInOrg: [
- "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"
- ],
- createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
- deleteDiscussionCommentInOrg: [
- "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
- ],
- deleteDiscussionInOrg: [
- "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
- ],
- deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
- getByName: ["GET /orgs/{org}/teams/{team_slug}"],
- getDiscussionCommentInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
- ],
- getDiscussionInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
- ],
- getMembershipForUserInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/memberships/{username}"
- ],
- list: ["GET /orgs/{org}/teams"],
- listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
- listDiscussionCommentsInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"
- ],
- listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
- listForAuthenticatedUser: ["GET /user/teams"],
- listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
- listPendingInvitationsInOrg: [
- "GET /orgs/{org}/teams/{team_slug}/invitations"
- ],
- listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
- listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
- removeMembershipForUserInOrg: [
- "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"
- ],
- removeProjectInOrg: [
- "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"
- ],
- removeRepoInOrg: [
- "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
- ],
- updateDiscussionCommentInOrg: [
- "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
- ],
- updateDiscussionInOrg: [
- "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
- ],
- updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
- },
- users: {
- addEmailForAuthenticated: [
- "POST /user/emails",
- {},
- { renamed: ["users", "addEmailForAuthenticatedUser"] }
- ],
- addEmailForAuthenticatedUser: ["POST /user/emails"],
- addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"],
- block: ["PUT /user/blocks/{username}"],
- checkBlocked: ["GET /user/blocks/{username}"],
- checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
- checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
- createGpgKeyForAuthenticated: [
- "POST /user/gpg_keys",
- {},
- { renamed: ["users", "createGpgKeyForAuthenticatedUser"] }
- ],
- createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"],
- createPublicSshKeyForAuthenticated: [
- "POST /user/keys",
- {},
- { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] }
- ],
- createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"],
- createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"],
- deleteEmailForAuthenticated: [
- "DELETE /user/emails",
- {},
- { renamed: ["users", "deleteEmailForAuthenticatedUser"] }
- ],
- deleteEmailForAuthenticatedUser: ["DELETE /user/emails"],
- deleteGpgKeyForAuthenticated: [
- "DELETE /user/gpg_keys/{gpg_key_id}",
- {},
- { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] }
- ],
- deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"],
- deletePublicSshKeyForAuthenticated: [
- "DELETE /user/keys/{key_id}",
- {},
- { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] }
- ],
- deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"],
- deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"],
- deleteSshSigningKeyForAuthenticatedUser: [
- "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"
- ],
- follow: ["PUT /user/following/{username}"],
- getAuthenticated: ["GET /user"],
- getByUsername: ["GET /users/{username}"],
- getContextForUser: ["GET /users/{username}/hovercard"],
- getGpgKeyForAuthenticated: [
- "GET /user/gpg_keys/{gpg_key_id}",
- {},
- { renamed: ["users", "getGpgKeyForAuthenticatedUser"] }
- ],
- getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"],
- getPublicSshKeyForAuthenticated: [
- "GET /user/keys/{key_id}",
- {},
- { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] }
- ],
- getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"],
- getSshSigningKeyForAuthenticatedUser: [
- "GET /user/ssh_signing_keys/{ssh_signing_key_id}"
- ],
- list: ["GET /users"],
- listBlockedByAuthenticated: [
- "GET /user/blocks",
- {},
- { renamed: ["users", "listBlockedByAuthenticatedUser"] }
- ],
- listBlockedByAuthenticatedUser: ["GET /user/blocks"],
- listEmailsForAuthenticated: [
- "GET /user/emails",
- {},
- { renamed: ["users", "listEmailsForAuthenticatedUser"] }
- ],
- listEmailsForAuthenticatedUser: ["GET /user/emails"],
- listFollowedByAuthenticated: [
- "GET /user/following",
- {},
- { renamed: ["users", "listFollowedByAuthenticatedUser"] }
- ],
- listFollowedByAuthenticatedUser: ["GET /user/following"],
- listFollowersForAuthenticatedUser: ["GET /user/followers"],
- listFollowersForUser: ["GET /users/{username}/followers"],
- listFollowingForUser: ["GET /users/{username}/following"],
- listGpgKeysForAuthenticated: [
- "GET /user/gpg_keys",
- {},
- { renamed: ["users", "listGpgKeysForAuthenticatedUser"] }
- ],
- listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"],
- listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
- listPublicEmailsForAuthenticated: [
- "GET /user/public_emails",
- {},
- { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] }
- ],
- listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"],
- listPublicKeysForUser: ["GET /users/{username}/keys"],
- listPublicSshKeysForAuthenticated: [
- "GET /user/keys",
- {},
- { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] }
- ],
- listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
- listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"],
- listSocialAccountsForUser: ["GET /users/{username}/social_accounts"],
- listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"],
- listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"],
- setPrimaryEmailVisibilityForAuthenticated: [
- "PATCH /user/email/visibility",
- {},
- { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] }
- ],
- setPrimaryEmailVisibilityForAuthenticatedUser: [
- "PATCH /user/email/visibility"
- ],
- unblock: ["DELETE /user/blocks/{username}"],
- unfollow: ["DELETE /user/following/{username}"],
- updateAuthenticated: ["PATCH /user"]
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
+ }
+
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
+
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
+
+ function onError(cause) {
+ connectReq.removeAllListeners();
+
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
}
};
-var endpoints_default = Endpoints;
-
-// pkg/dist-src/endpoints-to-methods.js
-var endpointMethodsMap = /* @__PURE__ */ new Map();
-for (const [scope, endpoints] of Object.entries(endpoints_default)) {
- for (const [methodName, endpoint] of Object.entries(endpoints)) {
- const [route, defaults, decorations] = endpoint;
- const [method, url] = route.split(/ /);
- const endpointDefaults = Object.assign(
- {
- method,
- url
- },
- defaults
- );
- if (!endpointMethodsMap.has(scope)) {
- endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());
- }
- endpointMethodsMap.get(scope).set(methodName, {
- scope,
- methodName,
- endpointDefaults,
- decorations
+
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket)
+ if (pos === -1) {
+ return;
+ }
+ this.sockets.splice(pos, 1);
+
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
});
}
+};
+
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
+ });
+
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
+ });
}
-var handler = {
- get({ octokit, scope, cache }, methodName) {
- if (cache[methodName]) {
- return cache[methodName];
- }
- const { decorations, endpointDefaults } = endpointMethodsMap.get(scope).get(methodName);
- if (decorations) {
- cache[methodName] = decorate(
- octokit,
- scope,
- methodName,
- endpointDefaults,
- decorations
- );
- } else {
- cache[methodName] = octokit.request.defaults(endpointDefaults);
- }
- return cache[methodName];
+
+
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
}
-};
-function endpointsToMethods(octokit) {
- const newMethods = {};
- for (const scope of endpointMethodsMap.keys()) {
- newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);
- }
- return newMethods;
-}
-function decorate(octokit, scope, methodName, defaults, decorations) {
- const requestWithDefaults = octokit.request.defaults(defaults);
- function withDecorations(...args) {
- let options = requestWithDefaults.endpoint.merge(...args);
- if (decorations.mapToData) {
- options = Object.assign({}, options, {
- data: options[decorations.mapToData],
- [decorations.mapToData]: void 0
- });
- return requestWithDefaults(options);
- }
- if (decorations.renamed) {
- const [newScope, newMethodName] = decorations.renamed;
- octokit.log.warn(
- `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`
- );
- }
- if (decorations.deprecated) {
- octokit.log.warn(decorations.deprecated);
- }
- if (decorations.renamedParameters) {
- const options2 = requestWithDefaults.endpoint.merge(...args);
- for (const [name, alias] of Object.entries(
- decorations.renamedParameters
- )) {
- if (name in options2) {
- octokit.log.warn(
- `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
- );
- if (!(alias in options2)) {
- options2[alias] = options2[name];
- }
- delete options2[name];
+ return host; // for v0.11 or later
+}
+
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
}
}
- return requestWithDefaults(options2);
}
- return requestWithDefaults(...args);
}
- return Object.assign(withDecorations, requestWithDefaults);
+ return target;
}
-// pkg/dist-src/index.js
-function restEndpointMethods(octokit) {
- const api = endpointsToMethods(octokit);
- return {
- rest: api
- };
-}
-restEndpointMethods.VERSION = VERSION;
-function legacyRestEndpointMethods(octokit) {
- const api = endpointsToMethods(octokit);
- return {
- ...api,
- rest: api
- };
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
+ }
+ console.error.apply(console, args);
+ }
+} else {
+ debug = function() {};
}
-legacyRestEndpointMethods.VERSION = VERSION;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+exports.debug = debug; // for test
/***/ }),
-/***/ 37471:
+/***/ 6752:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
-));
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- RequestError: () => RequestError
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_deprecation = __nccwpck_require__(58932);
-var import_once = __toESM(__nccwpck_require__(1223));
-var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));
-var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));
-var RequestError = class extends Error {
- constructor(message, statusCode, options) {
- super(message);
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
- this.name = "HttpError";
- this.status = statusCode;
- let headers;
- if ("headers" in options && typeof options.headers !== "undefined") {
- headers = options.headers;
- }
- if ("response" in options) {
- this.response = options.response;
- headers = options.response.headers;
- }
- const requestCopy = Object.assign({}, options.request);
- if (options.request.headers.authorization) {
- requestCopy.headers = Object.assign({}, options.request.headers, {
- authorization: options.request.headers.authorization.replace(
- / .*$/,
- " [REDACTED]"
- )
- });
- }
- requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
- this.request = requestCopy;
- Object.defineProperty(this, "code", {
- get() {
- logOnceCode(
- new import_deprecation.Deprecation(
- "[@octokit/request-error] `error.code` is deprecated, use `error.status`."
- )
- );
- return statusCode;
- }
- });
- Object.defineProperty(this, "headers", {
- get() {
- logOnceHeaders(
- new import_deprecation.Deprecation(
- "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."
- )
- );
- return headers || {};
- }
- });
- }
-};
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-/***/ }),
+const Client = __nccwpck_require__(6197)
+const Dispatcher = __nccwpck_require__(992)
+const errors = __nccwpck_require__(8707)
+const Pool = __nccwpck_require__(5076)
+const BalancedPool = __nccwpck_require__(1093)
+const Agent = __nccwpck_require__(9965)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError } = errors
+const api = __nccwpck_require__(6615)
+const buildConnector = __nccwpck_require__(9136)
+const MockClient = __nccwpck_require__(7365)
+const MockAgent = __nccwpck_require__(7501)
+const MockPool = __nccwpck_require__(4004)
+const mockErrors = __nccwpck_require__(2429)
+const ProxyAgent = __nccwpck_require__(2720)
+const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581)
+const DecoratorHandler = __nccwpck_require__(8840)
+const RedirectHandler = __nccwpck_require__(8299)
+const createRedirectInterceptor = __nccwpck_require__(4415)
-/***/ 89353:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+let hasCrypto
+try {
+ __nccwpck_require__(6982)
+ hasCrypto = true
+} catch {
+ hasCrypto = false
+}
-"use strict";
+Object.assign(Dispatcher.prototype, api)
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+module.exports.Dispatcher = Dispatcher
+module.exports.Client = Client
+module.exports.Pool = Pool
+module.exports.BalancedPool = BalancedPool
+module.exports.Agent = Agent
+module.exports.ProxyAgent = ProxyAgent
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
- request: () => request
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_endpoint = __nccwpck_require__(38713);
-var import_universal_user_agent = __nccwpck_require__(45030);
-
-// pkg/dist-src/version.js
-var VERSION = "8.1.4";
-
-// pkg/dist-src/fetch-wrapper.js
-var import_is_plain_object = __nccwpck_require__(63287);
-var import_request_error = __nccwpck_require__(37471);
-
-// pkg/dist-src/get-buffer-response.js
-function getBufferResponse(response) {
- return response.arrayBuffer();
-}
-
-// pkg/dist-src/fetch-wrapper.js
-function fetchWrapper(requestOptions) {
- var _a, _b, _c;
- const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
- const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;
- if ((0, import_is_plain_object.isPlainObject)(requestOptions.body) || Array.isArray(requestOptions.body)) {
- requestOptions.body = JSON.stringify(requestOptions.body);
- }
- let headers = {};
- let status;
- let url;
- let { fetch } = globalThis;
- if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {
- fetch = requestOptions.request.fetch;
- }
- if (!fetch) {
- throw new Error(
- "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing"
- );
- }
- return fetch(requestOptions.url, {
- method: requestOptions.method,
- body: requestOptions.body,
- headers: requestOptions.headers,
- signal: (_c = requestOptions.request) == null ? void 0 : _c.signal,
- // duplex must be set if request.body is ReadableStream or Async Iterables.
- // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.
- ...requestOptions.body && { duplex: "half" }
- }).then(async (response) => {
- url = response.url;
- status = response.status;
- for (const keyAndValue of response.headers) {
- headers[keyAndValue[0]] = keyAndValue[1];
- }
- if ("deprecation" in headers) {
- const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
- const deprecationLink = matches && matches.pop();
- log.warn(
- `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
- );
- }
- if (status === 204 || status === 205) {
- return;
+module.exports.DecoratorHandler = DecoratorHandler
+module.exports.RedirectHandler = RedirectHandler
+module.exports.createRedirectInterceptor = createRedirectInterceptor
+
+module.exports.buildConnector = buildConnector
+module.exports.errors = errors
+
+function makeDispatcher (fn) {
+ return (url, opts, handler) => {
+ if (typeof opts === 'function') {
+ handler = opts
+ opts = null
}
- if (requestOptions.method === "HEAD") {
- if (status < 400) {
- return;
- }
- throw new import_request_error.RequestError(response.statusText, status, {
- response: {
- url,
- status,
- headers,
- data: void 0
- },
- request: requestOptions
- });
- }
- if (status === 304) {
- throw new import_request_error.RequestError("Not modified", status, {
- response: {
- url,
- status,
- headers,
- data: await getResponseData(response)
- },
- request: requestOptions
- });
- }
- if (status >= 400) {
- const data = await getResponseData(response);
- const error = new import_request_error.RequestError(toErrorMessage(data), status, {
- response: {
- url,
- status,
- headers,
- data
- },
- request: requestOptions
- });
- throw error;
+
+ if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
+ throw new InvalidArgumentError('invalid url')
}
- return parseSuccessResponseBody ? await getResponseData(response) : response.body;
- }).then((data) => {
- return {
- status,
- url,
- headers,
- data
- };
- }).catch((error) => {
- if (error instanceof import_request_error.RequestError)
- throw error;
- else if (error.name === "AbortError")
- throw error;
- let message = error.message;
- if (error.name === "TypeError" && "cause" in error) {
- if (error.cause instanceof Error) {
- message = error.cause.message;
- } else if (typeof error.cause === "string") {
- message = error.cause;
+
+ if (opts != null && typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (opts && opts.path != null) {
+ if (typeof opts.path !== 'string') {
+ throw new InvalidArgumentError('invalid opts.path')
+ }
+
+ let path = opts.path
+ if (!opts.path.startsWith('/')) {
+ path = `/${path}`
+ }
+
+ url = new URL(util.parseOrigin(url).origin + path)
+ } else {
+ if (!opts) {
+ opts = typeof url === 'object' ? url : {}
}
+
+ url = util.parseURL(url)
}
- throw new import_request_error.RequestError(message, 500, {
- request: requestOptions
- });
- });
-}
-async function getResponseData(response) {
- const contentType = response.headers.get("content-type");
- if (/application\/json/.test(contentType)) {
- return response.json();
- }
- if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
- return response.text();
+
+ const { agent, dispatcher = getGlobalDispatcher() } = opts
+
+ if (agent) {
+ throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ }
+
+ return fn.call(dispatcher, {
+ ...opts,
+ origin: url.origin,
+ path: url.search ? `${url.pathname}${url.search}` : url.pathname,
+ method: opts.method || (opts.body ? 'PUT' : 'GET')
+ }, handler)
}
- return getBufferResponse(response);
}
-function toErrorMessage(data) {
- if (typeof data === "string")
- return data;
- if ("message" in data) {
- if (Array.isArray(data.errors)) {
- return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
+
+module.exports.setGlobalDispatcher = setGlobalDispatcher
+module.exports.getGlobalDispatcher = getGlobalDispatcher
+
+if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
+ let fetchImpl = null
+ module.exports.fetch = async function fetch (resource) {
+ if (!fetchImpl) {
+ fetchImpl = (__nccwpck_require__(2315).fetch)
+ }
+
+ try {
+ return await fetchImpl(...arguments)
+ } catch (err) {
+ if (typeof err === 'object') {
+ Error.captureStackTrace(err, this)
+ }
+
+ throw err
}
- return data.message;
}
- return `Unknown error: ${JSON.stringify(data)}`;
+ module.exports.Headers = __nccwpck_require__(6349).Headers
+ module.exports.Response = __nccwpck_require__(8676).Response
+ module.exports.Request = __nccwpck_require__(5194).Request
+ module.exports.FormData = __nccwpck_require__(3073).FormData
+ module.exports.File = __nccwpck_require__(3041).File
+ module.exports.FileReader = __nccwpck_require__(2160).FileReader
+
+ const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628)
+
+ module.exports.setGlobalOrigin = setGlobalOrigin
+ module.exports.getGlobalOrigin = getGlobalOrigin
+
+ const { CacheStorage } = __nccwpck_require__(4738)
+ const { kConstruct } = __nccwpck_require__(296)
+
+ // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
+ // in an older version of Node, it doesn't have any use without fetch.
+ module.exports.caches = new CacheStorage(kConstruct)
}
-// pkg/dist-src/with-defaults.js
-function withDefaults(oldEndpoint, newDefaults) {
- const endpoint2 = oldEndpoint.defaults(newDefaults);
- const newApi = function(route, parameters) {
- const endpointOptions = endpoint2.merge(route, parameters);
- if (!endpointOptions.request || !endpointOptions.request.hook) {
- return fetchWrapper(endpoint2.parse(endpointOptions));
- }
- const request2 = (route2, parameters2) => {
- return fetchWrapper(
- endpoint2.parse(endpoint2.merge(route2, parameters2))
- );
- };
- Object.assign(request2, {
- endpoint: endpoint2,
- defaults: withDefaults.bind(null, endpoint2)
- });
- return endpointOptions.request.hook(request2, endpointOptions);
- };
- return Object.assign(newApi, {
- endpoint: endpoint2,
- defaults: withDefaults.bind(null, endpoint2)
- });
+if (util.nodeMajor >= 16) {
+ const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168)
+
+ module.exports.deleteCookie = deleteCookie
+ module.exports.getCookies = getCookies
+ module.exports.getSetCookies = getSetCookies
+ module.exports.setCookie = setCookie
+
+ const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
+
+ module.exports.parseMIMEType = parseMIMEType
+ module.exports.serializeAMimeType = serializeAMimeType
}
-// pkg/dist-src/index.js
-var request = withDefaults(import_endpoint.endpoint, {
- headers: {
- "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
- }
-});
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+if (util.nodeMajor >= 18 && hasCrypto) {
+ const { WebSocket } = __nccwpck_require__(5171)
+
+ module.exports.WebSocket = WebSocket
+}
+
+module.exports.request = makeDispatcher(api.request)
+module.exports.stream = makeDispatcher(api.stream)
+module.exports.pipeline = makeDispatcher(api.pipeline)
+module.exports.connect = makeDispatcher(api.connect)
+module.exports.upgrade = makeDispatcher(api.upgrade)
+
+module.exports.MockClient = MockClient
+module.exports.MockPool = MockPool
+module.exports.MockAgent = MockAgent
+module.exports.mockErrors = mockErrors
/***/ }),
-/***/ 35526:
-/***/ (function(__unused_webpack_module, exports) {
+/***/ 9965:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;
-class BasicCredentialHandler {
- constructor(username, password) {
- this.username = username;
- this.password = password;
+
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443)
+const DispatcherBase = __nccwpck_require__(1)
+const Pool = __nccwpck_require__(5076)
+const Client = __nccwpck_require__(6197)
+const util = __nccwpck_require__(3440)
+const createRedirectInterceptor = __nccwpck_require__(4415)
+const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)()
+
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kMaxRedirections = Symbol('maxRedirections')
+const kOnDrain = Symbol('onDrain')
+const kFactory = Symbol('factory')
+const kFinalizer = Symbol('finalizer')
+const kOptions = Symbol('options')
+
+function defaultFactory (origin, opts) {
+ return opts && opts.connections === 1
+ ? new Client(origin, opts)
+ : new Pool(origin, opts)
+}
+
+class Agent extends DispatcherBase {
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
+ super()
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
+
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
}
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
+
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
}
- handleAuthentication() {
- return __awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
+
+ if (connect && typeof connect !== 'function') {
+ connect = { ...connect }
}
-}
-exports.BasicCredentialHandler = BasicCredentialHandler;
-class BearerCredentialHandler {
- constructor(token) {
- this.token = token;
+
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
+ ? options.interceptors.Agent
+ : [createRedirectInterceptor({ maxRedirections })]
+
+ this[kOptions] = { ...util.deepClone(options), connect }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kMaxRedirections] = maxRedirections
+ this[kFactory] = factory
+ this[kClients] = new Map()
+ this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
+ const ref = this[kClients].get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this[kClients].delete(key)
+ }
+ })
+
+ const agent = this
+
+ this[kOnDrain] = (origin, targets) => {
+ agent.emit('drain', origin, [agent, ...targets])
}
- // currently implements pre-authorization
- // TODO: support preAuth = false where it hooks on 401
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Bearer ${this.token}`;
+
+ this[kOnConnect] = (origin, targets) => {
+ agent.emit('connect', origin, [agent, ...targets])
}
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
+
+ this[kOnDisconnect] = (origin, targets, err) => {
+ agent.emit('disconnect', origin, [agent, ...targets], err)
}
- handleAuthentication() {
- return __awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
+
+ this[kOnConnectionError] = (origin, targets, err) => {
+ agent.emit('connectionError', origin, [agent, ...targets], err)
}
-}
-exports.BearerCredentialHandler = BearerCredentialHandler;
-class PersonalAccessTokenCredentialHandler {
- constructor(token) {
- this.token = token;
+ }
+
+ get [kRunning] () {
+ let ret = 0
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore next: gc is undeterministic */
+ if (client) {
+ ret += client[kRunning]
+ }
}
- // currently implements pre-authorization
- // TODO: support preAuth = false where it hooks on 401
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
+ return ret
+ }
+
+ [kDispatch] (opts, handler) {
+ let key
+ if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
+ key = String(opts.origin)
+ } else {
+ throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
}
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
+
+ const ref = this[kClients].get(key)
+
+ let dispatcher = ref ? ref.deref() : null
+ if (!dispatcher) {
+ dispatcher = this[kFactory](opts.origin, this[kOptions])
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
+
+ this[kClients].set(key, new WeakRef(dispatcher))
+ this[kFinalizer].register(dispatcher, key)
}
- handleAuthentication() {
- return __awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
+
+ return dispatcher.dispatch(opts, handler)
+ }
+
+ async [kClose] () {
+ const closePromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ closePromises.push(client.close())
+ }
+ }
+
+ await Promise.all(closePromises)
+ }
+
+ async [kDestroy] (err) {
+ const destroyPromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ destroyPromises.push(client.destroy(err))
+ }
}
+
+ await Promise.all(destroyPromises)
+ }
}
-exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
-//# sourceMappingURL=auth.js.map
+
+module.exports = Agent
+
/***/ }),
-/***/ 96255:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 158:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
+const { addAbortListener } = __nccwpck_require__(3440)
+const { RequestAbortedError } = __nccwpck_require__(8707)
-/* eslint-disable @typescript-eslint/no-explicit-any */
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
-const http = __importStar(__nccwpck_require__(13685));
-const https = __importStar(__nccwpck_require__(95687));
-const pm = __importStar(__nccwpck_require__(19835));
-const tunnel = __importStar(__nccwpck_require__(74294));
-const undici_1 = __nccwpck_require__(41773);
-var HttpCodes;
-(function (HttpCodes) {
- HttpCodes[HttpCodes["OK"] = 200] = "OK";
- HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
- HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
- HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
- HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
- HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
- HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
- HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
- HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
- HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
- HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
- HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
- HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
- HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
- HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
- HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
- HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
- HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
- HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
- HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
- HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
- HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
- HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
- HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
- HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
- HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
- HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
-})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));
-var Headers;
-(function (Headers) {
- Headers["Accept"] = "accept";
- Headers["ContentType"] = "content-type";
-})(Headers || (exports.Headers = Headers = {}));
-var MediaTypes;
-(function (MediaTypes) {
- MediaTypes["ApplicationJson"] = "application/json";
-})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));
-/**
- * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
- * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
- */
-function getProxyUrl(serverUrl) {
- const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
- return proxyUrl ? proxyUrl.href : '';
+const kListener = Symbol('kListener')
+const kSignal = Symbol('kSignal')
+
+function abort (self) {
+ if (self.abort) {
+ self.abort()
+ } else {
+ self.onError(new RequestAbortedError())
+ }
}
-exports.getProxyUrl = getProxyUrl;
-const HttpRedirectCodes = [
- HttpCodes.MovedPermanently,
- HttpCodes.ResourceMoved,
- HttpCodes.SeeOther,
- HttpCodes.TemporaryRedirect,
- HttpCodes.PermanentRedirect
-];
-const HttpResponseRetryCodes = [
- HttpCodes.BadGateway,
- HttpCodes.ServiceUnavailable,
- HttpCodes.GatewayTimeout
-];
-const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
-const ExponentialBackoffCeiling = 10;
-const ExponentialBackoffTimeSlice = 5;
-class HttpClientError extends Error {
- constructor(message, statusCode) {
- super(message);
- this.name = 'HttpClientError';
- this.statusCode = statusCode;
- Object.setPrototypeOf(this, HttpClientError.prototype);
- }
+
+function addSignal (self, signal) {
+ self[kSignal] = null
+ self[kListener] = null
+
+ if (!signal) {
+ return
+ }
+
+ if (signal.aborted) {
+ abort(self)
+ return
+ }
+
+ self[kSignal] = signal
+ self[kListener] = () => {
+ abort(self)
+ }
+
+ addAbortListener(self[kSignal], self[kListener])
}
-exports.HttpClientError = HttpClientError;
-class HttpClientResponse {
- constructor(message) {
- this.message = message;
- }
- readBody() {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
- let output = Buffer.alloc(0);
- this.message.on('data', (chunk) => {
- output = Buffer.concat([output, chunk]);
- });
- this.message.on('end', () => {
- resolve(output.toString());
- });
- }));
- });
- }
- readBodyBuffer() {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
- const chunks = [];
- this.message.on('data', (chunk) => {
- chunks.push(chunk);
- });
- this.message.on('end', () => {
- resolve(Buffer.concat(chunks));
- });
- }));
- });
- }
+
+function removeSignal (self) {
+ if (!self[kSignal]) {
+ return
+ }
+
+ if ('removeEventListener' in self[kSignal]) {
+ self[kSignal].removeEventListener('abort', self[kListener])
+ } else {
+ self[kSignal].removeListener('abort', self[kListener])
+ }
+
+ self[kSignal] = null
+ self[kListener] = null
}
-exports.HttpClientResponse = HttpClientResponse;
-function isHttps(requestUrl) {
- const parsedUrl = new URL(requestUrl);
- return parsedUrl.protocol === 'https:';
+
+module.exports = {
+ addSignal,
+ removeSignal
}
-exports.isHttps = isHttps;
-class HttpClient {
- constructor(userAgent, handlers, requestOptions) {
- this._ignoreSslError = false;
- this._allowRedirects = true;
- this._allowRedirectDowngrade = false;
- this._maxRedirects = 50;
- this._allowRetries = false;
- this._maxRetries = 1;
- this._keepAlive = false;
- this._disposed = false;
- this.userAgent = userAgent;
- this.handlers = handlers || [];
- this.requestOptions = requestOptions;
- if (requestOptions) {
- if (requestOptions.ignoreSslError != null) {
- this._ignoreSslError = requestOptions.ignoreSslError;
- }
- this._socketTimeout = requestOptions.socketTimeout;
- if (requestOptions.allowRedirects != null) {
- this._allowRedirects = requestOptions.allowRedirects;
- }
- if (requestOptions.allowRedirectDowngrade != null) {
- this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
- }
- if (requestOptions.maxRedirects != null) {
- this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
- }
- if (requestOptions.keepAlive != null) {
- this._keepAlive = requestOptions.keepAlive;
- }
- if (requestOptions.allowRetries != null) {
- this._allowRetries = requestOptions.allowRetries;
- }
- if (requestOptions.maxRetries != null) {
- this._maxRetries = requestOptions.maxRetries;
- }
- }
+
+
+/***/ }),
+
+/***/ 4660:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { AsyncResource } = __nccwpck_require__(290)
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+
+class ConnectHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- options(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
- });
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- get(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('GET', requestUrl, null, additionalHeaders || {});
- });
+
+ const { signal, opaque, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
- del(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('DELETE', requestUrl, null, additionalHeaders || {});
- });
+
+ super('UNDICI_CONNECT')
+
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.callback = callback
+ this.abort = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
}
- post(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('POST', requestUrl, data, additionalHeaders || {});
- });
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders () {
+ throw new SocketError('bad connect', null)
+ }
+
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ removeSignal(this)
+
+ this.callback = null
+
+ let headers = rawHeaders
+ // Indicates is an HTTP2Session
+ if (headers != null) {
+ headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
}
- patch(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('PATCH', requestUrl, data, additionalHeaders || {});
- });
+
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
+
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
}
- put(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('PUT', requestUrl, data, additionalHeaders || {});
- });
+ }
+}
+
+function connect (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ const connectHandler = new ConnectHandler(opts, callback)
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
- head(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('HEAD', requestUrl, null, additionalHeaders || {});
- });
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = connect
+
+
+/***/ }),
+
+/***/ 6862:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ Readable,
+ Duplex,
+ PassThrough
+} = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { AsyncResource } = __nccwpck_require__(290)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+const assert = __nccwpck_require__(2613)
+
+const kResume = Symbol('resume')
+
+class PipelineRequest extends Readable {
+ constructor () {
+ super({ autoDestroy: true })
+
+ this[kResume] = null
+ }
+
+ _read () {
+ const { [kResume]: resume } = this
+
+ if (resume) {
+ this[kResume] = null
+ resume()
}
- sendStream(verb, requestUrl, stream, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request(verb, requestUrl, stream, additionalHeaders);
- });
+ }
+
+ _destroy (err, callback) {
+ this._read()
+
+ callback(err)
+ }
+}
+
+class PipelineResponse extends Readable {
+ constructor (resume) {
+ super({ autoDestroy: true })
+ this[kResume] = resume
+ }
+
+ _read () {
+ this[kResume]()
+ }
+
+ _destroy (err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
}
- /**
- * Gets a typed object from an endpoint
- * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
- */
- getJson(requestUrl, additionalHeaders = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- const res = yield this.get(requestUrl, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
+
+ callback(err)
+ }
+}
+
+class PipelineHandler extends AsyncResource {
+ constructor (opts, handler) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- postJson(requestUrl, obj, additionalHeaders = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
- const res = yield this.post(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
+
+ if (typeof handler !== 'function') {
+ throw new InvalidArgumentError('invalid handler')
}
- putJson(requestUrl, obj, additionalHeaders = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
- const res = yield this.put(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
+
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
- patchJson(requestUrl, obj, additionalHeaders = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
- const res = yield this.patch(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
}
- /**
- * Makes a raw http request.
- * All other methods such as get, post, patch, and request ultimately call this.
- * Prefer get, del, post and patch
- */
- request(verb, requestUrl, data, headers) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this._disposed) {
- throw new Error('Client has already been disposed.');
- }
- const parsedUrl = new URL(requestUrl);
- let info = this._prepareRequest(verb, parsedUrl, headers);
- // Only perform retries on reads since writes may not be idempotent.
- const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
- ? this._maxRetries + 1
- : 1;
- let numTries = 0;
- let response;
- do {
- response = yield this.requestRaw(info, data);
- // Check if it's an authentication challenge
- if (response &&
- response.message &&
- response.message.statusCode === HttpCodes.Unauthorized) {
- let authenticationHandler;
- for (const handler of this.handlers) {
- if (handler.canHandleAuthentication(response)) {
- authenticationHandler = handler;
- break;
- }
- }
- if (authenticationHandler) {
- return authenticationHandler.handleAuthentication(this, info, data);
- }
- else {
- // We have received an unauthorized response but have no handlers to handle it.
- // Let the response return to the caller.
- return response;
- }
- }
- let redirectsRemaining = this._maxRedirects;
- while (response.message.statusCode &&
- HttpRedirectCodes.includes(response.message.statusCode) &&
- this._allowRedirects &&
- redirectsRemaining > 0) {
- const redirectUrl = response.message.headers['location'];
- if (!redirectUrl) {
- // if there's no location to redirect to, we won't
- break;
- }
- const parsedRedirectUrl = new URL(redirectUrl);
- if (parsedUrl.protocol === 'https:' &&
- parsedUrl.protocol !== parsedRedirectUrl.protocol &&
- !this._allowRedirectDowngrade) {
- throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
- }
- // we need to finish reading the response before reassigning response
- // which will leak the open socket.
- yield response.readBody();
- // strip authorization header if redirected to a different hostname
- if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
- for (const header in headers) {
- // header names are case insensitive
- if (header.toLowerCase() === 'authorization') {
- delete headers[header];
- }
- }
- }
- // let's make the request with the new redirectUrl
- info = this._prepareRequest(verb, parsedRedirectUrl, headers);
- response = yield this.requestRaw(info, data);
- redirectsRemaining--;
- }
- if (!response.message.statusCode ||
- !HttpResponseRetryCodes.includes(response.message.statusCode)) {
- // If not a retry code, return immediately instead of retrying
- return response;
- }
- numTries += 1;
- if (numTries < maxTries) {
- yield response.readBody();
- yield this._performExponentialBackoff(numTries);
- }
- } while (numTries < maxTries);
- return response;
- });
- }
- /**
- * Needs to be called if keepAlive is set to true in request options.
- */
- dispose() {
- if (this._agent) {
- this._agent.destroy();
- }
- this._disposed = true;
- }
- /**
- * Raw request.
- * @param info
- * @param data
- */
- requestRaw(info, data) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve, reject) => {
- function callbackForResult(err, res) {
- if (err) {
- reject(err);
- }
- else if (!res) {
- // If `err` is not passed, then `res` must be passed.
- reject(new Error('Unknown error'));
- }
- else {
- resolve(res);
- }
- }
- this.requestRawWithCallback(info, data, callbackForResult);
- });
- });
- }
- /**
- * Raw request with callback.
- * @param info
- * @param data
- * @param onResult
- */
- requestRawWithCallback(info, data, onResult) {
- if (typeof data === 'string') {
- if (!info.options.headers) {
- info.options.headers = {};
- }
- info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
- }
- let callbackCalled = false;
- function handleResult(err, res) {
- if (!callbackCalled) {
- callbackCalled = true;
- onResult(err, res);
- }
- }
- const req = info.httpModule.request(info.options, (msg) => {
- const res = new HttpClientResponse(msg);
- handleResult(undefined, res);
- });
- let socket;
- req.on('socket', sock => {
- socket = sock;
- });
- // If we ever get disconnected, we want the socket to timeout eventually
- req.setTimeout(this._socketTimeout || 3 * 60000, () => {
- if (socket) {
- socket.end();
- }
- handleResult(new Error(`Request timeout: ${info.options.path}`));
- });
- req.on('error', function (err) {
- // err has statusCode property
- // res should have headers
- handleResult(err);
- });
- if (data && typeof data === 'string') {
- req.write(data, 'utf8');
- }
- if (data && typeof data !== 'string') {
- data.on('close', function () {
- req.end();
- });
- data.pipe(req);
- }
- else {
- req.end();
- }
- }
- /**
- * Gets an http agent. This function is useful when you need an http agent that handles
- * routing through a proxy server - depending upon the url and proxy environment variables.
- * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
- */
- getAgent(serverUrl) {
- const parsedUrl = new URL(serverUrl);
- return this._getAgent(parsedUrl);
- }
- getAgentDispatcher(serverUrl) {
- const parsedUrl = new URL(serverUrl);
- const proxyUrl = pm.getProxyUrl(parsedUrl);
- const useProxy = proxyUrl && proxyUrl.hostname;
- if (!useProxy) {
- return;
- }
- return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
- }
- _prepareRequest(method, requestUrl, headers) {
- const info = {};
- info.parsedUrl = requestUrl;
- const usingSsl = info.parsedUrl.protocol === 'https:';
- info.httpModule = usingSsl ? https : http;
- const defaultPort = usingSsl ? 443 : 80;
- info.options = {};
- info.options.host = info.parsedUrl.hostname;
- info.options.port = info.parsedUrl.port
- ? parseInt(info.parsedUrl.port)
- : defaultPort;
- info.options.path =
- (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
- info.options.method = method;
- info.options.headers = this._mergeHeaders(headers);
- if (this.userAgent != null) {
- info.options.headers['user-agent'] = this.userAgent;
- }
- info.options.agent = this._getAgent(info.parsedUrl);
- // gives handlers an opportunity to participate
- if (this.handlers) {
- for (const handler of this.handlers) {
- handler.prepareRequest(info.options);
- }
- }
- return info;
- }
- _mergeHeaders(headers) {
- if (this.requestOptions && this.requestOptions.headers) {
- return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
- }
- return lowercaseKeys(headers || {});
- }
- _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
- let clientHeader;
- if (this.requestOptions && this.requestOptions.headers) {
- clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
- }
- return additionalHeaders[header] || clientHeader || _default;
- }
- _getAgent(parsedUrl) {
- let agent;
- const proxyUrl = pm.getProxyUrl(parsedUrl);
- const useProxy = proxyUrl && proxyUrl.hostname;
- if (this._keepAlive && useProxy) {
- agent = this._proxyAgent;
- }
- if (this._keepAlive && !useProxy) {
- agent = this._agent;
- }
- // if agent is already assigned use that agent.
- if (agent) {
- return agent;
- }
- const usingSsl = parsedUrl.protocol === 'https:';
- let maxSockets = 100;
- if (this.requestOptions) {
- maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
- }
- // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
- if (proxyUrl && proxyUrl.hostname) {
- const agentOptions = {
- maxSockets,
- keepAlive: this._keepAlive,
- proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
- proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
- })), { host: proxyUrl.hostname, port: proxyUrl.port })
- };
- let tunnelAgent;
- const overHttps = proxyUrl.protocol === 'https:';
- if (usingSsl) {
- tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
- }
- else {
- tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
- }
- agent = tunnelAgent(agentOptions);
- this._proxyAgent = agent;
- }
- // if reusing agent across request and tunneling agent isn't assigned create a new agent
- if (this._keepAlive && !agent) {
- const options = { keepAlive: this._keepAlive, maxSockets };
- agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
- this._agent = agent;
- }
- // if not using private agent and tunnel agent isn't setup then use global agent
- if (!agent) {
- agent = usingSsl ? https.globalAgent : http.globalAgent;
- }
- if (usingSsl && this._ignoreSslError) {
- // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
- // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
- // we have to cast it to any and change it directly
- agent.options = Object.assign(agent.options || {}, {
- rejectUnauthorized: false
- });
- }
- return agent;
- }
- _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
- let proxyAgent;
- if (this._keepAlive) {
- proxyAgent = this._proxyAgentDispatcher;
- }
- // if agent is already assigned use that agent.
- if (proxyAgent) {
- return proxyAgent;
- }
- const usingSsl = parsedUrl.protocol === 'https:';
- proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
- token: `${proxyUrl.username}:${proxyUrl.password}`
- })));
- this._proxyAgentDispatcher = proxyAgent;
- if (usingSsl && this._ignoreSslError) {
- // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
- // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
- // we have to cast it to any and change it directly
- proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
- rejectUnauthorized: false
- });
- }
- return proxyAgent;
- }
- _performExponentialBackoff(retryNumber) {
- return __awaiter(this, void 0, void 0, function* () {
- retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
- const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
- return new Promise(resolve => setTimeout(() => resolve(), ms));
- });
- }
- _processResponse(res, options) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
- const statusCode = res.message.statusCode || 0;
- const response = {
- statusCode,
- result: null,
- headers: {}
- };
- // not found leads to null obj returned
- if (statusCode === HttpCodes.NotFound) {
- resolve(response);
- }
- // get the result from the body
- function dateTimeDeserializer(key, value) {
- if (typeof value === 'string') {
- const a = new Date(value);
- if (!isNaN(a.valueOf())) {
- return a;
- }
- }
- return value;
- }
- let obj;
- let contents;
- try {
- contents = yield res.readBody();
- if (contents && contents.length > 0) {
- if (options && options.deserializeDates) {
- obj = JSON.parse(contents, dateTimeDeserializer);
- }
- else {
- obj = JSON.parse(contents);
- }
- response.result = obj;
- }
- response.headers = res.message.headers;
- }
- catch (err) {
- // Invalid resource (contents not json); leaving result obj null
- }
- // note that 3xx redirects are handled by the http layer.
- if (statusCode > 299) {
- let msg;
- // if exception/error in body, attempt to get better error
- if (obj && obj.message) {
- msg = obj.message;
- }
- else if (contents && contents.length > 0) {
- // it may be the case that the exception is in the body message as string
- msg = contents;
- }
- else {
- msg = `Failed request: (${statusCode})`;
- }
- const err = new HttpClientError(msg, statusCode);
- err.result = response.result;
- reject(err);
- }
- else {
- resolve(response);
- }
- }));
- });
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
}
-}
-exports.HttpClient = HttpClient;
-const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
-//# sourceMappingURL=index.js.map
-/***/ }),
+ super('UNDICI_PIPELINE')
-/***/ 19835:
-/***/ ((__unused_webpack_module, exports) => {
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.handler = handler
+ this.abort = null
+ this.context = null
+ this.onInfo = onInfo || null
-"use strict";
+ this.req = new PipelineRequest().on('error', util.nop)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.checkBypass = exports.getProxyUrl = void 0;
-function getProxyUrl(reqUrl) {
- const usingSsl = reqUrl.protocol === 'https:';
- if (checkBypass(reqUrl)) {
- return undefined;
- }
- const proxyVar = (() => {
- if (usingSsl) {
- return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: () => {
+ const { body } = this
+
+ if (body && body.resume) {
+ body.resume()
}
- else {
- return process.env['http_proxy'] || process.env['HTTP_PROXY'];
+ },
+ write: (chunk, encoding, callback) => {
+ const { req } = this
+
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
+ callback()
+ } else {
+ req[kResume] = callback
}
- })();
- if (proxyVar) {
- try {
- return new URL(proxyVar);
+ },
+ destroy: (err, callback) => {
+ const { body, req, res, ret, abort } = this
+
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError()
}
- catch (_a) {
- if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
- return new URL(`http://${proxyVar}`);
+
+ if (abort && err) {
+ abort()
}
+
+ util.destroy(body, err)
+ util.destroy(req, err)
+ util.destroy(res, err)
+
+ removeSignal(this)
+
+ callback(err)
+ }
+ }).on('prefinish', () => {
+ const { req } = this
+
+ // Node < 15 does not call _final in same tick.
+ req.push(null)
+ })
+
+ this.res = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ const { ret, res } = this
+
+ assert(!res, 'pipeline cannot be retried')
+
+ if (ret.destroyed) {
+ throw new RequestAbortedError()
}
- else {
- return undefined;
- }
-}
-exports.getProxyUrl = getProxyUrl;
-function checkBypass(reqUrl) {
- if (!reqUrl.hostname) {
- return false;
- }
- const reqHost = reqUrl.hostname;
- if (isLoopbackAddress(reqHost)) {
- return true;
- }
- const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
- if (!noProxy) {
- return false;
- }
- // Determine the request port
- let reqPort;
- if (reqUrl.port) {
- reqPort = Number(reqUrl.port);
- }
- else if (reqUrl.protocol === 'http:') {
- reqPort = 80;
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.onInfo({ statusCode, headers })
+ }
+ return
}
- else if (reqUrl.protocol === 'https:') {
- reqPort = 443;
+
+ this.res = new PipelineResponse(resume)
+
+ let body
+ try {
+ this.handler = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ body = this.runInAsyncScope(handler, null, {
+ statusCode,
+ headers,
+ opaque,
+ body: this.res,
+ context
+ })
+ } catch (err) {
+ this.res.on('error', util.nop)
+ throw err
}
- // Format the request hostname and hostname with port
- const upperReqHosts = [reqUrl.hostname.toUpperCase()];
- if (typeof reqPort === 'number') {
- upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+
+ if (!body || typeof body.on !== 'function') {
+ throw new InvalidReturnValueError('expected Readable')
}
- // Compare request host against noproxy
- for (const upperNoProxyItem of noProxy
- .split(',')
- .map(x => x.trim().toUpperCase())
- .filter(x => x)) {
- if (upperNoProxyItem === '*' ||
- upperReqHosts.some(x => x === upperNoProxyItem ||
- x.endsWith(`.${upperNoProxyItem}`) ||
- (upperNoProxyItem.startsWith('.') &&
- x.endsWith(`${upperNoProxyItem}`)))) {
- return true;
+
+ body
+ .on('data', (chunk) => {
+ const { ret, body } = this
+
+ if (!ret.push(chunk) && body.pause) {
+ body.pause()
}
- }
- return false;
-}
-exports.checkBypass = checkBypass;
-function isLoopbackAddress(host) {
- const hostLower = host.toLowerCase();
- return (hostLower === 'localhost' ||
- hostLower.startsWith('127.') ||
- hostLower.startsWith('[::1]') ||
- hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
-}
-//# sourceMappingURL=proxy.js.map
+ })
+ .on('error', (err) => {
+ const { ret } = this
-/***/ }),
+ util.destroy(ret, err)
+ })
+ .on('end', () => {
+ const { ret } = this
-/***/ 81962:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ ret.push(null)
+ })
+ .on('close', () => {
+ const { ret } = this
-"use strict";
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError())
+ }
+ })
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var _a;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;
-const fs = __importStar(__nccwpck_require__(57147));
-const path = __importStar(__nccwpck_require__(71017));
-_a = fs.promises
-// export const {open} = 'fs'
-, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
-// export const {open} = 'fs'
-exports.IS_WINDOWS = process.platform === 'win32';
-// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691
-exports.UV_FS_O_EXLOCK = 0x10000000;
-exports.READONLY = fs.constants.O_RDONLY;
-function exists(fsPath) {
- return __awaiter(this, void 0, void 0, function* () {
- try {
- yield exports.stat(fsPath);
- }
- catch (err) {
- if (err.code === 'ENOENT') {
- return false;
- }
- throw err;
- }
- return true;
- });
-}
-exports.exists = exists;
-function isDirectory(fsPath, useStat = false) {
- return __awaiter(this, void 0, void 0, function* () {
- const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
- return stats.isDirectory();
- });
-}
-exports.isDirectory = isDirectory;
-/**
- * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
- * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
- */
-function isRooted(p) {
- p = normalizeSeparators(p);
- if (!p) {
- throw new Error('isRooted() parameter "p" cannot be empty');
- }
- if (exports.IS_WINDOWS) {
- return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
- ); // e.g. C: or C:\hello
- }
- return p.startsWith('/');
-}
-exports.isRooted = isRooted;
-/**
- * Best effort attempt to determine whether a file exists and is executable.
- * @param filePath file path to check
- * @param extensions additional file extensions to try
- * @return if file exists and is executable, returns the file path. otherwise empty string.
- */
-function tryGetExecutablePath(filePath, extensions) {
- return __awaiter(this, void 0, void 0, function* () {
- let stats = undefined;
- try {
- // test file exists
- stats = yield exports.stat(filePath);
- }
- catch (err) {
- if (err.code !== 'ENOENT') {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
- }
- }
- if (stats && stats.isFile()) {
- if (exports.IS_WINDOWS) {
- // on Windows, test for valid extension
- const upperExt = path.extname(filePath).toUpperCase();
- if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
- return filePath;
- }
- }
- else {
- if (isUnixExecutable(stats)) {
- return filePath;
- }
- }
- }
- // try each extension
- const originalFilePath = filePath;
- for (const extension of extensions) {
- filePath = originalFilePath + extension;
- stats = undefined;
- try {
- stats = yield exports.stat(filePath);
- }
- catch (err) {
- if (err.code !== 'ENOENT') {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
- }
- }
- if (stats && stats.isFile()) {
- if (exports.IS_WINDOWS) {
- // preserve the case of the actual file (since an extension was appended)
- try {
- const directory = path.dirname(filePath);
- const upperName = path.basename(filePath).toUpperCase();
- for (const actualName of yield exports.readdir(directory)) {
- if (upperName === actualName.toUpperCase()) {
- filePath = path.join(directory, actualName);
- break;
- }
- }
- }
- catch (err) {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
- }
- return filePath;
- }
- else {
- if (isUnixExecutable(stats)) {
- return filePath;
- }
- }
- }
- }
- return '';
- });
-}
-exports.tryGetExecutablePath = tryGetExecutablePath;
-function normalizeSeparators(p) {
- p = p || '';
- if (exports.IS_WINDOWS) {
- // convert slashes on Windows
- p = p.replace(/\//g, '\\');
- // remove redundant slashes
- return p.replace(/\\\\+/g, '\\');
- }
- // remove redundant slashes
- return p.replace(/\/\/+/g, '/');
-}
-// on Mac/Linux, test the execute bit
-// R W X R W X R W X
-// 256 128 64 32 16 8 4 2 1
-function isUnixExecutable(stats) {
- return ((stats.mode & 1) > 0 ||
- ((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
- ((stats.mode & 64) > 0 && stats.uid === process.getuid()));
-}
-// Get the path of cmd.exe in windows
-function getCmdPath() {
- var _a;
- return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
-}
-exports.getCmdPath = getCmdPath;
-//# sourceMappingURL=io-util.js.map
-
-/***/ }),
+ this.body = body
+ }
-/***/ 47351:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
-"use strict";
+ onComplete (trailers) {
+ const { res } = this
+ res.push(null)
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0;
-const assert_1 = __nccwpck_require__(39491);
-const path = __importStar(__nccwpck_require__(71017));
-const ioUtil = __importStar(__nccwpck_require__(81962));
-/**
- * Copies a file or folder.
- * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
- *
- * @param source source path
- * @param dest destination path
- * @param options optional. See CopyOptions.
- */
-function cp(source, dest, options = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- const { force, recursive, copySourceDirectory } = readCopyOptions(options);
- const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
- // Dest is an existing file, but not forcing
- if (destStat && destStat.isFile() && !force) {
- return;
- }
- // If dest is an existing directory, should copy inside.
- const newDest = destStat && destStat.isDirectory() && copySourceDirectory
- ? path.join(dest, path.basename(source))
- : dest;
- if (!(yield ioUtil.exists(source))) {
- throw new Error(`no such file or directory: ${source}`);
- }
- const sourceStat = yield ioUtil.stat(source);
- if (sourceStat.isDirectory()) {
- if (!recursive) {
- throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
- }
- else {
- yield cpDirRecursive(source, newDest, 0, force);
- }
- }
- else {
- if (path.relative(source, newDest) === '') {
- // a file cannot be copied to itself
- throw new Error(`'${newDest}' and '${source}' are the same file`);
- }
- yield copyFile(source, newDest, force);
- }
- });
-}
-exports.cp = cp;
-/**
- * Moves a path.
- *
- * @param source source path
- * @param dest destination path
- * @param options optional. See MoveOptions.
- */
-function mv(source, dest, options = {}) {
- return __awaiter(this, void 0, void 0, function* () {
- if (yield ioUtil.exists(dest)) {
- let destExists = true;
- if (yield ioUtil.isDirectory(dest)) {
- // If dest is directory copy src into dest
- dest = path.join(dest, path.basename(source));
- destExists = yield ioUtil.exists(dest);
- }
- if (destExists) {
- if (options.force == null || options.force) {
- yield rmRF(dest);
- }
- else {
- throw new Error('Destination already exists');
- }
- }
- }
- yield mkdirP(path.dirname(dest));
- yield ioUtil.rename(source, dest);
- });
-}
-exports.mv = mv;
-/**
- * Remove a path recursively with force
- *
- * @param inputPath path to remove
- */
-function rmRF(inputPath) {
- return __awaiter(this, void 0, void 0, function* () {
- if (ioUtil.IS_WINDOWS) {
- // Check for invalid characters
- // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
- if (/[*"<>|]/.test(inputPath)) {
- throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
- }
- }
- try {
- // note if path does not exist, error is silent
- yield ioUtil.rm(inputPath, {
- force: true,
- maxRetries: 3,
- recursive: true,
- retryDelay: 300
- });
- }
- catch (err) {
- throw new Error(`File was unable to be removed ${err}`);
- }
- });
-}
-exports.rmRF = rmRF;
-/**
- * Make a directory. Creates the full path with folders in between
- * Will throw if it fails
- *
- * @param fsPath path to create
- * @returns Promise
- */
-function mkdirP(fsPath) {
- return __awaiter(this, void 0, void 0, function* () {
- assert_1.ok(fsPath, 'a path argument must be provided');
- yield ioUtil.mkdir(fsPath, { recursive: true });
- });
-}
-exports.mkdirP = mkdirP;
-/**
- * Returns path of a tool had the tool actually been invoked. Resolves via paths.
- * If you check and the tool does not exist, it will throw.
- *
- * @param tool name of the tool
- * @param check whether to check if tool exists
- * @returns Promise path to tool
- */
-function which(tool, check) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tool) {
- throw new Error("parameter 'tool' is required");
- }
- // recursive when check=true
- if (check) {
- const result = yield which(tool, false);
- if (!result) {
- if (ioUtil.IS_WINDOWS) {
- throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
- }
- else {
- throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
- }
- }
- return result;
- }
- const matches = yield findInPath(tool);
- if (matches && matches.length > 0) {
- return matches[0];
- }
- return '';
- });
-}
-exports.which = which;
-/**
- * Returns a list of all occurrences of the given tool on the system path.
- *
- * @returns Promise the paths of the tool
- */
-function findInPath(tool) {
- return __awaiter(this, void 0, void 0, function* () {
- if (!tool) {
- throw new Error("parameter 'tool' is required");
- }
- // build the list of extensions to try
- const extensions = [];
- if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) {
- for (const extension of process.env['PATHEXT'].split(path.delimiter)) {
- if (extension) {
- extensions.push(extension);
- }
- }
- }
- // if it's rooted, return it if exists. otherwise return empty.
- if (ioUtil.isRooted(tool)) {
- const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
- if (filePath) {
- return [filePath];
- }
- return [];
- }
- // if any path separators, return empty
- if (tool.includes(path.sep)) {
- return [];
- }
- // build the list of directories
- //
- // Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
- // it feels like we should not do this. Checking the current directory seems like more of a use
- // case of a shell, and the which() function exposed by the toolkit should strive for consistency
- // across platforms.
- const directories = [];
- if (process.env.PATH) {
- for (const p of process.env.PATH.split(path.delimiter)) {
- if (p) {
- directories.push(p);
- }
- }
- }
- // find all matches
- const matches = [];
- for (const directory of directories) {
- const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions);
- if (filePath) {
- matches.push(filePath);
- }
- }
- return matches;
- });
-}
-exports.findInPath = findInPath;
-function readCopyOptions(options) {
- const force = options.force == null ? true : options.force;
- const recursive = Boolean(options.recursive);
- const copySourceDirectory = options.copySourceDirectory == null
- ? true
- : Boolean(options.copySourceDirectory);
- return { force, recursive, copySourceDirectory };
-}
-function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
- return __awaiter(this, void 0, void 0, function* () {
- // Ensure there is not a run away recursive copy
- if (currentDepth >= 255)
- return;
- currentDepth++;
- yield mkdirP(destDir);
- const files = yield ioUtil.readdir(sourceDir);
- for (const fileName of files) {
- const srcFile = `${sourceDir}/${fileName}`;
- const destFile = `${destDir}/${fileName}`;
- const srcFileStat = yield ioUtil.lstat(srcFile);
- if (srcFileStat.isDirectory()) {
- // Recurse
- yield cpDirRecursive(srcFile, destFile, currentDepth, force);
- }
- else {
- yield copyFile(srcFile, destFile, force);
- }
- }
- // Change the mode for the newly created directory
- yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
- });
-}
-// Buffered file copy
-function copyFile(srcFile, destFile, force) {
- return __awaiter(this, void 0, void 0, function* () {
- if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
- // unlink/re-link it
- try {
- yield ioUtil.lstat(destFile);
- yield ioUtil.unlink(destFile);
- }
- catch (e) {
- // Try to override file permission
- if (e.code === 'EPERM') {
- yield ioUtil.chmod(destFile, '0666');
- yield ioUtil.unlink(destFile);
- }
- // other errors = it doesn't exist, no work to do
- }
- // Copy over symlink
- const symlinkFull = yield ioUtil.readlink(srcFile);
- yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
- }
- else if (!(yield ioUtil.exists(destFile)) || force) {
- yield ioUtil.copyFile(srcFile, destFile);
- }
- });
+ onError (err) {
+ const { ret } = this
+ this.handler = null
+ util.destroy(ret, err)
+ }
}
-//# sourceMappingURL=io.js.map
-/***/ }),
+function pipeline (opts, handler) {
+ try {
+ const pipelineHandler = new PipelineHandler(opts, handler)
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
+ return pipelineHandler.ret
+ } catch (err) {
+ return new PassThrough().destroy(err)
+ }
+}
-/***/ 14175:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+module.exports = pipeline
-/*
-The MIT License (MIT)
+/***/ }),
-Original Library
- - Copyright (c) Marak Squires
+/***/ 4043:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-Additional functionality
- - Copyright (c) Sindre Sorhus (sindresorhus.com)
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
+const Readable = __nccwpck_require__(9927)
+const {
+ InvalidArgumentError,
+ RequestAbortedError
+} = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
+const { AsyncResource } = __nccwpck_require__(290)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
-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.
+class RequestHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-*/
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
-var colors = {};
-module['exports'] = colors;
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
-colors.themes = {};
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
+ throw new InvalidArgumentError('invalid highWaterMark')
+ }
-var util = __nccwpck_require__(73837);
-var ansiStyles = colors.styles = __nccwpck_require__(95691);
-var defineProps = Object.defineProperties;
-var newLineRegex = new RegExp(/[\r\n]+/g);
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
-colors.supportsColor = (__nccwpck_require__(21959).supportsColor);
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
-if (typeof colors.enabled === 'undefined') {
- colors.enabled = colors.supportsColor() !== false;
-}
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
-colors.enable = function() {
- colors.enabled = true;
-};
+ super('UNDICI_REQUEST')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
-colors.disable = function() {
- colors.enabled = false;
-};
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.body = body
+ this.trailers = {}
+ this.context = null
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError
+ this.highWaterMark = highWaterMark
-colors.stripColors = colors.strip = function(str) {
- return ('' + str).replace(/\x1B\[\d+m/g, '');
-};
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
-// eslint-disable-next-line no-unused-vars
-var stylize = colors.stylize = function stylize(str, style) {
- if (!colors.enabled) {
- return str+'';
+ addSignal(this, signal)
}
- var styleMap = ansiStyles[style];
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
- // Stylize should work for non-ANSI styles, too
- if (!styleMap && style in colors) {
- // Style maps like trap operate as functions on strings;
- // they don't have properties like open or close.
- return colors[style](str);
+ this.abort = abort
+ this.context = context
}
- return styleMap.open + str + styleMap.close;
-};
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ const body = new Readable({ resume, abort, contentType, highWaterMark })
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-var escapeStringRegexp = function(str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
+ this.callback = null
+ this.res = body
+ if (callback !== null) {
+ if (this.throwOnError && statusCode >= 400) {
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body,
+ context
+ })
+ }
+ }
}
- return str.replace(matchOperatorsRe, '\\$&');
-};
-function build(_styles) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- // __proto__ is used because we must return a function, but there is
- // no way to create a function with a different prototype.
- builder.__proto__ = proto;
- return builder;
-}
-
-var styles = (function() {
- var ret = {};
- ansiStyles.grey = ansiStyles.gray;
- Object.keys(ansiStyles).forEach(function(key) {
- ansiStyles[key].closeRe =
- new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- ret[key] = {
- get: function() {
- return build(this._styles.concat(key));
- },
- };
- });
- return ret;
-})();
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
-var proto = defineProps(function colors() {}, styles);
+ onComplete (trailers) {
+ const { res } = this
-function applyStyle() {
- var args = Array.prototype.slice.call(arguments);
+ removeSignal(this)
- var str = args.map(function(arg) {
- // Use weak equality check so we can colorize null/undefined in safe mode
- if (arg != null && arg.constructor === String) {
- return arg;
- } else {
- return util.inspect(arg);
- }
- }).join(' ');
+ util.parseHeaders(trailers, this.trailers)
- if (!colors.enabled || !str) {
- return str;
+ res.push(null)
}
- var newLinesPresent = str.indexOf('\n') != -1;
+ onError (err) {
+ const { res, callback, body, opaque } = this
- var nestedStyles = this._styles;
+ removeSignal(this)
- var i = nestedStyles.length;
- while (i--) {
- var code = ansiStyles[nestedStyles[i]];
- str = code.open + str.replace(code.closeRe, code.open) + code.close;
- if (newLinesPresent) {
- str = str.replace(newLineRegex, function(match) {
- return code.close + match + code.open;
- });
+ if (callback) {
+ // TODO: Does this need queueMicrotask?
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
}
- }
- return str;
-}
+ if (res) {
+ this.res = null
+ // Ensure all queued handlers are invoked before destroying res.
+ queueMicrotask(() => {
+ util.destroy(res, err)
+ })
+ }
-colors.setTheme = function(theme) {
- if (typeof theme === 'string') {
- console.log('colors.setTheme now only accepts an object, not a string. ' +
- 'If you are trying to set a theme from a file, it is now your (the ' +
- 'caller\'s) responsibility to require the file. The old syntax ' +
- 'looked like colors.setTheme(__dirname + ' +
- '\'/../themes/generic-logging.js\'); The new syntax looks like '+
- 'colors.setTheme(require(__dirname + ' +
- '\'/../themes/generic-logging.js\'));');
- return;
- }
- for (var style in theme) {
- (function(style) {
- colors[style] = function(str) {
- if (typeof theme[style] === 'object') {
- var out = str;
- for (var i in theme[style]) {
- out = colors[theme[style][i]](out);
- }
- return out;
- }
- return colors[theme[style]](str);
- };
- })(style);
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
}
-};
-
-function init() {
- var ret = {};
- Object.keys(styles).forEach(function(name) {
- ret[name] = {
- get: function() {
- return build([name]);
- },
- };
- });
- return ret;
}
-var sequencer = function sequencer(map, str) {
- var exploded = str.split('');
- exploded = exploded.map(map);
- return exploded.join('');
-};
+function request (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
-// custom formatter methods
-colors.trap = __nccwpck_require__(29493);
-colors.zalgo = __nccwpck_require__(80090);
-
-// maps
-colors.maps = {};
-colors.maps.america = __nccwpck_require__(29337)(colors);
-colors.maps.zebra = __nccwpck_require__(3792)(colors);
-colors.maps.rainbow = __nccwpck_require__(19565)(colors);
-colors.maps.random = __nccwpck_require__(78212)(colors);
-
-for (var map in colors.maps) {
- (function(map) {
- colors[map] = function(str) {
- return sequencer(colors.maps[map], str);
- };
- })(map);
+ try {
+ this.dispatch(opts, new RequestHandler(opts, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
}
-defineProps(colors, init());
+module.exports = request
/***/ }),
-/***/ 29493:
-/***/ ((module) => {
+/***/ 3560:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module['exports'] = function runTheTrap(text, options) {
- var result = '';
- text = text || 'Run the trap, drop the bass';
- text = text.split('');
- var trap = {
- a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
- b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
- c: ['\u00a9', '\u023b', '\u03fe'],
- d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
- e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
- '\u0a6c'],
- f: ['\u04fa'],
- g: ['\u0262'],
- h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
- i: ['\u0f0f'],
- j: ['\u0134'],
- k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
- l: ['\u0139'],
- m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
- n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
- o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
- '\u06dd', '\u0e4f'],
- p: ['\u01f7', '\u048e'],
- q: ['\u09cd'],
- r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
- s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
- t: ['\u0141', '\u0166', '\u0373'],
- u: ['\u01b1', '\u054d'],
- v: ['\u05d8'],
- w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
- x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
- y: ['\u00a5', '\u04b0', '\u04cb'],
- z: ['\u01b5', '\u0240'],
- };
- text.forEach(function(c) {
- c = c.toLowerCase();
- var chars = trap[c] || [' '];
- var rand = Math.floor(Math.random() * chars.length);
- if (typeof trap[c] !== 'undefined') {
- result += trap[c][rand];
- } else {
- result += c;
+
+
+const { finished, PassThrough } = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
+const { AsyncResource } = __nccwpck_require__(290)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+
+class StreamHandler extends AsyncResource {
+ constructor (opts, factory, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- });
- return result;
-};
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
-/***/ }),
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
-/***/ 80090:
-/***/ ((module) => {
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('invalid factory')
+ }
-// please no
-module['exports'] = function zalgo(text, options) {
- text = text || ' he is here ';
- var soul = {
- 'up': [
- '̍', '̎', '̄', '̅',
- '̿', '̑', '̆', '̐',
- '͒', '͗', '͑', '̇',
- '̈', '̊', '͂', '̓',
- '̈', '͊', '͋', '͌',
- '̃', '̂', '̌', '͐',
- '̀', '́', '̋', '̏',
- '̒', '̓', '̔', '̽',
- '̉', 'ͣ', 'ͤ', 'ͥ',
- 'ͦ', 'ͧ', 'ͨ', 'ͩ',
- 'ͪ', 'ͫ', 'ͬ', 'ͭ',
- 'ͮ', 'ͯ', '̾', '͛',
- '͆', '̚',
- ],
- 'down': [
- '̖', '̗', '̘', '̙',
- '̜', '̝', '̞', '̟',
- '̠', '̤', '̥', '̦',
- '̩', '̪', '̫', '̬',
- '̭', '̮', '̯', '̰',
- '̱', '̲', '̳', '̹',
- '̺', '̻', '̼', 'ͅ',
- '͇', '͈', '͉', '͍',
- '͎', '͓', '͔', '͕',
- '͖', '͙', '͚', '̣',
- ],
- 'mid': [
- '̕', '̛', '̀', '́',
- '͘', '̡', '̢', '̧',
- '̨', '̴', '̵', '̶',
- '͜', '͝', '͞',
- '͟', '͠', '͢', '̸',
- '̷', '͡', ' ҉',
- ],
- };
- var all = [].concat(soul.up, soul.down, soul.mid);
-
- function randomNumber(range) {
- var r = Math.floor(Math.random() * range);
- return r;
- }
-
- function isChar(character) {
- var bool = false;
- all.filter(function(i) {
- bool = (i === character);
- });
- return bool;
- }
-
-
- function heComes(text, options) {
- var result = '';
- var counts;
- var l;
- options = options || {};
- options['up'] =
- typeof options['up'] !== 'undefined' ? options['up'] : true;
- options['mid'] =
- typeof options['mid'] !== 'undefined' ? options['mid'] : true;
- options['down'] =
- typeof options['down'] !== 'undefined' ? options['down'] : true;
- options['size'] =
- typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
- text = text.split('');
- for (l in text) {
- if (isChar(l)) {
- continue;
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
- result = result + text[l];
- counts = {'up': 0, 'down': 0, 'mid': 0};
- switch (options.size) {
- case 'mini':
- counts.up = randomNumber(8);
- counts.mid = randomNumber(2);
- counts.down = randomNumber(8);
- break;
- case 'maxi':
- counts.up = randomNumber(16) + 3;
- counts.mid = randomNumber(4) + 1;
- counts.down = randomNumber(64) + 3;
- break;
- default:
- counts.up = randomNumber(8) + 1;
- counts.mid = randomNumber(6) / 2;
- counts.down = randomNumber(8) + 1;
- break;
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
}
- var arr = ['up', 'mid', 'down'];
- for (var d in arr) {
- var index = arr[d];
- for (var i = 0; i <= counts[index]; i++) {
- if (options[index]) {
- result = result + soul[index][randomNumber(soul[index].length)];
- }
- }
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
}
- }
- return result;
- }
- // don't summon him
- return heComes(text, options);
-};
+ super('UNDICI_STREAM')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.factory = factory
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.context = null
+ this.trailers = null
+ this.body = body
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError || false
-/***/ }),
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
-/***/ 29337:
-/***/ ((module) => {
+ addSignal(this, signal)
+ }
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- if (letter === ' ') return letter;
- switch (i%3) {
- case 0: return colors.red(letter);
- case 1: return colors.white(letter);
- case 2: return colors.blue(letter);
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
}
- };
-};
+ this.abort = abort
+ this.context = context
+ }
-/***/ }),
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, callback, responseHeaders } = this
-/***/ 19565:
-/***/ ((module) => {
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
-module['exports'] = function(colors) {
- // RoY G BiV
- var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
- return function(letter, i, exploded) {
- if (letter === ' ') {
- return letter;
- } else {
- return colors[rainbowColors[i++ % rainbowColors.length]](letter);
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
}
- };
-};
-
+ this.factory = null
-/***/ }),
+ let res
-/***/ 78212:
-/***/ ((module) => {
+ if (this.throwOnError && statusCode >= 400) {
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ res = new PassThrough()
-module['exports'] = function(colors) {
- var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
- 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
- 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
- return function(letter, i, exploded) {
- return letter === ' ' ? letter :
- colors[
- available[Math.round(Math.random() * (available.length - 2))]
- ](letter);
- };
-};
+ this.callback = null
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ res = this.runInAsyncScope(factory, null, {
+ statusCode,
+ headers,
+ opaque,
+ context
+ })
+ if (
+ !res ||
+ typeof res.write !== 'function' ||
+ typeof res.end !== 'function' ||
+ typeof res.on !== 'function'
+ ) {
+ throw new InvalidReturnValueError('expected Writable')
+ }
-/***/ }),
+ // TODO: Avoid finished. It registers an unnecessary amount of listeners.
+ finished(res, { readable: false }, (err) => {
+ const { callback, res, opaque, trailers, abort } = this
-/***/ 3792:
-/***/ ((module) => {
+ this.res = null
+ if (err || !res.readable) {
+ util.destroy(res, err)
+ }
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- return i % 2 === 0 ? letter : colors.inverse(letter);
- };
-};
+ this.callback = null
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+ if (err) {
+ abort()
+ }
+ })
+ }
-/***/ }),
+ res.on('drain', resume)
-/***/ 95691:
-/***/ ((module) => {
+ this.res = res
-/*
-The MIT License (MIT)
-
-Copyright (c) Sindre Sorhus (sindresorhus.com)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-
-*/
-
-var styles = {};
-module['exports'] = styles;
-
-var codes = {
- reset: [0, 0],
-
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29],
-
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- grey: [90, 39],
-
- brightRed: [91, 39],
- brightGreen: [92, 39],
- brightYellow: [93, 39],
- brightBlue: [94, 39],
- brightMagenta: [95, 39],
- brightCyan: [96, 39],
- brightWhite: [97, 39],
-
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgGray: [100, 49],
- bgGrey: [100, 49],
-
- bgBrightRed: [101, 49],
- bgBrightGreen: [102, 49],
- bgBrightYellow: [103, 49],
- bgBrightBlue: [104, 49],
- bgBrightMagenta: [105, 49],
- bgBrightCyan: [106, 49],
- bgBrightWhite: [107, 49],
-
- // legacy styles for colors pre v1.0.0
- blackBG: [40, 49],
- redBG: [41, 49],
- greenBG: [42, 49],
- yellowBG: [43, 49],
- blueBG: [44, 49],
- magentaBG: [45, 49],
- cyanBG: [46, 49],
- whiteBG: [47, 49],
+ const needDrain = res.writableNeedDrain !== undefined
+ ? res.writableNeedDrain
+ : res._writableState && res._writableState.needDrain
-};
+ return needDrain !== true
+ }
-Object.keys(codes).forEach(function(key) {
- var val = codes[key];
- var style = styles[key] = [];
- style.open = '\u001b[' + val[0] + 'm';
- style.close = '\u001b[' + val[1] + 'm';
-});
+ onData (chunk) {
+ const { res } = this
+ return res.write(chunk)
+ }
-/***/ }),
+ onComplete (trailers) {
+ const { res } = this
-/***/ 63680:
-/***/ ((module) => {
+ removeSignal(this)
-"use strict";
-/*
-MIT License
+ this.trailers = util.parseHeaders(trailers)
-Copyright (c) Sindre Sorhus (sindresorhus.com)
+ res.end()
+ }
-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:
+ onError (err) {
+ const { res, callback, opaque, body } = this
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
+ removeSignal(this)
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
+ this.factory = null
+ if (res) {
+ this.res = null
+ util.destroy(res, err)
+ } else if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
+}
-module.exports = function(flag, argv) {
- argv = argv || process.argv;
+function stream (opts, factory, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ stream.call(this, opts, factory, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
- var terminatorPos = argv.indexOf('--');
- var prefix = /^-{1,2}/.test(flag) ? '' : '--';
- var pos = argv.indexOf(prefix + flag);
+ try {
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
-};
+module.exports = stream
/***/ }),
-/***/ 21959:
+/***/ 1882:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-/*
-The MIT License (MIT)
-
-Copyright (c) Sindre Sorhus (sindresorhus.com)
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707)
+const { AsyncResource } = __nccwpck_require__(290)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+const assert = __nccwpck_require__(2613)
-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.
-
-*/
+class UpgradeHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+ const { signal, opaque, responseHeaders } = opts
-var os = __nccwpck_require__(22037);
-var hasFlag = __nccwpck_require__(63680);
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
-var env = process.env;
+ super('UNDICI_UPGRADE')
-var forceColor = void 0;
-if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor = false;
-} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
- || hasFlag('color=always')) {
- forceColor = true;
-}
-if ('FORCE_COLOR' in env) {
- forceColor = env.FORCE_COLOR.length === 0
- || parseInt(env.FORCE_COLOR, 10) !== 0;
-}
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.abort = null
+ this.context = null
-function translateLevel(level) {
- if (level === 0) {
- return false;
+ addSignal(this, signal)
}
- return {
- level: level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3,
- };
-}
-
-function supportsColor(stream) {
- if (forceColor === false) {
- return 0;
- }
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
- if (hasFlag('color=16m') || hasFlag('color=full')
- || hasFlag('color=truecolor')) {
- return 3;
+ this.abort = abort
+ this.context = null
}
- if (hasFlag('color=256')) {
- return 2;
+ onHeaders () {
+ throw new SocketError('bad upgrade', null)
}
- if (stream && !stream.isTTY && forceColor !== true) {
- return 0;
- }
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
- var min = forceColor ? 1 : 0;
+ assert.strictEqual(statusCode, 101)
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first
- // Windows release that supports 256 colors. Windows 10 build 14931 is the
- // first release that supports 16m/TrueColor.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8
- && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
+ removeSignal(this)
- return 1;
+ this.callback = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.runInAsyncScope(callback, null, null, {
+ headers,
+ socket,
+ opaque,
+ context
+ })
}
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
- return sign in env;
- }) || env.CI_NAME === 'codeship') {
- return 1;
- }
+ onError (err) {
+ const { callback, opaque } = this
- return min;
- }
+ removeSignal(this)
- if ('TEAMCITY_VERSION' in env) {
- return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
- );
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
}
+}
- if ('TERM_PROGRAM' in env) {
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
+function upgrade (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ upgrade.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Hyper':
- return 3;
- case 'Apple_Terminal':
- return 2;
- // No default
+ try {
+ const upgradeHandler = new UpgradeHandler(opts, callback)
+ this.dispatch({
+ ...opts,
+ method: opts.method || 'GET',
+ upgrade: opts.protocol || 'Websocket'
+ }, upgradeHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
}
+}
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
+module.exports = upgrade
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env) {
- return 1;
- }
+/***/ }),
- if (env.TERM === 'dumb') {
- return min;
- }
+/***/ 6615:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return min;
-}
-function getSupportLevel(stream) {
- var level = supportsColor(stream);
- return translateLevel(level);
-}
-module.exports = {
- supportsColor: getSupportLevel,
- stdout: getSupportLevel(process.stdout),
- stderr: getSupportLevel(process.stderr),
-};
+module.exports.request = __nccwpck_require__(4043)
+module.exports.stream = __nccwpck_require__(3560)
+module.exports.pipeline = __nccwpck_require__(6862)
+module.exports.upgrade = __nccwpck_require__(1882)
+module.exports.connect = __nccwpck_require__(4660)
/***/ }),
-/***/ 59256:
+/***/ 9927:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-//
-// Remark: Requiring this file will use the "safe" colors API,
-// which will not touch String.prototype.
-//
-// var colors = require('colors/safe');
-// colors.red("foo")
-//
-//
-var colors = __nccwpck_require__(14175);
-module['exports'] = colors;
+// Ported from https://github.com/nodejs/undici/pull/907
-/***/ }),
-/***/ 2856:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const assert = __nccwpck_require__(2613)
+const { Readable } = __nccwpck_require__(2203)
+const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440)
-"use strict";
+let Blob
+const kConsume = Symbol('kConsume')
+const kReading = Symbol('kReading')
+const kBody = Symbol('kBody')
+const kAbort = Symbol('abort')
+const kContentType = Symbol('kContentType')
-const WritableStream = (__nccwpck_require__(84492).Writable)
-const inherits = (__nccwpck_require__(47261).inherits)
+module.exports = class BodyReadable extends Readable {
+ constructor ({
+ resume,
+ abort,
+ contentType = '',
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ })
-const StreamSearch = __nccwpck_require__(88534)
+ this._readableState.dataEmitted = false
-const PartStream = __nccwpck_require__(38710)
-const HeaderParser = __nccwpck_require__(90333)
+ this[kAbort] = abort
+ this[kConsume] = null
+ this[kBody] = null
+ this[kContentType] = contentType
-const DASH = 45
-const B_ONEDASH = Buffer.from('-')
-const B_CRLF = Buffer.from('\r\n')
-const EMPTY_FN = function () {}
+ // Is stream being consumed through Readable API?
+ // This is an optimization so that we avoid checking
+ // for 'data' and 'readable' listeners in the hot path
+ // inside push().
+ this[kReading] = false
+ }
-function Dicer (cfg) {
- if (!(this instanceof Dicer)) { return new Dicer(cfg) }
- WritableStream.call(this, cfg)
+ destroy (err) {
+ if (this.destroyed) {
+ // Node < 16
+ return this
+ }
- if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
- if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
+ if (err) {
+ this[kAbort]()
+ }
- this._headerFirst = cfg.headerFirst
+ return super.destroy(err)
+ }
- this._dashes = 0
- this._parts = 0
- this._finished = false
- this._realFinish = false
- this._isPreamble = true
- this._justMatched = false
- this._firstWrite = true
- this._inHeader = true
- this._part = undefined
- this._cb = undefined
- this._ignoreData = false
- this._partOpts = { highWaterMark: cfg.partHwm }
- this._pause = false
-
- const self = this
- this._hparser = new HeaderParser(cfg)
- this._hparser.on('header', function (header) {
- self._inHeader = false
- self._part.emit('header', header)
- })
-}
-inherits(Dicer, WritableStream)
+ emit (ev, ...args) {
+ if (ev === 'data') {
+ // Node < 16.7
+ this._readableState.dataEmitted = true
+ } else if (ev === 'error') {
+ // Node < 16
+ this._readableState.errorEmitted = true
+ }
+ return super.emit(ev, ...args)
+ }
-Dicer.prototype.emit = function (ev) {
- if (ev === 'finish' && !this._realFinish) {
- if (!this._finished) {
- const self = this
- process.nextTick(function () {
- self.emit('error', new Error('Unexpected end of multipart data'))
- if (self._part && !self._ignoreData) {
- const type = (self._isPreamble ? 'Preamble' : 'Part')
- self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
- self._part.push(null)
- process.nextTick(function () {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- })
- return
- }
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- })
+ on (ev, ...args) {
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = true
}
- } else { WritableStream.prototype.emit.apply(this, arguments) }
-}
+ return super.on(ev, ...args)
+ }
-Dicer.prototype._write = function (data, encoding, cb) {
- // ignore unexpected data (e.g. extra trailer data after finished)
- if (!this._hparser && !this._bparser) { return cb() }
+ addListener (ev, ...args) {
+ return this.on(ev, ...args)
+ }
- if (this._headerFirst && this._isPreamble) {
- if (!this._part) {
- this._part = new PartStream(this._partOpts)
- if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }
+ off (ev, ...args) {
+ const ret = super.off(ev, ...args)
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = (
+ this.listenerCount('data') > 0 ||
+ this.listenerCount('readable') > 0
+ )
}
- const r = this._hparser.push(data)
- if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ return ret
}
- // allows for "easier" testing
- if (this._firstWrite) {
- this._bparser.push(B_CRLF)
- this._firstWrite = false
+ removeListener (ev, ...args) {
+ return this.off(ev, ...args)
}
- this._bparser.push(data)
+ push (chunk) {
+ if (this[kConsume] && chunk !== null && this.readableLength === 0) {
+ consumePush(this[kConsume], chunk)
+ return this[kReading] ? super.push(chunk) : true
+ }
+ return super.push(chunk)
+ }
- if (this._pause) { this._cb = cb } else { cb() }
-}
+ // https://fetch.spec.whatwg.org/#dom-body-text
+ async text () {
+ return consume(this, 'text')
+ }
-Dicer.prototype.reset = function () {
- this._part = undefined
- this._bparser = undefined
- this._hparser = undefined
-}
+ // https://fetch.spec.whatwg.org/#dom-body-json
+ async json () {
+ return consume(this, 'json')
+ }
-Dicer.prototype.setBoundary = function (boundary) {
- const self = this
- this._bparser = new StreamSearch('\r\n--' + boundary)
- this._bparser.on('info', function (isMatch, data, start, end) {
- self._oninfo(isMatch, data, start, end)
- })
-}
+ // https://fetch.spec.whatwg.org/#dom-body-blob
+ async blob () {
+ return consume(this, 'blob')
+ }
-Dicer.prototype._ignore = function () {
- if (this._part && !this._ignoreData) {
- this._ignoreData = true
- this._part.on('error', EMPTY_FN)
- // we must perform some kind of read on the stream even though we are
- // ignoring the data, otherwise node's Readable stream will not emit 'end'
- // after pushing null to the stream
- this._part.resume()
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ async arrayBuffer () {
+ return consume(this, 'arrayBuffer')
}
-}
-Dicer.prototype._oninfo = function (isMatch, data, start, end) {
- let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
+ async formData () {
+ // TODO: Implement.
+ throw new NotSupportedError()
+ }
- if (!this._part && this._justMatched && data) {
- while (this._dashes < 2 && (start + i) < end) {
- if (data[start + i] === DASH) {
- ++i
- ++this._dashes
- } else {
- if (this._dashes) { buf = B_ONEDASH }
- this._dashes = 0
- break
- }
- }
- if (this._dashes === 2) {
- if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }
- this.reset()
- this._finished = true
- // no more parts will be added
- if (self._parts === 0) {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
+ get bodyUsed () {
+ return util.isDisturbed(this)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-body
+ get body () {
+ if (!this[kBody]) {
+ this[kBody] = ReadableStreamFrom(this)
+ if (this[kConsume]) {
+ // TODO: Is this the best way to force a lock?
+ this[kBody].getReader() // Ensure stream is locked.
+ assert(this[kBody].locked)
}
}
- if (this._dashes) { return }
+ return this[kBody]
}
- if (this._justMatched) { this._justMatched = false }
- if (!this._part) {
- this._part = new PartStream(this._partOpts)
- this._part._read = function (n) {
- self._unpause()
+
+ async dump (opts) {
+ let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
+ const signal = opts && opts.signal
+ const abortFn = () => {
+ this.destroy()
}
- if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part) } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part) } else { this._ignore() }
- if (!this._isPreamble) { this._inHeader = true }
- }
- if (data && start < end && !this._ignoreData) {
- if (this._isPreamble || !this._inHeader) {
- if (buf) { shouldWriteMore = this._part.push(buf) }
- shouldWriteMore = this._part.push(data.slice(start, end))
- if (!shouldWriteMore) { this._pause = true }
- } else if (!this._isPreamble && this._inHeader) {
- if (buf) { this._hparser.push(buf) }
- r = this._hparser.push(data.slice(start, end))
- if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ let signalListenerCleanup
+ if (signal) {
+ if (typeof signal !== 'object' || !('aborted' in signal)) {
+ throw new InvalidArgumentError('signal must be an AbortSignal')
+ }
+ util.throwIfAborted(signal)
+ signalListenerCleanup = util.addAbortListener(signal, abortFn)
}
- }
- if (isMatch) {
- this._hparser.reset()
- if (this._isPreamble) { this._isPreamble = false } else {
- if (start !== end) {
- ++this._parts
- this._part.on('end', function () {
- if (--self._parts === 0) {
- if (self._finished) {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- } else {
- self._unpause()
- }
- }
- })
+ try {
+ for await (const chunk of this) {
+ util.throwIfAborted(signal)
+ limit -= Buffer.byteLength(chunk)
+ if (limit < 0) {
+ return
+ }
+ }
+ } catch {
+ util.throwIfAborted(signal)
+ } finally {
+ if (typeof signalListenerCleanup === 'function') {
+ signalListenerCleanup()
+ } else if (signalListenerCleanup) {
+ signalListenerCleanup[Symbol.dispose]()
}
}
- this._part.push(null)
- this._part = undefined
- this._ignoreData = false
- this._justMatched = true
- this._dashes = 0
}
}
-Dicer.prototype._unpause = function () {
- if (!this._pause) { return }
-
- this._pause = false
- if (this._cb) {
- const cb = this._cb
- this._cb = undefined
- cb()
- }
+// https://streams.spec.whatwg.org/#readablestream-locked
+function isLocked (self) {
+ // Consume is an implicit lock.
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
}
-module.exports = Dicer
-
-
-/***/ }),
+// https://fetch.spec.whatwg.org/#body-unusable
+function isUnusable (self) {
+ return util.isDisturbed(self) || isLocked(self)
+}
-/***/ 90333:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+async function consume (stream, type) {
+ if (isUnusable(stream)) {
+ throw new TypeError('unusable')
+ }
-"use strict";
+ assert(!stream[kConsume])
+ return new Promise((resolve, reject) => {
+ stream[kConsume] = {
+ type,
+ stream,
+ resolve,
+ reject,
+ length: 0,
+ body: []
+ }
-const EventEmitter = (__nccwpck_require__(15673).EventEmitter)
-const inherits = (__nccwpck_require__(47261).inherits)
-const getLimit = __nccwpck_require__(49692)
+ stream
+ .on('error', function (err) {
+ consumeFinish(this[kConsume], err)
+ })
+ .on('close', function () {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError())
+ }
+ })
-const StreamSearch = __nccwpck_require__(88534)
+ process.nextTick(consumeStart, stream[kConsume])
+ })
+}
-const B_DCRLF = Buffer.from('\r\n\r\n')
-const RE_CRLF = /\r\n/g
-const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
+function consumeStart (consume) {
+ if (consume.body === null) {
+ return
+ }
-function HeaderParser (cfg) {
- EventEmitter.call(this)
+ const { _readableState: state } = consume.stream
- cfg = cfg || {}
- const self = this
- this.nread = 0
- this.maxed = false
- this.npairs = 0
- this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
- this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
- this.buffer = ''
- this.header = {}
- this.finished = false
- this.ss = new StreamSearch(B_DCRLF)
- this.ss.on('info', function (isMatch, data, start, end) {
- if (data && !self.maxed) {
- if (self.nread + end - start >= self.maxHeaderSize) {
- end = self.maxHeaderSize - self.nread + start
- self.nread = self.maxHeaderSize
- self.maxed = true
- } else { self.nread += (end - start) }
+ for (const chunk of state.buffer) {
+ consumePush(consume, chunk)
+ }
- self.buffer += data.toString('binary', start, end)
- }
- if (isMatch) { self._finish() }
- })
-}
-inherits(HeaderParser, EventEmitter)
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume])
+ } else {
+ consume.stream.on('end', function () {
+ consumeEnd(this[kConsume])
+ })
+ }
-HeaderParser.prototype.push = function (data) {
- const r = this.ss.push(data)
- if (this.finished) { return r }
-}
+ consume.stream.resume()
-HeaderParser.prototype.reset = function () {
- this.finished = false
- this.buffer = ''
- this.header = {}
- this.ss.reset()
+ while (consume.stream.read() != null) {
+ // Loop
+ }
}
-HeaderParser.prototype._finish = function () {
- if (this.buffer) { this._parseHeader() }
- this.ss.matches = this.ss.maxMatches
- const header = this.header
- this.header = {}
- this.buffer = ''
- this.finished = true
- this.nread = this.npairs = 0
- this.maxed = false
- this.emit('header', header)
-}
+function consumeEnd (consume) {
+ const { type, body, resolve, stream, length } = consume
-HeaderParser.prototype._parseHeader = function () {
- if (this.npairs === this.maxHeaderPairs) { return }
+ try {
+ if (type === 'text') {
+ resolve(toUSVString(Buffer.concat(body)))
+ } else if (type === 'json') {
+ resolve(JSON.parse(Buffer.concat(body)))
+ } else if (type === 'arrayBuffer') {
+ const dst = new Uint8Array(length)
- const lines = this.buffer.split(RE_CRLF)
- const len = lines.length
- let m, h
+ let pos = 0
+ for (const buf of body) {
+ dst.set(buf, pos)
+ pos += buf.byteLength
+ }
- for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
- if (lines[i].length === 0) { continue }
- if (lines[i][0] === '\t' || lines[i][0] === ' ') {
- // folded header content
- // RFC2822 says to just remove the CRLF and not the whitespace following
- // it, so we follow the RFC and include the leading whitespace ...
- if (h) {
- this.header[h][this.header[h].length - 1] += lines[i]
- continue
+ resolve(dst)
+ } else if (type === 'blob') {
+ if (!Blob) {
+ Blob = (__nccwpck_require__(181).Blob)
}
+ resolve(new Blob(body, { type: stream[kContentType] }))
}
- const posColon = lines[i].indexOf(':')
- if (
- posColon === -1 ||
- posColon === 0
- ) {
- return
- }
- m = RE_HDR.exec(lines[i])
- h = m[1].toLowerCase()
- this.header[h] = this.header[h] || []
- this.header[h].push((m[2] || ''))
- if (++this.npairs === this.maxHeaderPairs) { break }
+ consumeFinish(consume)
+ } catch (err) {
+ stream.destroy(err)
}
}
-module.exports = HeaderParser
-
-
-/***/ }),
-
-/***/ 38710:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+function consumePush (consume, chunk) {
+ consume.length += chunk.length
+ consume.body.push(chunk)
+}
+function consumeFinish (consume, err) {
+ if (consume.body === null) {
+ return
+ }
-const inherits = (__nccwpck_require__(47261).inherits)
-const ReadableStream = (__nccwpck_require__(84492).Readable)
+ if (err) {
+ consume.reject(err)
+ } else {
+ consume.resolve()
+ }
-function PartStream (opts) {
- ReadableStream.call(this, opts)
+ consume.type = null
+ consume.stream = null
+ consume.resolve = null
+ consume.reject = null
+ consume.length = 0
+ consume.body = null
}
-inherits(PartStream, ReadableStream)
-
-PartStream.prototype._read = function (n) {}
-
-module.exports = PartStream
/***/ }),
-/***/ 88534:
+/***/ 7655:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
+const assert = __nccwpck_require__(2613)
+const {
+ ResponseStatusCodeError
+} = __nccwpck_require__(8707)
+const { toUSVString } = __nccwpck_require__(3440)
+async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
+ assert(body)
-/**
- * Copyright Brian White. All rights reserved.
- *
- * @see https://github.com/mscdex/streamsearch
- *
- * 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.
- *
- * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
- * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
- */
-const EventEmitter = (__nccwpck_require__(15673).EventEmitter)
-const inherits = (__nccwpck_require__(47261).inherits)
+ let chunks = []
+ let limit = 0
-function SBMH (needle) {
- if (typeof needle === 'string') {
- needle = Buffer.from(needle)
+ for await (const chunk of body) {
+ chunks.push(chunk)
+ limit += chunk.length
+ if (limit > 128 * 1024) {
+ chunks = null
+ break
+ }
}
- if (!Buffer.isBuffer(needle)) {
- throw new TypeError('The needle has to be a String or a Buffer.')
+ if (statusCode === 204 || !contentType || !chunks) {
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+ return
}
- const needleLength = needle.length
+ try {
+ if (contentType.startsWith('application/json')) {
+ const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
- if (needleLength === 0) {
- throw new Error('The needle cannot be an empty String/Buffer.')
+ if (contentType.startsWith('text/')) {
+ const payload = toUSVString(Buffer.concat(chunks))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+ } catch (err) {
+ // Process in a fallback if error
}
- if (needleLength > 256) {
- throw new Error('The needle cannot have a length bigger than 256.')
- }
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+}
- this.maxMatches = Infinity
- this.matches = 0
+module.exports = { getResolveErrorBodyCallback }
- this._occ = new Array(256)
- .fill(needleLength) // Initialize occurrence table.
- this._lookbehind_size = 0
- this._needle = needle
- this._bufpos = 0
- this._lookbehind = Buffer.alloc(needleLength)
+/***/ }),
- // Populate occurrence table with analysis of the needle,
- // ignoring last letter.
- for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
- this._occ[needle[i]] = needleLength - 1 - i
- }
-}
-inherits(SBMH, EventEmitter)
+/***/ 1093:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-SBMH.prototype.reset = function () {
- this._lookbehind_size = 0
- this.matches = 0
- this._bufpos = 0
+
+
+const {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+} = __nccwpck_require__(8707)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+} = __nccwpck_require__(8640)
+const Pool = __nccwpck_require__(5076)
+const { kUrl, kInterceptors } = __nccwpck_require__(6443)
+const { parseOrigin } = __nccwpck_require__(3440)
+const kFactory = Symbol('factory')
+
+const kOptions = Symbol('options')
+const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
+const kCurrentWeight = Symbol('kCurrentWeight')
+const kIndex = Symbol('kIndex')
+const kWeight = Symbol('kWeight')
+const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
+const kErrorPenalty = Symbol('kErrorPenalty')
+
+function getGreatestCommonDivisor (a, b) {
+ if (b === 0) return a
+ return getGreatestCommonDivisor(b, a % b)
}
-SBMH.prototype.push = function (chunk, pos) {
- if (!Buffer.isBuffer(chunk)) {
- chunk = Buffer.from(chunk, 'binary')
- }
- const chlen = chunk.length
- this._bufpos = pos || 0
- let r
- while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
- return r
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
}
-SBMH.prototype._sbmh_feed = function (data) {
- const len = data.length
- const needle = this._needle
- const needleLength = needle.length
- const lastNeedleChar = needle[needleLength - 1]
+class BalancedPool extends PoolBase {
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ super()
- // Positive: points to a position in `data`
- // pos == 3 points to data[3]
- // Negative: points to a position in the lookbehind buffer
- // pos == -2 points to lookbehind[lookbehind_size - 2]
- let pos = -this._lookbehind_size
- let ch
+ this[kOptions] = opts
+ this[kIndex] = -1
+ this[kCurrentWeight] = 0
- if (pos < 0) {
- // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
- // search with character lookup code that considers both the
- // lookbehind buffer and the current round's haystack data.
- //
- // Loop until
- // there is a match.
- // or until
- // we've moved past the position that requires the
- // lookbehind buffer. In this case we switch to the
- // optimized loop.
- // or until
- // the character to look at lies outside the haystack.
- while (pos < 0 && pos <= len - needleLength) {
- ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
- if (
- ch === lastNeedleChar &&
- this._sbmh_memcmp(data, pos, needleLength - 1)
- ) {
- this._lookbehind_size = 0
- ++this.matches
- this.emit('info', true)
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams]
+ }
- return (this._bufpos = pos + needleLength)
- }
- pos += this._occ[ch]
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- // No match.
+ this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
+ ? opts.interceptors.BalancedPool
+ : []
+ this[kFactory] = factory
- if (pos < 0) {
- // There's too few data for Boyer-Moore-Horspool to run,
- // so let's use a different algorithm to skip as much as
- // we can.
- // Forward pos until
- // the trailing part of lookbehind + data
- // looks like the beginning of the needle
- // or until
- // pos == 0
- while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream)
}
+ this._updateBalancedPoolStats()
+ }
- if (pos >= 0) {
- // Discard lookbehind buffer.
- this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
- this._lookbehind_size = 0
- } else {
- // Cut off part of the lookbehind buffer that has
- // been processed and append the entire haystack
- // into it.
- const bytesToCutOff = this._lookbehind_size + pos
- if (bytesToCutOff > 0) {
- // The cut off data is guaranteed not to contain the needle.
- this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
- }
+ addUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
- this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
- this._lookbehind_size - bytesToCutOff)
- this._lookbehind_size -= bytesToCutOff
+ if (this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))) {
+ return this
+ }
+ const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
- data.copy(this._lookbehind, this._lookbehind_size)
- this._lookbehind_size += len
+ this[kAddClient](pool)
+ pool.on('connect', () => {
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
+ })
- this._bufpos = len
- return len
+ pool.on('connectionError', () => {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ })
+
+ pool.on('disconnect', (...args) => {
+ const err = args[2]
+ if (err && err.code === 'UND_ERR_SOCKET') {
+ // decrease the weight of the pool.
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ }
+ })
+
+ for (const client of this[kClients]) {
+ client[kWeight] = this[kMaxWeightPerServer]
}
- }
- pos += (pos >= 0) * this._bufpos
+ this._updateBalancedPoolStats()
- // Lookbehind buffer is now empty. We only need to check if the
- // needle is in the haystack.
- if (data.indexOf(needle, pos) !== -1) {
- pos = data.indexOf(needle, pos)
- ++this.matches
- if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+ return this
+ }
- return (this._bufpos = pos + needleLength)
- } else {
- pos = len - needleLength
+ _updateBalancedPoolStats () {
+ this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
}
- // There was no match. If there's trailing haystack data that we cannot
- // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
- // data is less than the needle size) then match using a modified
- // algorithm that starts matching from the beginning instead of the end.
- // Whatever trailing data is left after running this algorithm is added to
- // the lookbehind buffer.
- while (
- pos < len &&
- (
- data[pos] !== needle[0] ||
- (
- (Buffer.compare(
- data.subarray(pos, pos + len - pos),
- needle.subarray(0, len - pos)
- ) !== 0)
- )
- )
- ) {
- ++pos
+ removeUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
+
+ const pool = this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))
+
+ if (pool) {
+ this[kRemoveClient](pool)
+ }
+
+ return this
}
- if (pos < len) {
- data.copy(this._lookbehind, 0, pos, pos + (len - pos))
- this._lookbehind_size = len - pos
+
+ get upstreams () {
+ return this[kClients]
+ .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
+ .map((p) => p[kUrl].origin)
}
- // Everything until pos is guaranteed not to contain needle data.
- if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
+ [kGetDispatcher] () {
+ // We validate that pools is greater than 0,
+ // otherwise we would have to wait until an upstream
+ // is added, which might never happen.
+ if (this[kClients].length === 0) {
+ throw new BalancedPoolMissingUpstreamError()
+ }
- this._bufpos = len
- return len
-}
+ const dispatcher = this[kClients].find(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
-SBMH.prototype._sbmh_lookup_char = function (data, pos) {
- return (pos < 0)
- ? this._lookbehind[this._lookbehind_size + pos]
- : data[pos]
-}
+ if (!dispatcher) {
+ return
+ }
-SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
- for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
- if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+
+ if (allClientsBusy) {
+ return
+ }
+
+ let counter = 0
+
+ let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+
+ while (counter++ < this[kClients].length) {
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length
+ const pool = this[kClients][this[kIndex]]
+
+ // find pool index with the largest weight
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
+ maxWeightIndex = this[kIndex]
+ }
+
+ // decrease the current weight every `this[kClients].length`.
+ if (this[kIndex] === 0) {
+ // Set the current weight to the next lower weight.
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+
+ if (this[kCurrentWeight] <= 0) {
+ this[kCurrentWeight] = this[kMaxWeightPerServer]
+ }
+ }
+ if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
+ return pool
+ }
+ }
+
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
+ this[kIndex] = maxWeightIndex
+ return this[kClients][maxWeightIndex]
}
- return true
}
-module.exports = SBMH
+module.exports = BalancedPool
/***/ }),
-/***/ 33438:
+/***/ 479:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-const WritableStream = (__nccwpck_require__(84492).Writable)
-const { inherits } = __nccwpck_require__(47261)
-const Dicer = __nccwpck_require__(2856)
+const { kConstruct } = __nccwpck_require__(296)
+const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993)
+const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440)
+const { kHeadersList } = __nccwpck_require__(6443)
+const { webidl } = __nccwpck_require__(4222)
+const { Response, cloneResponse } = __nccwpck_require__(8676)
+const { Request } = __nccwpck_require__(5194)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
+const { fetching } = __nccwpck_require__(2315)
+const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523)
+const assert = __nccwpck_require__(2613)
+const { getGlobalDispatcher } = __nccwpck_require__(2581)
-const MultipartParser = __nccwpck_require__(90415)
-const UrlencodedParser = __nccwpck_require__(16780)
-const parseParams = __nccwpck_require__(34426)
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
+ * @typedef {Object} CacheBatchOperation
+ * @property {'delete' | 'put'} type
+ * @property {any} request
+ * @property {any} response
+ * @property {import('../../types/cache').CacheQueryOptions} options
+ */
-function Busboy (opts) {
- if (!(this instanceof Busboy)) { return new Busboy(opts) }
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
+ * @typedef {[any, any][]} requestResponseList
+ */
- if (typeof opts !== 'object') {
- throw new TypeError('Busboy expected an options-Object.')
- }
- if (typeof opts.headers !== 'object') {
- throw new TypeError('Busboy expected an options-Object with headers-attribute.')
- }
- if (typeof opts.headers['content-type'] !== 'string') {
- throw new TypeError('Missing Content-Type-header.')
- }
+class Cache {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList
- const {
- headers,
- ...streamOptions
- } = opts
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
- this.opts = {
- autoDestroy: false,
- ...streamOptions
+ this.#relevantRequestResponseList = arguments[1]
}
- WritableStream.call(this, this.opts)
- this._done = false
- this._parser = this.getParserByHeaders(headers)
- this._finished = false
-}
-inherits(Busboy, WritableStream)
+ async match (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
-Busboy.prototype.emit = function (ev) {
- if (ev === 'finish') {
- if (!this._done) {
- this._parser?.end()
- return
- } else if (this._finished) {
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ const p = await this.matchAll(request, options)
+
+ if (p.length === 0) {
return
}
- this._finished = true
+
+ return p[0]
}
- WritableStream.prototype.emit.apply(this, arguments)
-}
-Busboy.prototype.getParserByHeaders = function (headers) {
- const parsed = parseParams(headers['content-type'])
+ async matchAll (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
- const cfg = {
- defCharset: this.opts.defCharset,
- fileHwm: this.opts.fileHwm,
- headers,
- highWaterMark: this.opts.highWaterMark,
- isPartAFile: this.opts.isPartAFile,
- limits: this.opts.limits,
- parsedConType: parsed,
- preservePath: this.opts.preservePath
- }
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
- if (MultipartParser.detect.test(parsed[0])) {
- return new MultipartParser(this, cfg)
- }
- if (UrlencodedParser.detect.test(parsed[0])) {
- return new UrlencodedParser(this, cfg)
- }
- throw new Error('Unsupported Content-Type.')
-}
+ // 1.
+ let r = null
-Busboy.prototype._write = function (chunk, encoding, cb) {
- this._parser.write(chunk, cb)
-}
+ // 2.
+ if (request !== undefined) {
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
-module.exports = Busboy
-module.exports["default"] = Busboy
-module.exports.Busboy = Busboy
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') {
+ // 2.2.1
+ r = new Request(request)[kState]
+ }
+ }
-module.exports.Dicer = Dicer
+ // 5.
+ // 5.1
+ const responses = []
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ responses.push(requestResponse[1])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
-/***/ }),
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1])
+ }
+ }
-/***/ 90415:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 5.4
+ // We don't implement CORs so we don't need to loop over the responses, yay!
-"use strict";
+ // 5.5.1
+ const responseList = []
+ // 5.5.2
+ for (const response of responses) {
+ // 5.5.2.1
+ const responseObject = new Response(response.body?.source ?? null)
+ const body = responseObject[kState].body
+ responseObject[kState] = response
+ responseObject[kState].body = body
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
-// TODO:
-// * support 1 nested multipart level
-// (see second multipart example here:
-// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
-// * support limits.fieldNameSize
-// -- this will require modifications to utils.parseParams
+ responseList.push(responseObject)
+ }
-const { Readable } = __nccwpck_require__(84492)
-const { inherits } = __nccwpck_require__(47261)
+ // 6.
+ return Object.freeze(responseList)
+ }
-const Dicer = __nccwpck_require__(2856)
+ async add (request) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
-const parseParams = __nccwpck_require__(34426)
-const decodeText = __nccwpck_require__(99136)
-const basename = __nccwpck_require__(60496)
-const getLimit = __nccwpck_require__(49692)
+ request = webidl.converters.RequestInfo(request)
-const RE_BOUNDARY = /^boundary$/i
-const RE_FIELD = /^form-data$/i
-const RE_CHARSET = /^charset$/i
-const RE_FILENAME = /^filename$/i
-const RE_NAME = /^name$/i
+ // 1.
+ const requests = [request]
-Multipart.detect = /^multipart\/form-data/i
-function Multipart (boy, cfg) {
- let i
- let len
- const self = this
- let boundary
- const limits = cfg.limits
- const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
- const parsedConType = cfg.parsedConType || []
- const defCharset = cfg.defCharset || 'utf8'
- const preservePath = cfg.preservePath
- const fileOpts = { highWaterMark: cfg.fileHwm }
+ // 2.
+ const responseArrayPromise = this.addAll(requests)
- for (i = 0, len = parsedConType.length; i < len; ++i) {
- if (Array.isArray(parsedConType[i]) &&
- RE_BOUNDARY.test(parsedConType[i][0])) {
- boundary = parsedConType[i][1]
- break
- }
+ // 3.
+ return await responseArrayPromise
}
- function checkFinished () {
- if (nends === 0 && finished && !boy._done) {
- finished = false
- self.end()
- }
- }
+ async addAll (requests) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
- if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
+ requests = webidl.converters['sequence'](requests)
- const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
- const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
- const filesLimit = getLimit(limits, 'files', Infinity)
- const fieldsLimit = getLimit(limits, 'fields', Infinity)
- const partsLimit = getLimit(limits, 'parts', Infinity)
- const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
- const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
+ // 1.
+ const responsePromises = []
- let nfiles = 0
- let nfields = 0
- let nends = 0
- let curFile
- let curField
- let finished = false
+ // 2.
+ const requestList = []
- this._needDrain = false
- this._pause = false
- this._cb = undefined
- this._nparts = 0
- this._boy = boy
+ // 3.
+ for (const request of requests) {
+ if (typeof request === 'string') {
+ continue
+ }
- const parserCfg = {
- boundary,
- maxHeaderPairs: headerPairsLimit,
- maxHeaderSize: headerSizeLimit,
- partHwm: fileOpts.highWaterMark,
- highWaterMark: cfg.highWaterMark
- }
+ // 3.1
+ const r = request[kState]
- this.parser = new Dicer(parserCfg)
- this.parser.on('drain', function () {
- self._needDrain = false
- if (self._cb && !self._pause) {
- const cb = self._cb
- self._cb = undefined
- cb()
- }
- }).on('part', function onPart (part) {
- if (++self._nparts > partsLimit) {
- self.parser.removeListener('part', onPart)
- self.parser.on('part', skipPart)
- boy.hitPartsLimit = true
- boy.emit('partsLimit')
- return skipPart(part)
+ // 3.2
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme when method is not GET.'
+ })
+ }
}
- // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
- // us emit 'end' early since we know the part has ended if we are already
- // seeing the next part
- if (curField) {
- const field = curField
- field.emit('end')
- field.removeAllListeners('end')
- }
+ // 4.
+ /** @type {ReturnType[]} */
+ const fetchControllers = []
- part.on('header', function (header) {
- let contype
- let fieldname
- let parsed
- let charset
- let encoding
- let filename
- let nsize = 0
+ // 5.
+ for (const request of requests) {
+ // 5.1
+ const r = new Request(request)[kState]
- if (header['content-type']) {
- parsed = parseParams(header['content-type'][0])
- if (parsed[0]) {
- contype = parsed[0].toLowerCase()
- for (i = 0, len = parsed.length; i < len; ++i) {
- if (RE_CHARSET.test(parsed[i][0])) {
- charset = parsed[i][1].toLowerCase()
- break
- }
- }
- }
+ // 5.2
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme.'
+ })
}
- if (contype === undefined) { contype = 'text/plain' }
- if (charset === undefined) { charset = defCharset }
-
- if (header['content-disposition']) {
- parsed = parseParams(header['content-disposition'][0])
- if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
- for (i = 0, len = parsed.length; i < len; ++i) {
- if (RE_NAME.test(parsed[i][0])) {
- fieldname = parsed[i][1]
- } else if (RE_FILENAME.test(parsed[i][0])) {
- filename = parsed[i][1]
- if (!preservePath) { filename = basename(filename) }
- }
- }
- } else { return skipPart(part) }
+ // 5.4
+ r.initiator = 'fetch'
+ r.destination = 'subresource'
- if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
+ // 5.5
+ requestList.push(r)
- let onData,
- onEnd
+ // 5.6
+ const responsePromise = createDeferredPromise()
- if (isPartAFile(fieldname, contype, filename)) {
- // file/binary field
- if (nfiles === filesLimit) {
- if (!boy.hitFilesLimit) {
- boy.hitFilesLimit = true
- boy.emit('filesLimit')
- }
- return skipPart(part)
- }
+ // 5.7
+ fetchControllers.push(fetching({
+ request: r,
+ dispatcher: getGlobalDispatcher(),
+ processResponse (response) {
+ // 1.
+ if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Received an invalid status code or the request failed.'
+ }))
+ } else if (response.headersList.contains('vary')) { // 2.
+ // 2.1
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
- ++nfiles
+ // 2.2
+ for (const fieldValue of fieldValues) {
+ // 2.2.1
+ if (fieldValue === '*') {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'invalid vary field value'
+ }))
- if (!boy._events.file) {
- self.parser._ignore()
- return
- }
+ for (const controller of fetchControllers) {
+ controller.abort()
+ }
- ++nends
- const file = new FileStream(fileOpts)
- curFile = file
- file.on('end', function () {
- --nends
- self._pause = false
- checkFinished()
- if (self._cb && !self._needDrain) {
- const cb = self._cb
- self._cb = undefined
- cb()
+ return
+ }
+ }
}
- })
- file._read = function (n) {
- if (!self._pause) { return }
- self._pause = false
- if (self._cb && !self._needDrain) {
- const cb = self._cb
- self._cb = undefined
- cb()
+ },
+ processResponseEndOfBody (response) {
+ // 1.
+ if (response.aborted) {
+ responsePromise.reject(new DOMException('aborted', 'AbortError'))
+ return
}
+
+ // 2.
+ responsePromise.resolve(response)
}
- boy.emit('file', fieldname, file, filename, encoding, contype)
+ }))
- onData = function (data) {
- if ((nsize += data.length) > fileSizeLimit) {
- const extralen = fileSizeLimit - nsize + data.length
- if (extralen > 0) { file.push(data.slice(0, extralen)) }
- file.truncated = true
- file.bytesRead = fileSizeLimit
- part.removeAllListeners('data')
- file.emit('limit')
- return
- } else if (!file.push(data)) { self._pause = true }
+ // 5.8
+ responsePromises.push(responsePromise.promise)
+ }
- file.bytesRead = nsize
- }
+ // 6.
+ const p = Promise.all(responsePromises)
- onEnd = function () {
- curFile = undefined
- file.push(null)
- }
- } else {
- // non-file field
- if (nfields === fieldsLimit) {
- if (!boy.hitFieldsLimit) {
- boy.hitFieldsLimit = true
- boy.emit('fieldsLimit')
- }
- return skipPart(part)
- }
+ // 7.
+ const responses = await p
- ++nfields
- ++nends
- let buffer = ''
- let truncated = false
- curField = part
+ // 7.1
+ const operations = []
- onData = function (data) {
- if ((nsize += data.length) > fieldSizeLimit) {
- const extralen = (fieldSizeLimit - (nsize - data.length))
- buffer += data.toString('binary', 0, extralen)
- truncated = true
- part.removeAllListeners('data')
- } else { buffer += data.toString('binary') }
- }
+ // 7.2
+ let index = 0
- onEnd = function () {
- curField = undefined
- if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
- boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
- --nends
- checkFinished()
- }
+ // 7.3
+ for (const response of responses) {
+ // 7.3.1
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 7.3.2
+ request: requestList[index], // 7.3.3
+ response // 7.3.4
}
- /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
- broken. Streams2/streams3 is a huge black box of confusion, but
- somehow overriding the sync state seems to fix things again (and still
- seems to work for previous node versions).
- */
- part._readableState.sync = false
+ operations.push(operation) // 7.3.5
- part.on('data', onData)
- part.on('end', onEnd)
- }).on('error', function (err) {
- if (curFile) { curFile.emit('error', err) }
- })
- }).on('error', function (err) {
- boy.emit('error', err)
- }).on('finish', function () {
- finished = true
- checkFinished()
- })
-}
+ index++ // 7.3.6
+ }
-Multipart.prototype.write = function (chunk, cb) {
- const r = this.parser.write(chunk)
- if (r && !this._pause) {
- cb()
- } else {
- this._needDrain = !r
- this._cb = cb
- }
-}
+ // 7.5
+ const cacheJobPromise = createDeferredPromise()
-Multipart.prototype.end = function () {
- const self = this
+ // 7.6.1
+ let errorData = null
- if (self.parser.writable) {
- self.parser.end()
- } else if (!self._boy._done) {
- process.nextTick(function () {
- self._boy._done = true
- self._boy.emit('finish')
+ // 7.6.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 7.6.3
+ queueMicrotask(() => {
+ // 7.6.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve(undefined)
+ } else {
+ // 7.6.3.2
+ cacheJobPromise.reject(errorData)
+ }
})
+
+ // 7.7
+ return cacheJobPromise.promise
}
-}
-function skipPart (part) {
- part.resume()
-}
+ async put (request, response) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
-function FileStream (opts) {
- Readable.call(this, opts)
+ request = webidl.converters.RequestInfo(request)
+ response = webidl.converters.Response(response)
- this.bytesRead = 0
+ // 1.
+ let innerRequest = null
- this.truncated = false
-}
+ // 2.
+ if (request instanceof Request) {
+ innerRequest = request[kState]
+ } else { // 3.
+ innerRequest = new Request(request)[kState]
+ }
-inherits(FileStream, Readable)
+ // 4.
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Expected an http/s scheme when method is not GET'
+ })
+ }
-FileStream.prototype._read = function (n) {}
+ // 5.
+ const innerResponse = response[kState]
-module.exports = Multipart
+ // 6.
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got 206 status'
+ })
+ }
+ // 7.
+ if (innerResponse.headersList.contains('vary')) {
+ // 7.1.
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
-/***/ }),
+ // 7.2.
+ for (const fieldValue of fieldValues) {
+ // 7.2.1
+ if (fieldValue === '*') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got * vary field value'
+ })
+ }
+ }
+ }
-/***/ 16780:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 8.
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Response body is locked or disturbed'
+ })
+ }
-"use strict";
+ // 9.
+ const clonedResponse = cloneResponse(innerResponse)
+ // 10.
+ const bodyReadPromise = createDeferredPromise()
-const Decoder = __nccwpck_require__(89730)
-const decodeText = __nccwpck_require__(99136)
-const getLimit = __nccwpck_require__(49692)
+ // 11.
+ if (innerResponse.body != null) {
+ // 11.1
+ const stream = innerResponse.body.stream
-const RE_CHARSET = /^charset$/i
+ // 11.2
+ const reader = stream.getReader()
-UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
-function UrlEncoded (boy, cfg) {
- const limits = cfg.limits
- const parsedConType = cfg.parsedConType
- this.boy = boy
+ // 11.3
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
+ } else {
+ bodyReadPromise.resolve(undefined)
+ }
- this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
- this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
- this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+ // 12.
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- let charset
- for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
- if (Array.isArray(parsedConType[i]) &&
- RE_CHARSET.test(parsedConType[i][0])) {
- charset = parsedConType[i][1].toLowerCase()
- break
+ // 13.
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 14.
+ request: innerRequest, // 15.
+ response: clonedResponse // 16.
}
- }
- if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
+ // 17.
+ operations.push(operation)
- this.decoder = new Decoder()
- this.charset = charset
- this._fields = 0
- this._state = 'key'
- this._checkingBytes = true
- this._bytesKey = 0
- this._bytesVal = 0
- this._key = ''
- this._val = ''
- this._keyTrunc = false
- this._valTrunc = false
- this._hitLimit = false
-}
+ // 19.
+ const bytes = await bodyReadPromise.promise
-UrlEncoded.prototype.write = function (data, cb) {
- if (this._fields === this.fieldsLimit) {
- if (!this.boy.hitFieldsLimit) {
- this.boy.hitFieldsLimit = true
- this.boy.emit('fieldsLimit')
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes
}
- return cb()
- }
- let idxeq; let idxamp; let i; let p = 0; const len = data.length
+ // 19.1
+ const cacheJobPromise = createDeferredPromise()
- while (p < len) {
- if (this._state === 'key') {
- idxeq = idxamp = undefined
- for (i = p; i < len; ++i) {
- if (!this._checkingBytes) { ++p }
- if (data[i] === 0x3D/* = */) {
- idxeq = i
- break
- } else if (data[i] === 0x26/* & */) {
- idxamp = i
- break
- }
- if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
- this._hitLimit = true
- break
- } else if (this._checkingBytes) { ++this._bytesKey }
+ // 19.2.1
+ let errorData = null
+
+ // 19.2.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 19.2.3
+ queueMicrotask(() => {
+ // 19.2.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve()
+ } else { // 19.2.3.2
+ cacheJobPromise.reject(errorData)
}
+ })
- if (idxeq !== undefined) {
- // key with assignment
- if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
- this._state = 'val'
+ return cacheJobPromise.promise
+ }
- this._hitLimit = false
- this._checkingBytes = true
- this._val = ''
- this._bytesVal = 0
- this._valTrunc = false
- this.decoder.reset()
+ async delete (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
- p = idxeq + 1
- } else if (idxamp !== undefined) {
- // key with no assignment
- ++this._fields
- let key; const keyTrunc = this._keyTrunc
- if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
- this._hitLimit = false
- this._checkingBytes = true
- this._key = ''
- this._bytesKey = 0
- this._keyTrunc = false
- this.decoder.reset()
+ /**
+ * @type {Request}
+ */
+ let r = null
- if (key.length) {
- this.boy.emit('field', decodeText(key, 'binary', this.charset),
- '',
- keyTrunc,
- false)
- }
+ if (request instanceof Request) {
+ r = request[kState]
- p = idxamp + 1
- if (this._fields === this.fieldsLimit) { return cb() }
- } else if (this._hitLimit) {
- // we may not have hit the actual limit if there are encoded bytes...
- if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
- p = i
- if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
- // yep, we actually did hit the limit
- this._checkingBytes = false
- this._keyTrunc = true
- }
- } else {
- if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
- p = len
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return false
}
} else {
- idxamp = undefined
- for (i = p; i < len; ++i) {
- if (!this._checkingBytes) { ++p }
- if (data[i] === 0x26/* & */) {
- idxamp = i
- break
- }
- if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
- this._hitLimit = true
- break
- } else if (this._checkingBytes) { ++this._bytesVal }
- }
+ assert(typeof request === 'string')
- if (idxamp !== undefined) {
- ++this._fields
- if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- decodeText(this._val, 'binary', this.charset),
- this._keyTrunc,
- this._valTrunc)
- this._state = 'key'
+ r = new Request(request)[kState]
+ }
- this._hitLimit = false
- this._checkingBytes = true
- this._key = ''
- this._bytesKey = 0
- this._keyTrunc = false
- this.decoder.reset()
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- p = idxamp + 1
- if (this._fields === this.fieldsLimit) { return cb() }
- } else if (this._hitLimit) {
- // we may not have hit the actual limit if there are encoded bytes...
- if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
- p = i
- if ((this._val === '' && this.fieldSizeLimit === 0) ||
- (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
- // yep, we actually did hit the limit
- this._checkingBytes = false
- this._valTrunc = true
- }
- } else {
- if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
- p = len
- }
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'delete',
+ request: r,
+ options
}
- }
- cb()
-}
-UrlEncoded.prototype.end = function () {
- if (this.boy._done) { return }
+ operations.push(operation)
- if (this._state === 'key' && this._key.length > 0) {
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- '',
- this._keyTrunc,
- false)
- } else if (this._state === 'val') {
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- decodeText(this._val, 'binary', this.charset),
- this._keyTrunc,
- this._valTrunc)
- }
- this.boy._done = true
- this.boy.emit('finish')
-}
+ const cacheJobPromise = createDeferredPromise()
-module.exports = UrlEncoded
+ let errorData = null
+ let requestResponses
+ try {
+ requestResponses = this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
-/***/ }),
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length)
+ } else {
+ cacheJobPromise.reject(errorData)
+ }
+ })
-/***/ 89730:
-/***/ ((module) => {
+ return cacheJobPromise.promise
+ }
-"use strict";
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @returns {readonly Request[]}
+ */
+ async keys (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
-const RE_PLUS = /\+/g
+ // 1.
+ let r = null
-const HEX = [
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-]
+ // 2.
+ if (request !== undefined) {
+ // 2.1
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
-function Decoder () {
- this.buffer = undefined
-}
-Decoder.prototype.write = function (str) {
- // Replace '+' with ' ' before decoding
- str = str.replace(RE_PLUS, ' ')
- let res = ''
- let i = 0; let p = 0; const len = str.length
- for (; i < len; ++i) {
- if (this.buffer !== undefined) {
- if (!HEX[str.charCodeAt(i)]) {
- res += '%' + this.buffer
- this.buffer = undefined
- --i // retry character
- } else {
- this.buffer += str[i]
- ++p
- if (this.buffer.length === 2) {
- res += String.fromCharCode(parseInt(this.buffer, 16))
- this.buffer = undefined
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
}
+ } else if (typeof request === 'string') { // 2.2
+ r = new Request(request)[kState]
}
- } else if (str[i] === '%') {
- if (i > p) {
- res += str.substring(p, i)
- p = i
- }
- this.buffer = ''
- ++p
}
- }
- if (p < len && this.buffer === undefined) { res += str.substring(p) }
- return res
-}
-Decoder.prototype.reset = function () {
- this.buffer = undefined
-}
-module.exports = Decoder
+ // 4.
+ const promise = createDeferredPromise()
+ // 5.
+ // 5.1
+ const requests = []
-/***/ }),
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ // 5.2.1.1
+ requests.push(requestResponse[0])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
-/***/ 60496:
-/***/ ((module) => {
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ // 5.3.2.1
+ requests.push(requestResponse[0])
+ }
+ }
-"use strict";
+ // 5.4
+ queueMicrotask(() => {
+ // 5.4.1
+ const requestList = []
+ // 5.4.2
+ for (const request of requests) {
+ const requestObject = new Request('https://a')
+ requestObject[kState] = request
+ requestObject[kHeaders][kHeadersList] = request.headersList
+ requestObject[kHeaders][kGuard] = 'immutable'
+ requestObject[kRealm] = request.client
-module.exports = function basename (path) {
- if (typeof path !== 'string') { return '' }
- for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
- switch (path.charCodeAt(i)) {
- case 0x2F: // '/'
- case 0x5C: // '\'
- path = path.slice(i + 1)
- return (path === '..' || path === '.' ? '' : path)
- }
- }
- return (path === '..' || path === '.' ? '' : path)
-}
+ // 5.4.2.1
+ requestList.push(requestObject)
+ }
+ // 5.4.3
+ promise.resolve(Object.freeze(requestList))
+ })
-/***/ }),
+ return promise.promise
+ }
-/***/ 99136:
-/***/ ((module) => {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations (operations) {
+ // 1.
+ const cache = this.#relevantRequestResponseList
-"use strict";
+ // 2.
+ const backupCache = [...cache]
+ // 3.
+ const addedItems = []
-// Node has always utf-8
-const utf8Decoder = new TextDecoder('utf-8')
-const textDecoders = new Map([
- ['utf-8', utf8Decoder],
- ['utf8', utf8Decoder]
-])
+ // 4.1
+ const resultList = []
-function decodeText (text, textEncoding, destEncoding) {
- if (text) {
- if (textDecoders.has(destEncoding)) {
- try {
- return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
- } catch (e) { }
- } else {
- try {
- textDecoders.set(destEncoding, new TextDecoder(destEncoding))
- return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
- } catch (e) { }
- }
- }
- return text
-}
+ try {
+ // 4.2
+ for (const operation of operations) {
+ // 4.2.1
+ if (operation.type !== 'delete' && operation.type !== 'put') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'operation type does not match "delete" or "put"'
+ })
+ }
-module.exports = decodeText
+ // 4.2.2
+ if (operation.type === 'delete' && operation.response != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'delete operation should not have an associated response'
+ })
+ }
+ // 4.2.3
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException('???', 'InvalidStateError')
+ }
-/***/ }),
+ // 4.2.4
+ let requestResponses
-/***/ 49692:
-/***/ ((module) => {
+ // 4.2.5
+ if (operation.type === 'delete') {
+ // 4.2.5.1
+ requestResponses = this.#queryCache(operation.request, operation.options)
-"use strict";
+ // TODO: the spec is wrong, this is needed to pass WPTs
+ if (requestResponses.length === 0) {
+ return []
+ }
+ // 4.2.5.2
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
-module.exports = function getLimit (limits, name, defaultLimit) {
- if (
- !limits ||
- limits[name] === undefined ||
- limits[name] === null
- ) { return defaultLimit }
+ // 4.2.5.2.1
+ cache.splice(idx, 1)
+ }
+ } else if (operation.type === 'put') { // 4.2.6
+ // 4.2.6.1
+ if (operation.response == null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'put operation should have an associated response'
+ })
+ }
- if (
- typeof limits[name] !== 'number' ||
- isNaN(limits[name])
- ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
+ // 4.2.6.2
+ const r = operation.request
- return limits[name]
-}
+ // 4.2.6.3
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'expected http or https scheme'
+ })
+ }
+ // 4.2.6.4
+ if (r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'not get method'
+ })
+ }
-/***/ }),
+ // 4.2.6.5
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'options must not be defined'
+ })
+ }
-/***/ 34426:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4.2.6.6
+ requestResponses = this.#queryCache(operation.request)
-"use strict";
+ // 4.2.6.7
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
+ // 4.2.6.7.1
+ cache.splice(idx, 1)
+ }
-const decodeText = __nccwpck_require__(99136)
+ // 4.2.6.8
+ cache.push([operation.request, operation.response])
-const RE_ENCODED = /%([a-fA-F0-9]{2})/g
+ // 4.2.6.10
+ addedItems.push([operation.request, operation.response])
+ }
-function encodedReplacer (match, byte) {
- return String.fromCharCode(parseInt(byte, 16))
-}
+ // 4.2.7
+ resultList.push([operation.request, operation.response])
+ }
-function parseParams (str) {
- const res = []
- let state = 'key'
- let charset = ''
- let inquote = false
- let escaping = false
- let p = 0
- let tmp = ''
+ // 4.3
+ return resultList
+ } catch (e) { // 5.
+ // 5.1
+ this.#relevantRequestResponseList.length = 0
- for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var
- const char = str[i]
- if (char === '\\' && inquote) {
- if (escaping) { escaping = false } else {
- escaping = true
- continue
- }
- } else if (char === '"') {
- if (!escaping) {
- if (inquote) {
- inquote = false
- state = 'key'
- } else { inquote = true }
- continue
- } else { escaping = false }
- } else {
- if (escaping && inquote) { tmp += '\\' }
- escaping = false
- if ((state === 'charset' || state === 'lang') && char === "'") {
- if (state === 'charset') {
- state = 'lang'
- charset = tmp.substring(1)
- } else { state = 'value' }
- tmp = ''
- continue
- } else if (state === 'key' &&
- (char === '*' || char === '=') &&
- res.length) {
- if (char === '*') { state = 'charset' } else { state = 'value' }
- res[p] = [tmp, undefined]
- tmp = ''
- continue
- } else if (!inquote && char === ';') {
- state = 'key'
- if (charset) {
- if (tmp.length) {
- tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
- 'binary',
- charset)
- }
- charset = ''
- } else if (tmp.length) {
- tmp = decodeText(tmp, 'binary', 'utf8')
- }
- if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
- tmp = ''
- ++p
- continue
- } else if (!inquote && (char === ' ' || char === '\t')) { continue }
+ // 5.2
+ this.#relevantRequestResponseList = backupCache
+
+ // 5.3
+ throw e
}
- tmp += char
- }
- if (charset && tmp.length) {
- tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
- 'binary',
- charset)
- } else if (tmp) {
- tmp = decodeText(tmp, 'binary', 'utf8')
}
- if (res[p] === undefined) {
- if (tmp) { res[p] = tmp }
- } else { res[p][1] = tmp }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
+ * @param {any} requestQuery
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @param {requestResponseList} targetStorage
+ * @returns {requestResponseList}
+ */
+ #queryCache (requestQuery, options, targetStorage) {
+ /** @type {requestResponseList} */
+ const resultList = []
- return res
-}
+ const storage = targetStorage ?? this.#relevantRequestResponseList
-module.exports = parseParams
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
+ resultList.push(requestResponse)
+ }
+ }
+
+ return resultList
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
+ * @param {any} requestQuery
+ * @param {any} request
+ * @param {any | null} response
+ * @param {import('../../types/cache').CacheQueryOptions | undefined} options
+ * @returns {boolean}
+ */
+ #requestMatchesCachedItem (requestQuery, request, response = null, options) {
+ // if (options?.ignoreMethod === false && request.method === 'GET') {
+ // return false
+ // }
-/***/ }),
+ const queryURL = new URL(requestQuery.url)
-/***/ 55128:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ const cachedURL = new URL(request.url)
-"use strict";
+ if (options?.ignoreSearch) {
+ cachedURL.search = ''
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const rabin_karp_1 = __nccwpck_require__(8105);
-const validators_1 = __nccwpck_require__(82218);
-const mode_1 = __nccwpck_require__(27899);
-// TODO replace to own event emitter
-const EventEmitter = __nccwpck_require__(11848);
-class Detector extends EventEmitter {
- constructor(tokenizer, store, cloneValidators = [], options) {
- super();
- this.tokenizer = tokenizer;
- this.store = store;
- this.cloneValidators = cloneValidators;
- this.options = options;
- this.initCloneValidators();
- this.algorithm = new rabin_karp_1.RabinKarp(this.options, this, this.cloneValidators);
- this.options.minTokens = this.options.minTokens || 50;
- this.options.maxLines = this.options.maxLines || 500;
- this.options.minLines = this.options.minLines || 5;
- this.options.mode = this.options.mode || mode_1.mild;
- }
- detect(id, text, format) {
- return __awaiter(this, void 0, void 0, function* () {
- const tokenMaps = this.tokenizer.generateMaps(id, text, format, this.options);
- // TODO change stores implementation
- this.store.namespace(format);
- const detect = (tokenMap, clones) => __awaiter(this, void 0, void 0, function* () {
- if (tokenMap) {
- this.emit('START_DETECTION', { source: tokenMap });
- return this.algorithm
- .run(tokenMap, this.store)
- .then((clns) => {
- clones.push(...clns);
- const nextTokenMap = tokenMaps.pop();
- if (nextTokenMap) {
- return detect(nextTokenMap, clones);
- }
- else {
- return clones;
- }
- });
- }
- });
- return detect(tokenMaps.pop(), []);
- });
- }
- initCloneValidators() {
- if (this.options.minLines || this.options.maxLines) {
- this.cloneValidators.push(new validators_1.LinesLengthCloneValidator());
- }
+ queryURL.search = ''
}
-}
-exports.Detector = Detector;
-//# sourceMappingURL=detector.js.map
-/***/ }),
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false
+ }
-/***/ 84511:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(55128));
-__export(__nccwpck_require__(27899));
-__export(__nccwpck_require__(81070));
-__export(__nccwpck_require__(67799));
-__export(__nccwpck_require__(54628));
-//# sourceMappingURL=index.js.map
+ if (
+ response == null ||
+ options?.ignoreVary ||
+ !response.headersList.contains('vary')
+ ) {
+ return true
+ }
-/***/ }),
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
-/***/ 27899:
-/***/ ((__unused_webpack_module, exports) => {
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === '*') {
+ return false
+ }
-"use strict";
+ const requestValue = request.headersList.get(fieldValue)
+ const queryValue = requestQuery.headersList.get(fieldValue)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-function strict(token) {
- return token.type !== 'ignore';
-}
-exports.strict = strict;
-function mild(token) {
- return strict(token) && token.type !== 'empty' && token.type !== 'new_line';
-}
-exports.mild = mild;
-function weak(token) {
- return mild(token)
- && token.format !== 'comment'
- && token.type !== 'comment'
- && token.type !== 'block-comment';
-}
-exports.weak = weak;
-const MODES = {
- mild,
- strict,
- weak,
-};
-function getModeByName(name) {
- if (name in MODES) {
- return MODES[name];
+ // If one has the header and the other doesn't, or one has
+ // a different value than the other, return false
+ if (requestValue !== queryValue) {
+ return false
+ }
}
- throw new Error(`Mode ${name} does not supported yet.`);
-}
-exports.getModeByName = getModeByName;
-function getModeHandler(mode) {
- return typeof mode === 'string' ? getModeByName(mode) : mode;
-}
-exports.getModeHandler = getModeHandler;
-//# sourceMappingURL=mode.js.map
-
-/***/ }),
-/***/ 81070:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const mode_1 = __nccwpck_require__(27899);
-function getDefaultOptions() {
- return {
- executionId: new Date().toISOString(),
- path: [process.cwd()],
- mode: mode_1.getModeHandler('mild'),
- minLines: 5,
- maxLines: 1000,
- maxSize: '100kb',
- minTokens: 50,
- output: './report',
- reporters: ['console'],
- ignore: [],
- threshold: undefined,
- formatsExts: {},
- debug: false,
- silent: false,
- blame: false,
- cache: true,
- absolute: false,
- noSymlinks: false,
- skipLocal: false,
- ignoreCase: false,
- gitignore: false,
- reportersOptions: {},
- exitCode: 0,
- };
-}
-exports.getDefaultOptions = getDefaultOptions;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function getOption(name, options) {
- const defaultOptions = getDefaultOptions();
- return options ? options[name] || defaultOptions[name] : defaultOptions[name];
+ return true
+ }
}
-exports.getOption = getOption;
-//# sourceMappingURL=options.js.map
-
-/***/ }),
-/***/ 8105:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'Cache',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
-"use strict";
+const cacheQueryOptionConverters = [
+ {
+ key: 'ignoreSearch',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreMethod',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreVary',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ }
+]
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const validators_1 = __nccwpck_require__(82218);
-class RabinKarp {
- constructor(options, eventEmitter, cloneValidators) {
- this.options = options;
- this.eventEmitter = eventEmitter;
- this.cloneValidators = cloneValidators;
- }
- run(tokenMap, store) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve => {
- let mapFrameInStore;
- let clone = null;
- const clones = [];
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
- const loop = () => {
- const iteration = tokenMap.next();
- store
- .get(iteration.value.id)
- .then((mapFrameFromStore) => {
- mapFrameInStore = mapFrameFromStore;
- if (!clone) {
- clone = RabinKarp.createClone(tokenMap.getFormat(), iteration.value, mapFrameInStore);
- }
- }, () => {
- if (clone && this.validate(clone)) {
- clones.push(clone);
- }
- clone = null;
- if (iteration.value.id) {
- return store.set(iteration.value.id, iteration.value);
- }
- })
- .finally(() => {
- if (!iteration.done) {
- if (clone) {
- clone = RabinKarp.enlargeClone(clone, iteration.value, mapFrameInStore);
- }
- loop();
- }
- else {
- resolve(clones);
- }
- });
- };
- loop();
- }));
- });
- }
- validate(clone) {
- const validation = validators_1.runCloneValidators(clone, this.options, this.cloneValidators);
- if (validation.status) {
- this.eventEmitter.emit('CLONE_FOUND', { clone });
- }
- else {
- this.eventEmitter.emit('CLONE_SKIPPED', { clone, validation });
- }
- return validation.status;
- }
- static createClone(format, mapFrameA, mapFrameB) {
- return {
- format,
- foundDate: new Date().getTime(),
- duplicationA: {
- sourceId: mapFrameA.sourceId,
- start: mapFrameA.start.loc.start,
- end: mapFrameA.end.loc.end,
- range: [mapFrameA.start.range[0], mapFrameA.end.range[1]],
- },
- duplicationB: {
- sourceId: mapFrameB.sourceId,
- start: mapFrameB.start.loc.start,
- end: mapFrameB.end.loc.end,
- range: [mapFrameB.start.range[0], mapFrameB.end.range[1]],
- },
- };
- }
- static enlargeClone(clone, mapFrameA, mapFrameB) {
- clone.duplicationA.range[1] = mapFrameA.end.range[1];
- clone.duplicationA.end = mapFrameA.end.loc.end;
- clone.duplicationB.range[1] = mapFrameB.end.range[1];
- clone.duplicationB.end = mapFrameB.end.loc.end;
- return clone;
- }
-}
-exports.RabinKarp = RabinKarp;
-//# sourceMappingURL=rabin-karp.js.map
+webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
-/***/ }),
+webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: 'cacheName',
+ converter: webidl.converters.DOMString
+ }
+])
-/***/ 67799:
-/***/ ((__unused_webpack_module, exports) => {
+webidl.converters.Response = webidl.interfaceConverter(Response)
-"use strict";
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-class Statistic {
- constructor() {
- this.statistic = {
- detectionDate: new Date().toISOString(),
- formats: {},
- total: Statistic.getDefaultStatistic(),
- };
- }
- static getDefaultStatistic() {
- return {
- lines: 0,
- tokens: 0,
- sources: 0,
- clones: 0,
- duplicatedLines: 0,
- duplicatedTokens: 0,
- percentage: 0,
- percentageTokens: 0,
- newDuplicatedLines: 0,
- newClones: 0,
- };
- }
- subscribe() {
- return {
- CLONE_FOUND: this.cloneFound.bind(this),
- START_DETECTION: this.matchSource.bind(this),
- };
- }
- getStatistic() {
- return this.statistic;
- }
- cloneFound(payload) {
- const { clone } = payload;
- const id = clone.duplicationA.sourceId;
- const id2 = clone.duplicationB.sourceId;
- const linesCount = clone.duplicationA.end.line - clone.duplicationA.start.line;
- const duplicatedTokens = clone.duplicationA.end.position - clone.duplicationA.start.position;
- this.statistic.total.clones++;
- this.statistic.total.duplicatedLines += linesCount;
- this.statistic.total.duplicatedTokens += duplicatedTokens;
- this.statistic.formats[clone.format].total.clones++;
- this.statistic.formats[clone.format].total.duplicatedLines += linesCount;
- this.statistic.formats[clone.format].total.duplicatedTokens += duplicatedTokens;
- this.statistic.formats[clone.format].sources[id].clones++;
- this.statistic.formats[clone.format].sources[id].duplicatedLines += linesCount;
- this.statistic.formats[clone.format].sources[id].duplicatedTokens += duplicatedTokens;
- this.statistic.formats[clone.format].sources[id2].clones++;
- this.statistic.formats[clone.format].sources[id2].duplicatedLines += linesCount;
- this.statistic.formats[clone.format].sources[id2].duplicatedTokens += duplicatedTokens;
- this.updatePercentage(clone.format);
- }
- matchSource(payload) {
- const { source } = payload;
- const format = source.getFormat();
- if (!(format in this.statistic.formats)) {
- this.statistic.formats[format] = {
- sources: {},
- total: Statistic.getDefaultStatistic(),
- };
- }
- this.statistic.total.sources++;
- this.statistic.total.lines += source.getLinesCount();
- this.statistic.total.tokens += source.getTokensCount();
- this.statistic.formats[format].total.sources++;
- this.statistic.formats[format].total.lines += source.getLinesCount();
- this.statistic.formats[format].total.tokens += source.getTokensCount();
- this.statistic.formats[format].sources[source.getId()] =
- this.statistic.formats[format].sources[source.getId()] || Statistic.getDefaultStatistic();
- this.statistic.formats[format].sources[source.getId()].sources = 1;
- this.statistic.formats[format].sources[source.getId()].lines += source.getLinesCount();
- this.statistic.formats[format].sources[source.getId()].tokens += source.getTokensCount();
- this.updatePercentage(format);
- }
- updatePercentage(format) {
- this.statistic.total.percentage = Statistic.calculatePercentage(this.statistic.total.lines, this.statistic.total.duplicatedLines);
- this.statistic.total.percentageTokens = Statistic.calculatePercentage(this.statistic.total.tokens, this.statistic.total.duplicatedTokens);
- this.statistic.formats[format].total.percentage = Statistic.calculatePercentage(this.statistic.formats[format].total.lines, this.statistic.formats[format].total.duplicatedLines);
- this.statistic.formats[format].total.percentageTokens = Statistic.calculatePercentage(this.statistic.formats[format].total.tokens, this.statistic.formats[format].total.duplicatedTokens);
- Object.entries(this.statistic.formats[format].sources).forEach(([id, stat]) => {
- this.statistic.formats[format].sources[id].percentage = Statistic.calculatePercentage(stat.lines, stat.duplicatedLines);
- this.statistic.formats[format].sources[id].percentageTokens = Statistic.calculatePercentage(stat.tokens, stat.duplicatedTokens);
- });
- }
- static calculatePercentage(total, cloned) {
- return total ? Math.round((10000 * cloned) / total) / 100 : 0.0;
- }
+module.exports = {
+ Cache
}
-exports.Statistic = Statistic;
-//# sourceMappingURL=statistic.js.map
-
-/***/ }),
-
-/***/ 54628:
-/***/ ((__unused_webpack_module, exports) => {
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-class MemoryStore {
- constructor() {
- this.values = {};
- }
- namespace(namespace) {
- this._namespace = namespace;
- this.values[namespace] = this.values[namespace] || {};
- }
- get(key) {
- return new Promise((resolve, reject) => {
- if (key in this.values[this._namespace]) {
- resolve(this.values[this._namespace][key]);
- }
- else {
- reject(new Error('not found'));
- }
- });
- }
- set(key, value) {
- this.values[this._namespace][key] = value;
- return Promise.resolve(value);
- }
- close() {
- this.values = {};
- }
-}
-exports.MemoryStore = MemoryStore;
-//# sourceMappingURL=memory.js.map
/***/ }),
-/***/ 82218:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+/***/ 4738:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(52214));
-__export(__nccwpck_require__(43865));
-//# sourceMappingURL=index.js.map
-/***/ }),
-/***/ 52214:
-/***/ ((__unused_webpack_module, exports) => {
+const { kConstruct } = __nccwpck_require__(296)
+const { Cache } = __nccwpck_require__(479)
+const { webidl } = __nccwpck_require__(4222)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
-"use strict";
+class CacheStorage {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map= options.minLines;
- return {
- status,
- message: status ? ['ok'] : [`Lines of code less than limit (${lines} < ${options.minLines})`],
- };
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
}
-}
-exports.LinesLengthCloneValidator = LinesLengthCloneValidator;
-//# sourceMappingURL=lines-length-clone.validator.js.map
-
-/***/ }),
-
-/***/ 43865:
-/***/ ((__unused_webpack_module, exports) => {
+ }
-"use strict";
+ async match (request, options = {}) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' })
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-function runCloneValidators(clone, options, validators) {
- return validators.reduce((acc, validator) => {
- const res = validator.validate(clone, options);
- return Object.assign(Object.assign({}, acc), { status: res.status && acc.status, message: res.message ? [...acc.message, ...res.message] : acc.message });
- }, { status: true, message: [], clone });
-}
-exports.runCloneValidators = runCloneValidators;
-//# sourceMappingURL=validator.js.map
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.MultiCacheQueryOptions(options)
-/***/ }),
+ // 1.
+ if (options.cacheName != null) {
+ // 1.1.1.1
+ if (this.#caches.has(options.cacheName)) {
+ // 1.1.1.1.1
+ const cacheList = this.#caches.get(options.cacheName)
+ const cache = new Cache(kConstruct, cacheList)
-/***/ 51908:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return await cache.match(request, options)
+ }
+ } else { // 2.
+ // 2.2
+ for (const cacheList of this.#caches.values()) {
+ const cache = new Cache(kConstruct, cacheList)
-"use strict";
+ // 2.2.1.2
+ const response = await cache.match(request, options)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const core_1 = __nccwpck_require__(84511);
-const fast_glob_1 = __nccwpck_require__(43664);
-const tokenizer_1 = __nccwpck_require__(92080);
-const fs_extra_1 = __nccwpck_require__(5630);
-const safe_1 = __nccwpck_require__(41997);
-const fs_1 = __nccwpck_require__(57147);
-const bytes = __nccwpck_require__(86966);
-function isFile(path) {
- try {
- const stat = fs_1.lstatSync(path);
- return stat.isFile();
- }
- catch (e) {
- // lstatSync throws an error if path doesn't exist
- return false;
- }
-}
-function isSymlink(path) {
- try {
- const stat = fs_1.lstatSync(path);
- return stat.isSymbolicLink();
- }
- catch (e) {
- // lstatSync throws an error if path doesn't exist
- return false;
- }
-}
-function skipNotSupportedFormats(options) {
- return (entry) => {
- const { path } = entry;
- const format = tokenizer_1.getFormatByFile(path, options.formatsExts);
- const shouldNotSkip = format && options.format && options.format.includes(format);
- if ((options.debug || options.verbose) && !shouldNotSkip) {
- console.log(`File ${path} skipped! Format "${format}" does not included to supported formats.`);
- }
- return shouldNotSkip;
- };
-}
-function skipBigFiles(options) {
- return (entry) => {
- const { stats, path } = entry;
- const shouldSkip = bytes.parse(stats.size) > bytes.parse(core_1.getOption('maxSize', options));
- if (options.debug && shouldSkip) {
- console.log(`File ${path} skipped! Size more then limit (${bytes(stats.size)} > ${core_1.getOption('maxSize', options)})`);
- }
- return !shouldSkip;
- };
-}
-function skipFilesIfLinesOfContentNotInLimits(options) {
- return (entry) => {
- const { path, content } = entry;
- const lines = content.split('\n').length;
- const minLines = core_1.getOption('minLines', options);
- const maxLines = core_1.getOption('maxLines', options);
- if (lines < minLines || lines > maxLines) {
- if ((options.debug || options.verbose)) {
- console.log(safe_1.grey(`File ${path} skipped! Code lines=${lines} not in limits (${minLines}:${maxLines})`));
- }
- return false;
- }
- return true;
- };
-}
-function addContentToEntry(entry) {
- const { path } = entry;
- const content = fs_extra_1.readFileSync(path).toString();
- return Object.assign(Object.assign({}, entry), { content });
-}
-function getFilesToDetect(options) {
- const pattern = options.pattern || '**/*';
- let patterns = options.path;
- if (options.noSymlinks) {
- patterns = patterns.filter((path) => !isSymlink(path));
- }
- patterns = patterns.map((path) => {
- const currentPath = fs_extra_1.realpathSync(path);
- if (isFile(currentPath)) {
- return path;
+ if (response !== undefined) {
+ return response
}
- return path.endsWith('/') ? `${path}${pattern}` : `${path}/${pattern}`;
- });
- return fast_glob_1.sync(patterns, {
- ignore: options.ignore,
- onlyFiles: true,
- dot: true,
- stats: true,
- absolute: options.absolute,
- followSymbolicLinks: !options.noSymlinks,
- })
- .filter(skipNotSupportedFormats(options))
- .filter(skipBigFiles(options))
- .map(addContentToEntry)
- .filter(skipFilesIfLinesOfContentNotInLimits(options));
-}
-exports.getFilesToDetect = getFilesToDetect;
-//# sourceMappingURL=files.js.map
+ }
+ }
+ }
-/***/ }),
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async has (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
-/***/ 74574:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ cacheName = webidl.converters.DOMString(cacheName)
-"use strict";
+ // 2.1.1
+ // 2.2
+ return this.#caches.has(cacheName)
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const blamer_1 = __nccwpck_require__(56781);
-class BlamerHook {
- process(clones) {
- return Promise.all(clones.map((clone) => BlamerHook.blameLines(clone)));
- }
- static blameLines(clone) {
- return __awaiter(this, void 0, void 0, function* () {
- const blamer = new blamer_1.default();
- const blamedFileA = yield blamer.blameByFile(clone.duplicationA.sourceId);
- const blamedFileB = yield blamer.blameByFile(clone.duplicationB.sourceId);
- clone.duplicationA.blame = BlamerHook.getBlamedLines(blamedFileA, clone.duplicationA.start.line, clone.duplicationA.end.line);
- clone.duplicationB.blame = BlamerHook.getBlamedLines(blamedFileB, clone.duplicationB.start.line, clone.duplicationB.end.line);
- return clone;
- });
- }
- static getBlamedLines(blamedFiles, start, end) {
- // TODO rewrite the method
- const [file] = Object.keys(blamedFiles);
- const result = {};
- Object.keys(blamedFiles[file])
- .filter((lineNumber) => {
- return Number(lineNumber) >= start && Number(lineNumber) <= end;
- })
- .map((lineNumber) => blamedFiles[file][lineNumber])
- .forEach((info) => {
- result[info.line] = info;
- });
- return result;
- }
-}
-exports.BlamerHook = BlamerHook;
-//# sourceMappingURL=blamer.js.map
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async open (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
-/***/ }),
+ cacheName = webidl.converters.DOMString(cacheName)
-/***/ 44810:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2.1
+ if (this.#caches.has(cacheName)) {
+ // await caches.open('v1') !== await caches.open('v1')
-"use strict";
+ // 2.1.1
+ const cache = this.#caches.get(cacheName)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fs_1 = __nccwpck_require__(57147);
-class FragmentsHook {
- process(clones) {
- return Promise.all(clones.map((clone) => FragmentsHook.addFragments(clone)));
- }
- static addFragments(clone) {
- const codeA = fs_1.readFileSync(clone.duplicationA.sourceId).toString();
- const codeB = fs_1.readFileSync(clone.duplicationB.sourceId).toString();
- clone.duplicationA.fragment = codeA.substring(clone.duplicationA.range[0], clone.duplicationA.range[1]);
- clone.duplicationB.fragment = codeB.substring(clone.duplicationB.range[0], clone.duplicationB.range[1]);
- return clone;
+ // 2.1.1.1
+ return new Cache(kConstruct, cache)
}
-}
-exports.FragmentsHook = FragmentsHook;
-//# sourceMappingURL=fragment.js.map
-
-/***/ }),
-/***/ 88131:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(74574));
-__export(__nccwpck_require__(44810));
-//# sourceMappingURL=index.js.map
+ // 2.2
+ const cache = []
-/***/ }),
+ // 2.3
+ this.#caches.set(cacheName, cache)
-/***/ 88241:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2.4
+ return new Cache(kConstruct, cache)
+ }
-"use strict";
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const core_1 = __nccwpck_require__(84511);
-const tokenizer_1 = __nccwpck_require__(92080);
-const validators_1 = __nccwpck_require__(20733);
-class InFilesDetector {
- constructor(tokenizer, store, statistic, options) {
- this.tokenizer = tokenizer;
- this.store = store;
- this.statistic = statistic;
- this.options = options;
- this.reporters = [];
- this.subscribes = [];
- this.postHooks = [];
- this.registerSubscriber(this.statistic);
- }
- registerReporter(reporter) {
- this.reporters.push(reporter);
- }
- registerSubscriber(subscriber) {
- this.subscribes.push(subscriber);
- }
- registerHook(hook) {
- this.postHooks.push(hook);
- }
- detect(fls) {
- const files = fls.filter((f) => !!f);
- if (files.length === 0) {
- return Promise.resolve([]);
- }
- const options = this.options;
- const hooks = [...this.postHooks];
- const store = this.store;
- const validators = [];
- if (options.skipLocal) {
- validators.push(new validators_1.SkipLocalValidator());
- }
- const detector = new core_1.Detector(this.tokenizer, store, validators, options);
- this.subscribes.forEach((listener) => {
- Object
- .entries(listener.subscribe())
- .map(([event, handler]) => detector.on(event, handler));
- });
- const detect = (entry, clones = []) => {
- const { path, content } = entry;
- const format = tokenizer_1.getFormatByFile(path, options.formatsExts);
- return detector
- .detect(path, content, format)
- .then((clns) => {
- if (clns) {
- clones.push(...clns);
- }
- const file = files.pop();
- if (file) {
- return detect(file, clones);
- }
- return clones;
- });
- };
- const processHooks = (hook, detectedClones) => {
- return hook
- .process(detectedClones)
- .then((clones) => {
- const nextHook = hooks.pop();
- if (nextHook) {
- return processHooks(nextHook, clones);
- }
- return clones;
- });
- };
- return detect(files.pop())
- .then((clones) => {
- const hook = hooks.pop();
- if (hook) {
- return processHooks(hook, clones);
- }
- return clones;
- })
- .then((clones) => {
- const statistic = this.statistic.getStatistic();
- this.reporters.forEach((reporter) => {
- reporter.report(clones, statistic);
- });
- return clones;
- });
- }
-}
-exports.InFilesDetector = InFilesDetector;
-//# sourceMappingURL=in-files-detector.js.map
+ cacheName = webidl.converters.DOMString(cacheName)
-/***/ }),
+ return this.#caches.delete(cacheName)
+ }
-/***/ 39148:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {string[]}
+ */
+ async keys () {
+ webidl.brandCheck(this, CacheStorage)
-"use strict";
+ // 2.1
+ const keys = this.#caches.keys()
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
+ // 2.2
+ return [...keys]
+ }
}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(88241));
-__export(__nccwpck_require__(51908));
-__export(__nccwpck_require__(88131));
-__export(__nccwpck_require__(48812));
-__export(__nccwpck_require__(16872));
-__export(__nccwpck_require__(20733));
-__export(__nccwpck_require__(43465));
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 57959:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CacheStorage',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const reports_1 = __nccwpck_require__(42083);
-const clone_found_1 = __nccwpck_require__(17304);
-const safe_1 = __nccwpck_require__(41997);
-const Table = __nccwpck_require__(2101);
-const TABLE_OPTIONS = {
- chars: {
- top: '',
- 'top-mid': '',
- 'top-left': '',
- 'top-right': '',
- bottom: '',
- 'bottom-mid': '',
- 'bottom-left': '',
- 'bottom-right': '',
- left: '',
- 'left-mid': '',
- mid: '',
- 'mid-mid': '',
- right: '',
- 'right-mid': '',
- middle: '│',
- },
-};
-class ConsoleFullReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones) {
- clones.forEach((clone) => {
- this.cloneFullFound(clone);
- });
- console.log(safe_1.grey(`Found ${clones.length} clones.`));
- }
- cloneFullFound(clone) {
- const table = new Table(TABLE_OPTIONS);
- clone_found_1.cloneFound(clone, this.options);
- clone.duplicationA.fragment.split('\n').forEach((line, position) => {
- (table).push(reports_1.generateLine(clone, position, line));
- });
- console.log(table.toString());
- console.log('');
- }
+module.exports = {
+ CacheStorage
}
-exports.ConsoleFullReporter = ConsoleFullReporter;
-//# sourceMappingURL=console-full.js.map
-
-/***/ }),
-
-/***/ 94513:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const safe_1 = __nccwpck_require__(41997);
-const reports_1 = __nccwpck_require__(42083);
-const Table = __nccwpck_require__(2101);
-class ConsoleReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones, statistic = undefined) {
- if (statistic && !this.options.silent) {
- const table = new Table({
- head: ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'],
- });
- Object.keys(statistic.formats)
- .filter((format) => statistic.formats[format].sources)
- .forEach((format) => {
- table.push(reports_1.convertStatisticToArray(format, statistic.formats[format].total));
- });
- table.push(reports_1.convertStatisticToArray(safe_1.bold('Total:'), statistic.total));
- console.log(table.toString());
- console.log(safe_1.grey(`Found ${clones.length} clones.`));
- }
- }
-}
-exports.ConsoleReporter = ConsoleReporter;
-//# sourceMappingURL=console.js.map
/***/ }),
-/***/ 54038:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const core_1 = __nccwpck_require__(84511);
-const fs_extra_1 = __nccwpck_require__(5630);
-const safe_1 = __nccwpck_require__(41997);
-const path_1 = __nccwpck_require__(71017);
-const reports_1 = __nccwpck_require__(42083);
-class CSVReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones, statistic) {
- const report = [
- ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'],
- ...Object.keys(statistic.formats).map((format) => reports_1.convertStatisticToArray(format, statistic.formats[format].total)),
- reports_1.convertStatisticToArray('Total:', statistic.total)
- ].map((arr) => arr.join(',')).join('\n');
- fs_extra_1.ensureDirSync(core_1.getOption('output', this.options));
- fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.csv', report);
- console.log(safe_1.green(`CSV report saved to ${path_1.join(this.options.output, 'jscpd-report.csv')}`));
- }
-}
-exports.CSVReporter = CSVReporter;
-//# sourceMappingURL=csv.js.map
-
-/***/ }),
+/***/ 296:
+/***/ ((module) => {
-/***/ 16872:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
+module.exports = {
+ kConstruct: Symbol('constructable')
}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(94513));
-__export(__nccwpck_require__(57959));
-__export(__nccwpck_require__(78634));
-__export(__nccwpck_require__(54038));
-__export(__nccwpck_require__(91708));
-__export(__nccwpck_require__(9319));
-__export(__nccwpck_require__(87850));
-__export(__nccwpck_require__(42639));
-__export(__nccwpck_require__(39774));
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-/***/ 78634:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fs_extra_1 = __nccwpck_require__(5630);
-const core_1 = __nccwpck_require__(84511);
-const reports_1 = __nccwpck_require__(42083);
-const safe_1 = __nccwpck_require__(41997);
-const path_1 = __nccwpck_require__(71017);
-class JsonReporter {
- constructor(options) {
- this.options = options;
- }
- generateJson(clones, statistics) {
- return {
- statistics,
- duplicates: clones.map(clone => this.cloneFound(clone))
- };
- }
- report(clones, statistic) {
- const json = this.generateJson(clones, statistic);
- fs_extra_1.ensureDirSync(core_1.getOption('output', this.options));
- fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.json', JSON.stringify(json, null, ' '));
- console.log(safe_1.green(`JSON report saved to ${path_1.join(this.options.output, 'jscpd-report.json')}`));
- }
- cloneFound(clone) {
- const startLineA = clone.duplicationA.start.line;
- const endLineA = clone.duplicationA.end.line;
- const startLineB = clone.duplicationB.start.line;
- const endLineB = clone.duplicationB.end.line;
- return {
- format: clone.format,
- lines: endLineA - startLineA + 1,
- fragment: clone.duplicationA.fragment,
- tokens: 0,
- firstFile: {
- name: reports_1.getPath(clone.duplicationA.sourceId, this.options),
- start: startLineA,
- end: endLineA,
- startLoc: clone.duplicationA.start,
- endLoc: clone.duplicationA.end,
- blame: clone.duplicationA.blame,
- },
- secondFile: {
- name: reports_1.getPath(clone.duplicationB.sourceId, this.options),
- start: startLineB,
- end: endLineB,
- startLoc: clone.duplicationB.start,
- endLoc: clone.duplicationB.end,
- blame: clone.duplicationB.blame,
- },
- };
- }
-}
-exports.JsonReporter = JsonReporter;
-//# sourceMappingURL=json.js.map
/***/ }),
-/***/ 91708:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const core_1 = __nccwpck_require__(84511);
-const fs_extra_1 = __nccwpck_require__(5630);
-const safe_1 = __nccwpck_require__(41997);
-const path_1 = __nccwpck_require__(71017);
-const reports_1 = __nccwpck_require__(42083);
-const table = __nccwpck_require__(41062);
-class MarkdownReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones, statistic) {
- const report = `
-# Copy/paste detection report
+/***/ 3993:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-> Duplications detection: Found ${clones.length} exact clones with ${statistic.total.duplicatedLines}(${statistic.total.percentage}%) duplicated lines in ${statistic.total.sources} (${Object.keys(statistic.formats).length} formats) files.
-${table([
- ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'],
- ...Object.keys(statistic.formats).map((format) => reports_1.convertStatisticToArray(format, statistic.formats[format].total)),
- reports_1.convertStatisticToArray('Total:', statistic.total).map(item => `**${item}**`)
- ])}
-`;
- fs_extra_1.ensureDirSync(core_1.getOption('output', this.options));
- fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.md', report);
- console.log(safe_1.green(`Markdown report saved to ${path_1.join(this.options.output, 'jscpd-report.md')}`));
- }
-}
-exports.MarkdownReporter = MarkdownReporter;
-//# sourceMappingURL=markdown.js.map
-/***/ }),
+const assert = __nccwpck_require__(2613)
+const { URLSerializer } = __nccwpck_require__(4322)
+const { isValidHeaderName } = __nccwpck_require__(5523)
-/***/ 87850:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/**
+ * @see https://url.spec.whatwg.org/#concept-url-equals
+ * @param {URL} A
+ * @param {URL} B
+ * @param {boolean | undefined} excludeFragment
+ * @returns {boolean}
+ */
+function urlEquals (A, B, excludeFragment = false) {
+ const serializedA = URLSerializer(A, excludeFragment)
-"use strict";
+ const serializedB = URLSerializer(B, excludeFragment)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const safe_1 = __nccwpck_require__(41997);
-class SilentReporter {
- report(clones, statistic) {
- if (statistic) {
- console.log(`Duplications detection: Found ${safe_1.bold(clones.length.toString())} ` +
- `exact clones with ${safe_1.bold(statistic.total.duplicatedLines.toString())}(${statistic.total.percentage}%) ` +
- `duplicated lines in ${safe_1.bold(statistic.total.sources.toString())} ` +
- `(${Object.keys(statistic.formats).length} formats) files.`);
- }
- }
+ return serializedA === serializedB
}
-exports.SilentReporter = SilentReporter;
-//# sourceMappingURL=silent.js.map
-/***/ }),
+/**
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
+ * @param {string} header
+ */
+function fieldValues (header) {
+ assert(header !== null)
-/***/ 42639:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const values = []
-"use strict";
+ for (let value of header.split(',')) {
+ value = value.trim()
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const safe_1 = __nccwpck_require__(41997);
-class ThresholdReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones, statistic) {
- if (statistic && this.options.threshold !== undefined && this.options.threshold < statistic.total.percentage) {
- const message = `ERROR: jscpd found too many duplicates (${statistic.total.percentage}%) over threshold (${this.options.threshold}%)`;
- console.error(safe_1.red(message));
- throw new Error(message);
- }
+ if (!value.length) {
+ continue
+ } else if (!isValidHeaderName(value)) {
+ continue
}
-}
-exports.ThresholdReporter = ThresholdReporter;
-//# sourceMappingURL=threshold.js.map
-
-/***/ }),
-/***/ 39774:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+ values.push(value)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const reports_1 = __nccwpck_require__(42083);
-class XcodeReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones) {
- clones.forEach((clone) => {
- this.cloneFound(clone);
- });
- console.log(`Found ${clones.length} clones.`);
- }
- cloneFound(clone) {
- const pathA = reports_1.getPath(clone.duplicationA.sourceId, Object.assign(Object.assign({}, this.options), { absolute: true }));
- const pathB = reports_1.getPath(clone.duplicationB.sourceId, this.options);
- const startLineA = clone.duplicationA.start.line;
- const characterA = clone.duplicationA.start.column;
- const endLineA = clone.duplicationA.end.line;
- const startLineB = clone.duplicationB.start.line;
- const endLineB = clone.duplicationB.end.line;
- console.log(`${pathA}:${startLineA}:${characterA}: warning: Found ${endLineA - startLineA} lines (${startLineA}-${endLineA}) duplicated on file ${pathB} (${startLineB}-${endLineB})`);
- }
+ return values
}
-exports.XcodeReporter = XcodeReporter;
-//# sourceMappingURL=xcode.js.map
-
-/***/ }),
-
-/***/ 9319:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fs_1 = __nccwpck_require__(57147);
-const fs_extra_1 = __nccwpck_require__(5630);
-const core_1 = __nccwpck_require__(84511);
-const reports_1 = __nccwpck_require__(42083);
-const safe_1 = __nccwpck_require__(41997);
-const path_1 = __nccwpck_require__(71017);
-class XmlReporter {
- constructor(options) {
- this.options = options;
- }
- report(clones) {
- let xmlDoc = '';
- xmlDoc += '';
- clones.forEach((clone) => {
- xmlDoc = `${xmlDoc}
-
-
- /i, 'CDATA_END')}]]>
-
-
- /i, 'CDATA_END')}]]>
-
- /i, 'CDATA_END')}]]>
-
- `;
- });
- xmlDoc += '';
- fs_extra_1.ensureDirSync(core_1.getOption('output', this.options));
- fs_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.xml', xmlDoc);
- console.log(safe_1.green(`XML report saved to ${path_1.join(this.options.output, 'jscpd-report.xml')}`));
- }
+module.exports = {
+ urlEquals,
+ fieldValues
}
-exports.XmlReporter = XmlReporter;
-//# sourceMappingURL=xml.js.map
-/***/ }),
-/***/ 48812:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ }),
-"use strict";
+/***/ 6197:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(14941));
-__export(__nccwpck_require__(10865));
-//# sourceMappingURL=index.js.map
+// @ts-check
-/***/ }),
-/***/ 14941:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+/* global WebAssembly */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const clone_found_1 = __nccwpck_require__(17304);
-class ProgressSubscriber {
- constructor(options) {
- this.options = options;
- }
- subscribe() {
- return {
- CLONE_FOUND: (payload) => clone_found_1.cloneFound(payload.clone, this.options),
- };
- }
-}
-exports.ProgressSubscriber = ProgressSubscriber;
-//# sourceMappingURL=progress.js.map
-
-/***/ }),
-
-/***/ 10865:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+const assert = __nccwpck_require__(2613)
+const net = __nccwpck_require__(9278)
+const { pipeline } = __nccwpck_require__(2203)
+const util = __nccwpck_require__(3440)
+const timers = __nccwpck_require__(8804)
+const Request = __nccwpck_require__(4655)
+const DispatcherBase = __nccwpck_require__(1)
+const {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ InvalidArgumentError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError,
+ ClientDestroyedError
+} = __nccwpck_require__(8707)
+const buildConnector = __nccwpck_require__(9136)
+const {
+ kUrl,
+ kReset,
+ kServerName,
+ kClient,
+ kBusy,
+ kParser,
+ kConnect,
+ kBlocking,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRedirections,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kInterceptors,
+ kLocalAddress,
+ kMaxResponseSize,
+ kHTTPConnVersion,
+ // HTTP2
+ kHost,
+ kHTTP2Session,
+ kHTTP2SessionState,
+ kHTTP2BuildRequest,
+ kHTTP2CopyHeaders,
+ kHTTP1BuildRequest
+} = __nccwpck_require__(6443)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const safe_1 = __nccwpck_require__(41997);
-class VerboseSubscriber {
- constructor(options) {
- this.options = options;
- }
- subscribe() {
- return {
- 'CLONE_FOUND': (payload) => {
- const { clone } = payload;
- console.log(safe_1.yellow('CLONE_FOUND'));
- console.log(safe_1.grey(JSON.stringify(clone, null, '\t')));
- },
- 'CLONE_SKIPPED': (payload) => {
- const { validation } = payload;
- console.log(safe_1.yellow('CLONE_SKIPPED'));
- console.log(safe_1.grey('Clone skipped: ' + validation.message.join(' ')));
- },
- 'START_DETECTION': (payload) => {
- const { source } = payload;
- console.log(safe_1.yellow('START_DETECTION'));
- console.log(safe_1.grey('Start detection for source id=' + source.getId() + ' format=' + source.getFormat()));
- },
- };
- }
+/** @type {import('http2')} */
+let http2
+try {
+ http2 = __nccwpck_require__(5675)
+} catch {
+ // @ts-ignore
+ http2 = { constants: {} }
}
-exports.VerboseSubscriber = VerboseSubscriber;
-//# sourceMappingURL=verbose.js.map
-
-/***/ }),
-
-/***/ 17304:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+const {
+ constants: {
+ HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_PATH,
+ HTTP2_HEADER_CONTENT_LENGTH,
+ HTTP2_HEADER_EXPECT,
+ HTTP2_HEADER_STATUS
+ }
+} = http2
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const safe_1 = __nccwpck_require__(41997);
-const reports_1 = __nccwpck_require__(42083);
-function cloneFound(clone, options) {
- const { duplicationA, duplicationB, format, isNew } = clone;
- console.log('Clone found (' + format + '):' + (isNew ? safe_1.red('*') : ''));
- console.log(` - ${reports_1.getPathConsoleString(duplicationA.sourceId, options)} [${reports_1.getSourceLocation(duplicationA.start, duplicationA.end)}] (${duplicationA.end.line - duplicationA.start.line} lines${duplicationA.end.position ? ', ' + (duplicationA.end.position - duplicationA.start.position) + ' tokens' : ''})`);
- console.log(` ${reports_1.getPathConsoleString(duplicationB.sourceId, options)} [${reports_1.getSourceLocation(duplicationB.start, duplicationB.end)}]`);
- console.log('');
-}
-exports.cloneFound = cloneFound;
-//# sourceMappingURL=clone-found.js.map
+// Experimental
+let h2ExperimentalWarned = false
-/***/ }),
+const FastBuffer = Buffer[Symbol.species]
-/***/ 43465:
-/***/ ((__unused_webpack_module, exports) => {
+const kClosedResolve = Symbol('kClosedResolve')
-"use strict";
+const channels = {}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-function parseFormatsExtensions(extensions = '') {
- const result = {};
- if (!extensions) {
- return undefined;
- }
- extensions.split(';').forEach((format) => {
- const pair = format.split(':');
- result[pair[0]] = pair[1].split(',');
- });
- return result;
+try {
+ const diagnosticsChannel = __nccwpck_require__(1637)
+ channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
+ channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
+ channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
+ channels.connected = diagnosticsChannel.channel('undici:client:connected')
+} catch {
+ channels.sendHeaders = { hasSubscribers: false }
+ channels.beforeConnect = { hasSubscribers: false }
+ channels.connectError = { hasSubscribers: false }
+ channels.connected = { hasSubscribers: false }
}
-exports.parseFormatsExtensions = parseFormatsExtensions;
-//# sourceMappingURL=options.js.map
-
-/***/ }),
-
-/***/ 42083:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+/**
+ * @type {import('../types/client').default}
+ */
+class Client extends DispatcherBase {
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../types/client').Client.Options} options
+ */
+ constructor (url, {
+ interceptors,
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ maxRedirections,
+ connect,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ allowH2,
+ maxConcurrentStreams
+ } = {}) {
+ super()
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path_1 = __nccwpck_require__(71017);
-const process_1 = __nccwpck_require__(77282);
-const safe_1 = __nccwpck_require__(41997);
-exports.compareDates = (firstDate, secondDate) => {
- const first = new Date(firstDate);
- const second = new Date(secondDate);
- switch (true) {
- case first < second:
- return '=>';
- case first > second:
- return '<=';
- default:
- return '==';
- }
-};
-function escapeXml(unsafe) {
- return unsafe.replace(/[<>&'"]/g, function (c) {
- switch (c) {
- case '<': return '<';
- case '>': return '>';
- case '&': return '&';
- case '\'': return ''';
- case '"': return '"';
- }
- });
-}
-exports.escapeXml = escapeXml;
-function getPath(path, options) {
- return options.absolute ? path : path_1.relative(process_1.cwd(), path);
-}
-exports.getPath = getPath;
-function getPathConsoleString(path, options) {
- return safe_1.bold(safe_1.green(getPath(path, options)));
-}
-exports.getPathConsoleString = getPathConsoleString;
-function getSourceLocation(start, end) {
- return `${start.line}:${start.column} - ${end.line}:${end.column}`;
-}
-exports.getSourceLocation = getSourceLocation;
-function generateLine(clone, position, line) {
- const lineNumberA = (clone.duplicationA.start.line + position).toString();
- const lineNumberB = (clone.duplicationB.start.line + position).toString();
- if (clone.duplicationA.blame && clone.duplicationB.blame) {
- return [
- lineNumberA,
- clone.duplicationA.blame[lineNumberA] ? clone.duplicationA.blame[lineNumberA].author : '',
- clone.duplicationA.blame[lineNumberA] && clone.duplicationB.blame[lineNumberB]
- ? exports.compareDates(clone.duplicationA.blame[lineNumberA].date, clone.duplicationB.blame[lineNumberB].date)
- : '',
- lineNumberB,
- clone.duplicationB.blame[lineNumberB] ? clone.duplicationB.blame[lineNumberB].author : '',
- safe_1.grey(line),
- ];
+ if (keepAlive !== undefined) {
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
}
- else {
- return [lineNumberA, lineNumberB, safe_1.grey(line)];
+
+ if (socketTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
}
-}
-exports.generateLine = generateLine;
-function convertStatisticToArray(format, statistic) {
- return [
- format,
- `${statistic.sources}`,
- `${statistic.lines}`,
- `${statistic.tokens}`,
- `${statistic.clones}`,
- `${statistic.duplicatedLines} (${statistic.percentage}%)`,
- `${statistic.duplicatedTokens} (${statistic.percentageTokens}%)`,
- ];
-}
-exports.convertStatisticToArray = convertStatisticToArray;
-//# sourceMappingURL=reports.js.map
-/***/ }),
+ if (requestTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
+ }
-/***/ 20733:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (idleTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
+ }
-"use strict";
+ if (maxKeepAliveTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
+ }
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__export(__nccwpck_require__(69653));
-//# sourceMappingURL=index.js.map
+ if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
+ throw new InvalidArgumentError('invalid maxHeaderSize')
+ }
-/***/ }),
+ if (socketPath != null && typeof socketPath !== 'string') {
+ throw new InvalidArgumentError('invalid socketPath')
+ }
-/***/ 69653:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
+ throw new InvalidArgumentError('invalid connectTimeout')
+ }
-"use strict";
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const core_1 = __nccwpck_require__(84511);
-const path_1 = __nccwpck_require__(71017);
-class SkipLocalValidator {
- validate(clone, options) {
- const status = !this.shouldSkipClone(clone, options);
- return {
- status,
- clone,
- message: [
- `Sources of duplication located in same local folder (${clone.duplicationA.sourceId}, ${clone.duplicationB.sourceId})`
- ]
- };
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
}
- shouldSkipClone(clone, options) {
- const path = core_1.getOption('path', options);
- return path.some((dir) => SkipLocalValidator.isRelative(clone.duplicationA.sourceId, dir) && SkipLocalValidator.isRelative(clone.duplicationB.sourceId, dir));
+
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
}
- static isRelative(file, path) {
- const rel = path_1.relative(path, file);
- return rel !== '' && !rel.startsWith('..') && !path_1.isAbsolute(rel);
+
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
}
-}
-exports.SkipLocalValidator = SkipLocalValidator;
-//# sourceMappingURL=skip-local.validator.js.map
-/***/ }),
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
+ }
-/***/ 71084:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
-"use strict";
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path_1 = __nccwpck_require__(71017);
-const finder_1 = __nccwpck_require__(39148);
-const fs_extra_1 = __nccwpck_require__(5630);
-const safe_1 = __nccwpck_require__(41997);
-const pug = __nccwpck_require__(40316);
-class HtmlReporter {
- constructor(options) {
- this.options = options;
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
}
- report(clones, statistic) {
- const jsonReporter = new finder_1.JsonReporter(this.options);
- const json = jsonReporter.generateJson(clones, statistic);
- const result = pug.renderFile(__nccwpck_require__.ab + "main.pug", json);
- if (this.options.output) {
- const destination = path_1.join(this.options.output, 'html/');
- try {
- fs_extra_1.copySync(__nccwpck_require__.ab + "public", destination, { overwrite: true });
- const index = path_1.join(destination, 'index.html');
- fs_extra_1.writeFileSync(index, result);
- fs_extra_1.writeFileSync(path_1.join(destination, 'jscpd-report.json'), JSON.stringify(json, null, ' '));
- console.log(safe_1.green(`HTML report saved to ${path_1.join(this.options.output, 'html/')}`));
- }
- catch (e) {
- console.log(safe_1.red(e));
- }
- }
+
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
}
-}
-exports["default"] = HtmlReporter;
-//# sourceMappingURL=index.js.map
-/***/ }),
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
+ }
-/***/ 85049:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (
+ autoSelectFamilyAttemptTimeout != null &&
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
+ ) {
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
+ }
-"use strict";
+ // h2
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path_1 = __nccwpck_require__(71017);
-exports.FORMATS = {
- abap: {
- exts: [],
- },
- actionscript: {
- exts: ['as'],
- },
- ada: {
- exts: ['ada'],
- },
- apacheconf: {
- exts: [],
- },
- apl: {
- exts: ['apl'],
- },
- applescript: {
- exts: [],
- },
- arduino: {
- exts: [],
- },
- arff: {
- exts: [],
- },
- asciidoc: {
- exts: [],
- },
- asm6502: {
- exts: [],
- },
- aspnet: {
- exts: ['asp', 'aspx'],
- },
- autohotkey: {
- exts: [],
- },
- autoit: {
- exts: [],
- },
- bash: {
- exts: ['sh', 'ksh', 'bash'],
- },
- basic: {
- exts: ['bas'],
- },
- batch: {
- exts: [],
- },
- bison: {
- exts: [],
- },
- brainfuck: {
- exts: ['b', 'bf'],
- },
- bro: {
- exts: [],
- },
- c: {
- exts: ['c', 'z80'],
- },
- 'c-header': {
- exts: ['h'],
- parent: 'c',
- },
- clike: {
- exts: [],
- },
- clojure: {
- exts: ['cljs', 'clj', 'cljc', 'cljx', 'edn'],
- },
- coffeescript: {
- exts: ['coffee'],
- },
- comments: {
- exts: []
- },
- cpp: {
- exts: ['cpp', 'c++', 'cc', 'cxx'],
- },
- 'cpp-header': {
- exts: ['hpp', 'h++', 'hh', 'hxx'],
- parent: 'cpp',
- },
- crystal: {
- exts: ['cr'],
- },
- csharp: {
- exts: ['cs'],
- },
- csp: {
- exts: [],
- },
- 'css-extras': {
- exts: [],
- },
- css: {
- exts: ['css', 'gss'],
- },
- d: {
- exts: ['d'],
- },
- dart: {
- exts: ['dart'],
- },
- diff: {
- exts: ['diff', 'patch'],
- },
- django: {
- exts: [],
- },
- docker: {
- exts: [],
- },
- eiffel: {
- exts: ['e'],
- },
- elixir: {
- exts: [],
- },
- elm: {
- exts: ['elm'],
- },
- erb: {
- exts: [],
- },
- erlang: {
- exts: ['erl', 'erlang'],
- },
- flow: {
- exts: [],
- },
- fortran: {
- exts: ['f', 'for', 'f77', 'f90'],
- },
- fsharp: {
- exts: ['fs'],
- },
- gedcom: {
- exts: [],
- },
- gherkin: {
- exts: ['feature'],
- },
- git: {
- exts: [],
- },
- glsl: {
- exts: [],
- },
- go: {
- exts: ['go'],
- },
- graphql: {
- exts: ['graphql'],
- },
- groovy: {
- exts: ['groovy', 'gradle'],
- },
- haml: {
- exts: ['haml'],
- },
- handlebars: {
- exts: ['hb', 'hbs', 'handlebars'],
- },
- haskell: {
- exts: ['hs', 'lhs '],
- },
- haxe: {
- exts: ['hx', 'hxml'],
- },
- hpkp: {
- exts: [],
- },
- hsts: {
- exts: [],
- },
- http: {
- exts: [],
- },
- ichigojam: {
- exts: [],
- },
- icon: {
- exts: [],
- },
- inform7: {
- exts: [],
- },
- ini: {
- exts: ['ini'],
- },
- io: {
- exts: [],
- },
- j: {
- exts: [],
- },
- java: {
- exts: ['java'],
- },
- javascript: {
- exts: ['js', 'es', 'es6', 'mjs', 'cjs'],
- },
- jolie: {
- exts: [],
- },
- json: {
- exts: ['json', 'map', 'jsonld'],
- },
- jsx: {
- exts: ['jsx'],
- },
- julia: {
- exts: ['jl'],
- },
- keymap: {
- exts: [],
- },
- kotlin: {
- exts: ['kt', 'kts'],
- },
- latex: {
- exts: ['tex'],
- },
- less: {
- exts: ['less'],
- },
- liquid: {
- exts: [],
- },
- lisp: {
- exts: ['cl', 'lisp', 'el'],
- },
- livescript: {
- exts: ['ls'],
- },
- lolcode: {
- exts: [],
- },
- lua: {
- exts: ['lua'],
- },
- makefile: {
- exts: [],
- },
- markdown: {
- exts: ['md', 'markdown', 'mkd', 'txt'],
- },
- markup: {
- exts: ['html', 'htm', 'xml', 'xsl', 'xslt', 'svg', 'vue', 'ejs', 'jsp'],
- },
- matlab: {
- exts: [],
- },
- mel: {
- exts: [],
- },
- mizar: {
- exts: [],
- },
- monkey: {
- exts: [],
- },
- n4js: {
- exts: [],
- },
- nasm: {
- exts: [],
- },
- nginx: {
- exts: [],
- },
- nim: {
- exts: [],
- },
- nix: {
- exts: [],
- },
- nsis: {
- exts: ['nsh', 'nsi'],
- },
- objectivec: {
- exts: ['m', 'mm'],
- },
- ocaml: {
- exts: ['ocaml', 'ml', 'mli', 'mll', 'mly'],
- },
- opencl: {
- exts: [],
- },
- oz: {
- exts: ['oz'],
- },
- parigp: {
- exts: [],
- },
- pascal: {
- exts: ['pas', 'p'],
- },
- perl: {
- exts: ['pl', 'pm'],
- },
- php: {
- exts: ['php', 'phtml'],
- },
- plsql: {
- exts: ['plsql'],
- },
- powershell: {
- exts: ['ps1', 'psd1', 'psm1'],
- },
- processing: {
- exts: [],
- },
- prolog: {
- exts: ['pro'],
- },
- properties: {
- exts: ['properties'],
- },
- protobuf: {
- exts: ['proto'],
- },
- pug: {
- exts: ['pug', 'jade'],
- },
- puppet: {
- exts: ['pp', 'puppet'],
- },
- pure: {
- exts: [],
- },
- python: {
- exts: ['py', 'pyx', 'pxd', 'pxi'],
- },
- q: {
- exts: ['q'],
- },
- qore: {
- exts: [],
- },
- r: {
- exts: ['r', 'R'],
- },
- reason: {
- exts: [],
- },
- renpy: {
- exts: [],
- },
- rest: {
- exts: [],
- },
- rip: {
- exts: [],
- },
- roboconf: {
- exts: [],
- },
- ruby: {
- exts: ['rb'],
- },
- rust: {
- exts: ['rs'],
- },
- sas: {
- exts: ['sas'],
- },
- sass: {
- exts: ['sass'],
- },
- scala: {
- exts: ['scala'],
- },
- scheme: {
- exts: ['scm', 'ss'],
- },
- scss: {
- exts: ['scss'],
- },
- smalltalk: {
- exts: ['st'],
- },
- smarty: {
- exts: ['smarty', 'tpl'],
- },
- soy: {
- exts: ['soy'],
- },
- sql: {
- exts: ['sql', 'cql'],
- },
- stylus: {
- exts: ['styl', 'stylus'],
- },
- swift: {
- exts: ['swift'],
- },
- tap: {
- exts: ['tap'],
- },
- tcl: {
- exts: ['tcl'],
- },
- textile: {
- exts: ['textile'],
- },
- tsx: {
- exts: ['tsx'],
- },
- tt2: {
- exts: ['tt2'],
- },
- twig: {
- exts: ['twig'],
- },
- typescript: {
- exts: ['ts', 'mts', 'cts'],
- },
- vbnet: {
- exts: ['vb'],
- },
- velocity: {
- exts: ['vtl'],
- },
- verilog: {
- exts: ['v'],
- },
- vhdl: {
- exts: ['vhd', 'vhdl'],
- },
- vim: {
- exts: [],
- },
- 'visual-basic': {
- exts: ['vb'],
- },
- wasm: {
- exts: [],
- },
- url: {
- exts: [],
- },
- wiki: {
- exts: [],
- },
- xeora: {
- exts: [],
- },
- xojo: {
- exts: [],
- },
- xquery: {
- exts: ['xy', 'xquery'],
- },
- yaml: {
- exts: ['yaml', 'yml'],
- },
-};
-function getSupportedFormats() {
- return Object.keys(exports.FORMATS).filter((name) => name !== 'important' && name !== 'url');
-}
-exports.getSupportedFormats = getSupportedFormats;
-function getFormatByFile(path, formatsExts) {
- const ext = path_1.extname(path).slice(1);
- if (formatsExts && Object.keys(formatsExts).length) {
- return Object.keys(formatsExts).find((format) => formatsExts[format].includes(ext));
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
}
- return Object.keys(exports.FORMATS).find((language) => exports.FORMATS[language].exts.includes(ext));
-}
-exports.getFormatByFile = getFormatByFile;
-//# sourceMappingURL=formats.js.map
-/***/ }),
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
-/***/ 53524:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
+ ? interceptors.Client
+ : [createRedirectInterceptor({ maxRedirections })]
+ this[kUrl] = util.parseOrigin(url)
+ this[kConnector] = connect
+ this[kSocket] = null
+ this[kPipelining] = pipelining != null ? pipelining : 1
+ this[kMaxHeadersSize] = maxHeaderSize || 16384
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
+ this[kServerName] = null
+ this[kLocalAddress] = localAddress != null ? localAddress : null
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
+ this[kMaxRedirections] = maxRedirections
+ this[kMaxRequests] = maxRequestsPerClient
+ this[kClosedResolve] = null
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
+ this[kHTTPConnVersion] = 'h1'
-"use strict";
+ // HTTP/2
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = !allowH2
+ ? null
+ : {
+ // streams: null, // Fixed queue of streams - For future support of `push`
+ openStreams: 0, // Keep track of them to decide wether or not unref the session
+ maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
+ }
+ this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const reprism = __nccwpck_require__(18042);
-const abap = __nccwpck_require__(65444);
-const actionscript = __nccwpck_require__(21019);
-const ada = __nccwpck_require__(99040);
-const apacheconf = __nccwpck_require__(70629);
-const apl = __nccwpck_require__(13529);
-const applescript = __nccwpck_require__(95394);
-const arff = __nccwpck_require__(56245);
-const asciidoc = __nccwpck_require__(86002);
-const asm6502 = __nccwpck_require__(68737);
-const aspnet = __nccwpck_require__(16326);
-const autohotkey = __nccwpck_require__(3183);
-const autoit = __nccwpck_require__(41502);
-const bash = __nccwpck_require__(15209);
-const basic = __nccwpck_require__(46676);
-const batch = __nccwpck_require__(20986);
-const brainfuck = __nccwpck_require__(64636);
-const bro = __nccwpck_require__(57206);
-const c = __nccwpck_require__(98220);
-const clike = __nccwpck_require__(17403);
-const clojure = __nccwpck_require__(45685);
-const coffeescript = __nccwpck_require__(20525);
-const cpp = __nccwpck_require__(26433);
-const csharp = __nccwpck_require__(3204);
-const csp = __nccwpck_require__(12115);
-const cssExtras = __nccwpck_require__(16590);
-const css = __nccwpck_require__(58302);
-const d = __nccwpck_require__(60310);
-const dart = __nccwpck_require__(14572);
-const diff = __nccwpck_require__(35844);
-const django = __nccwpck_require__(97535);
-const docker = __nccwpck_require__(94508);
-const eiffel = __nccwpck_require__(79209);
-const elixir = __nccwpck_require__(74952);
-const erlang = __nccwpck_require__(15691);
-const flow = __nccwpck_require__(53794);
-const fortran = __nccwpck_require__(90374);
-const fsharp = __nccwpck_require__(63354);
-const gedcom = __nccwpck_require__(25605);
-const gherkin = __nccwpck_require__(14194);
-const git = __nccwpck_require__(96602);
-const glsl = __nccwpck_require__(96860);
-const go = __nccwpck_require__(96509);
-const graphql = __nccwpck_require__(6219);
-const groovy = __nccwpck_require__(90897);
-const haml = __nccwpck_require__(33412);
-const handlebars = __nccwpck_require__(62023);
-const haskell = __nccwpck_require__(2524);
-const haxe = __nccwpck_require__(7267);
-const hpkp = __nccwpck_require__(358);
-const hsts = __nccwpck_require__(42669);
-const http = __nccwpck_require__(7378);
-const ichigojam = __nccwpck_require__(79406);
-const icon = __nccwpck_require__(87849);
-const inform7 = __nccwpck_require__(63411);
-const ini = __nccwpck_require__(49597);
-const io = __nccwpck_require__(28985);
-const j = __nccwpck_require__(83738);
-const java = __nccwpck_require__(47998);
-const javascript = __nccwpck_require__(48430);
-const jolie = __nccwpck_require__(37234);
-const json = __nccwpck_require__(96317);
-const jsx = __nccwpck_require__(16054);
-const julia = __nccwpck_require__(18521);
-const keyman = __nccwpck_require__(1453);
-const kotlin = __nccwpck_require__(69707);
-const latex = __nccwpck_require__(78387);
-const less = __nccwpck_require__(25526);
-const liquid = __nccwpck_require__(110);
-const lisp = __nccwpck_require__(5716);
-const livescript = __nccwpck_require__(4273);
-const lolcode = __nccwpck_require__(78908);
-const lua = __nccwpck_require__(28482);
-const makefile = __nccwpck_require__(65822);
-const markdown = __nccwpck_require__(20518);
-const markupTemplating = __nccwpck_require__(8914);
-const markup = __nccwpck_require__(42152);
-const matlab = __nccwpck_require__(21372);
-const mel = __nccwpck_require__(19177);
-const mizar = __nccwpck_require__(37457);
-const monkey = __nccwpck_require__(26314);
-const n4js = __nccwpck_require__(41630);
-const nasm = __nccwpck_require__(57062);
-const nginx = __nccwpck_require__(44909);
-const nim = __nccwpck_require__(64441);
-const nix = __nccwpck_require__(51758);
-const nsis = __nccwpck_require__(47159);
-const objectivec = __nccwpck_require__(41466);
-const ocaml = __nccwpck_require__(20505);
-const opencl = __nccwpck_require__(24484);
-const oz = __nccwpck_require__(70834);
-const parigp = __nccwpck_require__(29775);
-const parser = __nccwpck_require__(28480);
-const pascal = __nccwpck_require__(98305);
-const perl = __nccwpck_require__(46306);
-const phpExtras = __nccwpck_require__(78800);
-const php = __nccwpck_require__(92619);
-const powershell = __nccwpck_require__(31896);
-const processing = __nccwpck_require__(63028);
-const prolog = __nccwpck_require__(11831);
-const properties = __nccwpck_require__(6971);
-const protobuf = __nccwpck_require__(9802);
-const pug = __nccwpck_require__(47602);
-const puppet = __nccwpck_require__(16015);
-const pure = __nccwpck_require__(96047);
-const python = __nccwpck_require__(42212);
-const q = __nccwpck_require__(70061);
-const qore = __nccwpck_require__(97631);
-const r = __nccwpck_require__(20420);
-const reason = __nccwpck_require__(39443);
-const renpy = __nccwpck_require__(48755);
-const rest = __nccwpck_require__(57652);
-const rip = __nccwpck_require__(11090);
-const roboconf = __nccwpck_require__(72149);
-const ruby = __nccwpck_require__(40415);
-const rust = __nccwpck_require__(93399);
-const sas = __nccwpck_require__(96939);
-const sass = __nccwpck_require__(37650);
-const scala = __nccwpck_require__(60988);
-const scheme = __nccwpck_require__(14150);
-const scss = __nccwpck_require__(56838);
-const smalltalk = __nccwpck_require__(81200);
-const smarty = __nccwpck_require__(94171);
-const soy = __nccwpck_require__(89135);
-const stylus = __nccwpck_require__(94920);
-const swift = __nccwpck_require__(58479);
-const tcl = __nccwpck_require__(59758);
-const textile = __nccwpck_require__(38347);
-const tsx = __nccwpck_require__(13220);
-const twig = __nccwpck_require__(99323);
-const typescript = __nccwpck_require__(148);
-const vbnet = __nccwpck_require__(15305);
-const velocity = __nccwpck_require__(16657);
-const verilog = __nccwpck_require__(26734);
-const vhdl = __nccwpck_require__(19450);
-const vim = __nccwpck_require__(38565);
-const visualBasic = __nccwpck_require__(58229);
-const wasm = __nccwpck_require__(63735);
-const wiki = __nccwpck_require__(9213);
-const xeora = __nccwpck_require__(93867);
-const xojo = __nccwpck_require__(81975);
-const yaml = __nccwpck_require__(54163);
-const tap = __nccwpck_require__(33636);
-const sql = __nccwpck_require__(19325);
-const plsql = __nccwpck_require__(23678);
-exports.languages = {
- abap, actionscript, ada, apacheconf, apl, applescript, arff,
- asciidoc, asm6502, aspnet, autohotkey, autoit, bash, basic, batch,
- brainfuck, bro, c, clike, clojure, coffeescript, cpp, csharp, csp, cssExtras,
- css, d, dart, diff, django, docker, eiffel, elixir, erlang, flow, fortran, fsharp,
- gedcom, gherkin, git, glsl, go, graphql, groovy, haml, handlebars, haskell, haxe,
- hpkp, hsts, http, ichigojam, icon, inform7, ini, io, j, java, javascript, jolie,
- json, jsx, julia, keyman, kotlin, latex, less, liquid, lisp, livescript,
- lolcode, lua, makefile, markdown, markupTemplating, markup, matlab, mel, mizar,
- monkey, n4js, nasm, nginx, nim, nix, nsis, objectivec, ocaml, opencl, oz, parigp,
- parser, pascal, perl, php, phpExtras, powershell, processing, prolog,
- properties, protobuf, pug, puppet, pure, python, q, qore, r, reason, renpy, rest,
- rip, roboconf, ruby, rust, sas, sass, scala, scheme, scss, smalltalk, smarty, soy,
- stylus, swift, tcl, textile, twig, typescript, vbnet, velocity, verilog, vhdl,
- vim, visualBasic, wasm, wiki, xeora, xojo, yaml, tsx, sql, plsql, tap
-};
-exports.loadLanguages = () => {
- reprism.loadLanguages(Object.values(exports.languages).map(v => v.default));
-};
-//# sourceMappingURL=grammar-loader.js.map
+ // kQueue is built up of 3 sections separated by
+ // the kRunningIdx and kPendingIdx indices.
+ // | complete | running | pending |
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
+ // kRunningIdx points to the first running element.
+ // kPendingIdx points to the first pending element.
+ // This implements a fast queue with an amortized
+ // time of O(1).
-/***/ }),
+ this[kQueue] = []
+ this[kRunningIdx] = 0
+ this[kPendingIdx] = 0
+ }
-/***/ 43439:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ get pipelining () {
+ return this[kPipelining]
+ }
-"use strict";
+ set pipelining (value) {
+ this[kPipelining] = value
+ resume(this, true)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const SparkMD5 = __nccwpck_require__(70220);
-function hash(value) {
- return SparkMD5.hash(value);
-}
-exports.hash = hash;
-//# sourceMappingURL=hash.js.map
+ get [kPending] () {
+ return this[kQueue].length - this[kPendingIdx]
+ }
-/***/ }),
+ get [kRunning] () {
+ return this[kPendingIdx] - this[kRunningIdx]
+ }
-/***/ 92080:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ get [kSize] () {
+ return this[kQueue].length - this[kRunningIdx]
+ }
-"use strict";
+ get [kConnected] () {
+ return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
+ }
-function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
-}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const tokenize_1 = __nccwpck_require__(74749);
-__export(__nccwpck_require__(74749));
-__export(__nccwpck_require__(78199));
-__export(__nccwpck_require__(85049));
-class Tokenizer {
- generateMaps(id, data, format, options) {
- return tokenize_1.createTokenMapBasedOnCode(id, data, format, options);
- }
-}
-exports.Tokenizer = Tokenizer;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
+ get [kBusy] () {
+ const socket = this[kSocket]
+ return (
+ (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
+ (this[kSize] >= (this[kPipelining] || 1)) ||
+ this[kPending] > 0
+ )
+ }
-/***/ 23678:
-/***/ ((__unused_webpack_module, exports) => {
+ /* istanbul ignore: only used for test */
+ [kConnect] (cb) {
+ connect(this)
+ this.once('connect', cb)
+ }
-"use strict";
+ [kDispatch] (opts, handler) {
+ const origin = opts.origin || this[kUrl].origin
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const grammar = {
- language: 'plsql',
- init(Prism) {
- Prism.languages.plsql = Prism.languages.extend('sql', {
- comment: [/\/\*[\s\S]*?\*\//, /--.*/],
- });
- if (Prism.util.type(Prism.languages.plsql.keyword) !== 'Array') {
- Prism.languages.plsql.keyword = [Prism.languages.plsql.keyword];
- }
- Prism.languages.plsql.keyword.unshift(/\b(?:ACCESS|AGENT|AGGREGATE|ARRAY|ARROW|AT|ATTRIBUTE|AUDIT|AUTHID|BFILE_BASE|BLOB_BASE|BLOCK|BODY|BOTH|BOUND|BYTE|CALLING|CHAR_BASE|CHARSET(?:FORM|ID)|CLOB_BASE|COLAUTH|COLLECT|CLUSTERS?|COMPILED|COMPRESS|CONSTANT|CONSTRUCTOR|CONTEXT|CRASH|CUSTOMDATUM|DANGLING|DATE_BASE|DEFINE|DETERMINISTIC|DURATION|ELEMENT|EMPTY|EXCEPTIONS?|EXCLUSIVE|EXTERNAL|FINAL|FORALL|FORM|FOUND|GENERAL|HEAP|HIDDEN|IDENTIFIED|IMMEDIATE|INCLUDING|INCREMENT|INDICATOR|INDEXES|INDICES|INFINITE|INITIAL|ISOPEN|INSTANTIABLE|INTERFACE|INVALIDATE|JAVA|LARGE|LEADING|LENGTH|LIBRARY|LIKE[24C]|LIMITED|LONG|LOOP|MAP|MAXEXTENTS|MAXLEN|MEMBER|MINUS|MLSLABEL|MULTISET|NAME|NAN|NATIVE|NEW|NOAUDIT|NOCOMPRESS|NOCOPY|NOTFOUND|NOWAIT|NUMBER(?:_BASE)?|OBJECT|OCI(?:COLL|DATE|DATETIME|DURATION|INTERVAL|LOBLOCATOR|NUMBER|RAW|REF|REFCURSOR|ROWID|STRING|TYPE)|OFFLINE|ONLINE|ONLY|OPAQUE|OPERATOR|ORACLE|ORADATA|ORGANIZATION|ORL(?:ANY|VARY)|OTHERS|OVERLAPS|OVERRIDING|PACKAGE|PARALLEL_ENABLE|PARAMETERS?|PASCAL|PCTFREE|PIPE(?:LINED)?|PRAGMA|PRIOR|PRIVATE|RAISE|RANGE|RAW|RECORD|REF|REFERENCE|REM|REMAINDER|RESULT|RESOURCE|RETURNING|REVERSE|ROW(?:ID|NUM|TYPE)|SAMPLE|SB[124]|SEGMENT|SELF|SEPARATE|SEQUENCE|SHORT|SIZE(?:_T)?|SPARSE|SQL(?:CODE|DATA|NAME|STATE)|STANDARD|STATIC|STDDEV|STORED|STRING|STRUCT|STYLE|SUBMULTISET|SUBPARTITION|SUBSTITUTABLE|SUBTYPE|SUCCESSFUL|SYNONYM|SYSDATE|TABAUTH|TDO|THE|TIMEZONE_(?:ABBR|HOUR|MINUTE|REGION)|TRAILING|TRANSAC(?:TIONAL)?|TRUSTED|UB[124]|UID|UNDER|UNTRUSTED|VALIDATE|VALIST|VARCHAR2|VARIABLE|VARIANCE|VARRAY|VIEWS|VOID|WHENEVER|WRAPPED|ZONE)\b/i);
- if (Prism.util.type(Prism.languages.plsql.operator) !== 'Array') {
- Prism.languages.plsql.operator = [Prism.languages.plsql.operator];
- }
- Prism.languages.plsql.operator.unshift(/:=/);
- },
-};
-exports["default"] = grammar;
-//# sourceMappingURL=plsql.js.map
+ const request = this[kHTTPConnVersion] === 'h2'
+ ? Request[kHTTP2BuildRequest](origin, opts, handler)
+ : Request[kHTTP1BuildRequest](origin, opts, handler)
-/***/ }),
+ this[kQueue].push(request)
+ if (this[kResuming]) {
+ // Do nothing.
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
+ // Wait a tick in case stream/iterator is ended in the same tick.
+ this[kResuming] = 1
+ process.nextTick(resume, this)
+ } else {
+ resume(this, true)
+ }
-/***/ 19325:
-/***/ ((__unused_webpack_module, exports) => {
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2
+ }
-"use strict";
+ return this[kNeedDrain] < 2
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const grammar = {
- language: 'sql',
- init(Prism) {
- Prism.languages.sql = {
- 'comment': {
- pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,
- lookbehind: true,
- },
- 'variable': [
- {
- pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,
- greedy: true,
- },
- /@[\w.$]+/,
- ],
- 'string': {
- pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,
- greedy: true,
- lookbehind: true,
- },
- 'function': /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,
- 'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,
- 'boolean': /\b(?:TRUE|FALSE|NULL)\b/i,
- 'number': /\b0x[\da-f]+\b|\b\d+\.?\d*|\B\.\d+\b/i,
- 'operator': /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
- 'punctuation': /[;[\]()`,.]/,
- };
- },
-};
-exports["default"] = grammar;
-//# sourceMappingURL=sql.js.map
+ async [kClose] () {
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
+ // request and close each stream.
+ return new Promise((resolve) => {
+ if (!this[kSize]) {
+ resolve(null)
+ } else {
+ this[kClosedResolve] = resolve
+ }
+ })
+ }
-/***/ }),
+ async [kDestroy] (err) {
+ return new Promise((resolve) => {
+ const requests = this[kQueue].splice(this[kPendingIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
-/***/ 33636:
-/***/ ((__unused_webpack_module, exports) => {
+ const callback = () => {
+ if (this[kClosedResolve]) {
+ // TODO (fix): Should we error here with ClientDestroyedError?
+ this[kClosedResolve]()
+ this[kClosedResolve] = null
+ }
+ resolve()
+ }
-"use strict";
+ if (this[kHTTP2Session] != null) {
+ util.destroy(this[kHTTP2Session], err)
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = null
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const grammar = {
- language: 'tap',
- init(Prism) {
- Prism.languages.tap = {
- fail: /not ok[^#{\n\r]*/,
- pass: /ok[^#{\n\r]*/,
- pragma: /pragma [+-][a-z]+/,
- bailout: /bail out!.*/i,
- version: /TAP version \d+/i,
- plan: /\d+\.\.\d+(?: +#.*)?/,
- subtest: {
- pattern: /# Subtest(?:: .*)?/,
- greedy: true
- },
- punctuation: /[{}]/,
- directive: /#.*/,
- yamlish: {
- pattern: /(^[ \t]*)---[\s\S]*?[\r\n][ \t]*\.\.\.$/m,
- lookbehind: true,
- inside: Prism.languages.yaml,
- alias: 'language-yaml'
- }
- };
- },
-};
-exports["default"] = grammar;
-//# sourceMappingURL=tap.js.map
+ if (!this[kSocket]) {
+ queueMicrotask(callback)
+ } else {
+ util.destroy(this[kSocket].on('close', callback), err)
+ }
-/***/ }),
+ resume(this)
+ })
+ }
+}
-/***/ 78199:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function onHttp2SessionError (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-"use strict";
+ this[kSocket][kError] = err
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const hash_1 = __nccwpck_require__(43439);
-const TOKEN_HASH_LENGTH = 20;
-function createTokenHash(token, hashFunction = undefined) {
- return hashFunction ?
- hashFunction(token.type + token.value).substr(0, TOKEN_HASH_LENGTH) :
- hash_1.hash(token.type + token.value).substr(0, TOKEN_HASH_LENGTH);
-}
-function groupByFormat(tokens) {
- const result = {};
- // TODO change to reduce
- tokens.forEach((token) => {
- (result[token.format] = result[token.format] ? [...result[token.format], token] : [token]);
- });
- return result;
-}
-class TokensMap {
- constructor(id, data, tokens, format, options) {
- this.id = id;
- this.data = data;
- this.tokens = tokens;
- this.format = format;
- this.options = options;
- this.position = 0;
- this.hashMap = this.tokens.map((token) => {
- if (options.ignoreCase) {
- token.value = token.value.toLocaleLowerCase();
- }
- return createTokenHash(token, this.options.hashFunction);
- }).join('');
- }
- getTokensCount() {
- return this.tokens[this.tokens.length - 1].loc.end.position - this.tokens[0].loc.start.position;
- }
- getId() {
- return this.id;
- }
- getLinesCount() {
- return this.tokens[this.tokens.length - 1].loc.end.line - this.tokens[0].loc.start.line;
- }
- getFormat() {
- return this.format;
- }
- [Symbol.iterator]() {
- return this;
- }
- next() {
- const hashFunction = this.options.hashFunction ? this.options.hashFunction : hash_1.hash;
- const mapFrame = hashFunction(this.hashMap.substring(this.position * TOKEN_HASH_LENGTH, this.position * TOKEN_HASH_LENGTH + this.options.minTokens * TOKEN_HASH_LENGTH)).substring(0, TOKEN_HASH_LENGTH);
- if (this.position < this.tokens.length - this.options.minTokens) {
- this.position++;
- return {
- done: false,
- value: {
- id: mapFrame,
- sourceId: this.getId(),
- start: this.tokens[this.position - 1],
- end: this.tokens[this.position + this.options.minTokens - 1],
- },
- };
- }
- else {
- return {
- done: true,
- value: false,
- };
- }
- }
-}
-exports.TokensMap = TokensMap;
-function generateMapsForFormats(id, data, tokens, options) {
- return Object
- .values(groupByFormat(tokens))
- .map((formatTokens) => new TokensMap(id, data, formatTokens, formatTokens[0].format, options));
-}
-exports.generateMapsForFormats = generateMapsForFormats;
-function createTokensMaps(id, data, tokens, options) {
- return generateMapsForFormats(id, data, tokens, options);
+ onError(this[kClient], err)
}
-exports.createTokensMaps = createTokensMaps;
-//# sourceMappingURL=token-map.js.map
-/***/ }),
+function onHttp2FrameError (type, code, id) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
-/***/ 74749:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (id === 0) {
+ this[kSocket][kError] = err
+ onError(this[kClient], err)
+ }
+}
-"use strict";
+function onHttp2SessionEnd () {
+ util.destroy(this, new SocketError('other side closed'))
+ util.destroy(this[kSocket], new SocketError('other side closed'))
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const reprism = __nccwpck_require__(18042);
-const formats_1 = __nccwpck_require__(85049);
-const token_map_1 = __nccwpck_require__(78199);
-const grammar_loader_1 = __nccwpck_require__(53524);
-const ignore = {
- ignore: [
- {
- pattern: /(jscpd:ignore-start)[\s\S]*?(?=jscpd:ignore-end)/,
- lookbehind: true,
- greedy: true,
- },
- {
- pattern: /jscpd:ignore-start/,
- greedy: false,
- },
- {
- pattern: /jscpd:ignore-end/,
- greedy: false,
- },
- ],
-};
-const punctuation = {
- // eslint-disable-next-line @typescript-eslint/camelcase
- new_line: /\n/,
- empty: /\s+/,
-};
-const initializeFormats = () => {
- grammar_loader_1.loadLanguages();
- Object
- .keys(reprism.default.languages)
- .forEach((lang) => {
- if (lang !== 'extend' && lang !== 'insertBefore' && lang !== 'DFS') {
- reprism.default.languages[lang] = Object.assign(Object.assign(Object.assign({}, ignore), reprism.default.languages[lang]), punctuation);
- }
- });
-};
-initializeFormats();
-function getLanguagePrismName(lang) {
- if (lang in formats_1.FORMATS && formats_1.FORMATS[lang].parent) {
- return formats_1.FORMATS[lang].parent;
- }
- return lang;
-}
-function tokenize(code, language) {
- let length = 0;
- let line = 1;
- let column = 1;
- function sanitizeLangName(name) {
- return name && name.replace ? name.replace('language-', '') : 'unknown';
- }
- function createTokenFromString(token, lang) {
- return [
- {
- format: lang,
- type: 'default',
- value: token,
- length: token.length,
- },
- ];
- }
- function calculateLocation(token, position) {
- const result = token;
- const lines = typeof result.value === 'string' && result.value.split ? result.value.split('\n') : [];
- const newLines = lines.length - 1;
- const start = {
- line,
- column,
- position
- };
- column = newLines >= 0 ? lines[lines.length - 1].length + 1 : column;
- const end = {
- line: line + newLines,
- column,
- position
- };
- result.loc = { start, end };
- result.range = [length, length + result.length];
- length += result.length;
- line += newLines;
- return result;
- }
- function createTokenFromFlatToken(token, lang) {
- return [
- {
- format: lang,
- type: token.type,
- value: token.content,
- length: token.length,
- },
- ];
- }
- function createTokens(token, lang) {
- if (token.content && typeof token.content === 'string') {
- return createTokenFromFlatToken(token, lang);
- }
- if (token.content && Array.isArray(token.content)) {
- let res = [];
- token.content.forEach((t) => (res = res.concat(createTokens(t, token.alias ? sanitizeLangName(token.alias) : lang))));
- return res;
- }
- return createTokenFromString(token, lang);
- }
- let tokens = [];
- const grammar = reprism.default.languages[getLanguagePrismName(language)];
- if (!reprism.default.languages[getLanguagePrismName(language)]) {
- console.warn('Warn: jscpd has issue with support of "' + getLanguagePrismName(language) + '"');
- return [];
- }
- reprism.default.tokenize(code, grammar)
- .forEach((t) => (tokens = tokens.concat(createTokens(t, language))));
- return tokens
- .filter((t) => t.format in formats_1.FORMATS)
- .map((token, index) => calculateLocation(token, index));
-}
-exports.tokenize = tokenize;
-function setupIgnorePatterns(format, ignorePattern) {
- const language = getLanguagePrismName(format);
- const ignorePatterns = ignorePattern.map(pattern => ({
- pattern: new RegExp(pattern),
- greedy: false,
- }));
- reprism.default.languages[language] = Object.assign(Object.assign({}, ignorePatterns), reprism.default.languages[language]);
-}
-function createTokenMapBasedOnCode(id, data, format, options = {}) {
- const { mode, ignoreCase, ignorePattern } = options;
- const tokens = tokenize(data, format)
- .filter((token) => mode(token, options));
- if (ignorePattern)
- setupIgnorePatterns(format, options.ignorePattern);
- if (ignoreCase) {
- return token_map_1.createTokensMaps(id, data, tokens.map((token) => {
- token.value = token.value.toLocaleLowerCase();
- return token;
- }), options);
- }
- return token_map_1.createTokensMaps(id, data, tokens, options);
-}
-exports.createTokenMapBasedOnCode = createTokenMapBasedOnCode;
-//# sourceMappingURL=tokenize.js.map
+function onHTTP2GoAway (code) {
+ const client = this[kClient]
+ const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
+ client[kSocket] = null
+ client[kHTTP2Session] = null
-/***/ }),
+ if (client.destroyed) {
+ assert(this[kPending] === 0)
-/***/ 63803:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+ } else if (client[kRunning] > 0) {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
-"use strict";
+ errorRequest(client, request, err)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(57147);
-exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs.lstat,
- stat: fs.stat,
- lstatSync: fs.lstatSync,
- statSync: fs.statSync,
- readdir: fs.readdir,
- readdirSync: fs.readdirSync
-};
-function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
- }
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
-}
-exports.createFileSystemAdapter = createFileSystemAdapter;
+ client[kPendingIdx] = client[kRunningIdx]
+ assert(client[kRunning] === 0)
-/***/ }),
+ client.emit('disconnect',
+ client[kUrl],
+ [client],
+ err
+ )
-/***/ 18838:
-/***/ ((__unused_webpack_module, exports) => {
+ resume(client)
+}
-"use strict";
+const constants = __nccwpck_require__(2824)
+const createRedirectInterceptor = __nccwpck_require__(4415)
+const EMPTY_BUF = Buffer.alloc(0)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
-const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
-if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
- throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
-}
-const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
-const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
-const SUPPORTED_MAJOR_VERSION = 10;
-const SUPPORTED_MINOR_VERSION = 10;
-const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
-const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
-/**
- * IS `true` for Node.js 10.10 and greater.
- */
-exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
+async function lazyllhttp () {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined
+ let mod
+ try {
+ mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64'))
+ } catch (e) {
+ /* istanbul ignore next */
-/***/ }),
+ // We could check if the error was caused by the simd option not
+ // being enabled, but the occurring of this other error
+ // * https://github.com/emscripten-core/emscripten/issues/11495
+ // got me to remove that check to avoid breaking Node 12.
+ mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64'))
+ }
-/***/ 75667:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return await WebAssembly.instantiate(mod, {
+ env: {
+ /* eslint-disable camelcase */
-"use strict";
+ wasm_on_url: (p, at, len) => {
+ /* istanbul ignore next */
+ return 0
+ },
+ wasm_on_status: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_begin: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageBegin() || 0
+ },
+ wasm_on_header_field: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_header_value: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
+ },
+ wasm_on_body: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_complete: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageComplete() || 0
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Settings = exports.scandirSync = exports.scandir = void 0;
-const async = __nccwpck_require__(84507);
-const sync = __nccwpck_require__(69560);
-const settings_1 = __nccwpck_require__(88662);
-exports.Settings = settings_1.default;
-function scandir(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- async.read(path, getSettings(), optionsOrSettingsOrCallback);
- return;
- }
- async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
-}
-exports.scandir = scandir;
-function scandirSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync.read(path, settings);
-}
-exports.scandirSync = scandirSync;
-function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings_1.default) {
- return settingsOrOptions;
+ /* eslint-enable camelcase */
}
- return new settings_1.default(settingsOrOptions);
+ })
}
+let llhttpInstance = null
+let llhttpPromise = lazyllhttp()
+llhttpPromise.catch()
-/***/ }),
-
-/***/ 84507:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+let currentParser = null
+let currentBufferRef = null
+let currentBufferSize = 0
+let currentBufferPtr = null
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
-const fsStat = __nccwpck_require__(70109);
-const rpl = __nccwpck_require__(75288);
-const constants_1 = __nccwpck_require__(18838);
-const utils = __nccwpck_require__(16297);
-const common = __nccwpck_require__(3847);
-function read(directory, settings, callback) {
- if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- readdirWithFileTypes(directory, settings, callback);
- return;
- }
- readdir(directory, settings, callback);
-}
-exports.read = read;
-function readdirWithFileTypes(directory, settings, callback) {
- settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
- if (readdirError !== null) {
- callFailureCallback(callback, readdirError);
- return;
- }
- const entries = dirents.map((dirent) => ({
- dirent,
- name: dirent.name,
- path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
- }));
- if (!settings.followSymbolicLinks) {
- callSuccessCallback(callback, entries);
- return;
- }
- const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
- rpl(tasks, (rplError, rplEntries) => {
- if (rplError !== null) {
- callFailureCallback(callback, rplError);
- return;
- }
- callSuccessCallback(callback, rplEntries);
- });
- });
-}
-exports.readdirWithFileTypes = readdirWithFileTypes;
-function makeRplTaskEntry(entry, settings) {
- return (done) => {
- if (!entry.dirent.isSymbolicLink()) {
- done(null, entry);
- return;
- }
- settings.fs.stat(entry.path, (statError, stats) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- done(statError);
- return;
- }
- done(null, entry);
- return;
- }
- entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
- done(null, entry);
- });
- };
-}
-function readdir(directory, settings, callback) {
- settings.fs.readdir(directory, (readdirError, names) => {
- if (readdirError !== null) {
- callFailureCallback(callback, readdirError);
- return;
- }
- const tasks = names.map((name) => {
- const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
- return (done) => {
- fsStat.stat(path, settings.fsStatSettings, (error, stats) => {
- if (error !== null) {
- done(error);
- return;
- }
- const entry = {
- name,
- path,
- dirent: utils.fs.createDirentFromStats(name, stats)
- };
- if (settings.stats) {
- entry.stats = stats;
- }
- done(null, entry);
- });
- };
- });
- rpl(tasks, (rplError, entries) => {
- if (rplError !== null) {
- callFailureCallback(callback, rplError);
- return;
- }
- callSuccessCallback(callback, entries);
- });
- });
-}
-exports.readdir = readdir;
-function callFailureCallback(callback, error) {
- callback(error);
-}
-function callSuccessCallback(callback, result) {
- callback(null, result);
-}
+const TIMEOUT_HEADERS = 1
+const TIMEOUT_BODY = 2
+const TIMEOUT_IDLE = 3
+class Parser {
+ constructor (client, socket, { exports }) {
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
-/***/ }),
+ this.llhttp = exports
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
+ this.client = client
+ this.socket = socket
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+ this.statusCode = null
+ this.statusText = ''
+ this.upgrade = false
+ this.headers = []
+ this.headersSize = 0
+ this.headersMaxSize = client[kMaxHeadersSize]
+ this.shouldKeepAlive = false
+ this.paused = false
+ this.resume = this.resume.bind(this)
-/***/ 3847:
-/***/ ((__unused_webpack_module, exports) => {
+ this.bytesRead = 0
-"use strict";
+ this.keepAlive = ''
+ this.contentLength = ''
+ this.connection = ''
+ this.maxResponseSize = client[kMaxResponseSize]
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.joinPathSegments = void 0;
-function joinPathSegments(a, b, separator) {
- /**
- * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
- */
- if (a.endsWith(separator)) {
- return a + b;
+ setTimeout (value, type) {
+ this.timeoutType = type
+ if (value !== this.timeoutValue) {
+ timers.clearTimeout(this.timeout)
+ if (value) {
+ this.timeout = timers.setTimeout(onParserTimeout, value, this)
+ // istanbul ignore else: only for jest
+ if (this.timeout.unref) {
+ this.timeout.unref()
+ }
+ } else {
+ this.timeout = null
+ }
+ this.timeoutValue = value
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
}
- return a + separator + b;
-}
-exports.joinPathSegments = joinPathSegments;
-
+ }
-/***/ }),
+ resume () {
+ if (this.socket.destroyed || !this.paused) {
+ return
+ }
-/***/ 69560:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ assert(this.ptr != null)
+ assert(currentParser == null)
-"use strict";
+ this.llhttp.llhttp_resume(this.ptr)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
-const fsStat = __nccwpck_require__(70109);
-const constants_1 = __nccwpck_require__(18838);
-const utils = __nccwpck_require__(16297);
-const common = __nccwpck_require__(3847);
-function read(directory, settings) {
- if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- return readdirWithFileTypes(directory, settings);
- }
- return readdir(directory, settings);
-}
-exports.read = read;
-function readdirWithFileTypes(directory, settings) {
- const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
- return dirents.map((dirent) => {
- const entry = {
- dirent,
- name: dirent.name,
- path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
- };
- if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
- try {
- const stats = settings.fs.statSync(entry.path);
- entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
- }
- catch (error) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- throw error;
- }
- }
- }
- return entry;
- });
-}
-exports.readdirWithFileTypes = readdirWithFileTypes;
-function readdir(directory, settings) {
- const names = settings.fs.readdirSync(directory);
- return names.map((name) => {
- const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
- const stats = fsStat.statSync(entryPath, settings.fsStatSettings);
- const entry = {
- name,
- path: entryPath,
- dirent: utils.fs.createDirentFromStats(name, stats)
- };
- if (settings.stats) {
- entry.stats = stats;
- }
- return entry;
- });
-}
-exports.readdir = readdir;
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+ this.paused = false
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
+ this.readMore()
+ }
-/***/ }),
+ readMore () {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read()
+ if (chunk === null) {
+ break
+ }
+ this.execute(chunk)
+ }
+ }
-/***/ 88662:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ execute (data) {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+ assert(!this.paused)
-"use strict";
+ const { socket, llhttp } = this
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(71017);
-const fsStat = __nccwpck_require__(70109);
-const fs = __nccwpck_require__(63803);
-class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
- this.fs = fs.createFileSystemAdapter(this._options.fs);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
- this.stats = this._getValue(this._options.stats, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- this.fsStatSettings = new fsStat.Settings({
- followSymbolicLink: this.followSymbolicLinks,
- fs: this.fs,
- throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
- });
- }
- _getValue(option, value) {
- return option !== null && option !== void 0 ? option : value;
+ if (data.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr)
+ }
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
}
-}
-exports["default"] = Settings;
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
-/***/ }),
+ // Call `execute` on the wasm parser.
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
+ // and finally the length of bytes to parse.
+ // The return value is an error code or `constants.ERROR.OK`.
+ try {
+ let ret
-/***/ 60883:
-/***/ ((__unused_webpack_module, exports) => {
+ try {
+ currentBufferRef = data
+ currentParser = this
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
+ /* eslint-disable-next-line no-useless-catch */
+ } catch (err) {
+ /* istanbul ignore next: difficult to make a test case for */
+ throw err
+ } finally {
+ currentParser = null
+ currentBufferRef = null
+ }
-"use strict";
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createDirentFromStats = void 0;
-class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data.slice(offset))
+ } else if (ret === constants.ERROR.PAUSED) {
+ this.paused = true
+ socket.unshift(data.slice(offset))
+ } else if (ret !== constants.ERROR.OK) {
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
+ let message = ''
+ /* istanbul ignore else: difficult to make a test case for */
+ if (ptr) {
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
+ message =
+ 'Response does not match the HTTP/1.1 protocol (' +
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
+ ')'
+ }
+ throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
+ }
+ } catch (err) {
+ util.destroy(socket, err)
}
-}
-function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
-}
-exports.createDirentFromStats = createDirentFromStats;
+ }
+ destroy () {
+ assert(this.ptr != null)
+ assert(currentParser == null)
-/***/ }),
+ this.llhttp.llhttp_free(this.ptr)
+ this.ptr = null
-/***/ 16297:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ timers.clearTimeout(this.timeout)
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
-"use strict";
+ this.paused = false
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.fs = void 0;
-const fs = __nccwpck_require__(60883);
-exports.fs = fs;
+ onStatus (buf) {
+ this.statusText = buf.toString()
+ }
+ onMessageBegin () {
+ const { socket, client } = this
-/***/ }),
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
-/***/ 32987:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const request = client[kQueue][client[kRunningIdx]]
+ if (!request) {
+ return -1
+ }
+ }
-"use strict";
+ onHeaderField (buf) {
+ const len = this.headers.length
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(57147);
-exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs.lstat,
- stat: fs.stat,
- lstatSync: fs.lstatSync,
- statSync: fs.statSync
-};
-function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
+ if ((len & 1) === 0) {
+ this.headers.push(buf)
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
}
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
-}
-exports.createFileSystemAdapter = createFileSystemAdapter;
+ this.trackHeader(buf.length)
+ }
-/***/ }),
-
-/***/ 70109:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ onHeaderValue (buf) {
+ let len = this.headers.length
-"use strict";
+ if ((len & 1) === 1) {
+ this.headers.push(buf)
+ len += 1
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.statSync = exports.stat = exports.Settings = void 0;
-const async = __nccwpck_require__(34147);
-const sync = __nccwpck_require__(34527);
-const settings_1 = __nccwpck_require__(12410);
-exports.Settings = settings_1.default;
-function stat(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- async.read(path, getSettings(), optionsOrSettingsOrCallback);
- return;
+ const key = this.headers[len - 2]
+ if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
+ this.keepAlive += buf.toString()
+ } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
+ this.connection += buf.toString()
+ } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
+ this.contentLength += buf.toString()
}
- async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
-}
-exports.stat = stat;
-function statSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync.read(path, settings);
-}
-exports.statSync = statSync;
-function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings_1.default) {
- return settingsOrOptions;
+
+ this.trackHeader(buf.length)
+ }
+
+ trackHeader (len) {
+ this.headersSize += len
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError())
}
- return new settings_1.default(settingsOrOptions);
-}
+ }
+ onUpgrade (head) {
+ const { upgrade, client, socket, headers, statusCode } = this
-/***/ }),
+ assert(upgrade)
-/***/ 34147:
-/***/ ((__unused_webpack_module, exports) => {
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
-"use strict";
+ assert(!socket.destroyed)
+ assert(socket === client[kSocket])
+ assert(!this.paused)
+ assert(request.upgrade || request.method === 'CONNECT')
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.read = void 0;
-function read(path, settings, callback) {
- settings.fs.lstat(path, (lstatError, lstat) => {
- if (lstatError !== null) {
- callFailureCallback(callback, lstatError);
- return;
- }
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- callSuccessCallback(callback, lstat);
- return;
- }
- settings.fs.stat(path, (statError, stat) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- callFailureCallback(callback, statError);
- return;
- }
- callSuccessCallback(callback, lstat);
- return;
- }
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
- callSuccessCallback(callback, stat);
- });
- });
-}
-exports.read = read;
-function callFailureCallback(callback, error) {
- callback(error);
-}
-function callSuccessCallback(callback, result) {
- callback(null, result);
-}
+ this.statusCode = null
+ this.statusText = ''
+ this.shouldKeepAlive = null
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
-/***/ }),
+ socket.unshift(head)
-/***/ 34527:
-/***/ ((__unused_webpack_module, exports) => {
+ socket[kParser].destroy()
+ socket[kParser] = null
-"use strict";
+ socket[kClient] = null
+ socket[kError] = null
+ socket
+ .removeListener('error', onSocketError)
+ .removeListener('readable', onSocketReadable)
+ .removeListener('end', onSocketEnd)
+ .removeListener('close', onSocketClose)
+
+ client[kSocket] = null
+ client[kQueue][client[kRunningIdx]++] = null
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.read = void 0;
-function read(path, settings) {
- const lstat = settings.fs.lstatSync(path);
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- return lstat;
- }
try {
- const stat = settings.fs.statSync(path);
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
- return stat;
- }
- catch (error) {
- if (!settings.throwErrorOnBrokenSymbolicLink) {
- return lstat;
- }
- throw error;
+ request.onUpgrade(statusCode, headers, socket)
+ } catch (err) {
+ util.destroy(socket, err)
}
-}
-exports.read = read;
+ resume(client)
+ }
-/***/ }),
-
-/***/ 12410:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fs = __nccwpck_require__(32987);
-class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
- this.fs = fs.createFileSystemAdapter(this._options.fs);
- this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- }
- _getValue(option, value) {
- return option !== null && option !== void 0 ? option : value;
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
}
-}
-exports["default"] = Settings;
+ const request = client[kQueue][client[kRunningIdx]]
-/***/ }),
-
-/***/ 26026:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ /* istanbul ignore next: difficult to make a test case for */
+ if (!request) {
+ return -1
+ }
-"use strict";
+ assert(!this.upgrade)
+ assert(this.statusCode < 200)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0;
-const async_1 = __nccwpck_require__(77523);
-const stream_1 = __nccwpck_require__(96737);
-const sync_1 = __nccwpck_require__(13068);
-const settings_1 = __nccwpck_require__(50141);
-exports.Settings = settings_1.default;
-function walk(directory, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
- return;
- }
- new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
-}
-exports.walk = walk;
-function walkSync(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new sync_1.default(directory, settings);
- return provider.read();
-}
-exports.walkSync = walkSync;
-function walkStream(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new stream_1.default(directory, settings);
- return provider.read();
-}
-exports.walkStream = walkStream;
-function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings_1.default) {
- return settingsOrOptions;
+ if (statusCode === 100) {
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
+ return -1
}
- return new settings_1.default(settingsOrOptions);
-}
+ /* this can only happen if server is misbehaving */
+ if (upgrade && !request.upgrade) {
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
+ return -1
+ }
-/***/ }),
+ assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
-/***/ 77523:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ this.statusCode = statusCode
+ this.shouldKeepAlive = (
+ shouldKeepAlive ||
+ // Override llhttp value which does not allow keepAlive for HEAD.
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
+ )
-"use strict";
+ if (this.statusCode >= 200) {
+ const bodyTimeout = request.bodyTimeout != null
+ ? request.bodyTimeout
+ : client[kBodyTimeout]
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const async_1 = __nccwpck_require__(55732);
-class AsyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async_1.default(this._root, this._settings);
- this._storage = [];
- }
- read(callback) {
- this._reader.onError((error) => {
- callFailureCallback(callback, error);
- });
- this._reader.onEntry((entry) => {
- this._storage.push(entry);
- });
- this._reader.onEnd(() => {
- callSuccessCallback(callback, this._storage);
- });
- this._reader.read();
+ if (request.method === 'CONNECT') {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
}
-}
-exports["default"] = AsyncProvider;
-function callFailureCallback(callback, error) {
- callback(error);
-}
-function callSuccessCallback(callback, entries) {
- callback(null, entries);
-}
+ if (upgrade) {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
+ }
-/***/ }),
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
-/***/ 96737:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (this.shouldKeepAlive && client[kPipelining]) {
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
-"use strict";
+ if (keepAliveTimeout != null) {
+ const timeout = Math.min(
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
+ client[kKeepAliveMaxTimeout]
+ )
+ if (timeout <= 0) {
+ socket[kReset] = true
+ } else {
+ client[kKeepAliveTimeoutValue] = timeout
+ }
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
+ }
+ } else {
+ // Stop more requests from being dispatched.
+ socket[kReset] = true
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(12781);
-const async_1 = __nccwpck_require__(55732);
-class StreamProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async_1.default(this._root, this._settings);
- this._stream = new stream_1.Readable({
- objectMode: true,
- read: () => { },
- destroy: () => {
- if (!this._reader.isDestroyed) {
- this._reader.destroy();
- }
- }
- });
+ let pause
+ try {
+ pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+ } catch (err) {
+ util.destroy(socket, err)
+ return -1
}
- read() {
- this._reader.onError((error) => {
- this._stream.emit('error', error);
- });
- this._reader.onEntry((entry) => {
- this._stream.push(entry);
- });
- this._reader.onEnd(() => {
- this._stream.push(null);
- });
- this._reader.read();
- return this._stream;
+
+ if (request.method === 'HEAD') {
+ return 1
}
-}
-exports["default"] = StreamProvider;
+ if (statusCode < 200) {
+ return 1
+ }
-/***/ }),
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false
+ resume(client)
+ }
-/***/ 13068:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return pause ? constants.ERROR.PAUSED : 0
+ }
-"use strict";
+ onBody (buf) {
+ const { client, socket, statusCode, maxResponseSize } = this
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const sync_1 = __nccwpck_require__(13595);
-class SyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new sync_1.default(this._root, this._settings);
- }
- read() {
- return this._reader.read();
+ if (socket.destroyed) {
+ return -1
}
-}
-exports["default"] = SyncProvider;
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
-/***/ }),
-
-/***/ 55732:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
-"use strict";
+ assert(statusCode >= 200)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const events_1 = __nccwpck_require__(82361);
-const fsScandir = __nccwpck_require__(75667);
-const fastq = __nccwpck_require__(7340);
-const common = __nccwpck_require__(97988);
-const reader_1 = __nccwpck_require__(88311);
-class AsyncReader extends reader_1.default {
- constructor(_root, _settings) {
- super(_root, _settings);
- this._settings = _settings;
- this._scandir = fsScandir.scandir;
- this._emitter = new events_1.EventEmitter();
- this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
- this._isFatalError = false;
- this._isDestroyed = false;
- this._queue.drain = () => {
- if (!this._isFatalError) {
- this._emitter.emit('end');
- }
- };
- }
- read() {
- this._isFatalError = false;
- this._isDestroyed = false;
- setImmediate(() => {
- this._pushToQueue(this._root, this._settings.basePath);
- });
- return this._emitter;
- }
- get isDestroyed() {
- return this._isDestroyed;
- }
- destroy() {
- if (this._isDestroyed) {
- throw new Error('The reader is already destroyed');
- }
- this._isDestroyed = true;
- this._queue.killAndDrain();
- }
- onEntry(callback) {
- this._emitter.on('entry', callback);
- }
- onError(callback) {
- this._emitter.once('error', callback);
- }
- onEnd(callback) {
- this._emitter.once('end', callback);
- }
- _pushToQueue(directory, base) {
- const queueItem = { directory, base };
- this._queue.push(queueItem, (error) => {
- if (error !== null) {
- this._handleError(error);
- }
- });
- }
- _worker(item, done) {
- this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
- if (error !== null) {
- done(error, undefined);
- return;
- }
- for (const entry of entries) {
- this._handleEntry(entry, item.base);
- }
- done(null, undefined);
- });
- }
- _handleError(error) {
- if (this._isDestroyed || !common.isFatalError(this._settings, error)) {
- return;
- }
- this._isFatalError = true;
- this._isDestroyed = true;
- this._emitter.emit('error', error);
- }
- _handleEntry(entry, base) {
- if (this._isDestroyed || this._isFatalError) {
- return;
- }
- const fullpath = entry.path;
- if (base !== undefined) {
- entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
- if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._emitEntry(entry);
- }
- if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
- }
- }
- _emitEntry(entry) {
- this._emitter.emit('entry', entry);
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError())
+ return -1
}
-}
-exports["default"] = AsyncReader;
-
-/***/ }),
+ this.bytesRead += buf.length
-/***/ 97988:
-/***/ ((__unused_webpack_module, exports) => {
+ try {
+ if (request.onData(buf) === false) {
+ return constants.ERROR.PAUSED
+ }
+ } catch (err) {
+ util.destroy(socket, err)
+ return -1
+ }
+ }
-"use strict";
+ onMessageComplete () {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0;
-function isFatalError(settings, error) {
- if (settings.errorFilter === null) {
- return true;
- }
- return !settings.errorFilter(error);
-}
-exports.isFatalError = isFatalError;
-function isAppliedFilter(filter, value) {
- return filter === null || filter(value);
-}
-exports.isAppliedFilter = isAppliedFilter;
-function replacePathSegmentSeparator(filepath, separator) {
- return filepath.split(/[/\\]/).join(separator);
-}
-exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
-function joinPathSegments(a, b, separator) {
- if (a === '') {
- return b;
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1
}
- /**
- * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
- */
- if (a.endsWith(separator)) {
- return a + b;
+
+ if (upgrade) {
+ return
}
- return a + separator + b;
-}
-exports.joinPathSegments = joinPathSegments;
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
-/***/ }),
+ assert(statusCode >= 100)
-/***/ 88311:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ this.statusCode = null
+ this.statusText = ''
+ this.bytesRead = 0
+ this.contentLength = ''
+ this.keepAlive = ''
+ this.connection = ''
-"use strict";
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const common = __nccwpck_require__(97988);
-class Reader {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
+ if (statusCode < 200) {
+ return
}
-}
-exports["default"] = Reader;
+ /* istanbul ignore next: should be handled by llhttp? */
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError())
+ return -1
+ }
-/***/ }),
-
-/***/ 13595:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ try {
+ request.onComplete(headers)
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
-"use strict";
+ client[kQueue][client[kRunningIdx]++] = null
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fsScandir = __nccwpck_require__(75667);
-const common = __nccwpck_require__(97988);
-const reader_1 = __nccwpck_require__(88311);
-class SyncReader extends reader_1.default {
- constructor() {
- super(...arguments);
- this._scandir = fsScandir.scandirSync;
- this._storage = [];
- this._queue = new Set();
- }
- read() {
- this._pushToQueue(this._root, this._settings.basePath);
- this._handleQueue();
- return this._storage;
- }
- _pushToQueue(directory, base) {
- this._queue.add({ directory, base });
- }
- _handleQueue() {
- for (const item of this._queue.values()) {
- this._handleDirectory(item.directory, item.base);
- }
- }
- _handleDirectory(directory, base) {
- try {
- const entries = this._scandir(directory, this._settings.fsScandirSettings);
- for (const entry of entries) {
- this._handleEntry(entry, base);
- }
- }
- catch (error) {
- this._handleError(error);
- }
- }
- _handleError(error) {
- if (!common.isFatalError(this._settings, error)) {
- return;
- }
- throw error;
- }
- _handleEntry(entry, base) {
- const fullpath = entry.path;
- if (base !== undefined) {
- entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
- if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._pushToStorage(entry);
- }
- if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
- }
- }
- _pushToStorage(entry) {
- this._storage.push(entry);
+ if (socket[kWriting]) {
+ assert.strictEqual(client[kRunning], 0)
+ // Response completed before request.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (!shouldKeepAlive) {
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (socket[kReset] && client[kRunning] === 0) {
+ // Destroy socket once all requests have completed.
+ // The request at the tail of the pipeline is the one
+ // that requested reset and no further requests should
+ // have been queued since then.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (client[kPipelining] === 1) {
+ // We must wait a full event loop cycle to reuse this socket to make sure
+ // that non-spec compliant servers are not closing the connection even if they
+ // said they won't.
+ setImmediate(resume, client)
+ } else {
+ resume(client)
}
+ }
}
-exports["default"] = SyncReader;
-
-
-/***/ }),
-
-/***/ 50141:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
+function onParserTimeout (parser) {
+ const { socket, timeoutType, client } = parser
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(71017);
-const fsScandir = __nccwpck_require__(75667);
-class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.basePath = this._getValue(this._options.basePath, undefined);
- this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
- this.deepFilter = this._getValue(this._options.deepFilter, null);
- this.entryFilter = this._getValue(this._options.entryFilter, null);
- this.errorFilter = this._getValue(this._options.errorFilter, null);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
- this.fsScandirSettings = new fsScandir.Settings({
- followSymbolicLinks: this._options.followSymbolicLinks,
- fs: this._options.fs,
- pathSegmentSeparator: this._options.pathSegmentSeparator,
- stats: this._options.stats,
- throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
- });
+ /* istanbul ignore else */
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert(!parser.paused, 'cannot be paused while waiting for headers')
+ util.destroy(socket, new HeadersTimeoutError())
}
- _getValue(option, value) {
- return option !== null && option !== void 0 ? option : value;
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!parser.paused) {
+ util.destroy(socket, new BodyTimeoutError())
}
-}
-exports["default"] = Settings;
-
-
-/***/ }),
-
-/***/ 40334:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
-const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
-const REGEX_IS_INSTALLATION = /^ghs_/;
-const REGEX_IS_USER_TO_SERVER = /^ghu_/;
-async function auth(token) {
- const isApp = token.split(/\./).length === 3;
- const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
- const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
- const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
- return {
- type: "token",
- token: token,
- tokenType
- };
-}
-
-/**
- * Prefix token for usage in the Authorization header
- *
- * @param token OAuth token or JSON Web Token
- */
-function withAuthorizationPrefix(token) {
- if (token.split(/\./).length === 3) {
- return `bearer ${token}`;
+ } else if (timeoutType === TIMEOUT_IDLE) {
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
+ util.destroy(socket, new InformationalError('socket idle timeout'))
}
-
- return `token ${token}`;
}
-async function hook(token, request, route, parameters) {
- const endpoint = request.endpoint.merge(route, parameters);
- endpoint.headers.authorization = withAuthorizationPrefix(token);
- return request(endpoint);
+function onSocketReadable () {
+ const { [kParser]: parser } = this
+ parser.readMore()
}
-const createTokenAuth = function createTokenAuth(token) {
- if (!token) {
- throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
- }
-
- if (typeof token !== "string") {
- throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
- }
-
- token = token.replace(/^(token|bearer) +/i, "");
- return Object.assign(auth.bind(null, token), {
- hook: hook.bind(null, token)
- });
-};
-
-exports.createTokenAuth = createTokenAuth;
-//# sourceMappingURL=index.js.map
-
-
-/***/ }),
+function onSocketError (err) {
+ const { [kClient]: client, [kParser]: parser } = this
-/***/ 76762:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-"use strict";
+ if (client[kHTTPConnVersion] !== 'h2') {
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
+ // to the user.
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so for as a valid response.
+ parser.onMessageComplete()
+ return
+ }
+ }
+ this[kError] = err
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ onError(this[kClient], err)
+}
-var universalUserAgent = __nccwpck_require__(45030);
-var beforeAfterHook = __nccwpck_require__(83682);
-var request = __nccwpck_require__(36234);
-var graphql = __nccwpck_require__(88467);
-var authToken = __nccwpck_require__(40334);
+function onError (client, err) {
+ if (
+ client[kRunning] === 0 &&
+ err.code !== 'UND_ERR_INFO' &&
+ err.code !== 'UND_ERR_SOCKET'
+ ) {
+ // Error is not caused by running request and not a recoverable
+ // socket error.
-function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
+ assert(client[kPendingIdx] === client[kRunningIdx])
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ assert(client[kSize] === 0)
}
-
- return target;
}
-function _objectWithoutProperties(source, excluded) {
- if (source == null) return {};
-
- var target = _objectWithoutPropertiesLoose(source, excluded);
-
- var key, i;
-
- if (Object.getOwnPropertySymbols) {
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
+function onSocketEnd () {
+ const { [kParser]: parser, [kClient]: client } = this
- for (i = 0; i < sourceSymbolKeys.length; i++) {
- key = sourceSymbolKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
- target[key] = source[key];
+ if (client[kHTTPConnVersion] !== 'h2') {
+ if (parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ return
}
}
- return target;
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
}
-const VERSION = "3.6.0";
-
-const _excluded = ["authStrategy"];
-class Octokit {
- constructor(options = {}) {
- const hook = new beforeAfterHook.Collection();
- const requestDefaults = {
- baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
- headers: {},
- request: Object.assign({}, options.request, {
- // @ts-ignore internal usage only, no need to type
- hook: hook.bind(null, "request")
- }),
- mediaType: {
- previews: [],
- format: ""
- }
- }; // prepend default user agent with `options.userAgent` if set
-
- requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
-
- if (options.baseUrl) {
- requestDefaults.baseUrl = options.baseUrl;
- }
-
- if (options.previews) {
- requestDefaults.mediaType.previews = options.previews;
- }
+function onSocketClose () {
+ const { [kClient]: client, [kParser]: parser } = this
- if (options.timeZone) {
- requestDefaults.headers["time-zone"] = options.timeZone;
+ if (client[kHTTPConnVersion] === 'h1' && parser) {
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
}
- this.request = request.request.defaults(requestDefaults);
- this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);
- this.log = Object.assign({
- debug: () => {},
- info: () => {},
- warn: console.warn.bind(console),
- error: console.error.bind(console)
- }, options.log);
- this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
- // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
- // (2) If only `options.auth` is set, use the default token authentication strategy.
- // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
- // TODO: type `options.auth` based on `options.authStrategy`.
-
- if (!options.authStrategy) {
- if (!options.auth) {
- // (1)
- this.auth = async () => ({
- type: "unauthenticated"
- });
- } else {
- // (2)
- const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯
-
- hook.wrap("request", auth.hook);
- this.auth = auth;
- }
- } else {
- const {
- authStrategy
- } = options,
- otherOptions = _objectWithoutProperties(options, _excluded);
-
- const auth = authStrategy(Object.assign({
- request: this.request,
- log: this.log,
- // we pass the current octokit instance as well as its constructor options
- // to allow for authentication strategies that return a new octokit instance
- // that shares the same internal state as the current one. The original
- // requirement for this was the "event-octokit" authentication strategy
- // of https://github.com/probot/octokit-auth-probot.
- octokit: this,
- octokitOptions: otherOptions
- }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯
-
- hook.wrap("request", auth.hook);
- this.auth = auth;
- } // apply plugins
- // https://stackoverflow.com/a/16345172
-
-
- const classConstructor = this.constructor;
- classConstructor.plugins.forEach(plugin => {
- Object.assign(this, plugin(this, options));
- });
+ this[kParser].destroy()
+ this[kParser] = null
}
- static defaults(defaults) {
- const OctokitWithDefaults = class extends this {
- constructor(...args) {
- const options = args[0] || {};
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
- if (typeof defaults === "function") {
- super(defaults(options));
- return;
- }
+ client[kSocket] = null
- super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
- userAgent: `${options.userAgent} ${defaults.userAgent}`
- } : null));
- }
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
- };
- return OctokitWithDefaults;
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+
+ errorRequest(client, request, err)
}
- /**
- * Attach a plugin (or many) to your Octokit instance.
- *
- * @example
- * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
- */
+ client[kPendingIdx] = client[kRunningIdx]
- static plugin(...newPlugins) {
- var _a;
+ assert(client[kRunning] === 0)
- const currentPlugins = this.plugins;
- const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);
- return NewOctokit;
- }
+ client.emit('disconnect', client[kUrl], [client], err)
+ resume(client)
}
-Octokit.VERSION = VERSION;
-Octokit.plugins = [];
-exports.Octokit = Octokit;
-//# sourceMappingURL=index.js.map
+async function connect (client) {
+ assert(!client[kConnecting])
+ assert(!client[kSocket])
+ let { host, hostname, protocol, port } = client[kUrl]
-/***/ }),
-
-/***/ 59440:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+ // Resolve ipv6
+ if (hostname[0] === '[') {
+ const idx = hostname.indexOf(']')
+ assert(idx !== -1)
+ const ip = hostname.substr(1, idx - 1)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ assert(net.isIP(ip))
+ hostname = ip
+ }
-var isPlainObject = __nccwpck_require__(63287);
-var universalUserAgent = __nccwpck_require__(45030);
+ client[kConnecting] = true
-function lowercaseKeys(object) {
- if (!object) {
- return {};
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ })
}
- return Object.keys(object).reduce((newObj, key) => {
- newObj[key.toLowerCase()] = object[key];
- return newObj;
- }, {});
-}
+ try {
+ const socket = await new Promise((resolve, reject) => {
+ client[kConnector]({
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ }, (err, socket) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(socket)
+ }
+ })
+ })
-function mergeDeep(defaults, options) {
- const result = Object.assign({}, defaults);
- Object.keys(options).forEach(key => {
- if (isPlainObject.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]
- });
+ if (client.destroyed) {
+ util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
+ return
}
- });
- return result;
-}
-function removeUndefinedProperties(obj) {
- for (const key in obj) {
- if (obj[key] === undefined) {
- delete obj[key];
- }
- }
+ client[kConnecting] = false
- return obj;
-}
+ assert(socket)
-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 = Object.assign({}, route);
- } // lowercase header names before merging with defaults to avoid duplicates
+ const isH2 = socket.alpnProtocol === 'h2'
+ if (isH2) {
+ if (!h2ExperimentalWarned) {
+ h2ExperimentalWarned = true
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
+ code: 'UNDICI-H2'
+ })
+ }
+ const session = http2.connect(client[kUrl], {
+ createConnection: () => socket,
+ peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
+ })
- options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
+ client[kHTTPConnVersion] = 'h2'
+ session[kClient] = client
+ session[kSocket] = socket
+ session.on('error', onHttp2SessionError)
+ session.on('frameError', onHttp2FrameError)
+ session.on('end', onHttp2SessionEnd)
+ session.on('goaway', onHTTP2GoAway)
+ session.on('close', onSocketClose)
+ session.unref()
- removeUndefinedProperties(options);
- removeUndefinedProperties(options.headers);
- const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
+ client[kHTTP2Session] = session
+ socket[kHTTP2Session] = session
+ } else {
+ if (!llhttpInstance) {
+ llhttpInstance = await llhttpPromise
+ llhttpPromise = null
+ }
- if (defaults && defaults.mediaType.previews.length) {
- mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
- }
+ socket[kNoRef] = false
+ socket[kWriting] = false
+ socket[kReset] = false
+ socket[kBlocking] = false
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
+ }
- mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
- return mergedOptions;
-}
+ socket[kCounter] = 0
+ socket[kMaxRequests] = client[kMaxRequests]
+ socket[kClient] = client
+ socket[kError] = null
-function addQueryParameters(url, parameters) {
- const separator = /\?/.test(url) ? "&" : "?";
- const names = Object.keys(parameters);
+ socket
+ .on('error', onSocketError)
+ .on('readable', onSocketReadable)
+ .on('end', onSocketEnd)
+ .on('close', onSocketClose)
- if (names.length === 0) {
- return url;
- }
+ client[kSocket] = socket
- return url + separator + names.map(name => {
- if (name === "q") {
- return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ })
+ }
+ client.emit('connect', client[kUrl], [client])
+ } catch (err) {
+ if (client.destroyed) {
+ return
}
- return `${name}=${encodeURIComponent(parameters[name])}`;
- }).join("&");
-}
-
-const urlVariableRegex = /\{[^}]+\}/g;
+ client[kConnecting] = false
-function removeNonChars(variableName) {
- return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
-}
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
+ }
-function extractUrlVariableNames(url) {
- const matches = url.match(urlVariableRegex);
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ assert(client[kRunning] === 0)
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ const request = client[kQueue][client[kPendingIdx]++]
+ errorRequest(client, request, err)
+ }
+ } else {
+ onError(client, err)
+ }
- if (!matches) {
- return [];
+ client.emit('connectionError', client[kUrl], [client], err)
}
- return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
-}
-
-function omit(object, keysToOmit) {
- return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
- obj[key] = object[key];
- return obj;
- }, {});
+ resume(client)
}
-// 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 emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain', client[kUrl], [client])
}
-function encodeValue(operator, value, key) {
- value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
-
- if (key) {
- return encodeUnreserved(key) + "=" + value;
- } else {
- return value;
+function resume (client, sync) {
+ if (client[kResuming] === 2) {
+ return
}
-}
-function isDefined(value) {
- return value !== undefined && value !== null;
-}
+ client[kResuming] = 2
-function isKeyOperator(operator) {
- return operator === ";" || operator === "&" || operator === "?";
+ _resume(client, sync)
+ client[kResuming] = 0
+
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx])
+ client[kPendingIdx] -= client[kRunningIdx]
+ client[kRunningIdx] = 0
+ }
}
-function getValues(context, operator, key, modifier) {
- var value = context[key],
- result = [];
+function _resume (client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ return
+ }
- if (isDefined(value) && value !== "") {
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- value = value.toString();
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]()
+ client[kClosedResolve] = null
+ return
+ }
- if (modifier && modifier !== "*") {
- value = value.substring(0, parseInt(modifier, 10));
- }
+ const socket = client[kSocket]
- 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));
- }
- });
+ if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
+ if (client[kSize] === 0) {
+ if (!socket[kNoRef] && socket.unref) {
+ socket.unref()
+ socket[kNoRef] = true
}
- } else {
- const tmp = [];
+ } else if (socket[kNoRef] && socket.ref) {
+ socket.ref()
+ socket[kNoRef] = false
+ }
- 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 (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
}
-
- if (isKeyOperator(operator)) {
- result.push(encodeUnreserved(key) + "=" + tmp.join(","));
- } else if (tmp.length !== 0) {
- result.push(tmp.join(","));
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
+ const request = client[kQueue][client[kRunningIdx]]
+ const headersTimeout = request.headersTimeout != null
+ ? request.headersTimeout
+ : client[kHeadersTimeout]
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
}
}
}
- } else {
- if (operator === ";") {
- if (isDefined(value)) {
- result.push(encodeUnreserved(key));
+
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ process.nextTick(emitDrain, client)
+ } else {
+ emitDrain(client)
}
- } else if (value === "" && (operator === "&" || operator === "?")) {
- result.push(encodeUnreserved(key) + "=");
- } else if (value === "") {
- result.push("");
+ continue
}
- }
- return result;
-}
+ if (client[kPending] === 0) {
+ return
+ }
-function parseUrl(template) {
- return {
- expand: expand.bind(null, template)
- };
-}
+ if (client[kRunning] >= (client[kPipelining] || 1)) {
+ return
+ }
-function expand(template, context) {
- var operators = ["+", "#", ".", "/", ";", "?", "&"];
- return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
- if (expression) {
- let operator = "";
- const values = [];
+ const request = client[kQueue][client[kPendingIdx]]
- if (operators.indexOf(expression.charAt(0)) !== -1) {
- operator = expression.charAt(0);
- expression = expression.substr(1);
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return
}
- 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;
- }
+ client[kServerName] = request.servername
- return (values.length !== 0 ? operator : "") + values.join(separator);
- } else {
- return values.join(",");
+ if (socket && socket.servername !== request.servername) {
+ util.destroy(socket, new InformationalError('servername changed'))
+ return
}
- } else {
- return encodeReserved(literal);
}
- });
-}
-
-function parse(options) {
- // https://fetch.spec.whatwg.org/#methods
- 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 headers = Object.assign({}, options.headers);
- let body;
- let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
-
- const urlVariableNames = extractUrlVariableNames(url);
- url = parseUrl(url).expand(parameters);
-
- if (!/^http/.test(url)) {
- url = options.baseUrl + url;
- }
- const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
- const remainingParameters = omit(parameters, omittedParameters);
- const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
-
- if (!isBinaryRequest) {
- if (options.mediaType.format) {
- // 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.${options.mediaType.format}`)).join(",");
+ if (client[kConnecting]) {
+ return
}
- if (options.mediaType.previews.length) {
- const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
- headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
- const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
- return `application/vnd.github.${preview}-preview${format}`;
- }).join(",");
+ if (!socket && !client[kHTTP2Session]) {
+ connect(client)
+ return
}
- } // for GET/HEAD requests, set URL query parameters from remaining parameters
- // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
-
- if (["GET", "HEAD"].includes(method)) {
- url = addQueryParameters(url, remainingParameters);
- } else {
- if ("data" in remainingParameters) {
- body = remainingParameters.data;
- } else {
- if (Object.keys(remainingParameters).length) {
- body = remainingParameters;
- } else {
- headers["content-length"] = 0;
- }
+ if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
+ return
}
- } // default content-type for JSON if body is set
-
- if (!headers["content-type"] && typeof body !== "undefined") {
- headers["content-type"] = "application/json; charset=utf-8";
- } // 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
+ if (client[kRunning] > 0 && !request.idempotent) {
+ // Non-idempotent request cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
+ // Don't dispatch an upgrade until all preceding requests have completed.
+ // A misbehaving server might upgrade the connection before all pipelined
+ // request has completed.
+ return
+ }
- if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
- body = "";
- } // Only return body/request keys if present
+ if (util.isStream(request.body) && util.bodyLength(request.body) === 0) {
+ request.body
+ .on('data', /* istanbul ignore next */ function () {
+ /* istanbul ignore next */
+ assert(false)
+ })
+ .on('error', function (err) {
+ errorRequest(client, request, err)
+ })
+ .on('end', function () {
+ util.destroy(this)
+ })
+ request.body = null
+ }
- return Object.assign({
- method,
- url,
- headers
- }, typeof body !== "undefined" ? {
- body
- } : null, options.request ? {
- request: options.request
- } : null);
-}
+ if (client[kRunning] > 0 &&
+ (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
+ // Request with stream or iterator body can error while other requests
+ // are inflight and indirectly error those as well.
+ // Ensure this doesn't happen by waiting for inflight
+ // to complete before dispatching.
-function endpointWithDefaults(defaults, route, options) {
- return parse(merge(defaults, route, options));
-}
+ // Request with stream or iterator body cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
-function withDefaults(oldDefaults, newDefaults) {
- const DEFAULTS = merge(oldDefaults, newDefaults);
- const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
- return Object.assign(endpoint, {
- DEFAULTS,
- defaults: withDefaults.bind(null, DEFAULTS),
- merge: merge.bind(null, DEFAULTS),
- parse
- });
+ if (!request.aborted && write(client, request)) {
+ client[kPendingIdx]++
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1)
+ }
+ }
}
-const VERSION = "6.0.12";
-
-const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
-// So we use RequestParameters and add method as additional required property.
-
-const DEFAULTS = {
- method: "GET",
- baseUrl: "https://api.github.com",
- headers: {
- accept: "application/vnd.github.v3+json",
- "user-agent": userAgent
- },
- mediaType: {
- format: "",
- previews: []
+function write (client, request) {
+ if (client[kHTTPConnVersion] === 'h2') {
+ writeH2(client, client[kHTTP2Session], request)
+ return
}
-};
-
-const endpoint = withDefaults(null, DEFAULTS);
-
-exports.endpoint = endpoint;
-//# sourceMappingURL=index.js.map
-
-
-/***/ }),
-
-/***/ 88467:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
-var request = __nccwpck_require__(36234);
-var universalUserAgent = __nccwpck_require__(45030);
+ const { body, method, path, host, upgrade, headers, blocking, reset } = request
-const VERSION = "4.8.0";
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
-function _buildMessageForResponseErrors(data) {
- return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n");
-}
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
-class GraphqlResponseError extends Error {
- constructor(request, headers, response) {
- super(_buildMessageForResponseErrors(response));
- this.request = request;
- this.headers = headers;
- this.response = response;
- this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties.
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
- this.errors = response.errors;
- this.data = response.data; // Maintains proper stack trace (only available on V8)
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
- /* istanbul ignore next */
+ let contentLength = util.bodyLength(body)
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
+ if (contentLength === null) {
+ contentLength = request.contentLength
}
-}
-
-const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
-const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
-const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
-function graphql(request, query, options) {
- if (options) {
- if (typeof query === "string" && "query" in options) {
- return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
- }
+ if (contentLength === 0 && !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
- for (const key in options) {
- if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
- return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
- }
+ contentLength = null
}
- const parsedOptions = typeof query === "string" ? Object.assign({
- query
- }, options) : query;
- const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
- if (NON_VARIABLE_OPTIONS.includes(key)) {
- result[key] = parsedOptions[key];
- return result;
- }
-
- if (!result.variables) {
- result.variables = {};
+ if (request.contentLength !== null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
}
- result.variables[key] = parsedOptions[key];
- return result;
- }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
- // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
-
- const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
-
- if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
- requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
+ process.emitWarning(new RequestContentLengthMismatchError())
}
- return request(requestOptions).then(response => {
- if (response.data.errors) {
- const headers = {};
+ const socket = client[kSocket]
- for (const key of Object.keys(response.headers)) {
- headers[key] = response.headers[key];
+ try {
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
}
- throw new GraphqlResponseError(requestOptions, headers, response.data);
- }
-
- return response.data.data;
- });
-}
-
-function withDefaults(request$1, newDefaults) {
- const newRequest = request$1.defaults(newDefaults);
-
- const newApi = (query, options) => {
- return graphql(newRequest, query, options);
- };
+ errorRequest(client, request, err || new RequestAbortedError())
- return Object.assign(newApi, {
- defaults: withDefaults.bind(null, newRequest),
- endpoint: request.request.endpoint
- });
-}
+ util.destroy(socket, new InformationalError('aborted'))
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
-const graphql$1 = withDefaults(request.request, {
- headers: {
- "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`
- },
- method: "POST",
- url: "/graphql"
-});
-function withCustomRequest(customRequest) {
- return withDefaults(customRequest, {
- method: "POST",
- url: "/graphql"
- });
-}
+ if (request.aborted) {
+ return false
+ }
-exports.GraphqlResponseError = GraphqlResponseError;
-exports.graphql = graphql$1;
-exports.withCustomRequest = withCustomRequest;
-//# sourceMappingURL=index.js.map
+ if (method === 'HEAD') {
+ // https://github.com/mcollina/undici/issues/258
+ // Close after a HEAD request to interop with misbehaving servers
+ // that may send a body in the response.
+ socket[kReset] = true
+ }
-/***/ }),
+ if (upgrade || method === 'CONNECT') {
+ // On CONNECT or upgrade, block pipeline from dispatching further
+ // requests on this connection.
-/***/ 64193:
-/***/ ((__unused_webpack_module, exports) => {
+ socket[kReset] = true
+ }
-"use strict";
+ if (reset != null) {
+ socket[kReset] = reset
+ }
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset] = true
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ if (blocking) {
+ socket[kBlocking] = true
+ }
-const VERSION = "2.21.3";
+ let header = `${method} ${path} HTTP/1.1\r\n`
-function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
+ if (typeof host === 'string') {
+ header += `host: ${host}\r\n`
+ } else {
+ header += client[kHostHeader]
+ }
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
- enumerableOnly && (symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- })), keys.push.apply(keys, symbols);
+ if (upgrade) {
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
+ } else if (client[kPipelining] && !socket[kReset]) {
+ header += 'connection: keep-alive\r\n'
+ } else {
+ header += 'connection: close\r\n'
}
- return keys;
-}
+ if (headers) {
+ header += headers
+ }
-function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = null != arguments[i] ? arguments[i] : {};
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
- _defineProperty(target, key, source[key]);
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket })
}
- return target;
-}
+ /* istanbul ignore else: assertion */
+ if (!body) {
+ if (contentLength === 0) {
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ assert(contentLength === null, 'no body must not have content length')
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
-function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(body)
+ socket.uncork()
+ request.onBodySent(body)
+ request.onRequestSent()
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else if (util.isIterable(body)) {
+ writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
} else {
- obj[key] = value;
+ assert(false)
}
- return obj;
+ return true
}
-/**
- * Some “list” response that can be paginated have a different response structure
- *
- * They have a `total_count` key in the response (search also has `incomplete_results`,
- * /installation/repositories also has `repository_selection`), as well as a key with
- * the list of the items which name varies from endpoint to endpoint.
- *
- * Octokit normalizes these responses so that paginated results are always returned following
- * the same structure. One challenge is that if the list response has only one page, no Link
- * header is provided, so this header alone is not sufficient to check wether a response is
- * paginated or not.
- *
- * We check if a "total_count" key is present in the response data, but also make sure that
- * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would
- * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
- */
-function normalizePaginatedListResponse(response) {
- // endpoints can respond with 204 if repository is empty
- if (!response.data) {
- return _objectSpread2(_objectSpread2({}, response), {}, {
- data: []
- });
- }
+function writeH2 (client, session, request) {
+ const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+
+ let headers
+ if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
+ else headers = reqHeaders
- const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
- if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way
- // to retrieve the same information.
+ if (upgrade) {
+ errorRequest(client, request, new Error('Upgrade not supported for H2'))
+ return false
+ }
- const incompleteResults = response.data.incomplete_results;
- const repositorySelection = response.data.repository_selection;
- const totalCount = response.data.total_count;
- delete response.data.incomplete_results;
- delete response.data.repository_selection;
- delete response.data.total_count;
- const namespaceKey = Object.keys(response.data)[0];
- const data = response.data[namespaceKey];
- response.data = data;
+ try {
+ // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
- if (typeof incompleteResults !== "undefined") {
- response.data.incomplete_results = incompleteResults;
+ errorRequest(client, request, err || new RequestAbortedError())
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
}
- if (typeof repositorySelection !== "undefined") {
- response.data.repository_selection = repositorySelection;
+ if (request.aborted) {
+ return false
}
- response.data.total_count = totalCount;
- return response;
-}
+ let stream
+ const h2State = client[kHTTP2SessionState]
-function iterator(octokit, route, parameters) {
- const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
- const requestMethod = typeof route === "function" ? route : octokit.request;
- const method = options.method;
- const headers = options.headers;
- let url = options.url;
- return {
- [Symbol.asyncIterator]: () => ({
- async next() {
- if (!url) return {
- done: true
- };
+ headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
+ headers[HTTP2_HEADER_PATH] = path
- try {
- const response = await requestMethod({
- method,
- url,
- headers
- });
- const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format:
- // '; rel="next", ; rel="last"'
- // sets `url` to undefined if "next" URL is not present or `link` header is not set
-
- url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
- return {
- value: normalizedResponse
- };
- } catch (error) {
- if (error.status !== 409) throw error;
- url = "";
- return {
- value: {
- status: 200,
- headers: {},
- data: []
- }
- };
- }
- }
+ if (method === 'CONNECT') {
+ session.ref()
+ // we are already connected, streams are pending, first request
+ // will create a new stream. We trigger a request to create the stream and wait until
+ // `ready` event is triggered
+ // We disabled endStream to allow the user to write to the stream
+ stream = session.request(headers, { endStream: false, signal })
+
+ if (stream.id && !stream.pending) {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ } else {
+ stream.once('ready', () => {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ })
+ }
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) session.unref()
})
- };
-}
-function paginate(octokit, route, parameters, mapFn) {
- if (typeof parameters === "function") {
- mapFn = parameters;
- parameters = undefined;
+ return true
+ } else {
+ headers[HTTP2_HEADER_METHOD] = method
}
- return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);
-}
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
-function gather(octokit, results, iterator, mapFn) {
- return iterator.next().then(result => {
- if (result.done) {
- return results;
- }
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
- let earlyExit = false;
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
- function done() {
- earlyExit = true;
- }
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
- results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);
+ let contentLength = util.bodyLength(body)
- if (earlyExit) {
- return results;
- }
+ if (contentLength == null) {
+ contentLength = request.contentLength
+ }
- return gather(octokit, results, iterator, mapFn);
- });
-}
+ if (contentLength === 0 || !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
-const composePaginateRest = Object.assign(paginate, {
- iterator
-});
+ contentLength = null
+ }
-const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/audit-log", "GET /enterprises/{enterprise}/secret-scanning/alerts", "GET /enterprises/{enterprise}/settings/billing/advanced-security", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /licenses", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/cache/usage-by-repository", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/audit-log", "GET /orgs/{org}/blocks", "GET /orgs/{org}/code-scanning/alerts", "GET /orgs/{org}/codespaces", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/dependabot/secrets", "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", "GET /orgs/{org}/events", "GET /orgs/{org}/external-groups", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/settings/billing/advanced-security", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/caches", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/codespaces", "GET /repos/{owner}/{repo}/codespaces/devcontainers", "GET /repos/{owner}/{repo}/codespaces/secrets", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/status", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/dependabot/secrets", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/environments", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repos/{owner}/{repo}/topics", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/codespaces", "GET /user/codespaces/secrets", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/packages/{package_type}/{package_name}/versions", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"];
+ if (request.contentLength != null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
-function isPaginatingEndpoint(arg) {
- if (typeof arg === "string") {
- return paginatingEndpoints.includes(arg);
- } else {
- return false;
+ process.emitWarning(new RequestContentLengthMismatchError())
}
-}
-/**
- * @param octokit Octokit instance
- * @param options Options passed to Octokit constructor
- */
+ if (contentLength != null) {
+ assert(body, 'no body must not have content length')
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ }
-function paginateRest(octokit) {
- return {
- paginate: Object.assign(paginate.bind(null, octokit), {
- iterator: iterator.bind(null, octokit)
- })
- };
-}
-paginateRest.VERSION = VERSION;
+ session.ref()
-exports.composePaginateRest = composePaginateRest;
-exports.isPaginatingEndpoint = isPaginatingEndpoint;
-exports.paginateRest = paginateRest;
-exports.paginatingEndpoints = paginatingEndpoints;
-//# sourceMappingURL=index.js.map
+ const shouldEndStream = method === 'GET' || method === 'HEAD'
+ if (expectContinue) {
+ headers[HTTP2_HEADER_EXPECT] = '100-continue'
+ /**
+ * @type {import('node:http2').ClientHttp2Stream}
+ */
+ stream = session.request(headers, { endStream: shouldEndStream, signal })
+ stream.once('continue', writeBodyH2)
+ } else {
+ /** @type {import('node:http2').ClientHttp2Stream} */
+ stream = session.request(headers, {
+ endStream: shouldEndStream,
+ signal
+ })
+ writeBodyH2()
+ }
-/***/ }),
+ // Increment counter as we have new several streams open
+ ++h2State.openStreams
-/***/ 68883:
-/***/ ((__unused_webpack_module, exports) => {
+ stream.once('response', headers => {
+ if (request.onHeaders(Number(headers[HTTP2_HEADER_STATUS]), headers, stream.resume.bind(stream), '') === false) {
+ stream.pause()
+ }
+ })
-"use strict";
+ stream.once('end', () => {
+ request.onComplete([])
+ })
+ stream.on('data', (chunk) => {
+ if (request.onData(chunk) === false) stream.pause()
+ })
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) session.unref()
+ })
-const VERSION = "1.0.4";
+ stream.once('error', function (err) {
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
-/**
- * @param octokit Octokit instance
- * @param options Options passed to Octokit constructor
- */
+ stream.once('frameError', (type, code) => {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ errorRequest(client, request, err)
-function requestLog(octokit) {
- octokit.hook.wrap("request", (request, options) => {
- octokit.log.debug("request", options);
- const start = Date.now();
- const requestOptions = octokit.request.endpoint.parse(options);
- const path = requestOptions.url.replace(options.baseUrl, "");
- return request(options).then(response => {
- octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`);
- return response;
- }).catch(error => {
- octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`);
- throw error;
- });
- });
-}
-requestLog.VERSION = VERSION;
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
-exports.requestLog = requestLog;
-//# sourceMappingURL=index.js.map
+ // stream.on('aborted', () => {
+ // // TODO(HTTP/2): Support aborted
+ // })
+ // stream.on('timeout', () => {
+ // // TODO(HTTP/2): Support timeout
+ // })
-/***/ }),
+ // stream.on('push', headers => {
+ // // TODO(HTTP/2): Suppor push
+ // })
-/***/ 83044:
-/***/ ((__unused_webpack_module, exports) => {
+ // stream.on('trailers', headers => {
+ // // TODO(HTTP/2): Support trailers
+ // })
-"use strict";
+ return true
+ function writeBodyH2 () {
+ /* istanbul ignore else: assertion */
+ if (!body) {
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+ stream.cork()
+ stream.write(body)
+ stream.uncork()
+ request.onBodySent(body)
+ request.onRequestSent()
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({
+ client,
+ request,
+ contentLength,
+ h2stream: stream,
+ expectsPayload,
+ body: body.stream(),
+ socket: client[kSocket],
+ header: ''
+ })
+ } else {
+ writeBlob({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ h2stream: stream,
+ header: '',
+ socket: client[kSocket]
+ })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ socket: client[kSocket],
+ h2stream: stream,
+ header: ''
+ })
+ } else if (util.isIterable(body)) {
+ writeIterable({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ header: '',
+ h2stream: stream,
+ socket: client[kSocket]
+ })
+ } else {
+ assert(false)
+ }
+ }
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
-function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
+ if (client[kHTTPConnVersion] === 'h2') {
+ // For HTTP/2, is enough to pipe the stream
+ const pipe = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(body, err)
+ util.destroy(h2stream, err)
+ } else {
+ request.onRequestSent()
+ }
+ }
+ )
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
+ pipe.on('data', onPipeData)
+ pipe.once('end', () => {
+ pipe.removeListener('data', onPipeData)
+ util.destroy(pipe)
+ })
- if (enumerableOnly) {
- symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- });
+ function onPipeData (chunk) {
+ request.onBodySent(chunk)
}
- keys.push.apply(keys, symbols);
+ return
}
- return keys;
-}
+ let finished = false
-function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? arguments[i] : {};
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
- if (i % 2) {
- ownKeys(Object(source), true).forEach(function (key) {
- _defineProperty(target, key, source[key]);
- });
- } else if (Object.getOwnPropertyDescriptors) {
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
- } else {
- ownKeys(Object(source)).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
+ const onData = function (chunk) {
+ if (finished) {
+ return
}
- }
- return target;
-}
-
-function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
-
- return obj;
-}
-
-const Endpoints = {
- actions: {
- addCustomLabelsToSelfHostedRunnerForOrg: ["POST /orgs/{org}/actions/runners/{runner_id}/labels"],
- addCustomLabelsToSelfHostedRunnerForRepo: ["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
- addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
- approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],
- cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
- createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
- createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
- createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
- createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
- createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"],
- createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
- createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
- createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
- deleteActionsCacheById: ["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],
- deleteActionsCacheByKey: ["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],
- deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
- deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
- deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
- deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
- deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
- deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],
- deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
- deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
- disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],
- disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],
- downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],
- downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],
- downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],
- downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
- enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],
- enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],
- getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"],
- getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"],
- getActionsCacheUsageByRepoForOrg: ["GET /orgs/{org}/actions/cache/usage-by-repository"],
- getActionsCacheUsageForEnterprise: ["GET /enterprises/{enterprise}/actions/cache/usage"],
- getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"],
- getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"],
- getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],
- getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
- getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"],
- getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
- getGithubActionsDefaultWorkflowPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/workflow"],
- getGithubActionsDefaultWorkflowPermissionsOrganization: ["GET /orgs/{org}/actions/permissions/workflow"],
- getGithubActionsDefaultWorkflowPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/workflow"],
- getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"],
- getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"],
- getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
- getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
- getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
- getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
- getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, {
- renamed: ["actions", "getGithubActionsPermissionsRepository"]
- }],
- getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
- getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
- getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],
- getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
- getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
- getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
- getWorkflowAccessToRepository: ["GET /repos/{owner}/{repo}/actions/permissions/access"],
- getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
- getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],
- getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
- getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
- listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
- listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"],
- listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
- listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],
- listLabelsForSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}/labels"],
- listLabelsForSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
- listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
- listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
- listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
- listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"],
- listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],
- listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"],
- listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
- listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
- listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],
- listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],
- listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
- reRunJobForWorkflowRun: ["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],
- reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
- reRunWorkflowFailedJobs: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],
- removeAllCustomLabelsFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],
- removeAllCustomLabelsFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
- removeCustomLabelFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],
- removeCustomLabelFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],
- removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
- reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
- setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"],
- setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],
- setCustomLabelsForSelfHostedRunnerForOrg: ["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],
- setCustomLabelsForSelfHostedRunnerForRepo: ["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
- setGithubActionsDefaultWorkflowPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/workflow"],
- setGithubActionsDefaultWorkflowPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions/workflow"],
- setGithubActionsDefaultWorkflowPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],
- setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"],
- setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"],
- setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],
- setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"],
- setWorkflowAccessToRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/access"]
- },
- activity: {
- checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
- deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
- deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"],
- getFeeds: ["GET /feeds"],
- getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
- getThread: ["GET /notifications/threads/{thread_id}"],
- getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"],
- listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
- listNotificationsForAuthenticatedUser: ["GET /notifications"],
- listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"],
- listPublicEvents: ["GET /events"],
- listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
- listPublicEventsForUser: ["GET /users/{username}/events/public"],
- listPublicOrgEvents: ["GET /orgs/{org}/events"],
- listReceivedEventsForUser: ["GET /users/{username}/received_events"],
- listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"],
- listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
- listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"],
- listReposStarredByAuthenticatedUser: ["GET /user/starred"],
- listReposStarredByUser: ["GET /users/{username}/starred"],
- listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
- listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
- listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
- listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
- markNotificationsAsRead: ["PUT /notifications"],
- markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
- markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
- setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
- setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"],
- starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
- unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
- },
- apps: {
- addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, {
- renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"]
- }],
- addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"],
- checkToken: ["POST /applications/{client_id}/token"],
- createFromManifest: ["POST /app-manifests/{code}/conversions"],
- createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"],
- deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
- deleteInstallation: ["DELETE /app/installations/{installation_id}"],
- deleteToken: ["DELETE /applications/{client_id}/token"],
- getAuthenticated: ["GET /app"],
- getBySlug: ["GET /apps/{app_slug}"],
- getInstallation: ["GET /app/installations/{installation_id}"],
- getOrgInstallation: ["GET /orgs/{org}/installation"],
- getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
- getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"],
- getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"],
- getUserInstallation: ["GET /users/{username}/installation"],
- getWebhookConfigForApp: ["GET /app/hook/config"],
- getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
- listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
- listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],
- listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"],
- listInstallations: ["GET /app/installations"],
- listInstallationsForAuthenticatedUser: ["GET /user/installations"],
- listPlans: ["GET /marketplace_listing/plans"],
- listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
- listReposAccessibleToInstallation: ["GET /installation/repositories"],
- listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
- listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"],
- listWebhookDeliveries: ["GET /app/hook/deliveries"],
- redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"],
- removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, {
- renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"]
- }],
- removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],
- resetToken: ["PATCH /applications/{client_id}/token"],
- revokeInstallationAccessToken: ["DELETE /installation/token"],
- scopeToken: ["POST /applications/{client_id}/token/scoped"],
- suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
- unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"],
- updateWebhookConfigForApp: ["PATCH /app/hook/config"]
- },
- billing: {
- getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
- getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"],
- getGithubAdvancedSecurityBillingGhe: ["GET /enterprises/{enterprise}/settings/billing/advanced-security"],
- getGithubAdvancedSecurityBillingOrg: ["GET /orgs/{org}/settings/billing/advanced-security"],
- getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
- getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"],
- getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"],
- getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"]
- },
- checks: {
- create: ["POST /repos/{owner}/{repo}/check-runs"],
- createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
- get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
- getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
- listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],
- listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
- listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],
- listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
- rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],
- rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],
- setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"],
- update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
- },
- codeScanning: {
- deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],
- getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, {
- renamedParameters: {
- alert_id: "alert_number"
- }
- }],
- getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],
- getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
- listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],
- listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"],
- listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
- listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, {
- renamed: ["codeScanning", "listAlertInstances"]
- }],
- listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
- updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],
- uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
- },
- codesOfConduct: {
- getAllCodesOfConduct: ["GET /codes_of_conduct"],
- getConductCode: ["GET /codes_of_conduct/{key}"]
- },
- codespaces: {
- addRepositoryForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
- codespaceMachinesForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/machines"],
- createForAuthenticatedUser: ["POST /user/codespaces"],
- createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
- createOrUpdateSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}"],
- createWithPrForAuthenticatedUser: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],
- createWithRepoForAuthenticatedUser: ["POST /repos/{owner}/{repo}/codespaces"],
- deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"],
- deleteFromOrganization: ["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],
- deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
- deleteSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}"],
- exportForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/exports"],
- getExportDetailsForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/exports/{export_id}"],
- getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"],
- getPublicKeyForAuthenticatedUser: ["GET /user/codespaces/secrets/public-key"],
- getRepoPublicKey: ["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],
- getRepoSecret: ["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
- getSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}"],
- listDevcontainersInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/devcontainers"],
- listForAuthenticatedUser: ["GET /user/codespaces"],
- listInOrganization: ["GET /orgs/{org}/codespaces", {}, {
- renamedParameters: {
- org_id: "org"
- }
- }],
- listInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces"],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"],
- listRepositoriesForSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}/repositories"],
- listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"],
- removeRepositoryForSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
- repoMachinesForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/machines"],
- setRepositoriesForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories"],
- startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"],
- stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"],
- stopInOrganization: ["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],
- updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"]
- },
- dependabot: {
- addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
- createOrUpdateOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],
- createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
- deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],
- deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
- getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"],
- getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"],
- getRepoPublicKey: ["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],
- getRepoSecret: ["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
- listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"],
- listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"],
- listSelectedReposForOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],
- removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
- setSelectedReposForOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]
- },
- dependencyGraph: {
- createRepositorySnapshot: ["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],
- diffRange: ["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"]
- },
- emojis: {
- get: ["GET /emojis"]
- },
- enterpriseAdmin: {
- addCustomLabelsToSelfHostedRunnerForEnterprise: ["POST /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
- disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
- enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
- getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"],
- getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"],
- getServerStatistics: ["GET /enterprise-installation/{enterprise_or_org}/server-statistics"],
- listLabelsForSelfHostedRunnerForEnterprise: ["GET /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
- listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"],
- removeAllCustomLabelsFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
- removeCustomLabelFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels/{name}"],
- setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"],
- setCustomLabelsForSelfHostedRunnerForEnterprise: ["PUT /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
- setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"],
- setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"]
- },
- gists: {
- checkIsStarred: ["GET /gists/{gist_id}/star"],
- create: ["POST /gists"],
- createComment: ["POST /gists/{gist_id}/comments"],
- delete: ["DELETE /gists/{gist_id}"],
- deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
- fork: ["POST /gists/{gist_id}/forks"],
- get: ["GET /gists/{gist_id}"],
- getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
- getRevision: ["GET /gists/{gist_id}/{sha}"],
- list: ["GET /gists"],
- listComments: ["GET /gists/{gist_id}/comments"],
- listCommits: ["GET /gists/{gist_id}/commits"],
- listForUser: ["GET /users/{username}/gists"],
- listForks: ["GET /gists/{gist_id}/forks"],
- listPublic: ["GET /gists/public"],
- listStarred: ["GET /gists/starred"],
- star: ["PUT /gists/{gist_id}/star"],
- unstar: ["DELETE /gists/{gist_id}/star"],
- update: ["PATCH /gists/{gist_id}"],
- updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
- },
- git: {
- createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
- createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
- createRef: ["POST /repos/{owner}/{repo}/git/refs"],
- createTag: ["POST /repos/{owner}/{repo}/git/tags"],
- createTree: ["POST /repos/{owner}/{repo}/git/trees"],
- deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
- getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
- getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
- getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
- getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
- getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
- listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
- updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
- },
- gitignore: {
- getAllTemplates: ["GET /gitignore/templates"],
- getTemplate: ["GET /gitignore/templates/{name}"]
- },
- interactions: {
- getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
- getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
- getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
- getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, {
- renamed: ["interactions", "getRestrictionsForAuthenticatedUser"]
- }],
- removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
- removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
- removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"],
- removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, {
- renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"]
- }],
- setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
- setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
- setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
- setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, {
- renamed: ["interactions", "setRestrictionsForAuthenticatedUser"]
- }]
- },
- issues: {
- addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
- addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
- create: ["POST /repos/{owner}/{repo}/issues"],
- createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],
- createLabel: ["POST /repos/{owner}/{repo}/labels"],
- createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
- deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],
- deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
- deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],
- get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
- getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
- getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
- getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
- getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
- list: ["GET /issues"],
- listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
- listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
- listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
- listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
- listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
- listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],
- listForAuthenticatedUser: ["GET /user/issues"],
- listForOrg: ["GET /orgs/{org}/issues"],
- listForRepo: ["GET /repos/{owner}/{repo}/issues"],
- listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],
- listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
- listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
- lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
- removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
- removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],
- setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
- unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
- update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
- updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
- updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
- updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]
- },
- licenses: {
- get: ["GET /licenses/{license}"],
- getAllCommonlyUsed: ["GET /licenses"],
- getForRepo: ["GET /repos/{owner}/{repo}/license"]
- },
- markdown: {
- render: ["POST /markdown"],
- renderRaw: ["POST /markdown/raw", {
- headers: {
- "content-type": "text/plain; charset=utf-8"
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause()
}
- }]
- },
- meta: {
- get: ["GET /meta"],
- getOctocat: ["GET /octocat"],
- getZen: ["GET /zen"],
- root: ["GET /"]
- },
- migrations: {
- cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
- deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"],
- deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"],
- downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"],
- getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"],
- getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
- getImportStatus: ["GET /repos/{owner}/{repo}/import"],
- getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
- getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
- getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
- listForAuthenticatedUser: ["GET /user/migrations"],
- listForOrg: ["GET /orgs/{org}/migrations"],
- listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"],
- listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
- listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, {
- renamed: ["migrations", "listReposForAuthenticatedUser"]
- }],
- mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
- setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
- startForAuthenticatedUser: ["POST /user/migrations"],
- startForOrg: ["POST /orgs/{org}/migrations"],
- startImport: ["PUT /repos/{owner}/{repo}/import"],
- unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],
- unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"],
- updateImport: ["PATCH /repos/{owner}/{repo}/import"]
- },
- orgs: {
- blockUser: ["PUT /orgs/{org}/blocks/{username}"],
- cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
- checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
- checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
- checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
- convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"],
- createInvitation: ["POST /orgs/{org}/invitations"],
- createWebhook: ["POST /orgs/{org}/hooks"],
- deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
- get: ["GET /orgs/{org}"],
- getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
- getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
- getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
- getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
- getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],
- list: ["GET /organizations"],
- listAppInstallations: ["GET /orgs/{org}/installations"],
- listBlockedUsers: ["GET /orgs/{org}/blocks"],
- listCustomRoles: ["GET /organizations/{organization_id}/custom_roles"],
- listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
- listForAuthenticatedUser: ["GET /user/orgs"],
- listForUser: ["GET /users/{username}/orgs"],
- listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
- listMembers: ["GET /orgs/{org}/members"],
- listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
- listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
- listPendingInvitations: ["GET /orgs/{org}/invitations"],
- listPublicMembers: ["GET /orgs/{org}/public_members"],
- listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
- listWebhooks: ["GET /orgs/{org}/hooks"],
- pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
- redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
- removeMember: ["DELETE /orgs/{org}/members/{username}"],
- removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
- removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"],
- removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"],
- setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
- setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"],
- unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
- update: ["PATCH /orgs/{org}"],
- updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"],
- updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
- updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
- },
- packages: {
- deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"],
- deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],
- deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"],
- deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, {
- renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"]
- }],
- getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, {
- renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]
- }],
- getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"],
- getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],
- getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"],
- getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"],
- getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"],
- getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"],
- getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
- listPackagesForAuthenticatedUser: ["GET /user/packages"],
- listPackagesForOrganization: ["GET /orgs/{org}/packages"],
- listPackagesForUser: ["GET /users/{username}/packages"],
- restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"],
- restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],
- restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],
- restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
- restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
- restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]
- },
- projects: {
- addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
- createCard: ["POST /projects/columns/{column_id}/cards"],
- createColumn: ["POST /projects/{project_id}/columns"],
- createForAuthenticatedUser: ["POST /user/projects"],
- createForOrg: ["POST /orgs/{org}/projects"],
- createForRepo: ["POST /repos/{owner}/{repo}/projects"],
- delete: ["DELETE /projects/{project_id}"],
- deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
- deleteColumn: ["DELETE /projects/columns/{column_id}"],
- get: ["GET /projects/{project_id}"],
- getCard: ["GET /projects/columns/cards/{card_id}"],
- getColumn: ["GET /projects/columns/{column_id}"],
- getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"],
- listCards: ["GET /projects/columns/{column_id}/cards"],
- listCollaborators: ["GET /projects/{project_id}/collaborators"],
- listColumns: ["GET /projects/{project_id}/columns"],
- listForOrg: ["GET /orgs/{org}/projects"],
- listForRepo: ["GET /repos/{owner}/{repo}/projects"],
- listForUser: ["GET /users/{username}/projects"],
- moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
- moveColumn: ["POST /projects/columns/{column_id}/moves"],
- removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"],
- update: ["PATCH /projects/{project_id}"],
- updateCard: ["PATCH /projects/columns/cards/{card_id}"],
- updateColumn: ["PATCH /projects/columns/{column_id}"]
- },
- pulls: {
- checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
- create: ["POST /repos/{owner}/{repo}/pulls"],
- createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],
- createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
- createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
- deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
- deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
- dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],
- get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
- getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
- getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
- list: ["GET /repos/{owner}/{repo}/pulls"],
- listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],
- listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
- listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
- listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
- listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
- listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
- listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
- merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
- removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
- requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
- submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],
- update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
- updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],
- updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
- updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]
- },
- rateLimit: {
- get: ["GET /rate_limit"]
- },
- reactions: {
- createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
- createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
- createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
- createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
- createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],
- createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
- createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],
- deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],
- deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],
- deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],
- deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],
- deleteForRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],
- deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],
- deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],
- listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
- listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
- listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
- listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
- listForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],
- listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
- listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]
- },
- repos: {
- acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, {
- renamed: ["repos", "acceptInvitationForAuthenticatedUser"]
- }],
- acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"],
- addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
- mapToData: "apps"
- }],
- addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
- addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
- mapToData: "contexts"
- }],
- addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
- mapToData: "teams"
- }],
- addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
- mapToData: "users"
- }],
- checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
- checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"],
- codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"],
- compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
- compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"],
- createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
- createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
- createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
- createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
- createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
- createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
- createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
- createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
- createForAuthenticatedUser: ["POST /user/repos"],
- createFork: ["POST /repos/{owner}/{repo}/forks"],
- createInOrg: ["POST /orgs/{org}/repos"],
- createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"],
- createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
- createPagesSite: ["POST /repos/{owner}/{repo}/pages"],
- createRelease: ["POST /repos/{owner}/{repo}/releases"],
- createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"],
- createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"],
- createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
- declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, {
- renamed: ["repos", "declineInvitationForAuthenticatedUser"]
- }],
- declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"],
- delete: ["DELETE /repos/{owner}/{repo}"],
- deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
- deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
- deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],
- deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
- deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
- deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
- deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
- deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
- deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],
- deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
- deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],
- deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"],
- deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
- deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
- deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],
- deleteTagProtection: ["DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}"],
- deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
- disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"],
- disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"],
- disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],
- downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, {
- renamed: ["repos", "downloadZipballArchive"]
- }],
- downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
- downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
- enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"],
- enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"],
- enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"],
- generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"],
- get: ["GET /repos/{owner}/{repo}"],
- getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
- getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
- getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
- getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
- getAllTopics: ["GET /repos/{owner}/{repo}/topics"],
- getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],
- getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
- getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
- getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"],
- getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
- getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
- getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],
- getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
- getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
- getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
- getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
- getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
- getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
- getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
- getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
- getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
- getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
- getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
- getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"],
- getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
- getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
- getPages: ["GET /repos/{owner}/{repo}/pages"],
- getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
- getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
- getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
- getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
- getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
- getReadme: ["GET /repos/{owner}/{repo}/readme"],
- getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
- getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
- getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
- getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
- getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
- getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],
- getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
- getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
- getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],
- getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
- getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
- getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],
- getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],
- listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
- listBranches: ["GET /repos/{owner}/{repo}/branches"],
- listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],
- listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
- listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
- listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
- listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],
- listCommits: ["GET /repos/{owner}/{repo}/commits"],
- listContributors: ["GET /repos/{owner}/{repo}/contributors"],
- listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
- listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
- listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
- listForAuthenticatedUser: ["GET /user/repos"],
- listForOrg: ["GET /orgs/{org}/repos"],
- listForUser: ["GET /users/{username}/repos"],
- listForks: ["GET /repos/{owner}/{repo}/forks"],
- listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
- listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
- listLanguages: ["GET /repos/{owner}/{repo}/languages"],
- listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
- listPublic: ["GET /repositories"],
- listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],
- listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],
- listReleases: ["GET /repos/{owner}/{repo}/releases"],
- listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"],
- listTags: ["GET /repos/{owner}/{repo}/tags"],
- listTeams: ["GET /repos/{owner}/{repo}/teams"],
- listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],
- listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
- merge: ["POST /repos/{owner}/{repo}/merges"],
- mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
- pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
- redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
- removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
- mapToData: "apps"
- }],
- removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"],
- removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
- mapToData: "contexts"
- }],
- removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
- removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
- mapToData: "teams"
- }],
- removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
- mapToData: "users"
- }],
- renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
- replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"],
- requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
- setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
- setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
- mapToData: "apps"
- }],
- setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
- mapToData: "contexts"
- }],
- setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
- mapToData: "teams"
- }],
- setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
- mapToData: "users"
- }],
- testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
- transfer: ["POST /repos/{owner}/{repo}/transfer"],
- update: ["PATCH /repos/{owner}/{repo}"],
- updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],
- updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
- updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
- updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],
- updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
- updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
- updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],
- updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, {
- renamed: ["repos", "updateStatusCheckProtection"]
- }],
- updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
- updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
- updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],
- uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", {
- baseUrl: "https://uploads.github.com"
- }]
- },
- search: {
- code: ["GET /search/code"],
- commits: ["GET /search/commits"],
- issuesAndPullRequests: ["GET /search/issues"],
- labels: ["GET /search/labels"],
- repos: ["GET /search/repositories"],
- topics: ["GET /search/topics"],
- users: ["GET /search/users"]
- },
- secretScanning: {
- getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],
- listAlertsForEnterprise: ["GET /enterprises/{enterprise}/secret-scanning/alerts"],
- listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
- listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
- listLocationsForAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],
- updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"]
- },
- teams: {
- addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],
- addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
- addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
- checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
- checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
- create: ["POST /orgs/{org}/teams"],
- createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
- createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
- deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
- deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
- deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
- getByName: ["GET /orgs/{org}/teams/{team_slug}"],
- getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
- getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
- getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],
- list: ["GET /orgs/{org}/teams"],
- listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
- listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
- listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
- listForAuthenticatedUser: ["GET /user/teams"],
- listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
- listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"],
- listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
- listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
- removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],
- removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
- removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
- updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
- updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
- updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
- },
- users: {
- addEmailForAuthenticated: ["POST /user/emails", {}, {
- renamed: ["users", "addEmailForAuthenticatedUser"]
- }],
- addEmailForAuthenticatedUser: ["POST /user/emails"],
- block: ["PUT /user/blocks/{username}"],
- checkBlocked: ["GET /user/blocks/{username}"],
- checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
- checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
- createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, {
- renamed: ["users", "createGpgKeyForAuthenticatedUser"]
- }],
- createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"],
- createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, {
- renamed: ["users", "createPublicSshKeyForAuthenticatedUser"]
- }],
- createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"],
- deleteEmailForAuthenticated: ["DELETE /user/emails", {}, {
- renamed: ["users", "deleteEmailForAuthenticatedUser"]
- }],
- deleteEmailForAuthenticatedUser: ["DELETE /user/emails"],
- deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, {
- renamed: ["users", "deleteGpgKeyForAuthenticatedUser"]
- }],
- deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"],
- deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, {
- renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"]
- }],
- deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"],
- follow: ["PUT /user/following/{username}"],
- getAuthenticated: ["GET /user"],
- getByUsername: ["GET /users/{username}"],
- getContextForUser: ["GET /users/{username}/hovercard"],
- getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, {
- renamed: ["users", "getGpgKeyForAuthenticatedUser"]
- }],
- getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"],
- getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, {
- renamed: ["users", "getPublicSshKeyForAuthenticatedUser"]
- }],
- getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"],
- list: ["GET /users"],
- listBlockedByAuthenticated: ["GET /user/blocks", {}, {
- renamed: ["users", "listBlockedByAuthenticatedUser"]
- }],
- listBlockedByAuthenticatedUser: ["GET /user/blocks"],
- listEmailsForAuthenticated: ["GET /user/emails", {}, {
- renamed: ["users", "listEmailsForAuthenticatedUser"]
- }],
- listEmailsForAuthenticatedUser: ["GET /user/emails"],
- listFollowedByAuthenticated: ["GET /user/following", {}, {
- renamed: ["users", "listFollowedByAuthenticatedUser"]
- }],
- listFollowedByAuthenticatedUser: ["GET /user/following"],
- listFollowersForAuthenticatedUser: ["GET /user/followers"],
- listFollowersForUser: ["GET /users/{username}/followers"],
- listFollowingForUser: ["GET /users/{username}/following"],
- listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, {
- renamed: ["users", "listGpgKeysForAuthenticatedUser"]
- }],
- listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"],
- listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
- listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, {
- renamed: ["users", "listPublicEmailsForAuthenticatedUser"]
- }],
- listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"],
- listPublicKeysForUser: ["GET /users/{username}/keys"],
- listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, {
- renamed: ["users", "listPublicSshKeysForAuthenticatedUser"]
- }],
- listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
- setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, {
- renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"]
- }],
- setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"],
- unblock: ["DELETE /user/blocks/{username}"],
- unfollow: ["DELETE /user/following/{username}"],
- updateAuthenticated: ["PATCH /user"]
+ } catch (err) {
+ util.destroy(this, err)
+ }
}
-};
+ const onDrain = function () {
+ if (finished) {
+ return
+ }
-const VERSION = "5.16.2";
+ if (body.resume) {
+ body.resume()
+ }
+ }
+ const onAbort = function () {
+ onFinished(new RequestAbortedError())
+ }
+ const onFinished = function (err) {
+ if (finished) {
+ return
+ }
-function endpointsToMethods(octokit, endpointsMap) {
- const newMethods = {};
+ finished = true
- for (const [scope, endpoints] of Object.entries(endpointsMap)) {
- for (const [methodName, endpoint] of Object.entries(endpoints)) {
- const [route, defaults, decorations] = endpoint;
- const [method, url] = route.split(/ /);
- const endpointDefaults = Object.assign({
- method,
- url
- }, defaults);
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
- if (!newMethods[scope]) {
- newMethods[scope] = {};
- }
+ socket
+ .off('drain', onDrain)
+ .off('error', onFinished)
- const scopeMethods = newMethods[scope];
+ body
+ .removeListener('data', onData)
+ .removeListener('end', onFinished)
+ .removeListener('error', onFinished)
+ .removeListener('close', onAbort)
- if (decorations) {
- scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);
- continue;
+ if (!err) {
+ try {
+ writer.end()
+ } catch (er) {
+ err = er
}
+ }
+
+ writer.destroy(err)
- scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
+ util.destroy(body, err)
+ } else {
+ util.destroy(body)
}
}
- return newMethods;
-}
-
-function decorate(octokit, scope, methodName, defaults, decorations) {
- const requestWithDefaults = octokit.request.defaults(defaults);
- /* istanbul ignore next */
+ body
+ .on('data', onData)
+ .on('end', onFinished)
+ .on('error', onFinished)
+ .on('close', onAbort)
- function withDecorations(...args) {
- // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
- let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`
+ if (body.resume) {
+ body.resume()
+ }
- if (decorations.mapToData) {
- options = Object.assign({}, options, {
- data: options[decorations.mapToData],
- [decorations.mapToData]: undefined
- });
- return requestWithDefaults(options);
- }
+ socket
+ .on('drain', onDrain)
+ .on('error', onFinished)
+}
- if (decorations.renamed) {
- const [newScope, newMethodName] = decorations.renamed;
- octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);
- }
+async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength === body.size, 'blob body must have content length')
- if (decorations.deprecated) {
- octokit.log.warn(decorations.deprecated);
+ const isH2 = client[kHTTPConnVersion] === 'h2'
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
}
- if (decorations.renamedParameters) {
- // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
- const options = requestWithDefaults.endpoint.merge(...args);
-
- for (const [name, alias] of Object.entries(decorations.renamedParameters)) {
- if (name in options) {
- octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`);
-
- if (!(alias in options)) {
- options[alias] = options[name];
- }
+ const buffer = Buffer.from(await body.arrayBuffer())
- delete options[name];
- }
- }
+ if (isH2) {
+ h2stream.cork()
+ h2stream.write(buffer)
+ h2stream.uncork()
+ } else {
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(buffer)
+ socket.uncork()
+ }
- return requestWithDefaults(options);
- } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
+ request.onBodySent(buffer)
+ request.onRequestSent()
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
- return requestWithDefaults(...args);
+ resume(client)
+ } catch (err) {
+ util.destroy(isH2 ? h2stream : socket, err)
}
-
- return Object.assign(withDecorations, requestWithDefaults);
}
-function restEndpointMethods(octokit) {
- const api = endpointsToMethods(octokit, Endpoints);
- return {
- rest: api
- };
-}
-restEndpointMethods.VERSION = VERSION;
-function legacyRestEndpointMethods(octokit) {
- const api = endpointsToMethods(octokit, Endpoints);
- return _objectSpread2(_objectSpread2({}, api), {}, {
- rest: api
- });
-}
-legacyRestEndpointMethods.VERSION = VERSION;
+async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
-exports.legacyRestEndpointMethods = legacyRestEndpointMethods;
-exports.restEndpointMethods = restEndpointMethods;
-//# sourceMappingURL=index.js.map
+ let callback = null
+ function onDrain () {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb()
+ }
+ }
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
-/***/ }),
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
+ }
+ })
-/***/ 10537:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (client[kHTTPConnVersion] === 'h2') {
+ h2stream
+ .on('close', onDrain)
+ .on('drain', onDrain)
-"use strict";
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+ if (!h2stream.write(chunk)) {
+ await waitForDrain()
+ }
+ }
+ } catch (err) {
+ h2stream.destroy(err)
+ } finally {
+ h2stream
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ return
+ }
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+ socket
+ .on('close', onDrain)
+ .on('drain', onDrain)
-var deprecation = __nccwpck_require__(58932);
-var once = _interopDefault(__nccwpck_require__(1223));
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
-const logOnceCode = once(deprecation => console.warn(deprecation));
-const logOnceHeaders = once(deprecation => console.warn(deprecation));
-/**
- * Error with extra properties to help with debugging
- */
+ if (!writer.write(chunk)) {
+ await waitForDrain()
+ }
+ }
-class RequestError extends Error {
- constructor(message, statusCode, options) {
- super(message); // Maintains proper stack trace (only available on V8)
+ writer.end()
+ } catch (err) {
+ writer.destroy(err)
+ } finally {
+ socket
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+}
- /* istanbul ignore next */
+class AsyncWriter {
+ constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
+ this.socket = socket
+ this.request = request
+ this.contentLength = contentLength
+ this.client = client
+ this.bytesWritten = 0
+ this.expectsPayload = expectsPayload
+ this.header = header
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
+ socket[kWriting] = true
+ }
- this.name = "HttpError";
- this.status = statusCode;
- let headers;
+ write (chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
- if ("headers" in options && typeof options.headers !== "undefined") {
- headers = options.headers;
+ if (socket[kError]) {
+ throw socket[kError]
}
- if ("response" in options) {
- this.response = options.response;
- headers = options.response.headers;
- } // redact request credentials without mutating original request options
+ if (socket.destroyed) {
+ return false
+ }
+ const len = Buffer.byteLength(chunk)
+ if (!len) {
+ return true
+ }
- const requestCopy = Object.assign({}, options.request);
+ // We should defer writing chunks.
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ }
- if (options.request.headers.authorization) {
- requestCopy.headers = Object.assign({}, options.request.headers, {
- authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
- });
+ process.emitWarning(new RequestContentLengthMismatchError())
}
- requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
- // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
- .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
- // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
- .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
- this.request = requestCopy; // deprecations
+ socket.cork()
- Object.defineProperty(this, "code", {
- get() {
- logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
- return statusCode;
+ if (bytesWritten === 0) {
+ if (!expectsPayload) {
+ socket[kReset] = true
}
- });
- Object.defineProperty(this, "headers", {
- get() {
- logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
- return headers || {};
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
}
+ }
- });
- }
-
-}
-
-exports.RequestError = RequestError;
-//# sourceMappingURL=index.js.map
-
+ if (contentLength === null) {
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ }
-/***/ }),
+ this.bytesWritten += len
-/***/ 36234:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const ret = socket.write(chunk)
-"use strict";
+ socket.uncork()
+ request.onBodySent(chunk)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
-
-var endpoint = __nccwpck_require__(59440);
-var universalUserAgent = __nccwpck_require__(45030);
-var isPlainObject = __nccwpck_require__(63287);
-var nodeFetch = _interopDefault(__nccwpck_require__(81768));
-var requestError = __nccwpck_require__(10537);
-
-const VERSION = "5.6.3";
-
-function getBufferResponse(response) {
- return response.arrayBuffer();
-}
-
-function fetchWrapper(requestOptions) {
- const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+ if (!ret) {
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
+ }
- if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
- requestOptions.body = JSON.stringify(requestOptions.body);
+ return ret
}
- let headers = {};
- let status;
- let url;
- const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;
- return fetch(requestOptions.url, Object.assign({
- method: requestOptions.method,
- body: requestOptions.body,
- headers: requestOptions.headers,
- redirect: requestOptions.redirect
- }, // `requestOptions.request.agent` type is incompatible
- // see https://github.com/octokit/types.ts/pull/264
- requestOptions.request)).then(async response => {
- url = response.url;
- status = response.status;
+ end () {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
+ request.onRequestSent()
+
+ socket[kWriting] = false
- for (const keyAndValue of response.headers) {
- headers[keyAndValue[0]] = keyAndValue[1];
+ if (socket[kError]) {
+ throw socket[kError]
}
- if ("deprecation" in headers) {
- const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
- const deprecationLink = matches && matches.pop();
- log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
+ if (socket.destroyed) {
+ return
}
- if (status === 204 || status === 205) {
- return;
- } // GitHub API returns 200 for HEAD requests
-
+ if (bytesWritten === 0) {
+ if (expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD send a Content-Length in a request message when
+ // no Transfer-Encoding is sent and the request method defines a meaning
+ // for an enclosed payload body.
- if (requestOptions.method === "HEAD") {
- if (status < 400) {
- return;
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}\r\n`, 'latin1')
}
-
- throw new requestError.RequestError(response.statusText, status, {
- response: {
- url,
- status,
- headers,
- data: undefined
- },
- request: requestOptions
- });
+ } else if (contentLength === null) {
+ socket.write('\r\n0\r\n\r\n', 'latin1')
}
- if (status === 304) {
- throw new requestError.RequestError("Not modified", status, {
- response: {
- url,
- status,
- headers,
- data: await getResponseData(response)
- },
- request: requestOptions
- });
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
}
- if (status >= 400) {
- const data = await getResponseData(response);
- const error = new requestError.RequestError(toErrorMessage(data), status, {
- response: {
- url,
- status,
- headers,
- data
- },
- request: requestOptions
- });
- throw error;
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
}
- return getResponseData(response);
- }).then(data => {
- return {
- status,
- url,
- headers,
- data
- };
- }).catch(error => {
- if (error instanceof requestError.RequestError) throw error;
- throw new requestError.RequestError(error.message, 500, {
- request: requestOptions
- });
- });
-}
-
-async function getResponseData(response) {
- const contentType = response.headers.get("content-type");
-
- if (/application\/json/.test(contentType)) {
- return response.json();
- }
-
- if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
- return response.text();
+ resume(client)
}
- return getBufferResponse(response);
-}
-
-function toErrorMessage(data) {
- if (typeof data === "string") return data; // istanbul ignore else - just in case
-
- if ("message" in data) {
- if (Array.isArray(data.errors)) {
- return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
- }
-
- return data.message;
- } // istanbul ignore next - just in case
-
-
- return `Unknown error: ${JSON.stringify(data)}`;
-}
-
-function withDefaults(oldEndpoint, newDefaults) {
- const endpoint = oldEndpoint.defaults(newDefaults);
+ destroy (err) {
+ const { socket, client } = this
- const newApi = function (route, parameters) {
- const endpointOptions = endpoint.merge(route, parameters);
+ socket[kWriting] = false
- if (!endpointOptions.request || !endpointOptions.request.hook) {
- return fetchWrapper(endpoint.parse(endpointOptions));
+ if (err) {
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
+ util.destroy(socket, err)
}
-
- const request = (route, parameters) => {
- return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
- };
-
- Object.assign(request, {
- endpoint,
- defaults: withDefaults.bind(null, endpoint)
- });
- return endpointOptions.request.hook(request, endpointOptions);
- };
-
- return Object.assign(newApi, {
- endpoint,
- defaults: withDefaults.bind(null, endpoint)
- });
+ }
}
-const request = withDefaults(endpoint.endpoint, {
- headers: {
- "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+function errorRequest (client, request, err) {
+ try {
+ request.onError(err)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
}
-});
+}
-exports.request = request;
-//# sourceMappingURL=index.js.map
+module.exports = Client
/***/ }),
-/***/ 81768:
-/***/ ((module, exports, __nccwpck_require__) => {
-
-"use strict";
+/***/ 3194:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
-
-var Stream = _interopDefault(__nccwpck_require__(12781));
-var http = _interopDefault(__nccwpck_require__(13685));
-var Url = _interopDefault(__nccwpck_require__(57310));
-var whatwgUrl = _interopDefault(__nccwpck_require__(28665));
-var https = _interopDefault(__nccwpck_require__(95687));
-var zlib = _interopDefault(__nccwpck_require__(59796));
-
-// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
-
-// fix for "Readable" isn't a named export issue
-const Readable = Stream.Readable;
-
-const BUFFER = Symbol('buffer');
-const TYPE = Symbol('type');
-
-class Blob {
- constructor() {
- this[TYPE] = '';
-
- const blobParts = arguments[0];
- const options = arguments[1];
-
- const buffers = [];
- let size = 0;
-
- if (blobParts) {
- const a = blobParts;
- const length = Number(a.length);
- for (let i = 0; i < length; i++) {
- const element = a[i];
- let buffer;
- if (element instanceof Buffer) {
- buffer = element;
- } else if (ArrayBuffer.isView(element)) {
- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
- } else if (element instanceof ArrayBuffer) {
- buffer = Buffer.from(element);
- } else if (element instanceof Blob) {
- buffer = element[BUFFER];
- } else {
- buffer = Buffer.from(typeof element === 'string' ? element : String(element));
- }
- size += buffer.length;
- buffers.push(buffer);
- }
- }
-
- this[BUFFER] = Buffer.concat(buffers);
-
- let type = options && options.type !== undefined && String(options.type).toLowerCase();
- if (type && !/[^\u0020-\u007E]/.test(type)) {
- this[TYPE] = type;
- }
- }
- get size() {
- return this[BUFFER].length;
- }
- get type() {
- return this[TYPE];
- }
- text() {
- return Promise.resolve(this[BUFFER].toString());
- }
- arrayBuffer() {
- const buf = this[BUFFER];
- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- return Promise.resolve(ab);
- }
- stream() {
- const readable = new Readable();
- readable._read = function () {};
- readable.push(this[BUFFER]);
- readable.push(null);
- return readable;
- }
- toString() {
- return '[object Blob]';
- }
- slice() {
- const size = this.size;
-
- const start = arguments[0];
- const end = arguments[1];
- let relativeStart, relativeEnd;
- if (start === undefined) {
- relativeStart = 0;
- } else if (start < 0) {
- relativeStart = Math.max(size + start, 0);
- } else {
- relativeStart = Math.min(start, size);
- }
- if (end === undefined) {
- relativeEnd = size;
- } else if (end < 0) {
- relativeEnd = Math.max(size + end, 0);
- } else {
- relativeEnd = Math.min(end, size);
- }
- const span = Math.max(relativeEnd - relativeStart, 0);
-
- const buffer = this[BUFFER];
- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
- const blob = new Blob([], { type: arguments[2] });
- blob[BUFFER] = slicedBuffer;
- return blob;
- }
-}
-
-Object.defineProperties(Blob.prototype, {
- size: { enumerable: true },
- type: { enumerable: true },
- slice: { enumerable: true }
-});
+/* istanbul ignore file: only for Node 12 */
-Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
- value: 'Blob',
- writable: false,
- enumerable: false,
- configurable: true
-});
+const { kConnected, kSize } = __nccwpck_require__(6443)
-/**
- * fetch-error.js
- *
- * FetchError interface for operational errors
- */
+class CompatWeakRef {
+ constructor (value) {
+ this.value = value
+ }
-/**
- * Create FetchError instance
- *
- * @param String message Error message for human
- * @param String type Error type for machine
- * @param String systemError For Node.js system error
- * @return FetchError
- */
-function FetchError(message, type, systemError) {
- Error.call(this, message);
+ deref () {
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
+ ? undefined
+ : this.value
+ }
+}
- this.message = message;
- this.type = type;
+class CompatFinalizer {
+ constructor (finalizer) {
+ this.finalizer = finalizer
+ }
- // when err.type is `system`, err.code contains system error code
- if (systemError) {
- this.code = this.errno = systemError.code;
+ register (dispatcher, key) {
+ dispatcher.on('disconnect', () => {
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
+ this.finalizer(key)
+ }
+ })
}
+}
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
+module.exports = function () {
+ // FIXME: remove workaround when the Node bug is fixed
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+ if (process.env.NODE_V8_COVERAGE) {
+ return {
+ WeakRef: CompatWeakRef,
+ FinalizationRegistry: CompatFinalizer
+ }
+ }
+ return {
+ WeakRef: global.WeakRef || CompatWeakRef,
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+ }
}
-FetchError.prototype = Object.create(Error.prototype);
-FetchError.prototype.constructor = FetchError;
-FetchError.prototype.name = 'FetchError';
-let convert;
-try {
- convert = (__nccwpck_require__(22877).convert);
-} catch (e) {}
+/***/ }),
-const INTERNALS = Symbol('Body internals');
+/***/ 9237:
+/***/ ((module) => {
-// fix an issue where "PassThrough" isn't a named export for node <10
-const PassThrough = Stream.PassThrough;
-/**
- * Body mixin
- *
- * Ref: https://fetch.spec.whatwg.org/#body
- *
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
- */
-function Body(body) {
- var _this = this;
-
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
- _ref$size = _ref.size;
-
- let size = _ref$size === undefined ? 0 : _ref$size;
- var _ref$timeout = _ref.timeout;
- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
-
- if (body == null) {
- // body is undefined or null
- body = null;
- } else if (isURLSearchParams(body)) {
- // body is a URLSearchParams
- body = Buffer.from(body.toString());
- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
- // body is ArrayBuffer
- body = Buffer.from(body);
- } else if (ArrayBuffer.isView(body)) {
- // body is ArrayBufferView
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
- } else if (body instanceof Stream) ; else {
- // none of the above
- // coerce to string then buffer
- body = Buffer.from(String(body));
- }
- this[INTERNALS] = {
- body,
- disturbed: false,
- error: null
- };
- this.size = size;
- this.timeout = timeout;
-
- if (body instanceof Stream) {
- body.on('error', function (err) {
- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
- _this[INTERNALS].error = error;
- });
- }
-}
-
-Body.prototype = {
- get body() {
- return this[INTERNALS].body;
- },
-
- get bodyUsed() {
- return this[INTERNALS].disturbed;
- },
-
- /**
- * Decode response as ArrayBuffer
- *
- * @return Promise
- */
- arrayBuffer() {
- return consumeBody.call(this).then(function (buf) {
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- });
- },
-
- /**
- * Return raw response as Blob
- *
- * @return Promise
- */
- blob() {
- let ct = this.headers && this.headers.get('content-type') || '';
- return consumeBody.call(this).then(function (buf) {
- return Object.assign(
- // Prevent copying
- new Blob([], {
- type: ct.toLowerCase()
- }), {
- [BUFFER]: buf
- });
- });
- },
-
- /**
- * Decode response as json
- *
- * @return Promise
- */
- json() {
- var _this2 = this;
-
- return consumeBody.call(this).then(function (buffer) {
- try {
- return JSON.parse(buffer.toString());
- } catch (err) {
- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
- }
- });
- },
-
- /**
- * Decode response as text
- *
- * @return Promise
- */
- text() {
- return consumeBody.call(this).then(function (buffer) {
- return buffer.toString();
- });
- },
-
- /**
- * Decode response as buffer (non-spec api)
- *
- * @return Promise
- */
- buffer() {
- return consumeBody.call(this);
- },
-
- /**
- * Decode response as text, while automatically detecting the encoding and
- * trying to decode to UTF-8 (non-spec api)
- *
- * @return Promise
- */
- textConverted() {
- var _this3 = this;
-
- return consumeBody.call(this).then(function (buffer) {
- return convertBody(buffer, _this3.headers);
- });
- }
-};
-// In browsers, all properties are enumerable.
-Object.defineProperties(Body.prototype, {
- body: { enumerable: true },
- bodyUsed: { enumerable: true },
- arrayBuffer: { enumerable: true },
- blob: { enumerable: true },
- json: { enumerable: true },
- text: { enumerable: true }
-});
+// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
+const maxAttributeValueSize = 1024
-Body.mixIn = function (proto) {
- for (const name of Object.getOwnPropertyNames(Body.prototype)) {
- // istanbul ignore else: future proof
- if (!(name in proto)) {
- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
- Object.defineProperty(proto, name, desc);
- }
- }
-};
+// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
+const maxNameValuePairSize = 4096
-/**
- * Consume and convert an entire Body to a Buffer.
- *
- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
- *
- * @return Promise
- */
-function consumeBody() {
- var _this4 = this;
-
- if (this[INTERNALS].disturbed) {
- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
- }
-
- this[INTERNALS].disturbed = true;
-
- if (this[INTERNALS].error) {
- return Body.Promise.reject(this[INTERNALS].error);
- }
-
- let body = this.body;
-
- // body is null
- if (body === null) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
-
- // body is blob
- if (isBlob(body)) {
- body = body.stream();
- }
-
- // body is buffer
- if (Buffer.isBuffer(body)) {
- return Body.Promise.resolve(body);
- }
-
- // istanbul ignore if: should never happen
- if (!(body instanceof Stream)) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
-
- // body is stream
- // get ready to actually consume the body
- let accum = [];
- let accumBytes = 0;
- let abort = false;
-
- return new Body.Promise(function (resolve, reject) {
- let resTimeout;
-
- // allow timeout on slow response body
- if (_this4.timeout) {
- resTimeout = setTimeout(function () {
- abort = true;
- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
- }, _this4.timeout);
- }
-
- // handle stream errors
- body.on('error', function (err) {
- if (err.name === 'AbortError') {
- // if the request was aborted, reject with this Error
- abort = true;
- reject(err);
- } else {
- // other errors, such as incorrect content-encoding
- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
-
- body.on('data', function (chunk) {
- if (abort || chunk === null) {
- return;
- }
-
- if (_this4.size && accumBytes + chunk.length > _this4.size) {
- abort = true;
- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
- return;
- }
-
- accumBytes += chunk.length;
- accum.push(chunk);
- });
-
- body.on('end', function () {
- if (abort) {
- return;
- }
-
- clearTimeout(resTimeout);
-
- try {
- resolve(Buffer.concat(accum, accumBytes));
- } catch (err) {
- // handle streams that have accumulated too much data (issue #414)
- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
- });
+module.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
}
-/**
- * Detect buffer encoding and convert to target encoding
- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
- *
- * @param Buffer buffer Incoming buffer
- * @param String encoding Target encoding
- * @return String
- */
-function convertBody(buffer, headers) {
- if (typeof convert !== 'function') {
- throw new Error('The package `encoding` must be installed to use the textConverted() function');
- }
-
- const ct = headers.get('content-type');
- let charset = 'utf-8';
- let res, str;
-
- // header
- if (ct) {
- res = /charset=([^;]*)/i.exec(ct);
- }
-
- // no charset in content type, peek at response body for at most 1024 bytes
- str = buffer.slice(0, 1024).toString();
-
- // html5
- if (!res && str) {
- res = / {
-/**
- * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
- * @param {*} obj
- * @return {boolean}
- */
-function isBlob(obj) {
- return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
-}
-/**
- * Clone body given Res/Req instance
- *
- * @param Mixed instance Response or Request instance
- * @return Mixed
- */
-function clone(instance) {
- let p1, p2;
- let body = instance.body;
-
- // don't allow cloning a used body
- if (instance.bodyUsed) {
- throw new Error('cannot clone body after it is used');
- }
-
- // check that body is a stream and not form-data object
- // note: we can't clone the form-data object without having it as a dependency
- if (body instanceof Stream && typeof body.getBoundary !== 'function') {
- // tee instance body
- p1 = new PassThrough();
- p2 = new PassThrough();
- body.pipe(p1);
- body.pipe(p2);
- // set instance body to teed body and return the other teed body
- instance[INTERNALS].body = p1;
- body = p2;
- }
-
- return body;
-}
-/**
- * Performs the operation "extract a `Content-Type` value from |object|" as
- * specified in the specification:
- * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
- *
- * This function assumes that instance.body is present.
- *
- * @param Mixed instance Any options.body input
- */
-function extractContentType(body) {
- if (body === null) {
- // body is null
- return null;
- } else if (typeof body === 'string') {
- // body is string
- return 'text/plain;charset=UTF-8';
- } else if (isURLSearchParams(body)) {
- // body is a URLSearchParams
- return 'application/x-www-form-urlencoded;charset=UTF-8';
- } else if (isBlob(body)) {
- // body is blob
- return body.type || null;
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- return null;
- } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
- // body is ArrayBuffer
- return null;
- } else if (ArrayBuffer.isView(body)) {
- // body is ArrayBufferView
- return null;
- } else if (typeof body.getBoundary === 'function') {
- // detect form data input from form-data module
- return `multipart/form-data;boundary=${body.getBoundary()}`;
- } else if (body instanceof Stream) {
- // body is stream
- // can't really do much about this
- return null;
- } else {
- // Body constructor defaults other things to string
- return 'text/plain;charset=UTF-8';
- }
-}
+const { parseSetCookie } = __nccwpck_require__(8915)
+const { stringify, getHeadersList } = __nccwpck_require__(3834)
+const { webidl } = __nccwpck_require__(4222)
+const { Headers } = __nccwpck_require__(6349)
/**
- * The Fetch Standard treats this as if "total bytes" is a property on the body.
- * For us, we have to explicitly get it with a function.
- *
- * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
- *
- * @param Body instance Instance of Body
- * @return Number? Number of bytes, or null if not possible
+ * @typedef {Object} Cookie
+ * @property {string} name
+ * @property {string} value
+ * @property {Date|number|undefined} expires
+ * @property {number|undefined} maxAge
+ * @property {string|undefined} domain
+ * @property {string|undefined} path
+ * @property {boolean|undefined} secure
+ * @property {boolean|undefined} httpOnly
+ * @property {'Strict'|'Lax'|'None'} sameSite
+ * @property {string[]} unparsed
*/
-function getTotalBytes(instance) {
- const body = instance.body;
-
-
- if (body === null) {
- // body is null
- return 0;
- } else if (isBlob(body)) {
- return body.size;
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- return body.length;
- } else if (body && typeof body.getLengthSync === 'function') {
- // detect form data input from form-data module
- if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
- body.hasKnownLength && body.hasKnownLength()) {
- // 2.x
- return body.getLengthSync();
- }
- return null;
- } else {
- // body is stream
- return null;
- }
-}
/**
- * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
- *
- * @param Body instance Instance of Body
- * @return Void
+ * @param {Headers} headers
+ * @returns {Record}
*/
-function writeToStream(dest, instance) {
- const body = instance.body;
-
+function getCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
- if (body === null) {
- // body is null
- dest.end();
- } else if (isBlob(body)) {
- body.stream().pipe(dest);
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- dest.write(body);
- dest.end();
- } else {
- // body is stream
- body.pipe(dest);
- }
-}
+ webidl.brandCheck(headers, Headers, { strict: false })
-// expose Promise
-Body.Promise = global.Promise;
+ const cookie = headers.get('cookie')
+ const out = {}
-/**
- * headers.js
- *
- * Headers class offers convenient helpers
- */
+ if (!cookie) {
+ return out
+ }
-const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
-const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
+ for (const piece of cookie.split(';')) {
+ const [name, ...value] = piece.split('=')
-function validateName(name) {
- name = `${name}`;
- if (invalidTokenRegex.test(name) || name === '') {
- throw new TypeError(`${name} is not a legal HTTP header name`);
- }
-}
+ out[name.trim()] = value.join('=')
+ }
-function validateValue(value) {
- value = `${value}`;
- if (invalidHeaderCharRegex.test(value)) {
- throw new TypeError(`${value} is not a legal HTTP header value`);
- }
+ return out
}
/**
- * Find the key in the map object given a header name.
- *
- * Returns undefined if not found.
- *
- * @param String name Header name
- * @return String|Undefined
+ * @param {Headers} headers
+ * @param {string} name
+ * @param {{ path?: string, domain?: string }|undefined} attributes
+ * @returns {void}
*/
-function find(map, name) {
- name = name.toLowerCase();
- for (const key in map) {
- if (key.toLowerCase() === name) {
- return key;
- }
- }
- return undefined;
-}
-
-const MAP = Symbol('map');
-class Headers {
- /**
- * Headers class
- *
- * @param Object headers Response headers
- * @return Void
- */
- constructor() {
- let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
-
- this[MAP] = Object.create(null);
-
- if (init instanceof Headers) {
- const rawHeaders = init.raw();
- const headerNames = Object.keys(rawHeaders);
-
- for (const headerName of headerNames) {
- for (const value of rawHeaders[headerName]) {
- this.append(headerName, value);
- }
- }
-
- return;
- }
-
- // We don't worry about converting prop to ByteString here as append()
- // will handle it.
- if (init == null) ; else if (typeof init === 'object') {
- const method = init[Symbol.iterator];
- if (method != null) {
- if (typeof method !== 'function') {
- throw new TypeError('Header pairs must be iterable');
- }
-
- // sequence>
- // Note: per spec we have to first exhaust the lists then process them
- const pairs = [];
- for (const pair of init) {
- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
- throw new TypeError('Each header pair must be iterable');
- }
- pairs.push(Array.from(pair));
- }
-
- for (const pair of pairs) {
- if (pair.length !== 2) {
- throw new TypeError('Each header pair must be a name/value tuple');
- }
- this.append(pair[0], pair[1]);
- }
- } else {
- // record
- for (const key of Object.keys(init)) {
- const value = init[key];
- this.append(key, value);
- }
- }
- } else {
- throw new TypeError('Provided initializer must be an object');
- }
- }
-
- /**
- * Return combined header value given name
- *
- * @param String name Header name
- * @return Mixed
- */
- get(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key === undefined) {
- return null;
- }
-
- return this[MAP][key].join(', ');
- }
-
- /**
- * Iterate over all headers
- *
- * @param Function callback Executed for each item with parameters (value, name, thisArg)
- * @param Boolean thisArg `this` context for callback function
- * @return Void
- */
- forEach(callback) {
- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
-
- let pairs = getHeaders(this);
- let i = 0;
- while (i < pairs.length) {
- var _pairs$i = pairs[i];
- const name = _pairs$i[0],
- value = _pairs$i[1];
-
- callback.call(thisArg, value, name, this);
- pairs = getHeaders(this);
- i++;
- }
- }
-
- /**
- * Overwrite header values given name
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- set(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- this[MAP][key !== undefined ? key : name] = [value];
- }
-
- /**
- * Append a value onto existing header
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- append(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- this[MAP][key].push(value);
- } else {
- this[MAP][name] = [value];
- }
- }
-
- /**
- * Check for header name existence
- *
- * @param String name Header name
- * @return Boolean
- */
- has(name) {
- name = `${name}`;
- validateName(name);
- return find(this[MAP], name) !== undefined;
- }
-
- /**
- * Delete all header values given name
- *
- * @param String name Header name
- * @return Void
- */
- delete(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- delete this[MAP][key];
- }
- }
-
- /**
- * Return raw headers (non-spec api)
- *
- * @return Object
- */
- raw() {
- return this[MAP];
- }
-
- /**
- * Get an iterator on keys.
- *
- * @return Iterator
- */
- keys() {
- return createHeadersIterator(this, 'key');
- }
-
- /**
- * Get an iterator on values.
- *
- * @return Iterator
- */
- values() {
- return createHeadersIterator(this, 'value');
- }
-
- /**
- * Get an iterator on entries.
- *
- * This is the default iterator of the Headers object.
- *
- * @return Iterator
- */
- [Symbol.iterator]() {
- return createHeadersIterator(this, 'key+value');
- }
-}
-Headers.prototype.entries = Headers.prototype[Symbol.iterator];
-
-Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
- value: 'Headers',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-Object.defineProperties(Headers.prototype, {
- get: { enumerable: true },
- forEach: { enumerable: true },
- set: { enumerable: true },
- append: { enumerable: true },
- has: { enumerable: true },
- delete: { enumerable: true },
- keys: { enumerable: true },
- values: { enumerable: true },
- entries: { enumerable: true }
-});
-
-function getHeaders(headers) {
- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
-
- const keys = Object.keys(headers[MAP]).sort();
- return keys.map(kind === 'key' ? function (k) {
- return k.toLowerCase();
- } : kind === 'value' ? function (k) {
- return headers[MAP][k].join(', ');
- } : function (k) {
- return [k.toLowerCase(), headers[MAP][k].join(', ')];
- });
-}
-
-const INTERNAL = Symbol('internal');
-
-function createHeadersIterator(target, kind) {
- const iterator = Object.create(HeadersIteratorPrototype);
- iterator[INTERNAL] = {
- target,
- kind,
- index: 0
- };
- return iterator;
-}
-
-const HeadersIteratorPrototype = Object.setPrototypeOf({
- next() {
- // istanbul ignore if
- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
- throw new TypeError('Value of `this` is not a HeadersIterator');
- }
-
- var _INTERNAL = this[INTERNAL];
- const target = _INTERNAL.target,
- kind = _INTERNAL.kind,
- index = _INTERNAL.index;
-
- const values = getHeaders(target, kind);
- const len = values.length;
- if (index >= len) {
- return {
- value: undefined,
- done: true
- };
- }
-
- this[INTERNAL].index = index + 1;
-
- return {
- value: values[index],
- done: false
- };
- }
-}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
-
-Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
- value: 'HeadersIterator',
- writable: false,
- enumerable: false,
- configurable: true
-});
+function deleteCookie (headers, name, attributes) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
-/**
- * Export the Headers object in a form that Node.js can consume.
- *
- * @param Headers headers
- * @return Object
- */
-function exportNodeCompatibleHeaders(headers) {
- const obj = Object.assign({ __proto__: null }, headers[MAP]);
+ webidl.brandCheck(headers, Headers, { strict: false })
- // http.request() only supports string as Host header. This hack makes
- // specifying custom Host header possible.
- const hostHeaderKey = find(headers[MAP], 'Host');
- if (hostHeaderKey !== undefined) {
- obj[hostHeaderKey] = obj[hostHeaderKey][0];
- }
+ name = webidl.converters.DOMString(name)
+ attributes = webidl.converters.DeleteCookieAttributes(attributes)
- return obj;
+ // Matches behavior of
+ // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
+ setCookie(headers, {
+ name,
+ value: '',
+ expires: new Date(0),
+ ...attributes
+ })
}
/**
- * Create a Headers object from an object of headers, ignoring those that do
- * not conform to HTTP grammar productions.
- *
- * @param Object obj Object of headers
- * @return Headers
- */
-function createHeadersLenient(obj) {
- const headers = new Headers();
- for (const name of Object.keys(obj)) {
- if (invalidTokenRegex.test(name)) {
- continue;
- }
- if (Array.isArray(obj[name])) {
- for (const val of obj[name]) {
- if (invalidHeaderCharRegex.test(val)) {
- continue;
- }
- if (headers[MAP][name] === undefined) {
- headers[MAP][name] = [val];
- } else {
- headers[MAP][name].push(val);
- }
- }
- } else if (!invalidHeaderCharRegex.test(obj[name])) {
- headers[MAP][name] = [obj[name]];
- }
- }
- return headers;
-}
-
-const INTERNALS$1 = Symbol('Response internals');
-
-// fix an issue where "STATUS_CODES" aren't a named export for node <10
-const STATUS_CODES = http.STATUS_CODES;
-
-/**
- * Response class
- *
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
+ * @param {Headers} headers
+ * @returns {Cookie[]}
*/
-class Response {
- constructor() {
- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- Body.call(this, body, opts);
-
- const status = opts.status || 200;
- const headers = new Headers(opts.headers);
-
- if (body != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(body);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
-
- this[INTERNALS$1] = {
- url: opts.url,
- status,
- statusText: opts.statusText || STATUS_CODES[status],
- headers,
- counter: opts.counter
- };
- }
-
- get url() {
- return this[INTERNALS$1].url || '';
- }
-
- get status() {
- return this[INTERNALS$1].status;
- }
-
- /**
- * Convenience property representing if the request ended normally
- */
- get ok() {
- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
- }
-
- get redirected() {
- return this[INTERNALS$1].counter > 0;
- }
-
- get statusText() {
- return this[INTERNALS$1].statusText;
- }
-
- get headers() {
- return this[INTERNALS$1].headers;
- }
-
- /**
- * Clone this response
- *
- * @return Response
- */
- clone() {
- return new Response(clone(this), {
- url: this.url,
- status: this.status,
- statusText: this.statusText,
- headers: this.headers,
- ok: this.ok,
- redirected: this.redirected
- });
- }
-}
-
-Body.mixIn(Response.prototype);
-
-Object.defineProperties(Response.prototype, {
- url: { enumerable: true },
- status: { enumerable: true },
- ok: { enumerable: true },
- redirected: { enumerable: true },
- statusText: { enumerable: true },
- headers: { enumerable: true },
- clone: { enumerable: true }
-});
-
-Object.defineProperty(Response.prototype, Symbol.toStringTag, {
- value: 'Response',
- writable: false,
- enumerable: false,
- configurable: true
-});
+function getSetCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
-const INTERNALS$2 = Symbol('Request internals');
-const URL = Url.URL || whatwgUrl.URL;
+ webidl.brandCheck(headers, Headers, { strict: false })
-// fix an issue where "format", "parse" aren't a named export for node <10
-const parse_url = Url.parse;
-const format_url = Url.format;
+ const cookies = getHeadersList(headers).cookies
-/**
- * Wrapper around `new URL` to handle arbitrary URLs
- *
- * @param {string} urlStr
- * @return {void}
- */
-function parseURL(urlStr) {
- /*
- Check whether the URL is absolute or not
- Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
- Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
- */
- if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
- urlStr = new URL(urlStr).toString();
- }
+ if (!cookies) {
+ return []
+ }
- // Fallback to old implementation for arbitrary URLs
- return parse_url(urlStr);
+ // In older versions of undici, cookies is a list of name:value.
+ return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
}
-const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
-
/**
- * Check if a value is an instance of Request.
- *
- * @param Mixed input
- * @return Boolean
+ * @param {Headers} headers
+ * @param {Cookie} cookie
+ * @returns {void}
*/
-function isRequest(input) {
- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
-}
+function setCookie (headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
-function isAbortSignal(signal) {
- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
- return !!(proto && proto.constructor.name === 'AbortSignal');
-}
+ webidl.brandCheck(headers, Headers, { strict: false })
-/**
- * Request class
- *
- * @param Mixed input Url or Request instance
- * @param Object init Custom options
- * @return Void
- */
-class Request {
- constructor(input) {
- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- let parsedURL;
-
- // normalize input
- if (!isRequest(input)) {
- if (input && input.href) {
- // in order to support Node.js' Url objects; though WHATWG's URL objects
- // will fall into this branch also (since their `toString()` will return
- // `href` property anyway)
- parsedURL = parseURL(input.href);
- } else {
- // coerce input to a string before attempting to parse
- parsedURL = parseURL(`${input}`);
- }
- input = {};
- } else {
- parsedURL = parseURL(input.url);
- }
-
- let method = init.method || input.method || 'GET';
- method = method.toUpperCase();
-
- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
- throw new TypeError('Request with GET/HEAD method cannot have body');
- }
-
- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
-
- Body.call(this, inputBody, {
- timeout: init.timeout || input.timeout || 0,
- size: init.size || input.size || 0
- });
-
- const headers = new Headers(init.headers || input.headers || {});
-
- if (inputBody != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(inputBody);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
-
- let signal = isRequest(input) ? input.signal : null;
- if ('signal' in init) signal = init.signal;
-
- if (signal != null && !isAbortSignal(signal)) {
- throw new TypeError('Expected signal to be an instanceof AbortSignal');
- }
-
- this[INTERNALS$2] = {
- method,
- redirect: init.redirect || input.redirect || 'follow',
- headers,
- parsedURL,
- signal
- };
-
- // node-fetch-only options
- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
- this.counter = init.counter || input.counter || 0;
- this.agent = init.agent || input.agent;
- }
-
- get method() {
- return this[INTERNALS$2].method;
- }
-
- get url() {
- return format_url(this[INTERNALS$2].parsedURL);
- }
-
- get headers() {
- return this[INTERNALS$2].headers;
- }
-
- get redirect() {
- return this[INTERNALS$2].redirect;
- }
-
- get signal() {
- return this[INTERNALS$2].signal;
- }
-
- /**
- * Clone this request
- *
- * @return Request
- */
- clone() {
- return new Request(this);
- }
-}
-
-Body.mixIn(Request.prototype);
-
-Object.defineProperty(Request.prototype, Symbol.toStringTag, {
- value: 'Request',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ cookie = webidl.converters.Cookie(cookie)
-Object.defineProperties(Request.prototype, {
- method: { enumerable: true },
- url: { enumerable: true },
- headers: { enumerable: true },
- redirect: { enumerable: true },
- clone: { enumerable: true },
- signal: { enumerable: true }
-});
+ const str = stringify(cookie)
-/**
- * Convert a Request to Node.js http request options.
- *
- * @param Request A Request instance
- * @return Object The options object to be passed to http.request
- */
-function getNodeRequestOptions(request) {
- const parsedURL = request[INTERNALS$2].parsedURL;
- const headers = new Headers(request[INTERNALS$2].headers);
-
- // fetch step 1.3
- if (!headers.has('Accept')) {
- headers.set('Accept', '*/*');
- }
-
- // Basic fetch
- if (!parsedURL.protocol || !parsedURL.hostname) {
- throw new TypeError('Only absolute URLs are supported');
- }
-
- if (!/^https?:$/.test(parsedURL.protocol)) {
- throw new TypeError('Only HTTP(S) protocols are supported');
- }
-
- if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
- }
-
- // HTTP-network-or-cache fetch steps 2.4-2.7
- let contentLengthValue = null;
- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
- contentLengthValue = '0';
- }
- if (request.body != null) {
- const totalBytes = getTotalBytes(request);
- if (typeof totalBytes === 'number') {
- contentLengthValue = String(totalBytes);
- }
- }
- if (contentLengthValue) {
- headers.set('Content-Length', contentLengthValue);
- }
-
- // HTTP-network-or-cache fetch step 2.11
- if (!headers.has('User-Agent')) {
- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
- }
-
- // HTTP-network-or-cache fetch step 2.15
- if (request.compress && !headers.has('Accept-Encoding')) {
- headers.set('Accept-Encoding', 'gzip,deflate');
- }
-
- let agent = request.agent;
- if (typeof agent === 'function') {
- agent = agent(parsedURL);
- }
-
- if (!headers.has('Connection') && !agent) {
- headers.set('Connection', 'close');
- }
-
- // HTTP-network fetch step 4.2
- // chunked encoding is handled by Node.js
-
- return Object.assign({}, parsedURL, {
- method: request.method,
- headers: exportNodeCompatibleHeaders(headers),
- agent
- });
+ if (str) {
+ headers.append('Set-Cookie', stringify(cookie))
+ }
}
-/**
- * abort-error.js
- *
- * AbortError interface for cancelled requests
- */
+webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ }
+])
-/**
- * Create AbortError instance
- *
- * @param String message Error message for human
- * @return AbortError
- */
-function AbortError(message) {
- Error.call(this, message);
+webidl.converters.Cookie = webidl.dictionaryConverter([
+ {
+ converter: webidl.converters.DOMString,
+ key: 'name'
+ },
+ {
+ converter: webidl.converters.DOMString,
+ key: 'value'
+ },
+ {
+ converter: webidl.nullableConverter((value) => {
+ if (typeof value === 'number') {
+ return webidl.converters['unsigned long long'](value)
+ }
- this.type = 'aborted';
- this.message = message;
+ return new Date(value)
+ }),
+ key: 'expires',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters['long long']),
+ key: 'maxAge',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'secure',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'httpOnly',
+ defaultValue: null
+ },
+ {
+ converter: webidl.converters.USVString,
+ key: 'sameSite',
+ allowedValues: ['Strict', 'Lax', 'None']
+ },
+ {
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
+ key: 'unparsed',
+ defaultValue: []
+ }
+])
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
+module.exports = {
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie
}
-AbortError.prototype = Object.create(Error.prototype);
-AbortError.prototype.constructor = AbortError;
-AbortError.prototype.name = 'AbortError';
-const URL$1 = Url.URL || whatwgUrl.URL;
+/***/ }),
-// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
-const PassThrough$1 = Stream.PassThrough;
+/***/ 8915:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
- const orig = new URL$1(original).hostname;
- const dest = new URL$1(destination).hostname;
- return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
-};
+
+const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237)
+const { isCTLExcludingHtab } = __nccwpck_require__(3834)
+const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322)
+const assert = __nccwpck_require__(2613)
/**
- * Fetch function
- *
- * @param Mixed url Absolute url or Request instance
- * @param Object opts Fetch options
- * @return Promise
- */
-function fetch(url, opts) {
-
- // allow custom promise
- if (!fetch.Promise) {
- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
- }
-
- Body.Promise = fetch.Promise;
-
- // wrap http.request into fetch
- return new fetch.Promise(function (resolve, reject) {
- // build request object
- const request = new Request(url, opts);
- const options = getNodeRequestOptions(request);
-
- const send = (options.protocol === 'https:' ? https : http).request;
- const signal = request.signal;
-
- let response = null;
-
- const abort = function abort() {
- let error = new AbortError('The user aborted a request.');
- reject(error);
- if (request.body && request.body instanceof Stream.Readable) {
- request.body.destroy(error);
- }
- if (!response || !response.body) return;
- response.body.emit('error', error);
- };
-
- if (signal && signal.aborted) {
- abort();
- return;
- }
-
- const abortAndFinalize = function abortAndFinalize() {
- abort();
- finalize();
- };
-
- // send request
- const req = send(options);
- let reqTimeout;
-
- if (signal) {
- signal.addEventListener('abort', abortAndFinalize);
- }
-
- function finalize() {
- req.abort();
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- clearTimeout(reqTimeout);
- }
-
- if (request.timeout) {
- req.once('socket', function (socket) {
- reqTimeout = setTimeout(function () {
- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
- finalize();
- }, request.timeout);
- });
- }
-
- req.on('error', function (err) {
- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
- finalize();
- });
-
- req.on('response', function (res) {
- clearTimeout(reqTimeout);
-
- const headers = createHeadersLenient(res.headers);
-
- // HTTP fetch step 5
- if (fetch.isRedirect(res.statusCode)) {
- // HTTP fetch step 5.2
- const location = headers.get('Location');
-
- // HTTP fetch step 5.3
- let locationURL = null;
- try {
- locationURL = location === null ? null : new URL$1(location, request.url).toString();
- } catch (err) {
- // error here can only be invalid URL in Location: header
- // do not throw when options.redirect == manual
- // let the user extract the errorneous redirect URL
- if (request.redirect !== 'manual') {
- reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
- finalize();
- return;
- }
- }
-
- // HTTP fetch step 5.5
- switch (request.redirect) {
- case 'error':
- reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
- finalize();
- return;
- case 'manual':
- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
- if (locationURL !== null) {
- // handle corrupted header
- try {
- headers.set('Location', locationURL);
- } catch (err) {
- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
- reject(err);
- }
- }
- break;
- case 'follow':
- // HTTP-redirect fetch step 2
- if (locationURL === null) {
- break;
- }
-
- // HTTP-redirect fetch step 5
- if (request.counter >= request.follow) {
- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
- finalize();
- return;
- }
-
- // HTTP-redirect fetch step 6 (counter increment)
- // Create a new Request object.
- const requestOpts = {
- headers: new Headers(request.headers),
- follow: request.follow,
- counter: request.counter + 1,
- agent: request.agent,
- compress: request.compress,
- method: request.method,
- body: request.body,
- signal: request.signal,
- timeout: request.timeout,
- size: request.size
- };
-
- if (!isDomainOrSubdomain(request.url, locationURL)) {
- for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
- requestOpts.headers.delete(name);
- }
- }
-
- // HTTP-redirect fetch step 9
- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
- finalize();
- return;
- }
-
- // HTTP-redirect fetch step 11
- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
- requestOpts.method = 'GET';
- requestOpts.body = undefined;
- requestOpts.headers.delete('content-length');
- }
-
- // HTTP-redirect fetch step 15
- resolve(fetch(new Request(locationURL, requestOpts)));
- finalize();
- return;
- }
- }
-
- // prepare response
- res.once('end', function () {
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- });
- let body = res.pipe(new PassThrough$1());
-
- const response_options = {
- url: request.url,
- status: res.statusCode,
- statusText: res.statusMessage,
- headers: headers,
- size: request.size,
- timeout: request.timeout,
- counter: request.counter
- };
-
- // HTTP-network fetch step 12.1.1.3
- const codings = headers.get('Content-Encoding');
-
- // HTTP-network fetch step 12.1.1.4: handle content codings
-
- // in following scenarios we ignore compression support
- // 1. compression support is disabled
- // 2. HEAD request
- // 3. no Content-Encoding header
- // 4. no content response (204)
- // 5. content not modified response (304)
- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // For Node v6+
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- const zlibOptions = {
- flush: zlib.Z_SYNC_FLUSH,
- finishFlush: zlib.Z_SYNC_FLUSH
- };
-
- // for gzip
- if (codings == 'gzip' || codings == 'x-gzip') {
- body = body.pipe(zlib.createGunzip(zlibOptions));
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // for deflate
- if (codings == 'deflate' || codings == 'x-deflate') {
- // handle the infamous raw deflate response from old servers
- // a hack for old IIS and Apache servers
- const raw = res.pipe(new PassThrough$1());
- raw.once('data', function (chunk) {
- // see http://stackoverflow.com/questions/37519828
- if ((chunk[0] & 0x0F) === 0x08) {
- body = body.pipe(zlib.createInflate());
- } else {
- body = body.pipe(zlib.createInflateRaw());
- }
- response = new Response(body, response_options);
- resolve(response);
- });
- return;
- }
-
- // for br
- if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
- body = body.pipe(zlib.createBrotliDecompress());
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // otherwise, use response as-is
- response = new Response(body, response_options);
- resolve(response);
- });
-
- writeToStream(req, request);
- });
-}
-/**
- * Redirect code matching
- *
- * @param Number code Status code
- * @return Boolean
+ * @description Parses the field-value attributes of a set-cookie header string.
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} header
+ * @returns if the header is invalid, null will be returned
*/
-fetch.isRedirect = function (code) {
- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
-};
+function parseSetCookie (header) {
+ // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
+ // character (CTL characters excluding HTAB): Abort these steps and
+ // ignore the set-cookie-string entirely.
+ if (isCTLExcludingHtab(header)) {
+ return null
+ }
-// expose Promise
-fetch.Promise = global.Promise;
+ let nameValuePair = ''
+ let unparsedAttributes = ''
+ let name = ''
+ let value = ''
-module.exports = exports = fetch;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = exports;
-exports.Headers = Headers;
-exports.Request = Request;
-exports.Response = Response;
-exports.FetchError = FetchError;
+ // 2. If the set-cookie-string contains a %x3B (";") character:
+ if (header.includes(';')) {
+ // 1. The name-value-pair string consists of the characters up to,
+ // but not including, the first %x3B (";"), and the unparsed-
+ // attributes consist of the remainder of the set-cookie-string
+ // (including the %x3B (";") in question).
+ const position = { position: 0 }
+ nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
+ unparsedAttributes = header.slice(position.position)
+ } else {
+ // Otherwise:
-/***/ }),
+ // 1. The name-value-pair string consists of all the characters
+ // contained in the set-cookie-string, and the unparsed-
+ // attributes is the empty string.
+ nameValuePair = header
+ }
-/***/ 55375:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 3. If the name-value-pair string lacks a %x3D ("=") character, then
+ // the name string is empty, and the value string is the value of
+ // name-value-pair.
+ if (!nameValuePair.includes('=')) {
+ value = nameValuePair
+ } else {
+ // Otherwise, the name string consists of the characters up to, but
+ // not including, the first %x3D ("=") character, and the (possibly
+ // empty) value string consists of the characters after the first
+ // %x3D ("=") character.
+ const position = { position: 0 }
+ name = collectASequenceOfCodePointsFast(
+ '=',
+ nameValuePair,
+ position
+ )
+ value = nameValuePair.slice(position.position + 1)
+ }
-"use strict";
-var __webpack_unused_export__;
+ // 4. Remove any leading or trailing WSP characters from the name
+ // string and the value string.
+ name = name.trim()
+ value = value.trim()
+ // 5. If the sum of the lengths of the name string and the value string
+ // is more than 4096 octets, abort these steps and ignore the set-
+ // cookie-string entirely.
+ if (name.length + value.length > maxNameValuePairSize) {
+ return null
+ }
-__webpack_unused_export__ = ({ value: true });
+ // 6. The cookie-name is the name string, and the cookie-value is the
+ // value string.
+ return {
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
+ }
+}
-var core = __nccwpck_require__(76762);
-var pluginRequestLog = __nccwpck_require__(68883);
-var pluginPaginateRest = __nccwpck_require__(64193);
-var pluginRestEndpointMethods = __nccwpck_require__(83044);
+/**
+ * Parses the remaining attributes of a set-cookie header
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} unparsedAttributes
+ * @param {[Object.]={}} cookieAttributeList
+ */
+function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
+ // 1. If the unparsed-attributes string is empty, skip the rest of
+ // these steps.
+ if (unparsedAttributes.length === 0) {
+ return cookieAttributeList
+ }
-const VERSION = "18.12.0";
+ // 2. Discard the first character of the unparsed-attributes (which
+ // will be a %x3B (";") character).
+ assert(unparsedAttributes[0] === ';')
+ unparsedAttributes = unparsedAttributes.slice(1)
-const Octokit = core.Octokit.plugin(pluginRequestLog.requestLog, pluginRestEndpointMethods.legacyRestEndpointMethods, pluginPaginateRest.paginateRest).defaults({
- userAgent: `octokit-rest.js/${VERSION}`
-});
+ let cookieAv = ''
-exports.v = Octokit;
-//# sourceMappingURL=index.js.map
+ // 3. If the remaining unparsed-attributes contains a %x3B (";")
+ // character:
+ if (unparsedAttributes.includes(';')) {
+ // 1. Consume the characters of the unparsed-attributes up to, but
+ // not including, the first %x3B (";") character.
+ cookieAv = collectASequenceOfCodePointsFast(
+ ';',
+ unparsedAttributes,
+ { position: 0 }
+ )
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
+ } else {
+ // Otherwise:
+ // 1. Consume the remainder of the unparsed-attributes.
+ cookieAv = unparsedAttributes
+ unparsedAttributes = ''
+ }
-/***/ }),
+ // Let the cookie-av string be the characters consumed in this step.
-/***/ 65063:
-/***/ ((module) => {
+ let attributeName = ''
+ let attributeValue = ''
-"use strict";
+ // 4. If the cookie-av string contains a %x3D ("=") character:
+ if (cookieAv.includes('=')) {
+ // 1. The (possibly empty) attribute-name string consists of the
+ // characters up to, but not including, the first %x3D ("=")
+ // character, and the (possibly empty) attribute-value string
+ // consists of the characters after the first %x3D ("=")
+ // character.
+ const position = { position: 0 }
+ attributeName = collectASequenceOfCodePointsFast(
+ '=',
+ cookieAv,
+ position
+ )
+ attributeValue = cookieAv.slice(position.position + 1)
+ } else {
+ // Otherwise:
-module.exports = ({onlyFirst = false} = {}) => {
- const pattern = [
- '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
- '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
- ].join('|');
+ // 1. The attribute-name string consists of the entire cookie-av
+ // string, and the attribute-value string is empty.
+ attributeName = cookieAv
+ }
- return new RegExp(pattern, onlyFirst ? undefined : 'g');
-};
+ // 5. Remove any leading or trailing WSP characters from the attribute-
+ // name string and the attribute-value string.
+ attributeName = attributeName.trim()
+ attributeValue = attributeValue.trim()
+ // 6. If the attribute-value is longer than 1024 octets, ignore the
+ // cookie-av string and return to Step 1 of this algorithm.
+ if (attributeValue.length > maxAttributeValueSize) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ }
-/***/ }),
+ // 7. Process the attribute-name and attribute-value according to the
+ // requirements in the following subsections. (Notice that
+ // attributes with unrecognized attribute-names are ignored.)
+ const attributeNameLowercase = attributeName.toLowerCase()
-/***/ 87943:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
+ // If the attribute-name case-insensitively matches the string
+ // "Expires", the user agent MUST process the cookie-av as follows.
+ if (attributeNameLowercase === 'expires') {
+ // 1. Let the expiry-time be the result of parsing the attribute-value
+ // as cookie-date (see Section 5.1.1).
+ const expiryTime = new Date(attributeValue)
-"use strict";
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
+ // the cookie-av.
+ cookieAttributeList.expires = expiryTime
+ } else if (attributeNameLowercase === 'max-age') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
+ // If the attribute-name case-insensitively matches the string "Max-
+ // Age", the user agent MUST process the cookie-av as follows.
-var rawAsap = __nccwpck_require__(83691);
-var freeTasks = [];
+ // 1. If the first character of the attribute-value is not a DIGIT or a
+ // "-" character, ignore the cookie-av.
+ const charCode = attributeValue.charCodeAt(0)
-/**
- * Calls a task as soon as possible after returning, in its own event, with
- * priority over IO events. An exception thrown in a task can be handled by
- * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
- * crash the process. If the error is handled, all subsequent tasks will
- * resume.
- *
- * @param {{call}} task A callable object, typically a function that takes no
- * arguments.
- */
-module.exports = asap;
-function asap(task) {
- var rawTask;
- if (freeTasks.length) {
- rawTask = freeTasks.pop();
- } else {
- rawTask = new RawTask();
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- rawTask.task = task;
- rawTask.domain = process.domain;
- rawAsap(rawTask);
-}
-function RawTask() {
- this.task = null;
- this.domain = null;
-}
-
-RawTask.prototype.call = function () {
- if (this.domain) {
- this.domain.enter();
- }
- var threw = true;
- try {
- this.task.call();
- threw = false;
- // If the task throws an exception (presumably) Node.js restores the
- // domain stack for the next event.
- if (this.domain) {
- this.domain.exit();
- }
- } finally {
- // We use try/finally and a threw flag to avoid messing up stack traces
- // when we catch and release errors.
- if (threw) {
- // In Node.js, uncaught exceptions are considered fatal errors.
- // Re-throw them to interrupt flushing!
- // Ensure that flushing continues if an uncaught exception is
- // suppressed listening process.on("uncaughtException") or
- // domain.on("error").
- rawAsap.requestFlush();
- }
- // If the task threw an error, we do not want to exit the domain here.
- // Exiting the domain would prevent the domain from catching the error.
- this.task = null;
- this.domain = null;
- freeTasks.push(this);
+ // 2. If the remainder of attribute-value contains a non-DIGIT
+ // character, ignore the cookie-av.
+ if (!/^\d+$/.test(attributeValue)) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-};
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
+ const deltaSeconds = Number(attributeValue)
+ // 4. Let cookie-age-limit be the maximum age of the cookie (which
+ // SHOULD be 400 days or less, see Section 4.1.2.2).
-/***/ }),
-
-/***/ 83691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
+ // 5. Set delta-seconds to the smaller of its present value and cookie-
+ // age-limit.
+ // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
-var domain; // The domain module is executed on demand
-var hasSetImmediate = typeof setImmediate === "function";
+ // 6. If delta-seconds is less than or equal to zero (0), let expiry-
+ // time be the earliest representable date and time. Otherwise, let
+ // the expiry-time be the current date and time plus delta-seconds
+ // seconds.
+ // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
-// Use the fastest means possible to execute a task in its own turn, with
-// priority over other events including network IO events in Node.js.
-//
-// An exception thrown by a task will permanently interrupt the processing of
-// subsequent tasks. The higher level `asap` function ensures that if an
-// exception is thrown by a task, that the task queue will continue flushing as
-// soon as possible, but if you use `rawAsap` directly, you are responsible to
-// either ensure that no exceptions are thrown from your task, or to manually
-// call `rawAsap.requestFlush` if an exception is thrown.
-module.exports = rawAsap;
-function rawAsap(task) {
- if (!queue.length) {
- requestFlush();
- flushing = true;
- }
- // Avoids a function call
- queue[queue.length] = task;
-}
-
-var queue = [];
-// Once a flush has been requested, no further calls to `requestFlush` are
-// necessary until the next `flush` completes.
-var flushing = false;
-// The position of the next task to execute in the task queue. This is
-// preserved between calls to `flush` so that it can be resumed if
-// a task throws an exception.
-var index = 0;
-// If a task schedules additional tasks recursively, the task queue can grow
-// unbounded. To prevent memory excaustion, the task queue will periodically
-// truncate already-completed tasks.
-var capacity = 1024;
-
-// The flush function processes all tasks that have been scheduled with
-// `rawAsap` unless and until one of those tasks throws an exception.
-// If a task throws an exception, `flush` ensures that its state will remain
-// consistent and will resume where it left off when called again.
-// However, `flush` does not make any arrangements to be called again if an
-// exception is thrown.
-function flush() {
- while (index < queue.length) {
- var currentIndex = index;
- // Advance the index before calling the task. This ensures that we will
- // begin flushing on the next task the task throws an error.
- index = index + 1;
- queue[currentIndex].call();
- // Prevent leaking memory for long chains of recursive calls to `asap`.
- // If we call `asap` within tasks scheduled by `asap`, the queue will
- // grow, but to avoid an O(n) walk for every task we execute, we don't
- // shift tasks off the queue after they have been executed.
- // Instead, we periodically shift 1024 tasks off the queue.
- if (index > capacity) {
- // Manually shift all values starting at the index back to the
- // beginning of the queue.
- for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
- queue[scan] = queue[scan + index];
- }
- queue.length -= index;
- index = 0;
- }
- }
- queue.length = 0;
- index = 0;
- flushing = false;
-}
-
-rawAsap.requestFlush = requestFlush;
-function requestFlush() {
- // Ensure flushing is not bound to any domain.
- // It is not sufficient to exit the domain, because domains exist on a stack.
- // To execute code outside of any domain, the following dance is necessary.
- var parentDomain = process.domain;
- if (parentDomain) {
- if (!domain) {
- // Lazy execute the domain module.
- // Only employed if the user elects to use domains.
- domain = __nccwpck_require__(13639);
- }
- domain.active = process.domain = null;
- }
+ // 7. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Max-Age and an attribute-value of expiry-time.
+ cookieAttributeList.maxAge = deltaSeconds
+ } else if (attributeNameLowercase === 'domain') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
+ // If the attribute-name case-insensitively matches the string "Domain",
+ // the user agent MUST process the cookie-av as follows.
- // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
- // cannot handle recursion.
- // `requestFlush` will only be called recursively from `asap.js`, to resume
- // flushing after an error is thrown into a domain.
- // Conveniently, `setImmediate` was introduced in the same version
- // `process.nextTick` started throwing recursion errors.
- if (flushing && hasSetImmediate) {
- setImmediate(flush);
- } else {
- process.nextTick(flush);
- }
+ // 1. Let cookie-domain be the attribute-value.
+ let cookieDomain = attributeValue
- if (parentDomain) {
- domain.active = process.domain = parentDomain;
+ // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
+ // cookie-domain without its leading %x2E (".").
+ if (cookieDomain[0] === '.') {
+ cookieDomain = cookieDomain.slice(1)
}
-}
-
-/***/ }),
+ // 3. Convert the cookie-domain to lower case.
+ cookieDomain = cookieDomain.toLowerCase()
-/***/ 34355:
-/***/ ((__unused_webpack_module, exports) => {
+ // 4. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Domain and an attribute-value of cookie-domain.
+ cookieAttributeList.domain = cookieDomain
+ } else if (attributeNameLowercase === 'path') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
+ // If the attribute-name case-insensitively matches the string "Path",
+ // the user agent MUST process the cookie-av as follows.
-"use strict";
+ // 1. If the attribute-value is empty or if the first character of the
+ // attribute-value is not %x2F ("/"):
+ let cookiePath = ''
+ if (attributeValue.length === 0 || attributeValue[0] !== '/') {
+ // 1. Let cookie-path be the default-path.
+ cookiePath = '/'
+ } else {
+ // Otherwise:
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-/**
- * Helper function for exhaustive checks of discriminated unions.
- * https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html
- *
- * @example
- *
- * type A = {type: 'a'};
- * type B = {type: 'b'};
- * type Union = A | B;
- *
- * function doSomething(arg: Union) {
- * if (arg.type === 'a') {
- * return something;
- * }
- *
- * if (arg.type === 'b') {
- * return somethingElse;
- * }
- *
- * // TS will error if there are other types in the union
- * // Will throw an Error when called at runtime.
- * // Use `assertNever(arg, true)` instead to fail silently.
- * return assertNever(arg);
- * }
- */
-function assertNever(value, noThrow) {
- if (noThrow) {
- return value;
+ // 1. Let cookie-path be the attribute-value.
+ cookiePath = attributeValue
}
- throw new Error("Unhandled discriminated union member: " + JSON.stringify(value));
-}
-exports.assertNever = assertNever;
-exports["default"] = assertNever;
-
-
-/***/ }),
-
-/***/ 25995:
-/***/ ((module) => {
-module.exports = r => {
- const n = process.versions.node.split('.').map(x => parseInt(x, 10))
- r = r.split('.').map(x => parseInt(x, 10))
- return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2])))
-}
+ // 2. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Path and an attribute-value of cookie-path.
+ cookieAttributeList.path = cookiePath
+ } else if (attributeNameLowercase === 'secure') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
+ // If the attribute-name case-insensitively matches the string "Secure",
+ // the user agent MUST append an attribute to the cookie-attribute-list
+ // with an attribute-name of Secure and an empty attribute-value.
+ cookieAttributeList.secure = true
+ } else if (attributeNameLowercase === 'httponly') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
+ // If the attribute-name case-insensitively matches the string
+ // "HttpOnly", the user agent MUST append an attribute to the cookie-
+ // attribute-list with an attribute-name of HttpOnly and an empty
+ // attribute-value.
-/***/ }),
+ cookieAttributeList.httpOnly = true
+ } else if (attributeNameLowercase === 'samesite') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
+ // If the attribute-name case-insensitively matches the string
+ // "SameSite", the user agent MUST process the cookie-av as follows:
-/***/ 18098:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ // 1. Let enforcement be "Default".
+ let enforcement = 'Default'
-"use strict";
+ const attributeValueLowercase = attributeValue.toLowerCase()
+ // 2. If cookie-av's attribute-value is a case-insensitive match for
+ // "None", set enforcement to "None".
+ if (attributeValueLowercase.includes('none')) {
+ enforcement = 'None'
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const t = __importStar(__nccwpck_require__(7912));
-if (!(Array.isArray(t.TYPES) &&
- t.TYPES.every((t) => typeof t === 'string'))) {
- throw new Error('@babel/types TYPES does not match the expected type.');
-}
-const FLIPPED_ALIAS_KEYS = t
- .FLIPPED_ALIAS_KEYS;
-const TYPES = new Set(t.TYPES);
-if (!(FLIPPED_ALIAS_KEYS &&
- // tslint:disable-next-line: strict-type-predicates
- typeof FLIPPED_ALIAS_KEYS === 'object' &&
- Object.keys(FLIPPED_ALIAS_KEYS).every((key) => Array.isArray(FLIPPED_ALIAS_KEYS[key]) &&
- // tslint:disable-next-line: strict-type-predicates
- FLIPPED_ALIAS_KEYS[key].every((v) => typeof v === 'string')))) {
- throw new Error('@babel/types FLIPPED_ALIAS_KEYS does not match the expected type.');
-}
-/**
- * This serves thre functions:
- *
- * 1. Take any "aliases" and explode them to refecence the concrete types
- * 2. Normalize all handlers to have an `{enter, exit}` pair, rather than raw functions
- * 3. make the enter and exit handlers arrays, so that multiple handlers can be merged
- */
-function explode(input) {
- const results = {};
- for (const key in input) {
- const aliases = FLIPPED_ALIAS_KEYS[key];
- if (aliases) {
- for (const concreteKey of aliases) {
- if (concreteKey in results) {
- if (typeof input[key] === 'function') {
- results[concreteKey].enter.push(input[key]);
- }
- else {
- if (input[key].enter)
- results[concreteKey].enter.push(input[key].enter);
- if (input[key].exit)
- results[concreteKey].exit.push(input[key].exit);
- }
- }
- else {
- if (typeof input[key] === 'function') {
- results[concreteKey] = {
- enter: [input[key]],
- exit: [],
- };
- }
- else {
- results[concreteKey] = {
- enter: input[key].enter ? [input[key].enter] : [],
- exit: input[key].exit ? [input[key].exit] : [],
- };
- }
- }
- }
- }
- else if (TYPES.has(key)) {
- if (key in results) {
- if (typeof input[key] === 'function') {
- results[key].enter.push(input[key]);
- }
- else {
- if (input[key].enter)
- results[key].enter.push(input[key].enter);
- if (input[key].exit)
- results[key].exit.push(input[key].exit);
- }
- }
- else {
- if (typeof input[key] === 'function') {
- results[key] = {
- enter: [input[key]],
- exit: [],
- };
- }
- else {
- results[key] = {
- enter: input[key].enter ? [input[key].enter] : [],
- exit: input[key].exit ? [input[key].exit] : [],
- };
- }
- }
- }
+ // 3. If cookie-av's attribute-value is a case-insensitive match for
+ // "Strict", set enforcement to "Strict".
+ if (attributeValueLowercase.includes('strict')) {
+ enforcement = 'Strict'
}
- return results;
-}
-exports["default"] = explode;
-//# sourceMappingURL=explode.js.map
-/***/ }),
+ // 4. If cookie-av's attribute-value is a case-insensitive match for
+ // "Lax", set enforcement to "Lax".
+ if (attributeValueLowercase.includes('lax')) {
+ enforcement = 'Lax'
+ }
-/***/ 6407:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ // 5. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of "SameSite" and an attribute-value of
+ // enforcement.
+ cookieAttributeList.sameSite = enforcement
+ } else {
+ cookieAttributeList.unparsed ??= []
-"use strict";
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.recursive = exports.ancestor = exports.simple = void 0;
-const t = __importStar(__nccwpck_require__(7912));
-const explode_1 = __importDefault(__nccwpck_require__(18098));
-const VISITOR_KEYS = t.VISITOR_KEYS;
-if (!(VISITOR_KEYS &&
- // tslint:disable-next-line: strict-type-predicates
- typeof VISITOR_KEYS === 'object' &&
- Object.keys(VISITOR_KEYS).every((key) => Array.isArray(VISITOR_KEYS[key]) &&
- // tslint:disable-next-line: strict-type-predicates
- VISITOR_KEYS[key].every((v) => typeof v === 'string')))) {
- throw new Error('@babel/types VISITOR_KEYS does not match the expected type.');
-}
-function simple(visitors) {
- const vis = explode_1.default(visitors);
- return (node, state) => {
- (function recurse(node) {
- if (!node)
- return;
- const visitor = vis[node.type];
- if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) {
- for (const v of visitor.enter) {
- v(node, state);
- }
- }
- for (const key of VISITOR_KEYS[node.type] || []) {
- const subNode = node[key];
- if (Array.isArray(subNode)) {
- for (const subSubNode of subNode) {
- recurse(subSubNode);
- }
- }
- else {
- recurse(subNode);
- }
- }
- if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) {
- for (const v of visitor.exit) {
- v(node, state);
- }
- }
- })(node);
- };
-}
-exports.simple = simple;
-function ancestor(visitors) {
- const vis = explode_1.default(visitors);
- return (node, state) => {
- const ancestors = [];
- (function recurse(node) {
- if (!node)
- return;
- const visitor = vis[node.type];
- const isNew = node !== ancestors[ancestors.length - 1];
- if (isNew)
- ancestors.push(node);
- if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) {
- for (const v of visitor.enter) {
- v(node, state, ancestors);
- }
- }
- for (const key of VISITOR_KEYS[node.type] || []) {
- const subNode = node[key];
- if (Array.isArray(subNode)) {
- for (const subSubNode of subNode) {
- recurse(subSubNode);
- }
- }
- else {
- recurse(subNode);
- }
- }
- if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) {
- for (const v of visitor.exit) {
- v(node, state, ancestors);
- }
- }
- if (isNew)
- ancestors.pop();
- })(node);
- };
+ // 8. Return to Step 1 of this algorithm.
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-exports.ancestor = ancestor;
-function recursive(visitors) {
- const vis = explode_1.default(visitors);
- return (node, state) => {
- (function recurse(node) {
- if (!node)
- return;
- const visitor = vis[node.type];
- if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) {
- for (const v of visitor.enter) {
- v(node, state, recurse);
- }
- }
- else {
- for (const key of VISITOR_KEYS[node.type] || []) {
- const subNode = node[key];
- if (Array.isArray(subNode)) {
- for (const subSubNode of subNode) {
- recurse(subSubNode);
- }
- }
- else {
- recurse(subNode);
- }
- }
- }
- })(node);
- };
+
+module.exports = {
+ parseSetCookie,
+ parseUnparsedAttributes
}
-exports.recursive = recursive;
-//# sourceMappingURL=index.js.map
+
/***/ }),
-/***/ 9417:
-/***/ ((module) => {
+/***/ 3834:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"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);
+const assert = __nccwpck_require__(2613)
+const { kHeadersList } = __nccwpck_require__(6443)
- 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 isCTLExcludingHtab (value) {
+ if (value.length === 0) {
+ return false
+ }
+
+ for (const char of value) {
+ const code = char.charCodeAt(0)
-function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
+ if (
+ (code >= 0x00 || code <= 0x08) ||
+ (code >= 0x0A || code <= 0x1F) ||
+ code === 0x7F
+ ) {
+ return false
+ }
+ }
}
-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;
+/**
+ CHAR =
+ token = 1*
+ separators = "(" | ")" | "<" | ">" | "@"
+ | "," | ";" | ":" | "\" | <">
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+ * @param {string} name
+ */
+function validateCookieName (name) {
+ for (const char of name) {
+ const code = char.charCodeAt(0)
- if (ai >= 0 && bi > 0) {
- if(a===b) {
- return [ai, bi];
+ if (
+ (code <= 0x20 || code > 0x7F) ||
+ char === '(' ||
+ char === ')' ||
+ char === '>' ||
+ char === '<' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}'
+ ) {
+ throw new Error('Invalid cookie name')
}
- 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);
- }
+/**
+ cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
+ cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+ ; US-ASCII characters excluding CTLs,
+ ; whitespace DQUOTE, comma, semicolon,
+ ; and backslash
+ * @param {string} value
+ */
+function validateCookieValue (value) {
+ for (const char of value) {
+ const code = char.charCodeAt(0)
- i = ai < bi && ai >= 0 ? ai : bi;
+ if (
+ code < 0x21 || // exclude CTLs (0-31)
+ code === 0x22 ||
+ code === 0x2C ||
+ code === 0x3B ||
+ code === 0x5C ||
+ code > 0x7E // non-ascii
+ ) {
+ throw new Error('Invalid header value')
}
+ }
+}
+
+/**
+ * path-value =
+ * @param {string} path
+ */
+function validateCookiePath (path) {
+ for (const char of path) {
+ const code = char.charCodeAt(0)
- if (begs.length) {
- result = [ left, right ];
+ if (code < 0x21 || char === ';') {
+ throw new Error('Invalid cookie path')
}
}
-
- return result;
}
+/**
+ * I have no idea why these values aren't allowed to be honest,
+ * but Deno tests these. - Khafra
+ * @param {string} domain
+ */
+function validateCookieDomain (domain) {
+ if (
+ domain.startsWith('-') ||
+ domain.endsWith('.') ||
+ domain.endsWith('-')
+ ) {
+ throw new Error('Invalid cookie domain')
+ }
+}
-/***/ }),
-
-/***/ 83682:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
+ * @param {number|Date} date
+ IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
+ ; fixed length/zone/capitalization subset of the format
+ ; see Section 3.3 of [RFC5322]
-var register = __nccwpck_require__(44670)
-var addHook = __nccwpck_require__(5549)
-var removeHook = __nccwpck_require__(6819)
+ day-name = %x4D.6F.6E ; "Mon", case-sensitive
+ / %x54.75.65 ; "Tue", case-sensitive
+ / %x57.65.64 ; "Wed", case-sensitive
+ / %x54.68.75 ; "Thu", case-sensitive
+ / %x46.72.69 ; "Fri", case-sensitive
+ / %x53.61.74 ; "Sat", case-sensitive
+ / %x53.75.6E ; "Sun", case-sensitive
+ date1 = day SP month SP year
+ ; e.g., 02 Jun 1982
-// bind with array of arguments: https://stackoverflow.com/a/21792913
-var bind = Function.bind
-var bindable = bind.bind(bind)
+ day = 2DIGIT
+ month = %x4A.61.6E ; "Jan", case-sensitive
+ / %x46.65.62 ; "Feb", case-sensitive
+ / %x4D.61.72 ; "Mar", case-sensitive
+ / %x41.70.72 ; "Apr", case-sensitive
+ / %x4D.61.79 ; "May", case-sensitive
+ / %x4A.75.6E ; "Jun", case-sensitive
+ / %x4A.75.6C ; "Jul", case-sensitive
+ / %x41.75.67 ; "Aug", case-sensitive
+ / %x53.65.70 ; "Sep", case-sensitive
+ / %x4F.63.74 ; "Oct", case-sensitive
+ / %x4E.6F.76 ; "Nov", case-sensitive
+ / %x44.65.63 ; "Dec", case-sensitive
+ year = 4DIGIT
-function bindApi (hook, state, name) {
- var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])
- hook.api = { remove: removeHookRef }
- hook.remove = removeHookRef
+ GMT = %x47.4D.54 ; "GMT", case-sensitive
- ;['before', 'error', 'after', 'wrap'].forEach(function (kind) {
- var args = name ? [state, kind, name] : [state, kind]
- hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)
- })
-}
+ time-of-day = hour ":" minute ":" second
+ ; 00:00:00 - 23:59:60 (leap second)
-function HookSingular () {
- var singularHookName = 'h'
- var singularHookState = {
- registry: {}
+ hour = 2DIGIT
+ minute = 2DIGIT
+ second = 2DIGIT
+ */
+function toIMFDate (date) {
+ if (typeof date === 'number') {
+ date = new Date(date)
}
- var singularHook = register.bind(null, singularHookState, singularHookName)
- bindApi(singularHook, singularHookState, singularHookName)
- return singularHook
-}
-function HookCollection () {
- var state = {
- registry: {}
- }
+ const days = [
+ 'Sun', 'Mon', 'Tue', 'Wed',
+ 'Thu', 'Fri', 'Sat'
+ ]
+
+ const months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ]
- var hook = register.bind(null, state)
- bindApi(hook, state)
+ const dayName = days[date.getUTCDay()]
+ const day = date.getUTCDate().toString().padStart(2, '0')
+ const month = months[date.getUTCMonth()]
+ const year = date.getUTCFullYear()
+ const hour = date.getUTCHours().toString().padStart(2, '0')
+ const minute = date.getUTCMinutes().toString().padStart(2, '0')
+ const second = date.getUTCSeconds().toString().padStart(2, '0')
- return hook
+ return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
}
-var collectionHookDeprecationMessageDisplayed = false
-function Hook () {
- if (!collectionHookDeprecationMessageDisplayed) {
- console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4')
- collectionHookDeprecationMessageDisplayed = true
+/**
+ max-age-av = "Max-Age=" non-zero-digit *DIGIT
+ ; In practice, both expires-av and max-age-av
+ ; are limited to dates representable by the
+ ; user agent.
+ * @param {number} maxAge
+ */
+function validateCookieMaxAge (maxAge) {
+ if (maxAge < 0) {
+ throw new Error('Invalid cookie max-age')
}
- return HookCollection()
}
-Hook.Singular = HookSingular.bind()
-Hook.Collection = HookCollection.bind()
-
-module.exports = Hook
-// expose constructors as a named property for TypeScript
-module.exports.Hook = Hook
-module.exports.Singular = Hook.Singular
-module.exports.Collection = Hook.Collection
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
+ * @param {import('./index').Cookie} cookie
+ */
+function stringify (cookie) {
+ if (cookie.name.length === 0) {
+ return null
+ }
+ validateCookieName(cookie.name)
+ validateCookieValue(cookie.value)
-/***/ }),
+ const out = [`${cookie.name}=${cookie.value}`]
-/***/ 5549:
-/***/ ((module) => {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
+ if (cookie.name.startsWith('__Secure-')) {
+ cookie.secure = true
+ }
-module.exports = addHook;
+ if (cookie.name.startsWith('__Host-')) {
+ cookie.secure = true
+ cookie.domain = null
+ cookie.path = '/'
+ }
-function addHook(state, kind, name, hook) {
- var orig = hook;
- if (!state.registry[name]) {
- state.registry[name] = [];
+ if (cookie.secure) {
+ out.push('Secure')
}
- if (kind === "before") {
- hook = function (method, options) {
- return Promise.resolve()
- .then(orig.bind(null, options))
- .then(method.bind(null, options));
- };
+ if (cookie.httpOnly) {
+ out.push('HttpOnly')
}
- if (kind === "after") {
- hook = function (method, options) {
- var result;
- return Promise.resolve()
- .then(method.bind(null, options))
- .then(function (result_) {
- result = result_;
- return orig(result, options);
- })
- .then(function () {
- return result;
- });
- };
+ if (typeof cookie.maxAge === 'number') {
+ validateCookieMaxAge(cookie.maxAge)
+ out.push(`Max-Age=${cookie.maxAge}`)
}
- if (kind === "error") {
- hook = function (method, options) {
- return Promise.resolve()
- .then(method.bind(null, options))
- .catch(function (error) {
- return orig(error, options);
- });
- };
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain)
+ out.push(`Domain=${cookie.domain}`)
}
- state.registry[name].push({
- hook: hook,
- orig: orig,
- });
-}
-
-
-/***/ }),
-
-/***/ 44670:
-/***/ ((module) => {
-
-module.exports = register;
-
-function register(state, name, method, options) {
- if (typeof method !== "function") {
- throw new Error("method for before hook must be a function");
+ if (cookie.path) {
+ validateCookiePath(cookie.path)
+ out.push(`Path=${cookie.path}`)
}
- if (!options) {
- options = {};
+ if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
+ out.push(`Expires=${toIMFDate(cookie.expires)}`)
}
- if (Array.isArray(name)) {
- return name.reverse().reduce(function (callback, name) {
- return register.bind(null, state, name, callback, options);
- }, method)();
+ if (cookie.sameSite) {
+ out.push(`SameSite=${cookie.sameSite}`)
}
- return Promise.resolve().then(function () {
- if (!state.registry[name]) {
- return method(options);
+ for (const part of cookie.unparsed) {
+ if (!part.includes('=')) {
+ throw new Error('Invalid unparsed')
}
- return state.registry[name].reduce(function (method, registered) {
- return registered.hook.bind(null, method, options);
- }, method)();
- });
-}
-
+ const [key, ...value] = part.split('=')
-/***/ }),
+ out.push(`${key.trim()}=${value.join('=')}`)
+ }
-/***/ 6819:
-/***/ ((module) => {
+ return out.join('; ')
+}
-module.exports = removeHook;
+let kHeadersListNode
-function removeHook(state, name, method) {
- if (!state.registry[name]) {
- return;
+function getHeadersList (headers) {
+ if (headers[kHeadersList]) {
+ return headers[kHeadersList]
}
- var index = state.registry[name]
- .map(function (registered) {
- return registered.orig;
- })
- .indexOf(method);
+ if (!kHeadersListNode) {
+ kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
+ (symbol) => symbol.description === 'headers list'
+ )
- if (index === -1) {
- return;
+ assert(kHeadersListNode, 'Headers cannot be parsed')
}
- state.registry[name].splice(index, 1);
+ const headersList = headers[kHeadersListNode]
+ assert(headersList)
+
+ return headersList
+}
+
+module.exports = {
+ isCTLExcludingHtab,
+ stringify,
+ getHeadersList
}
/***/ }),
-/***/ 21491:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 9136:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWUtcmVzdWx0LmludGVyZmFjZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ibGFtZS1yZXN1bHQuaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ==
-/***/ }),
+const net = __nccwpck_require__(9278)
+const assert = __nccwpck_require__(2613)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707)
-/***/ 6686:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+let tls // include tls conditionally since it is not always available
-"use strict";
+// TODO: session re-use does not wait for the first
+// connection to resolve the session and might therefore
+// resolve the same servername multiple times even when
+// re-use is enabled.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Blamer = void 0;
-const git_1 = __nccwpck_require__(38295);
-class Blamer {
- async blameByFile(path) {
- return this.getVCSBlamer()(path);
- }
- getVCSBlamer() {
- return git_1.git;
- }
-}
-exports.Blamer = Blamer;
-//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2JsYW1lci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFDQSxtQ0FBZ0M7QUFFaEMsTUFBYSxNQUFNO0lBQ1YsS0FBSyxDQUFDLFdBQVcsQ0FBQyxJQUFZO1FBQ25DLE9BQU8sSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ25DLENBQUM7SUFFTyxZQUFZO1FBQ2xCLE9BQU8sU0FBRyxDQUFDO0lBQ2IsQ0FBQztDQUNGO0FBUkQsd0JBUUMifQ==
+let SessionCache
+// FIXME: remove workaround when the Node bug is fixed
+// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
+ SessionCache = class WeakSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return
+ }
-/***/ }),
+ const ref = this._sessionCache.get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this._sessionCache.delete(key)
+ }
+ })
+ }
-/***/ 56781:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ get (sessionKey) {
+ const ref = this._sessionCache.get(sessionKey)
+ return ref ? ref.deref() : null
+ }
-"use strict";
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+ this._sessionCache.set(sessionKey, new WeakRef(session))
+ this._sessionRegistry.register(session, sessionKey)
+ }
+ }
+} else {
+ SessionCache = class SimpleSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
}
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const blamer_1 = __nccwpck_require__(6686);
-__exportStar(__nccwpck_require__(21491), exports);
-exports["default"] = blamer_1.Blamer;
-//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLHFDQUFrQztBQUVsQywyREFBeUM7QUFDekMsa0JBQWUsZUFBTSxDQUFDIn0=
-/***/ }),
+ get (sessionKey) {
+ return this._sessionCache.get(sessionKey)
+ }
-/***/ 38295:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
-"use strict";
+ if (this._sessionCache.size >= this._maxCachedSessions) {
+ // remove the oldest session
+ const { value: oldestKey } = this._sessionCache.keys().next()
+ this._sessionCache.delete(oldestKey)
+ }
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.git = void 0;
-const execa_1 = __importDefault(__nccwpck_require__(20920));
-const which_1 = __importDefault(__nccwpck_require__(34207));
-const node_fs_1 = __nccwpck_require__(87561);
-const convertStringToObject = (sourceLine) => {
- const matches = sourceLine.match(/(.+)\s+\((.+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (\+|\-)\d{4})\s+(\d+)\)(.*)/);
- const [, rev, author, date, , line] = matches
- ? [...matches]
- : [null, '', '', '', '', ''];
- return {
- author,
- date,
- line,
- rev
- };
-};
-async function git(path) {
- const blamedLines = {};
- const pathToGit = await (0, which_1.default)('git');
- if (!(0, node_fs_1.existsSync)(path)) {
- throw new Error(`File ${path} does not exist`);
- }
- const result = execa_1.default.sync(pathToGit, ['blame', '-w', path]);
- result.stdout.split('\n').forEach(line => {
- if (line !== '') {
- const blamedLine = convertStringToObject(line);
- if (blamedLine.line) {
- blamedLines[blamedLine.line] = blamedLine;
- }
- }
- });
- return {
- [path]: blamedLines
- };
+ this._sessionCache.set(sessionKey, session)
+ }
+ }
}
-exports.git = git;
-//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2l0LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3Zjcy9naXQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7O0FBQUEsa0RBQTBCO0FBQzFCLGtEQUEwQjtBQUUxQixxQ0FBcUM7QUFFckMsTUFBTSxxQkFBcUIsR0FBRyxDQUFDLFVBQWtCLEVBQWMsRUFBRTtJQUMvRCxNQUFNLE9BQU8sR0FBRyxVQUFVLENBQUMsS0FBSyxDQUM5QixrRkFBa0YsQ0FDbkYsQ0FBQztJQUNGLE1BQU0sQ0FBQyxFQUFFLEdBQUcsRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLEFBQUQsRUFBRyxJQUFJLENBQUMsR0FBRyxPQUFPO1FBQzNDLENBQUMsQ0FBQyxDQUFDLEdBQUcsT0FBTyxDQUFDO1FBQ2QsQ0FBQyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLENBQUMsQ0FBQztJQUMvQixPQUFPO1FBQ0wsTUFBTTtRQUNOLElBQUk7UUFDSixJQUFJO1FBQ0osR0FBRztLQUNKLENBQUM7QUFDSixDQUFDLENBQUM7QUFFSyxLQUFLLFVBQVUsR0FBRyxDQUFDLElBQVk7SUFDcEMsTUFBTSxXQUFXLEdBQW1DLEVBQUUsQ0FBQztJQUN2RCxNQUFNLFNBQVMsR0FBVyxNQUFNLElBQUEsZUFBSyxFQUFDLEtBQUssQ0FBQyxDQUFDO0lBRTdDLElBQUksQ0FBQyxJQUFBLG9CQUFVLEVBQUMsSUFBSSxDQUFDLEVBQUU7UUFDckIsTUFBTSxJQUFJLEtBQUssQ0FBQyxRQUFRLElBQUksaUJBQWlCLENBQUMsQ0FBQztLQUNoRDtJQUVELE1BQU0sTUFBTSxHQUFHLGVBQUssQ0FBQyxJQUFJLENBQUMsU0FBUyxFQUFFLENBQUMsT0FBTyxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO0lBQzVELE1BQU0sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUN2QyxJQUFJLElBQUksS0FBSyxFQUFFLEVBQUU7WUFDZixNQUFNLFVBQVUsR0FBRyxxQkFBcUIsQ0FBQyxJQUFJLENBQUMsQ0FBQztZQUMvQyxJQUFJLFVBQVUsQ0FBQyxJQUFJLEVBQUU7Z0JBQ25CLFdBQVcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEdBQUcsVUFBVSxDQUFDO2FBQzNDO1NBQ0Y7SUFDSCxDQUFDLENBQUMsQ0FBQztJQUNILE9BQU87UUFDTCxDQUFDLElBQUksQ0FBQyxFQUFFLFdBQVc7S0FDcEIsQ0FBQztBQUNKLENBQUM7QUFwQkQsa0JBb0JDIn0=
-
-/***/ }),
-/***/ 20920:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
+ if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
+ throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
+ }
-"use strict";
+ const options = { path: socketPath, ...opts }
+ const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
+ timeout = timeout == null ? 10e3 : timeout
+ allowH2 = allowH2 != null ? allowH2 : false
+ return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
+ let socket
+ if (protocol === 'https:') {
+ if (!tls) {
+ tls = __nccwpck_require__(4756)
+ }
+ servername = servername || options.servername || util.getServerName(host) || null
-const path = __nccwpck_require__(71017);
-const childProcess = __nccwpck_require__(32081);
-const crossSpawn = __nccwpck_require__(72746);
-const stripFinalNewline = __nccwpck_require__(88174);
-const npmRunPath = __nccwpck_require__(20502);
-const onetime = __nccwpck_require__(89082);
-const makeError = __nccwpck_require__(11325);
-const normalizeStdio = __nccwpck_require__(54149);
-const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = __nccwpck_require__(77321);
-const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = __nccwpck_require__(2658);
-const {mergePromise, getSpawnedPromise} = __nccwpck_require__(51935);
-const {joinCommand, parseCommand} = __nccwpck_require__(1099);
+ const sessionKey = servername || hostname
+ const session = sessionCache.get(sessionKey) || null
-const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
+ assert(sessionKey)
-const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
- const env = extendEnv ? {...process.env, ...envOption} : envOption;
+ socket = tls.connect({
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
+ ...options,
+ servername,
+ session,
+ localAddress,
+ // TODO(HTTP/2): Add support for h2c
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
+ socket: httpSocket, // upgrade socket connection
+ port: port || 443,
+ host: hostname
+ })
- if (preferLocal) {
- return npmRunPath.env({env, cwd: localDir, execPath});
- }
+ socket
+ .on('session', function (session) {
+ // TODO (fix): Can a session become invalid once established? Don't think so?
+ sessionCache.set(sessionKey, session)
+ })
+ } else {
+ assert(!httpSocket, 'httpSocket can only be sent on TLS update')
+ socket = net.connect({
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
+ ...options,
+ localAddress,
+ port: port || 80,
+ host: hostname
+ })
+ }
- return env;
-};
+ // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
+ if (options.keepAlive == null || options.keepAlive) {
+ const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
+ socket.setKeepAlive(true, keepAliveInitialDelay)
+ }
-const handleArguments = (file, args, options = {}) => {
- const parsed = crossSpawn._parse(file, args, options);
- file = parsed.command;
- args = parsed.args;
- options = parsed.options;
-
- options = {
- maxBuffer: DEFAULT_MAX_BUFFER,
- buffer: true,
- stripFinalNewline: true,
- extendEnv: true,
- preferLocal: false,
- localDir: options.cwd || process.cwd(),
- execPath: process.execPath,
- encoding: 'utf8',
- reject: true,
- cleanup: true,
- all: false,
- windowsHide: true,
- ...options
- };
-
- options.env = getEnv(options);
-
- options.stdio = normalizeStdio(options);
-
- if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {
- // #116
- args.unshift('/q');
- }
-
- return {file, args, options, parsed};
-};
+ const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
-const handleOutput = (options, value, error) => {
- if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
- // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
- return error === undefined ? undefined : '';
- }
+ socket
+ .setNoDelay(true)
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
+ cancelTimeout()
- if (options.stripFinalNewline) {
- return stripFinalNewline(value);
- }
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(null, this)
+ }
+ })
+ .on('error', function (err) {
+ cancelTimeout()
- return value;
-};
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(err)
+ }
+ })
-const execa = (file, args, options) => {
- const parsed = handleArguments(file, args, options);
- const command = joinCommand(file, args);
-
- let spawned;
- try {
- spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
- } catch (error) {
- // Ensure the returned error is always both a promise and a child process
- const dummySpawned = new childProcess.ChildProcess();
- const errorPromise = Promise.reject(makeError({
- error,
- stdout: '',
- stderr: '',
- all: '',
- command,
- parsed,
- timedOut: false,
- isCanceled: false,
- killed: false
- }));
- return mergePromise(dummySpawned, errorPromise);
- }
-
- const spawnedPromise = getSpawnedPromise(spawned);
- const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
- const processDone = setExitHandler(spawned, parsed.options, timedPromise);
-
- const context = {isCanceled: false};
-
- spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
- spawned.cancel = spawnedCancel.bind(null, spawned, context);
-
- const handlePromise = async () => {
- const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
- const stdout = handleOutput(parsed.options, stdoutResult);
- const stderr = handleOutput(parsed.options, stderrResult);
- const all = handleOutput(parsed.options, allResult);
-
- if (error || exitCode !== 0 || signal !== null) {
- const returnedError = makeError({
- error,
- exitCode,
- signal,
- stdout,
- stderr,
- all,
- command,
- parsed,
- timedOut,
- isCanceled: context.isCanceled,
- killed: spawned.killed
- });
-
- if (!parsed.options.reject) {
- return returnedError;
- }
-
- throw returnedError;
- }
-
- return {
- command,
- exitCode: 0,
- stdout,
- stderr,
- all,
- failed: false,
- timedOut: false,
- isCanceled: false,
- killed: false
- };
- };
-
- const handlePromiseOnce = onetime(handlePromise);
-
- crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
-
- handleInput(spawned, parsed.options.input);
-
- spawned.all = makeAllStream(spawned, parsed.options);
-
- return mergePromise(spawned, handlePromiseOnce);
-};
+ return socket
+ }
+}
-module.exports = execa;
-
-module.exports.sync = (file, args, options) => {
- const parsed = handleArguments(file, args, options);
- const command = joinCommand(file, args);
-
- validateInputSync(parsed.options);
-
- let result;
- try {
- result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
- } catch (error) {
- throw makeError({
- error,
- stdout: '',
- stderr: '',
- all: '',
- command,
- parsed,
- timedOut: false,
- isCanceled: false,
- killed: false
- });
- }
-
- const stdout = handleOutput(parsed.options, result.stdout, result.error);
- const stderr = handleOutput(parsed.options, result.stderr, result.error);
-
- if (result.error || result.status !== 0 || result.signal !== null) {
- const error = makeError({
- stdout,
- stderr,
- error: result.error,
- signal: result.signal,
- exitCode: result.status,
- command,
- parsed,
- timedOut: result.error && result.error.code === 'ETIMEDOUT',
- isCanceled: false,
- killed: result.signal !== null
- });
-
- if (!parsed.options.reject) {
- return error;
- }
-
- throw error;
- }
-
- return {
- command,
- exitCode: 0,
- stdout,
- stderr,
- failed: false,
- timedOut: false,
- isCanceled: false,
- killed: false
- };
-};
+function setupTimeout (onConnectTimeout, timeout) {
+ if (!timeout) {
+ return () => {}
+ }
-module.exports.command = (command, options) => {
- const [file, ...args] = parseCommand(command);
- return execa(file, args, options);
-};
+ let s1 = null
+ let s2 = null
+ const timeoutId = setTimeout(() => {
+ // setImmediate is added to make sure that we priotorise socket error events over timeouts
+ s1 = setImmediate(() => {
+ if (process.platform === 'win32') {
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
+ s2 = setImmediate(() => onConnectTimeout())
+ } else {
+ onConnectTimeout()
+ }
+ })
+ }, timeout)
+ return () => {
+ clearTimeout(timeoutId)
+ clearImmediate(s1)
+ clearImmediate(s2)
+ }
+}
-module.exports.commandSync = (command, options) => {
- const [file, ...args] = parseCommand(command);
- return execa.sync(file, args, options);
-};
+function onConnectTimeout (socket) {
+ util.destroy(socket, new ConnectTimeoutError())
+}
-module.exports.node = (scriptPath, args, options = {}) => {
- if (args && !Array.isArray(args) && typeof args === 'object') {
- options = args;
- args = [];
- }
-
- const stdio = normalizeStdio.node(options);
- const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
-
- const {
- nodePath = process.execPath,
- nodeOptions = defaultExecArgv
- } = options;
-
- return execa(
- nodePath,
- [
- ...nodeOptions,
- scriptPath,
- ...(Array.isArray(args) ? args : [])
- ],
- {
- ...options,
- stdin: undefined,
- stdout: undefined,
- stderr: undefined,
- stdio,
- shell: false
- }
- );
-};
+module.exports = buildConnector
/***/ }),
-/***/ 1099:
+/***/ 8707:
/***/ ((module) => {
-"use strict";
-
-const SPACES_REGEXP = / +/g;
-
-const joinCommand = (file, args = []) => {
- if (!Array.isArray(args)) {
- return file;
- }
-
- return [file, ...args].join(' ');
-};
-
-// Handle `execa.command()`
-const parseCommand = command => {
- const tokens = [];
- for (const token of command.trim().split(SPACES_REGEXP)) {
- // Allow spaces to be escaped by a backslash if not meant as a delimiter
- const previousToken = tokens[tokens.length - 1];
- if (previousToken && previousToken.endsWith('\\')) {
- // Merge previous token with current one
- tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
- } else {
- tokens.push(token);
- }
- }
-
- return tokens;
-};
-
-module.exports = {
- joinCommand,
- parseCommand
-};
-
-
-/***/ }),
-/***/ 11325:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
+class UndiciError extends Error {
+ constructor (message) {
+ super(message)
+ this.name = 'UndiciError'
+ this.code = 'UND_ERR'
+ }
+}
-const {signalsByName} = __nccwpck_require__(27605);
+class ConnectTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ConnectTimeoutError)
+ this.name = 'ConnectTimeoutError'
+ this.message = message || 'Connect Timeout Error'
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
+ }
+}
-const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
- if (timedOut) {
- return `timed out after ${timeout} milliseconds`;
- }
+class HeadersTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersTimeoutError)
+ this.name = 'HeadersTimeoutError'
+ this.message = message || 'Headers Timeout Error'
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
+ }
+}
- if (isCanceled) {
- return 'was canceled';
- }
+class HeadersOverflowError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersOverflowError)
+ this.name = 'HeadersOverflowError'
+ this.message = message || 'Headers Overflow Error'
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
+ }
+}
- if (errorCode !== undefined) {
- return `failed with ${errorCode}`;
- }
+class BodyTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, BodyTimeoutError)
+ this.name = 'BodyTimeoutError'
+ this.message = message || 'Body Timeout Error'
+ this.code = 'UND_ERR_BODY_TIMEOUT'
+ }
+}
- if (signal !== undefined) {
- return `was killed with ${signal} (${signalDescription})`;
- }
+class ResponseStatusCodeError extends UndiciError {
+ constructor (message, statusCode, headers, body) {
+ super(message)
+ Error.captureStackTrace(this, ResponseStatusCodeError)
+ this.name = 'ResponseStatusCodeError'
+ this.message = message || 'Response Status Code Error'
+ this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
+ this.body = body
+ this.status = statusCode
+ this.statusCode = statusCode
+ this.headers = headers
+ }
+}
- if (exitCode !== undefined) {
- return `failed with exit code ${exitCode}`;
- }
+class InvalidArgumentError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidArgumentError)
+ this.name = 'InvalidArgumentError'
+ this.message = message || 'Invalid Argument Error'
+ this.code = 'UND_ERR_INVALID_ARG'
+ }
+}
- return 'failed';
-};
+class InvalidReturnValueError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidReturnValueError)
+ this.name = 'InvalidReturnValueError'
+ this.message = message || 'Invalid Return Value Error'
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
+ }
+}
-const makeError = ({
- stdout,
- stderr,
- all,
- error,
- signal,
- exitCode,
- command,
- timedOut,
- isCanceled,
- killed,
- parsed: {options: {timeout}}
-}) => {
- // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
- // We normalize them to `undefined`
- exitCode = exitCode === null ? undefined : exitCode;
- signal = signal === null ? undefined : signal;
- const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
-
- const errorCode = error && error.code;
-
- const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
- const execaMessage = `Command ${prefix}: ${command}`;
- const isError = Object.prototype.toString.call(error) === '[object Error]';
- const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
- const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
-
- if (isError) {
- error.originalMessage = error.message;
- error.message = message;
- } else {
- error = new Error(message);
- }
-
- error.shortMessage = shortMessage;
- error.command = command;
- error.exitCode = exitCode;
- error.signal = signal;
- error.signalDescription = signalDescription;
- error.stdout = stdout;
- error.stderr = stderr;
-
- if (all !== undefined) {
- error.all = all;
- }
-
- if ('bufferedData' in error) {
- delete error.bufferedData;
- }
-
- error.failed = true;
- error.timedOut = Boolean(timedOut);
- error.isCanceled = isCanceled;
- error.killed = killed && !timedOut;
-
- return error;
-};
+class RequestAbortedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestAbortedError)
+ this.name = 'AbortError'
+ this.message = message || 'Request aborted'
+ this.code = 'UND_ERR_ABORTED'
+ }
+}
-module.exports = makeError;
+class InformationalError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InformationalError)
+ this.name = 'InformationalError'
+ this.message = message || 'Request information'
+ this.code = 'UND_ERR_INFO'
+ }
+}
+class RequestContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestContentLengthMismatchError)
+ this.name = 'RequestContentLengthMismatchError'
+ this.message = message || 'Request body length does not match content-length header'
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
+ }
+}
-/***/ }),
+class ResponseContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError)
+ this.name = 'ResponseContentLengthMismatchError'
+ this.message = message || 'Response body length does not match content-length header'
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
+ }
+}
-/***/ 77321:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+class ClientDestroyedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientDestroyedError)
+ this.name = 'ClientDestroyedError'
+ this.message = message || 'The client is destroyed'
+ this.code = 'UND_ERR_DESTROYED'
+ }
+}
-"use strict";
+class ClientClosedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientClosedError)
+ this.name = 'ClientClosedError'
+ this.message = message || 'The client is closed'
+ this.code = 'UND_ERR_CLOSED'
+ }
+}
-const os = __nccwpck_require__(22037);
-const onExit = __nccwpck_require__(24931);
+class SocketError extends UndiciError {
+ constructor (message, socket) {
+ super(message)
+ Error.captureStackTrace(this, SocketError)
+ this.name = 'SocketError'
+ this.message = message || 'Socket error'
+ this.code = 'UND_ERR_SOCKET'
+ this.socket = socket
+ }
+}
-const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
+class NotSupportedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'NotSupportedError'
+ this.message = message || 'Not supported error'
+ this.code = 'UND_ERR_NOT_SUPPORTED'
+ }
+}
-// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
-const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
- const killResult = kill(signal);
- setKillTimeout(kill, signal, options, killResult);
- return killResult;
-};
+class BalancedPoolMissingUpstreamError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'MissingUpstreamError'
+ this.message = message || 'No upstream has been added to the BalancedPool'
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ }
+}
-const setKillTimeout = (kill, signal, options, killResult) => {
- if (!shouldForceKill(signal, options, killResult)) {
- return;
- }
-
- const timeout = getForceKillAfterTimeout(options);
- const t = setTimeout(() => {
- kill('SIGKILL');
- }, timeout);
-
- // Guarded because there's no `.unref()` when `execa` is used in the renderer
- // process in Electron. This cannot be tested since we don't run tests in
- // Electron.
- // istanbul ignore else
- if (t.unref) {
- t.unref();
- }
-};
+class HTTPParserError extends Error {
+ constructor (message, code, data) {
+ super(message)
+ Error.captureStackTrace(this, HTTPParserError)
+ this.name = 'HTTPParserError'
+ this.code = code ? `HPE_${code}` : undefined
+ this.data = data ? data.toString() : undefined
+ }
+}
-const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
- return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
-};
+class ResponseExceededMaxSizeError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError)
+ this.name = 'ResponseExceededMaxSizeError'
+ this.message = message || 'Response content exceeded max size'
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ }
+}
-const isSigterm = signal => {
- return signal === os.constants.signals.SIGTERM ||
- (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
-};
+module.exports = {
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ ResponseStatusCodeError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError
+}
-const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
- if (forceKillAfterTimeout === true) {
- return DEFAULT_FORCE_KILL_TIMEOUT;
- }
- if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
- throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
- }
+/***/ }),
- return forceKillAfterTimeout;
-};
+/***/ 4655:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// `childProcess.cancel()`
-const spawnedCancel = (spawned, context) => {
- const killResult = spawned.kill();
- if (killResult) {
- context.isCanceled = true;
- }
-};
-const timeoutKill = (spawned, signal, reject) => {
- spawned.kill(signal);
- reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
-};
+const {
+ InvalidArgumentError,
+ NotSupportedError
+} = __nccwpck_require__(8707)
+const assert = __nccwpck_require__(2613)
+const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443)
+const util = __nccwpck_require__(3440)
-// `timeout` option handling
-const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
- if (timeout === 0 || timeout === undefined) {
- return spawnedPromise;
- }
+// tokenRegExp and headerCharRegex have been lifted from
+// https://github.com/nodejs/node/blob/main/lib/_http_common.js
- if (!Number.isFinite(timeout) || timeout < 0) {
- throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
- }
+/**
+ * Verifies that the given val is a valid HTTP token
+ * per the rules defined in RFC 7230
+ * See https://tools.ietf.org/html/rfc7230#section-3.2.6
+ */
+const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
- let timeoutId;
- const timeoutPromise = new Promise((resolve, reject) => {
- timeoutId = setTimeout(() => {
- timeoutKill(spawned, killSignal, reject);
- }, timeout);
- });
+/**
+ * Matches if val contains an invalid field-vchar
+ * field-value = *( field-content / obs-fold )
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
+ */
+const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
- const safeSpawnedPromise = spawnedPromise.finally(() => {
- clearTimeout(timeoutId);
- });
+// Verifies that a given path is valid does not contain control chars \x00 to \x20
+const invalidPathRegex = /[^\u0021-\u00ff]/
- return Promise.race([timeoutPromise, safeSpawnedPromise]);
-};
+const kHandler = Symbol('handler')
-// `cleanup` option handling
-const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
- if (!cleanup || detached) {
- return timedPromise;
- }
+const channels = {}
- const removeExitHandler = onExit(() => {
- spawned.kill();
- });
+let extractBody
- return timedPromise.finally(() => {
- removeExitHandler();
- });
-};
+try {
+ const diagnosticsChannel = __nccwpck_require__(1637)
+ channels.create = diagnosticsChannel.channel('undici:request:create')
+ channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
+ channels.headers = diagnosticsChannel.channel('undici:request:headers')
+ channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
+ channels.error = diagnosticsChannel.channel('undici:request:error')
+} catch {
+ channels.create = { hasSubscribers: false }
+ channels.bodySent = { hasSubscribers: false }
+ channels.headers = { hasSubscribers: false }
+ channels.trailers = { hasSubscribers: false }
+ channels.error = { hasSubscribers: false }
+}
-module.exports = {
- spawnedKill,
- spawnedCancel,
- setupTimeout,
- setExitHandler
-};
-
-
-/***/ }),
+class Request {
+ constructor (origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ throwOnError,
+ expectContinue
+ }, handler) {
+ if (typeof path !== 'string') {
+ throw new InvalidArgumentError('path must be a string')
+ } else if (
+ path[0] !== '/' &&
+ !(path.startsWith('http://') || path.startsWith('https://')) &&
+ method !== 'CONNECT'
+ ) {
+ throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
+ } else if (invalidPathRegex.exec(path) !== null) {
+ throw new InvalidArgumentError('invalid request path')
+ }
-/***/ 51935:
-/***/ ((module) => {
+ if (typeof method !== 'string') {
+ throw new InvalidArgumentError('method must be a string')
+ } else if (tokenRegExp.exec(method) === null) {
+ throw new InvalidArgumentError('invalid request method')
+ }
-"use strict";
+ if (upgrade && typeof upgrade !== 'string') {
+ throw new InvalidArgumentError('upgrade must be a string')
+ }
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('invalid headersTimeout')
+ }
-const nativePromisePrototype = (async () => {})().constructor.prototype;
-const descriptors = ['then', 'catch', 'finally'].map(property => [
- property,
- Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
-]);
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('invalid bodyTimeout')
+ }
-// The return value is a mixin of `childProcess` and `Promise`
-const mergePromise = (spawned, promise) => {
- for (const [property, descriptor] of descriptors) {
- // Starting the main `promise` is deferred to avoid consuming streams
- const value = typeof promise === 'function' ?
- (...args) => Reflect.apply(descriptor.value, promise(), args) :
- descriptor.value.bind(promise);
+ if (reset != null && typeof reset !== 'boolean') {
+ throw new InvalidArgumentError('invalid reset')
+ }
- Reflect.defineProperty(spawned, property, {...descriptor, value});
- }
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
+ throw new InvalidArgumentError('invalid expectContinue')
+ }
- return spawned;
-};
+ this.headersTimeout = headersTimeout
-// Use promises instead of `child_process` events
-const getSpawnedPromise = spawned => {
- return new Promise((resolve, reject) => {
- spawned.on('exit', (exitCode, signal) => {
- resolve({exitCode, signal});
- });
-
- spawned.on('error', error => {
- reject(error);
- });
-
- if (spawned.stdin) {
- spawned.stdin.on('error', error => {
- reject(error);
- });
- }
- });
-};
+ this.bodyTimeout = bodyTimeout
-module.exports = {
- mergePromise,
- getSpawnedPromise
-};
+ this.throwOnError = throwOnError === true
+ this.method = method
+ if (body == null) {
+ this.body = null
+ } else if (util.isStream(body)) {
+ this.body = body
+ } else if (util.isBuffer(body)) {
+ this.body = body.byteLength ? body : null
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null
+ } else if (typeof body === 'string') {
+ this.body = body.length ? Buffer.from(body) : null
+ } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
+ this.body = body
+ } else {
+ throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
+ }
-/***/ }),
+ this.completed = false
-/***/ 54149:
-/***/ ((module) => {
+ this.aborted = false
-"use strict";
+ this.upgrade = upgrade || null
-const aliases = ['stdin', 'stdout', 'stderr'];
+ this.path = query ? util.buildURL(path, query) : path
-const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined);
+ this.origin = origin
-const normalizeStdio = opts => {
- if (!opts) {
- return;
- }
+ this.idempotent = idempotent == null
+ ? method === 'HEAD' || method === 'GET'
+ : idempotent
- const {stdio} = opts;
+ this.blocking = blocking == null ? false : blocking
- if (stdio === undefined) {
- return aliases.map(alias => opts[alias]);
- }
+ this.reset = reset == null ? null : reset
- if (hasAlias(opts)) {
- throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
- }
+ this.host = null
- if (typeof stdio === 'string') {
- return stdio;
- }
+ this.contentLength = null
- if (!Array.isArray(stdio)) {
- throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
- }
+ this.contentType = null
- const length = Math.max(stdio.length, aliases.length);
- return Array.from({length}, (value, index) => stdio[index]);
-};
+ this.headers = ''
-module.exports = normalizeStdio;
+ // Only for H2
+ this.expectContinue = expectContinue != null ? expectContinue : false
-// `ipc` is pushed unless it is already present
-module.exports.node = opts => {
- const stdio = normalizeStdio(opts);
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1])
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(this, key, headers[key])
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
- if (stdio === 'ipc') {
- return 'ipc';
- }
+ if (util.isFormDataLike(this.body)) {
+ if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
+ throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
+ }
- if (stdio === undefined || typeof stdio === 'string') {
- return [stdio, stdio, stdio, 'ipc'];
- }
+ if (!extractBody) {
+ extractBody = (__nccwpck_require__(8923).extractBody)
+ }
- if (stdio.includes('ipc')) {
- return stdio;
- }
+ const [bodyStream, contentType] = extractBody(body)
+ if (this.contentType == null) {
+ this.contentType = contentType
+ this.headers += `content-type: ${contentType}\r\n`
+ }
+ this.body = bodyStream.stream
+ this.contentLength = bodyStream.length
+ } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
+ this.contentType = body.type
+ this.headers += `content-type: ${body.type}\r\n`
+ }
- return [...stdio, 'ipc'];
-};
+ util.validateHandler(handler, method, upgrade)
+ this.servername = util.getServerName(this.host)
-/***/ }),
+ this[kHandler] = handler
-/***/ 2658:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this })
+ }
+ }
-"use strict";
-
-const isStream = __nccwpck_require__(41554);
-const getStream = __nccwpck_require__(80591);
-const mergeStream = __nccwpck_require__(2621);
-
-// `input` option
-const handleInput = (spawned, input) => {
- // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
- // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
- if (input === undefined || spawned.stdin === undefined) {
- return;
- }
-
- if (isStream(input)) {
- input.pipe(spawned.stdin);
- } else {
- spawned.stdin.end(input);
- }
-};
+ onBodySent (chunk) {
+ if (this[kHandler].onBodySent) {
+ try {
+ this[kHandler].onBodySent(chunk)
+ } catch (err) {
+ this.onError(err)
+ }
+ }
+ }
-// `all` interleaves `stdout` and `stderr`
-const makeAllStream = (spawned, {all}) => {
- if (!all || (!spawned.stdout && !spawned.stderr)) {
- return;
- }
+ onRequestSent () {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this })
+ }
+ }
- const mixed = mergeStream();
+ onConnect (abort) {
+ assert(!this.aborted)
+ assert(!this.completed)
- if (spawned.stdout) {
- mixed.add(spawned.stdout);
- }
+ return this[kHandler].onConnect(abort)
+ }
- if (spawned.stderr) {
- mixed.add(spawned.stderr);
- }
+ onHeaders (statusCode, headers, resume, statusText) {
+ assert(!this.aborted)
+ assert(!this.completed)
- return mixed;
-};
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ }
-// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
-const getBufferedData = async (stream, streamPromise) => {
- if (!stream) {
- return;
- }
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
+ }
- stream.destroy();
+ onData (chunk) {
+ assert(!this.aborted)
+ assert(!this.completed)
- try {
- return await streamPromise;
- } catch (error) {
- return error.bufferedData;
- }
-};
+ return this[kHandler].onData(chunk)
+ }
-const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
- if (!stream || !buffer) {
- return;
- }
+ onUpgrade (statusCode, headers, socket) {
+ assert(!this.aborted)
+ assert(!this.completed)
- if (encoding) {
- return getStream(stream, {encoding, maxBuffer});
- }
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
+ }
- return getStream.buffer(stream, {maxBuffer});
-};
+ onComplete (trailers) {
+ assert(!this.aborted)
-// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
-const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
- const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
- const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
- const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
-
- try {
- return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
- } catch (error) {
- return Promise.all([
- {error, signal: error.signal, timedOut: error.timedOut},
- getBufferedData(stdout, stdoutPromise),
- getBufferedData(stderr, stderrPromise),
- getBufferedData(all, allPromise)
- ]);
- }
-};
+ this.completed = true
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers })
+ }
+ return this[kHandler].onComplete(trailers)
+ }
-const validateInputSync = ({input}) => {
- if (isStream(input)) {
- throw new TypeError('The `input` option cannot be a stream in sync mode');
- }
-};
+ onError (error) {
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error })
+ }
-module.exports = {
- handleInput,
- makeAllStream,
- getSpawnedResult,
- validateInputSync
-};
+ if (this.aborted) {
+ return
+ }
+ this.aborted = true
+ return this[kHandler].onError(error)
+ }
+ // TODO: adjust to support H2
+ addHeader (key, value) {
+ processHeader(this, key, value)
+ return this
+ }
+ static [kHTTP1BuildRequest] (origin, opts, handler) {
+ // TODO: Migrate header parsing here, to make Requests
+ // HTTP agnostic
+ return new Request(origin, opts, handler)
+ }
-/***/ }),
+ static [kHTTP2BuildRequest] (origin, opts, handler) {
+ const headers = opts.headers
+ opts = { ...opts, headers: null }
-/***/ 33059:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const request = new Request(origin, opts, handler)
-"use strict";
+ request.headers = {}
-const {PassThrough: PassThroughStream} = __nccwpck_require__(12781);
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(request, headers[i], headers[i + 1], true)
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(request, key, headers[key], true)
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
-module.exports = options => {
- options = {...options};
+ return request
+ }
- const {array} = options;
- let {encoding} = options;
- const isBuffer = encoding === 'buffer';
- let objectMode = false;
+ static [kHTTP2CopyHeaders] (raw) {
+ const rawHeaders = raw.split('\r\n')
+ const headers = {}
- if (array) {
- objectMode = !(encoding || isBuffer);
- } else {
- encoding = encoding || 'utf8';
- }
+ for (const header of rawHeaders) {
+ const [key, value] = header.split(': ')
- if (isBuffer) {
- encoding = null;
- }
+ if (value == null || value.length === 0) continue
- const stream = new PassThroughStream({objectMode});
+ if (headers[key]) headers[key] += `,${value}`
+ else headers[key] = value
+ }
- if (encoding) {
- stream.setEncoding(encoding);
- }
+ return headers
+ }
+}
- let length = 0;
- const chunks = [];
+function processHeaderValue (key, val, skipAppend) {
+ if (val && typeof val === 'object') {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
- stream.on('data', chunk => {
- chunks.push(chunk);
+ val = val != null ? `${val}` : ''
- if (objectMode) {
- length = chunks.length;
- } else {
- length += chunk.length;
- }
- });
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
- stream.getBufferedValue = () => {
- if (array) {
- return chunks;
- }
+ return skipAppend ? val : `${key}: ${val}\r\n`
+}
- return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
- };
+function processHeader (request, key, val, skipAppend = false) {
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else if (val === undefined) {
+ return
+ }
- stream.getBufferedLength = () => length;
+ if (
+ request.host === null &&
+ key.length === 4 &&
+ key.toLowerCase() === 'host'
+ ) {
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
+ // Consumed by Client
+ request.host = val
+ } else if (
+ request.contentLength === null &&
+ key.length === 14 &&
+ key.toLowerCase() === 'content-length'
+ ) {
+ request.contentLength = parseInt(val, 10)
+ if (!Number.isFinite(request.contentLength)) {
+ throw new InvalidArgumentError('invalid content-length header')
+ }
+ } else if (
+ request.contentType === null &&
+ key.length === 12 &&
+ key.toLowerCase() === 'content-type'
+ ) {
+ request.contentType = val
+ request.headers += processHeaderValue(key, val)
+ } else if (
+ key.length === 17 &&
+ key.toLowerCase() === 'transfer-encoding'
+ ) {
+ throw new InvalidArgumentError('invalid transfer-encoding header')
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'connection'
+ ) {
+ const value = typeof val === 'string' ? val.toLowerCase() : null
+ if (value !== 'close' && value !== 'keep-alive') {
+ throw new InvalidArgumentError('invalid connection header')
+ } else if (value === 'close') {
+ request.reset = true
+ }
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'keep-alive'
+ ) {
+ throw new InvalidArgumentError('invalid keep-alive header')
+ } else if (
+ key.length === 7 &&
+ key.toLowerCase() === 'upgrade'
+ ) {
+ throw new InvalidArgumentError('invalid upgrade header')
+ } else if (
+ key.length === 6 &&
+ key.toLowerCase() === 'expect'
+ ) {
+ throw new NotSupportedError('expect header not supported')
+ } else if (tokenRegExp.exec(key) === null) {
+ throw new InvalidArgumentError('invalid header key')
+ } else {
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (skipAppend) {
+ if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
+ else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
+ } else {
+ request.headers += processHeaderValue(key, val[i])
+ }
+ }
+ } else {
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
+ }
+ }
+}
- return stream;
-};
+module.exports = Request
/***/ }),
-/***/ 80591:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-const {constants: BufferConstants} = __nccwpck_require__(14300);
-const pump = __nccwpck_require__(18341);
-const bufferStream = __nccwpck_require__(33059);
+/***/ 6443:
+/***/ ((module) => {
-class MaxBufferError extends Error {
- constructor() {
- super('maxBuffer exceeded');
- this.name = 'MaxBufferError';
- }
+module.exports = {
+ kClose: Symbol('close'),
+ kDestroy: Symbol('destroy'),
+ kDispatch: Symbol('dispatch'),
+ kUrl: Symbol('url'),
+ kWriting: Symbol('writing'),
+ kResuming: Symbol('resuming'),
+ kQueue: Symbol('queue'),
+ kConnect: Symbol('connect'),
+ kConnecting: Symbol('connecting'),
+ kHeadersList: Symbol('headers list'),
+ kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
+ kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
+ kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
+ kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
+ kKeepAlive: Symbol('keep alive'),
+ kHeadersTimeout: Symbol('headers timeout'),
+ kBodyTimeout: Symbol('body timeout'),
+ kServerName: Symbol('server name'),
+ kLocalAddress: Symbol('local address'),
+ kHost: Symbol('host'),
+ kNoRef: Symbol('no ref'),
+ kBodyUsed: Symbol('used'),
+ kRunning: Symbol('running'),
+ kBlocking: Symbol('blocking'),
+ kPending: Symbol('pending'),
+ kSize: Symbol('size'),
+ kBusy: Symbol('busy'),
+ kQueued: Symbol('queued'),
+ kFree: Symbol('free'),
+ kConnected: Symbol('connected'),
+ kClosed: Symbol('closed'),
+ kNeedDrain: Symbol('need drain'),
+ kReset: Symbol('reset'),
+ kDestroyed: Symbol.for('nodejs.stream.destroyed'),
+ kMaxHeadersSize: Symbol('max headers size'),
+ kRunningIdx: Symbol('running index'),
+ kPendingIdx: Symbol('pending index'),
+ kError: Symbol('error'),
+ kClients: Symbol('clients'),
+ kClient: Symbol('client'),
+ kParser: Symbol('parser'),
+ kOnDestroyed: Symbol('destroy callbacks'),
+ kPipelining: Symbol('pipelining'),
+ kSocket: Symbol('socket'),
+ kHostHeader: Symbol('host header'),
+ kConnector: Symbol('connector'),
+ kStrictContentLength: Symbol('strict content length'),
+ kMaxRedirections: Symbol('maxRedirections'),
+ kMaxRequests: Symbol('maxRequestsPerClient'),
+ kProxy: Symbol('proxy agent options'),
+ kCounter: Symbol('socket request counter'),
+ kInterceptors: Symbol('dispatch interceptors'),
+ kMaxResponseSize: Symbol('max response size'),
+ kHTTP2Session: Symbol('http2Session'),
+ kHTTP2SessionState: Symbol('http2Session state'),
+ kHTTP2BuildRequest: Symbol('http2 build request'),
+ kHTTP1BuildRequest: Symbol('http1 build request'),
+ kHTTP2CopyHeaders: Symbol('http2 copy headers'),
+ kHTTPConnVersion: Symbol('http connection version')
}
-async function getStream(inputStream, options) {
- if (!inputStream) {
- return Promise.reject(new Error('Expected a stream'));
- }
- options = {
- maxBuffer: Infinity,
- ...options
- };
+/***/ }),
- const {maxBuffer} = options;
+/***/ 3440:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- let stream;
- await new Promise((resolve, reject) => {
- const rejectPromise = error => {
- // Don't retrieve an oversized buffer.
- if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
- error.bufferedData = stream.getBufferedValue();
- }
- reject(error);
- };
- stream = pump(inputStream, bufferStream(options), error => {
- if (error) {
- rejectPromise(error);
- return;
- }
+const assert = __nccwpck_require__(2613)
+const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443)
+const { IncomingMessage } = __nccwpck_require__(8611)
+const stream = __nccwpck_require__(2203)
+const net = __nccwpck_require__(9278)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const { Blob } = __nccwpck_require__(181)
+const nodeUtil = __nccwpck_require__(9023)
+const { stringify } = __nccwpck_require__(3480)
- resolve();
- });
+const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
- stream.on('data', () => {
- if (stream.getBufferedLength() > maxBuffer) {
- rejectPromise(new MaxBufferError());
- }
- });
- });
+function nop () {}
- return stream.getBufferedValue();
+function isStream (obj) {
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
}
-module.exports = getStream;
-// TODO: Remove this for the next major release
-module.exports["default"] = getStream;
-module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
-module.exports.array = (stream, options) => getStream(stream, {...options, array: true});
-module.exports.MaxBufferError = MaxBufferError;
-
-
-/***/ }),
-
-/***/ 29778:
-/***/ ((__unused_webpack_module, exports) => {
+// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
+function isBlobLike (object) {
+ return (Blob && object instanceof Blob) || (
+ object &&
+ typeof object === 'object' &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
+ )
+}
-"use strict";
-Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0;
-
-const SIGNALS=[
-{
-name:"SIGHUP",
-number:1,
-action:"terminate",
-description:"Terminal closed",
-standard:"posix"},
-
-{
-name:"SIGINT",
-number:2,
-action:"terminate",
-description:"User interruption with CTRL-C",
-standard:"ansi"},
-
-{
-name:"SIGQUIT",
-number:3,
-action:"core",
-description:"User interruption with CTRL-\\",
-standard:"posix"},
-
-{
-name:"SIGILL",
-number:4,
-action:"core",
-description:"Invalid machine instruction",
-standard:"ansi"},
-
-{
-name:"SIGTRAP",
-number:5,
-action:"core",
-description:"Debugger breakpoint",
-standard:"posix"},
-
-{
-name:"SIGABRT",
-number:6,
-action:"core",
-description:"Aborted",
-standard:"ansi"},
-
-{
-name:"SIGIOT",
-number:6,
-action:"core",
-description:"Aborted",
-standard:"bsd"},
-
-{
-name:"SIGBUS",
-number:7,
-action:"core",
-description:
-"Bus error due to misaligned, non-existing address or paging error",
-standard:"bsd"},
-
-{
-name:"SIGEMT",
-number:7,
-action:"terminate",
-description:"Command should be emulated but is not implemented",
-standard:"other"},
-
-{
-name:"SIGFPE",
-number:8,
-action:"core",
-description:"Floating point arithmetic error",
-standard:"ansi"},
-
-{
-name:"SIGKILL",
-number:9,
-action:"terminate",
-description:"Forced termination",
-standard:"posix",
-forced:true},
-
-{
-name:"SIGUSR1",
-number:10,
-action:"terminate",
-description:"Application-specific signal",
-standard:"posix"},
-
-{
-name:"SIGSEGV",
-number:11,
-action:"core",
-description:"Segmentation fault",
-standard:"ansi"},
-
-{
-name:"SIGUSR2",
-number:12,
-action:"terminate",
-description:"Application-specific signal",
-standard:"posix"},
-
-{
-name:"SIGPIPE",
-number:13,
-action:"terminate",
-description:"Broken pipe or socket",
-standard:"posix"},
-
-{
-name:"SIGALRM",
-number:14,
-action:"terminate",
-description:"Timeout or timer",
-standard:"posix"},
-
-{
-name:"SIGTERM",
-number:15,
-action:"terminate",
-description:"Termination",
-standard:"ansi"},
-
-{
-name:"SIGSTKFLT",
-number:16,
-action:"terminate",
-description:"Stack is empty or overflowed",
-standard:"other"},
-
-{
-name:"SIGCHLD",
-number:17,
-action:"ignore",
-description:"Child process terminated, paused or unpaused",
-standard:"posix"},
-
-{
-name:"SIGCLD",
-number:17,
-action:"ignore",
-description:"Child process terminated, paused or unpaused",
-standard:"other"},
-
-{
-name:"SIGCONT",
-number:18,
-action:"unpause",
-description:"Unpaused",
-standard:"posix",
-forced:true},
-
-{
-name:"SIGSTOP",
-number:19,
-action:"pause",
-description:"Paused",
-standard:"posix",
-forced:true},
-
-{
-name:"SIGTSTP",
-number:20,
-action:"pause",
-description:"Paused using CTRL-Z or \"suspend\"",
-standard:"posix"},
-
-{
-name:"SIGTTIN",
-number:21,
-action:"pause",
-description:"Background process cannot read terminal input",
-standard:"posix"},
-
-{
-name:"SIGBREAK",
-number:21,
-action:"terminate",
-description:"User interruption with CTRL-BREAK",
-standard:"other"},
-
-{
-name:"SIGTTOU",
-number:22,
-action:"pause",
-description:"Background process cannot write to terminal output",
-standard:"posix"},
-
-{
-name:"SIGURG",
-number:23,
-action:"ignore",
-description:"Socket received out-of-band data",
-standard:"bsd"},
-
-{
-name:"SIGXCPU",
-number:24,
-action:"core",
-description:"Process timed out",
-standard:"bsd"},
-
-{
-name:"SIGXFSZ",
-number:25,
-action:"core",
-description:"File too big",
-standard:"bsd"},
-
-{
-name:"SIGVTALRM",
-number:26,
-action:"terminate",
-description:"Timeout or timer",
-standard:"bsd"},
-
-{
-name:"SIGPROF",
-number:27,
-action:"terminate",
-description:"Timeout or timer",
-standard:"bsd"},
-
-{
-name:"SIGWINCH",
-number:28,
-action:"ignore",
-description:"Terminal window size changed",
-standard:"bsd"},
-
-{
-name:"SIGIO",
-number:29,
-action:"terminate",
-description:"I/O is available",
-standard:"other"},
-
-{
-name:"SIGPOLL",
-number:29,
-action:"terminate",
-description:"Watched event",
-standard:"other"},
-
-{
-name:"SIGINFO",
-number:29,
-action:"ignore",
-description:"Request for process information",
-standard:"other"},
-
-{
-name:"SIGPWR",
-number:30,
-action:"terminate",
-description:"Device running out of power",
-standard:"systemv"},
-
-{
-name:"SIGSYS",
-number:31,
-action:"core",
-description:"Invalid system call",
-standard:"other"},
-
-{
-name:"SIGUNUSED",
-number:31,
-action:"terminate",
-description:"Invalid system call",
-standard:"other"}];exports.SIGNALS=SIGNALS;
-//# sourceMappingURL=core.js.map
+function buildURL (url, queryParams) {
+ if (url.includes('?') || url.includes('#')) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
+ }
-/***/ }),
+ const stringified = stringify(queryParams)
-/***/ 27605:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (stringified) {
+ url += '?' + stringified
+ }
-"use strict";
-Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037);
+ return url
+}
-var _signals=__nccwpck_require__(59519);
-var _realtime=__nccwpck_require__(45904);
+function parseURL (url) {
+ if (typeof url === 'string') {
+ url = new URL(url)
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
+ return url
+ }
-const getSignalsByName=function(){
-const signals=(0,_signals.getSignals)();
-return signals.reduce(getSignalByName,{});
-};
+ if (!url || typeof url !== 'object') {
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ }
-const getSignalByName=function(
-signalByNameMemo,
-{name,number,description,supported,action,forced,standard})
-{
-return{
-...signalByNameMemo,
-[name]:{name,number,description,supported,action,forced,standard}};
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
-};
+ if (!(url instanceof URL)) {
+ if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
+ }
-const signalsByName=getSignalsByName();exports.signalsByName=signalsByName;
+ if (url.path != null && typeof url.path !== 'string') {
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
+ }
+ if (url.pathname != null && typeof url.pathname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ }
+ if (url.hostname != null && typeof url.hostname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ }
+ if (url.origin != null && typeof url.origin !== 'string') {
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ }
-const getSignalsByNumber=function(){
-const signals=(0,_signals.getSignals)();
-const length=_realtime.SIGRTMAX+1;
-const signalsA=Array.from({length},(value,number)=>
-getSignalByNumber(number,signals));
+ const port = url.port != null
+ ? url.port
+ : (url.protocol === 'https:' ? 443 : 80)
+ let origin = url.origin != null
+ ? url.origin
+ : `${url.protocol}//${url.hostname}:${port}`
+ let path = url.path != null
+ ? url.path
+ : `${url.pathname || ''}${url.search || ''}`
-return Object.assign({},...signalsA);
-};
+ if (origin.endsWith('/')) {
+ origin = origin.substring(0, origin.length - 1)
+ }
-const getSignalByNumber=function(number,signals){
-const signal=findSignalByNumber(number,signals);
+ if (path && !path.startsWith('/')) {
+ path = `/${path}`
+ }
+ // new URL(path, origin) is unsafe when `path` contains an absolute URL
+ // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
+ // If first parameter is a relative URL, second param is required, and will be used as the base URL.
+ // If first parameter is an absolute URL, a given second param will be ignored.
+ url = new URL(origin + path)
+ }
-if(signal===undefined){
-return{};
+ return url
}
-const{name,description,supported,action,forced,standard}=signal;
-return{
-[number]:{
-name,
-number,
-description,
-supported,
-action,
-forced,
-standard}};
+function parseOrigin (url) {
+ url = parseURL(url)
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new InvalidArgumentError('invalid url')
+ }
-};
+ return url
+}
+function getHostname (host) {
+ if (host[0] === '[') {
+ const idx = host.indexOf(']')
+ assert(idx !== -1)
+ return host.substr(1, idx - 1)
+ }
-const findSignalByNumber=function(number,signals){
-const signal=signals.find(({name})=>_os.constants.signals[name]===number);
+ const idx = host.indexOf(':')
+ if (idx === -1) return host
-if(signal!==undefined){
-return signal;
+ return host.substr(0, idx)
}
-return signals.find(signalA=>signalA.number===number);
-};
-
-const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber;
-//# sourceMappingURL=main.js.map
-
-/***/ }),
-
-/***/ 45904:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0;
-const getRealtimeSignals=function(){
-const length=SIGRTMAX-SIGRTMIN+1;
-return Array.from({length},getRealtimeSignal);
-};exports.getRealtimeSignals=getRealtimeSignals;
-
-const getRealtimeSignal=function(value,index){
-return{
-name:`SIGRT${index+1}`,
-number:SIGRTMIN+index,
-action:"terminate",
-description:"Application-specific signal (realtime)",
-standard:"posix"};
-
-};
-
-const SIGRTMIN=34;
-const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX;
-//# sourceMappingURL=realtime.js.map
-
-/***/ }),
-
-/***/ 59519:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037);
-
-var _core=__nccwpck_require__(29778);
-var _realtime=__nccwpck_require__(45904);
-
-
-
-const getSignals=function(){
-const realtimeSignals=(0,_realtime.getRealtimeSignals)();
-const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);
-return signals;
-};exports.getSignals=getSignals;
-
-
-
-
-
-
-
-const normalizeSignal=function({
-name,
-number:defaultNumber,
-description,
-action,
-forced=false,
-standard})
-{
-const{
-signals:{[name]:constantSignal}}=
-_os.constants;
-const supported=constantSignal!==undefined;
-const number=supported?constantSignal:defaultNumber;
-return{name,number,description,supported,action,forced,standard};
-};
-//# sourceMappingURL=signals.js.map
-
-/***/ }),
-
-/***/ 33717:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var concatMap = __nccwpck_require__(86891);
-var balanced = __nccwpck_require__(9417);
+// IP addresses are not valid server names per RFC6066
+// > Currently, the only server names supported are DNS hostnames
+function getServerName (host) {
+ if (!host) {
+ return null
+ }
-module.exports = expandTop;
+ assert.strictEqual(typeof host, 'string')
-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';
+ const servername = getHostname(host)
+ if (net.isIP(servername)) {
+ return ''
+ }
-function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
+ return servername
}
-function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
+function deepClone (obj) {
+ return JSON.parse(JSON.stringify(obj))
}
-function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
+function isAsyncIterable (obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
}
-
-// 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 isIterable (obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
}
-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);
+function bodyLength (body) {
+ if (body == null) {
+ return 0
+ } else if (isStream(body)) {
+ const state = body._readableState
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
+ ? state.length
+ : null
+ } else if (isBlobLike(body)) {
+ return body.size != null ? body.size : null
+ } else if (isBuffer(body)) {
+ return body.byteLength
}
- return expand(escapeBraces(str), true).map(unescapeBraces);
-}
-
-function identity(e) {
- return e;
+ return null
}
-function embrace(str) {
- return '{' + str + '}';
-}
-function isPadded(el) {
- return /^-?0\d/.test(el);
+function isDestroyed (stream) {
+ return !stream || !!(stream.destroyed || stream[kDestroyed])
}
-function lte(i, y) {
- return i <= y;
-}
-function gte(i, y) {
- return i >= y;
+function isReadableAborted (stream) {
+ const state = stream && stream._readableState
+ return isDestroyed(stream) && state && !state.endEmitted
}
-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];
+function destroy (stream, err) {
+ if (!isStream(stream) || isDestroyed(stream)) {
+ return
}
- 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;
- });
- }
+ if (typeof stream.destroy === 'function') {
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
+ // See: https://github.com/nodejs/node/pull/38505/files
+ stream.socket = null
}
- }
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
+ stream.destroy(err)
+ } else if (err) {
+ process.nextTick((stream, err) => {
+ stream.emit('error', err)
+ }, stream, err)
+ }
- // 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)
- : [''];
+ if (stream.destroyed !== true) {
+ stream[kDestroyed] = true
+ }
+}
- var N;
+const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
+function parseKeepAliveTimeout (val) {
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
+ return m ? parseInt(m[1], 10) * 1000 : null
+}
- 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);
+function parseHeaders (headers, obj = {}) {
+ // For H2 support
+ if (!Array.isArray(headers)) return headers
- N = [];
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headers[i].toString().toLowerCase()
+ let val = obj[key]
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\')
- c = '';
+ if (!val) {
+ if (Array.isArray(headers[i + 1])) {
+ obj[key] = headers[i + 1]
} 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;
- }
- }
+ obj[key] = headers[i + 1].toString('utf8')
+ }
+ } else {
+ if (!Array.isArray(val)) {
+ val = [val]
+ obj[key] = val
}
- N.push(c);
+ val.push(headers[i + 1].toString('utf8'))
}
- } 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);
- }
+ // See https://github.com/nodejs/node/pull/46528
+ if ('content-length' in obj && 'content-disposition' in obj) {
+ obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
}
- return expansions;
+ return obj
}
+function parseRawHeaders (headers) {
+ const ret = []
+ let hasContentLength = false
+ let contentDispositionIdx = -1
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0].toString()
+ const val = headers[n + 1].toString('utf8')
-/***/ }),
-
-/***/ 50610:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const stringify = __nccwpck_require__(38750);
-const compile = __nccwpck_require__(79434);
-const expand = __nccwpck_require__(35873);
-const parse = __nccwpck_require__(96477);
-
-/**
- * Expand the given pattern or create a regex-compatible string.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
- * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {String}
- * @api public
- */
-
-const braces = (input, options = {}) => {
- let output = [];
-
- if (Array.isArray(input)) {
- for (let pattern of input) {
- let result = braces.create(pattern, options);
- if (Array.isArray(result)) {
- output.push(...result);
- } else {
- output.push(result);
- }
+ if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
+ ret.push(key, val)
+ hasContentLength = true
+ } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
+ contentDispositionIdx = ret.push(key, val) - 1
+ } else {
+ ret.push(key, val)
}
- } else {
- output = [].concat(braces.create(input, options));
}
- if (options && options.expand === true && options.nodupes === true) {
- output = [...new Set(output)];
+ // See https://github.com/nodejs/node/pull/46528
+ if (hasContentLength && contentDispositionIdx !== -1) {
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
}
- return output;
-};
-
-/**
- * Parse the given `str` with the given `options`.
- *
- * ```js
- * // braces.parse(pattern, [, options]);
- * const ast = braces.parse('a/{b,c}/d');
- * console.log(ast);
- * ```
- * @param {String} pattern Brace pattern to parse
- * @param {Object} options
- * @return {Object} Returns an AST
- * @api public
- */
-
-braces.parse = (input, options = {}) => parse(input, options);
-
-/**
- * Creates a braces string from an AST, or an AST node.
- *
- * ```js
- * const braces = require('braces');
- * let ast = braces.parse('foo/{a,b}/bar');
- * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
-braces.stringify = (input, options = {}) => {
- if (typeof input === 'string') {
- return stringify(braces.parse(input, options), options);
- }
- return stringify(input, options);
-};
+ return ret
+}
-/**
- * Compiles a brace pattern into a regex-compatible, optimized string.
- * This method is called by the main [braces](#braces) function by default.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.compile('a/{b,c}/d'));
- * //=> ['a/(b|c)/d']
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+function isBuffer (buffer) {
+ // See, https://github.com/mcollina/undici/pull/319
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+}
-braces.compile = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
+function validateHandler (handler, method, upgrade) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
}
- return compile(input, options);
-};
-
-/**
- * Expands a brace pattern into an array. This method is called by the
- * main [braces](#braces) function when `options.expand` is true. Before
- * using this method it's recommended that you read the [performance notes](#performance))
- * and advantages of using [.compile](#compile) instead.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.expand('a/{b,c}/d'));
- * //=> ['a/b/d', 'a/c/d'];
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
-braces.expand = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
+ if (typeof handler.onConnect !== 'function') {
+ throw new InvalidArgumentError('invalid onConnect method')
}
- let result = expand(input, options);
-
- // filter out empty strings if specified
- if (options.noempty === true) {
- result = result.filter(Boolean);
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
}
- // filter out duplicates if specified
- if (options.nodupes === true) {
- result = [...new Set(result)];
+ if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
+ throw new InvalidArgumentError('invalid onBodySent method')
}
- return result;
-};
+ if (upgrade || method === 'CONNECT') {
+ if (typeof handler.onUpgrade !== 'function') {
+ throw new InvalidArgumentError('invalid onUpgrade method')
+ }
+ } else {
+ if (typeof handler.onHeaders !== 'function') {
+ throw new InvalidArgumentError('invalid onHeaders method')
+ }
-/**
- * Processes a brace pattern and returns either an expanded array
- * (if `options.expand` is true), a highly optimized regex-compatible string.
- * This method is called by the main [braces](#braces) function.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
- * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+ if (typeof handler.onData !== 'function') {
+ throw new InvalidArgumentError('invalid onData method')
+ }
-braces.create = (input, options = {}) => {
- if (input === '' || input.length < 3) {
- return [input];
+ if (typeof handler.onComplete !== 'function') {
+ throw new InvalidArgumentError('invalid onComplete method')
+ }
}
+}
- return options.expand !== true
- ? braces.compile(input, options)
- : braces.expand(input, options);
-};
-
-/**
- * Expose "braces"
- */
-
-module.exports = braces;
-
-
-/***/ }),
-
-/***/ 79434:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// A body is disturbed if it has been read from and it cannot
+// be re-used without losing state or data.
+function isDisturbed (body) {
+ return !!(body && (
+ stream.isDisturbed
+ ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
+ : body[kBodyUsed] ||
+ body.readableDidRead ||
+ (body._readableState && body._readableState.dataEmitted) ||
+ isReadableAborted(body)
+ ))
+}
-"use strict";
+function isErrored (body) {
+ return !!(body && (
+ stream.isErrored
+ ? stream.isErrored(body)
+ : /state: 'errored'/.test(nodeUtil.inspect(body)
+ )))
+}
+function isReadable (body) {
+ return !!(body && (
+ stream.isReadable
+ ? stream.isReadable(body)
+ : /state: 'readable'/.test(nodeUtil.inspect(body)
+ )))
+}
-const fill = __nccwpck_require__(6330);
-const utils = __nccwpck_require__(45207);
+function getSocketInfo (socket) {
+ return {
+ localAddress: socket.localAddress,
+ localPort: socket.localPort,
+ remoteAddress: socket.remoteAddress,
+ remotePort: socket.remotePort,
+ remoteFamily: socket.remoteFamily,
+ timeout: socket.timeout,
+ bytesWritten: socket.bytesWritten,
+ bytesRead: socket.bytesRead
+ }
+}
-const compile = (ast, options = {}) => {
- let walk = (node, parent = {}) => {
- let invalidBlock = utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let invalid = invalidBlock === true || invalidNode === true;
- let prefix = options.escapeInvalid === true ? '\\' : '';
- let output = '';
+async function * convertIterableToBuffer (iterable) {
+ for await (const chunk of iterable) {
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ }
+}
- if (node.isOpen === true) {
- return prefix + node.value;
- }
- if (node.isClose === true) {
- return prefix + node.value;
- }
+let ReadableStream
+function ReadableStreamFrom (iterable) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ }
- if (node.type === 'open') {
- return invalid ? (prefix + node.value) : '(';
- }
+ if (ReadableStream.from) {
+ return ReadableStream.from(convertIterableToBuffer(iterable))
+ }
- if (node.type === 'close') {
- return invalid ? (prefix + node.value) : ')';
- }
+ let iterator
+ return new ReadableStream(
+ {
+ async start () {
+ iterator = iterable[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { done, value } = await iterator.next()
+ if (done) {
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
+ controller.enqueue(new Uint8Array(buf))
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ }
+ },
+ 0
+ )
+}
- if (node.type === 'comma') {
- return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
- }
+// The chunk should be a FormData instance and contains
+// all the required methods.
+function isFormDataLike (object) {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.append === 'function' &&
+ typeof object.delete === 'function' &&
+ typeof object.get === 'function' &&
+ typeof object.getAll === 'function' &&
+ typeof object.has === 'function' &&
+ typeof object.set === 'function' &&
+ object[Symbol.toStringTag] === 'FormData'
+ )
+}
- if (node.value) {
- return node.value;
+function throwIfAborted (signal) {
+ if (!signal) { return }
+ if (typeof signal.throwIfAborted === 'function') {
+ signal.throwIfAborted()
+ } else {
+ if (signal.aborted) {
+ // DOMException not available < v17.0.0
+ const err = new Error('The operation was aborted')
+ err.name = 'AbortError'
+ throw err
}
+ }
+}
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
- let range = fill(...args, { ...options, wrap: false, toRegex: true });
-
- if (range.length !== 0) {
- return args.length > 1 && range.length > 1 ? `(${range})` : range;
- }
+let events
+function addAbortListener (signal, listener) {
+ if (typeof Symbol.dispose === 'symbol') {
+ if (!events) {
+ events = __nccwpck_require__(4434)
}
-
- if (node.nodes) {
- for (let child of node.nodes) {
- output += walk(child, node);
- }
+ if (typeof events.addAbortListener === 'function' && 'aborted' in signal) {
+ return events.addAbortListener(signal, listener)
}
- return output;
- };
-
- return walk(ast);
-};
-
-module.exports = compile;
-
+ }
+ if ('addEventListener' in signal) {
+ signal.addEventListener('abort', listener, { once: true })
+ return () => signal.removeEventListener('abort', listener)
+ }
+ signal.addListener('abort', listener)
+ return () => signal.removeListener('abort', listener)
+}
-/***/ }),
+const hasToWellFormed = !!String.prototype.toWellFormed
-/***/ 18774:
-/***/ ((module) => {
+/**
+ * @param {string} val
+ */
+function toUSVString (val) {
+ if (hasToWellFormed) {
+ return `${val}`.toWellFormed()
+ } else if (nodeUtil.toUSVString) {
+ return nodeUtil.toUSVString(val)
+ }
-"use strict";
+ return `${val}`
+}
+const kEnumerableProperty = Object.create(null)
+kEnumerableProperty.enumerable = true
module.exports = {
- MAX_LENGTH: 1024 * 64,
-
- // Digits
- CHAR_0: '0', /* 0 */
- CHAR_9: '9', /* 9 */
-
- // Alphabet chars.
- CHAR_UPPERCASE_A: 'A', /* A */
- CHAR_LOWERCASE_A: 'a', /* a */
- CHAR_UPPERCASE_Z: 'Z', /* Z */
- CHAR_LOWERCASE_Z: 'z', /* z */
-
- CHAR_LEFT_PARENTHESES: '(', /* ( */
- CHAR_RIGHT_PARENTHESES: ')', /* ) */
-
- CHAR_ASTERISK: '*', /* * */
-
- // Non-alphabetic chars.
- CHAR_AMPERSAND: '&', /* & */
- CHAR_AT: '@', /* @ */
- CHAR_BACKSLASH: '\\', /* \ */
- CHAR_BACKTICK: '`', /* ` */
- CHAR_CARRIAGE_RETURN: '\r', /* \r */
- CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
- CHAR_COLON: ':', /* : */
- CHAR_COMMA: ',', /* , */
- CHAR_DOLLAR: '$', /* . */
- CHAR_DOT: '.', /* . */
- CHAR_DOUBLE_QUOTE: '"', /* " */
- CHAR_EQUAL: '=', /* = */
- CHAR_EXCLAMATION_MARK: '!', /* ! */
- CHAR_FORM_FEED: '\f', /* \f */
- CHAR_FORWARD_SLASH: '/', /* / */
- CHAR_HASH: '#', /* # */
- CHAR_HYPHEN_MINUS: '-', /* - */
- CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
- CHAR_LEFT_CURLY_BRACE: '{', /* { */
- CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
- CHAR_LINE_FEED: '\n', /* \n */
- CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
- CHAR_PERCENT: '%', /* % */
- CHAR_PLUS: '+', /* + */
- CHAR_QUESTION_MARK: '?', /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
- CHAR_RIGHT_CURLY_BRACE: '}', /* } */
- CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
- CHAR_SEMICOLON: ';', /* ; */
- CHAR_SINGLE_QUOTE: '\'', /* ' */
- CHAR_SPACE: ' ', /* */
- CHAR_TAB: '\t', /* \t */
- CHAR_UNDERSCORE: '_', /* _ */
- CHAR_VERTICAL_LINE: '|', /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
-};
+ kEnumerableProperty,
+ nop,
+ isDisturbed,
+ isErrored,
+ isReadable,
+ toUSVString,
+ isReadableAborted,
+ isBlobLike,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ isAsyncIterable,
+ isDestroyed,
+ parseRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom,
+ isBuffer,
+ validateHandler,
+ getSocketInfo,
+ isFormDataLike,
+ buildURL,
+ throwIfAborted,
+ addAbortListener,
+ nodeMajor,
+ nodeMinor,
+ nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13)
+}
/***/ }),
-/***/ 35873:
+/***/ 1:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-const fill = __nccwpck_require__(6330);
-const stringify = __nccwpck_require__(38750);
-const utils = __nccwpck_require__(45207);
+const Dispatcher = __nccwpck_require__(992)
+const {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+} = __nccwpck_require__(8707)
+const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443)
-const append = (queue = '', stash = '', enclose = false) => {
- let result = [];
+const kDestroyed = Symbol('destroyed')
+const kClosed = Symbol('closed')
+const kOnDestroyed = Symbol('onDestroyed')
+const kOnClosed = Symbol('onClosed')
+const kInterceptedDispatch = Symbol('Intercepted Dispatch')
- queue = [].concat(queue);
- stash = [].concat(stash);
+class DispatcherBase extends Dispatcher {
+ constructor () {
+ super()
- if (!stash.length) return queue;
- if (!queue.length) {
- return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
+ this[kDestroyed] = false
+ this[kOnDestroyed] = null
+ this[kClosed] = false
+ this[kOnClosed] = []
}
- for (let item of queue) {
- if (Array.isArray(item)) {
- for (let value of item) {
- result.push(append(value, stash, enclose));
- }
- } else {
- for (let ele of stash) {
- if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
- result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
- }
- }
+ get destroyed () {
+ return this[kDestroyed]
}
- return utils.flatten(result);
-};
-
-const expand = (ast, options = {}) => {
- let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
- let walk = (node, parent = {}) => {
- node.queue = [];
+ get closed () {
+ return this[kClosed]
+ }
- let p = parent;
- let q = parent.queue;
+ get interceptors () {
+ return this[kInterceptors]
+ }
- while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
- p = p.parent;
- q = p.queue;
+ set interceptors (newInterceptors) {
+ if (newInterceptors) {
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
+ const interceptor = this[kInterceptors][i]
+ if (typeof interceptor !== 'function') {
+ throw new InvalidArgumentError('interceptor must be an function')
+ }
+ }
}
- if (node.invalid || node.dollar) {
- q.push(append(q.pop(), stringify(node, options)));
- return;
+ this[kInterceptors] = newInterceptors
+ }
+
+ close (callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
}
- if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
- q.push(append(q.pop(), ['{}']));
- return;
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
+ if (this[kDestroyed]) {
+ queueMicrotask(() => callback(new ClientDestroyedError(), null))
+ return
+ }
- if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
- throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
+ if (this[kClosed]) {
+ if (this[kOnClosed]) {
+ this[kOnClosed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
}
+ return
+ }
- let range = fill(...args, options);
- if (range.length === 0) {
- range = stringify(node, options);
- }
+ this[kClosed] = true
+ this[kOnClosed].push(callback)
- q.push(append(q.pop(), range));
- node.nodes = [];
- return;
+ const onClosed = () => {
+ const callbacks = this[kOnClosed]
+ this[kOnClosed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
}
- let enclose = utils.encloseBrace(node);
- let queue = node.queue;
- let block = node;
+ // Should not error.
+ this[kClose]()
+ .then(() => this.destroy())
+ .then(() => {
+ queueMicrotask(onClosed)
+ })
+ }
- while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
- block = block.parent;
- queue = block.queue;
+ destroy (err, callback) {
+ if (typeof err === 'function') {
+ callback = err
+ err = null
}
- for (let i = 0; i < node.nodes.length; i++) {
- let child = node.nodes[i];
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.destroy(err, (err, data) => {
+ return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
+ })
+ })
+ }
- if (child.type === 'comma' && node.type === 'brace') {
- if (i === 1) queue.push('');
- queue.push('');
- continue;
- }
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
- if (child.type === 'close') {
- q.push(append(q.pop(), queue, enclose));
- continue;
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
}
+ return
+ }
- if (child.value && child.type !== 'open') {
- queue.push(append(queue.pop(), child.value));
- continue;
- }
-
- if (child.nodes) {
- walk(child, node);
- }
+ if (!err) {
+ err = new ClientDestroyedError()
}
- return queue;
- };
-
- return utils.flatten(walk(ast));
-};
-
-module.exports = expand;
-
-
-/***/ }),
-
-/***/ 96477:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const stringify = __nccwpck_require__(38750);
-
-/**
- * Constants
- */
-
-const {
- MAX_LENGTH,
- CHAR_BACKSLASH, /* \ */
- CHAR_BACKTICK, /* ` */
- CHAR_COMMA, /* , */
- CHAR_DOT, /* . */
- CHAR_LEFT_PARENTHESES, /* ( */
- CHAR_RIGHT_PARENTHESES, /* ) */
- CHAR_LEFT_CURLY_BRACE, /* { */
- CHAR_RIGHT_CURLY_BRACE, /* } */
- CHAR_LEFT_SQUARE_BRACKET, /* [ */
- CHAR_RIGHT_SQUARE_BRACKET, /* ] */
- CHAR_DOUBLE_QUOTE, /* " */
- CHAR_SINGLE_QUOTE, /* ' */
- CHAR_NO_BREAK_SPACE,
- CHAR_ZERO_WIDTH_NOBREAK_SPACE
-} = __nccwpck_require__(18774);
-
-/**
- * parse
- */
+ this[kDestroyed] = true
+ this[kOnDestroyed] = this[kOnDestroyed] || []
+ this[kOnDestroyed].push(callback)
-const parse = (input, options = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
+ const onDestroyed = () => {
+ const callbacks = this[kOnDestroyed]
+ this[kOnDestroyed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
+ }
- let opts = options || {};
- let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- if (input.length > max) {
- throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
+ // Should not error.
+ this[kDestroy](err).then(() => {
+ queueMicrotask(onDestroyed)
+ })
}
- let ast = { type: 'root', input, nodes: [] };
- let stack = [ast];
- let block = ast;
- let prev = ast;
- let brackets = 0;
- let length = input.length;
- let index = 0;
- let depth = 0;
- let value;
- let memo = {};
-
- /**
- * Helpers
- */
-
- const advance = () => input[index++];
- const push = node => {
- if (node.type === 'text' && prev.type === 'dot') {
- prev.type = 'text';
+ [kInterceptedDispatch] (opts, handler) {
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
+ this[kInterceptedDispatch] = this[kDispatch]
+ return this[kDispatch](opts, handler)
}
- if (prev && prev.type === 'text' && node.type === 'text') {
- prev.value += node.value;
- return;
+ let dispatch = this[kDispatch].bind(this)
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
+ dispatch = this[kInterceptors][i](dispatch)
}
+ this[kInterceptedDispatch] = dispatch
+ return dispatch(opts, handler)
+ }
- block.nodes.push(node);
- node.parent = block;
- node.prev = prev;
- prev = node;
- return node;
- };
+ dispatch (opts, handler) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
- push({ type: 'bos' });
+ try {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object.')
+ }
- while (index < length) {
- block = stack[stack.length - 1];
- value = advance();
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError()
+ }
- /**
- * Invalid chars
- */
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
- if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
- continue;
- }
+ return this[kInterceptedDispatch](opts, handler)
+ } catch (err) {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
- /**
- * Escaped chars
- */
+ handler.onError(err)
- if (value === CHAR_BACKSLASH) {
- push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
- continue;
+ return false
}
+ }
+}
- /**
- * Right square bracket (literal): ']'
- */
+module.exports = DispatcherBase
- if (value === CHAR_RIGHT_SQUARE_BRACKET) {
- push({ type: 'text', value: '\\' + value });
- continue;
- }
- /**
- * Left square bracket: '['
- */
+/***/ }),
- if (value === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
+/***/ 992:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- let closed = true;
- let next;
- while (index < length && (next = advance())) {
- value += next;
- if (next === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- continue;
- }
+const EventEmitter = __nccwpck_require__(4434)
- if (next === CHAR_BACKSLASH) {
- value += advance();
- continue;
- }
+class Dispatcher extends EventEmitter {
+ dispatch () {
+ throw new Error('not implemented')
+ }
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- brackets--;
+ close () {
+ throw new Error('not implemented')
+ }
- if (brackets === 0) {
- break;
- }
- }
- }
+ destroy () {
+ throw new Error('not implemented')
+ }
+}
- push({ type: 'text', value });
- continue;
- }
+module.exports = Dispatcher
- /**
- * Parentheses
- */
- if (value === CHAR_LEFT_PARENTHESES) {
- block = push({ type: 'paren', nodes: [] });
- stack.push(block);
- push({ type: 'text', value });
- continue;
- }
+/***/ }),
- if (value === CHAR_RIGHT_PARENTHESES) {
- if (block.type !== 'paren') {
- push({ type: 'text', value });
- continue;
- }
- block = stack.pop();
- push({ type: 'text', value });
- block = stack[stack.length - 1];
- continue;
- }
+/***/ 8923:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /**
- * Quotes: '|"|`
- */
- if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
- let open = value;
- let next;
- if (options.keepQuotes !== true) {
- value = '';
- }
+const Busboy = __nccwpck_require__(4652)
+const util = __nccwpck_require__(3440)
+const {
+ ReadableStreamFrom,
+ isBlobLike,
+ isReadableStreamLike,
+ readableStreamClose,
+ createDeferredPromise,
+ fullyReadBody
+} = __nccwpck_require__(5523)
+const { FormData } = __nccwpck_require__(3073)
+const { kState } = __nccwpck_require__(9710)
+const { webidl } = __nccwpck_require__(4222)
+const { DOMException, structuredClone } = __nccwpck_require__(7326)
+const { Blob, File: NativeFile } = __nccwpck_require__(181)
+const { kBodyUsed } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(2613)
+const { isErrored } = __nccwpck_require__(3440)
+const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253)
+const { File: UndiciFile } = __nccwpck_require__(3041)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
- while (index < length && (next = advance())) {
- if (next === CHAR_BACKSLASH) {
- value += next + advance();
- continue;
- }
+let ReadableStream = globalThis.ReadableStream
- if (next === open) {
- if (options.keepQuotes === true) value += next;
- break;
- }
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
- value += next;
- }
+// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+function extractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ }
- push({ type: 'text', value });
- continue;
- }
+ // 1. Let stream be null.
+ let stream = null
- /**
- * Left curly brace: '{'
- */
+ // 2. If object is a ReadableStream object, then set stream to object.
+ if (object instanceof ReadableStream) {
+ stream = object
+ } else if (isBlobLike(object)) {
+ // 3. Otherwise, if object is a Blob object, set stream to the
+ // result of running object’s get stream.
+ stream = object.stream()
+ } else {
+ // 4. Otherwise, set stream to a new ReadableStream object, and set
+ // up stream.
+ stream = new ReadableStream({
+ async pull (controller) {
+ controller.enqueue(
+ typeof source === 'string' ? new TextEncoder().encode(source) : source
+ )
+ queueMicrotask(() => readableStreamClose(controller))
+ },
+ start () {},
+ type: undefined
+ })
+ }
- if (value === CHAR_LEFT_CURLY_BRACE) {
- depth++;
+ // 5. Assert: stream is a ReadableStream object.
+ assert(isReadableStreamLike(stream))
- let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
- let brace = {
- type: 'brace',
- open: true,
- close: false,
- dollar,
- depth,
- commas: 0,
- ranges: 0,
- nodes: []
- };
+ // 6. Let action be null.
+ let action = null
- block = push(brace);
- stack.push(block);
- push({ type: 'open', value });
- continue;
- }
+ // 7. Let source be null.
+ let source = null
- /**
- * Right curly brace: '}'
- */
+ // 8. Let length be null.
+ let length = null
- if (value === CHAR_RIGHT_CURLY_BRACE) {
- if (block.type !== 'brace') {
- push({ type: 'text', value });
- continue;
- }
+ // 9. Let type be null.
+ let type = null
- let type = 'close';
- block = stack.pop();
- block.close = true;
+ // 10. Switch on object:
+ if (typeof object === 'string') {
+ // Set source to the UTF-8 encoding of object.
+ // Note: setting source to a Uint8Array here breaks some mocking assumptions.
+ source = object
- push({ type, value });
- depth--;
+ // Set type to `text/plain;charset=UTF-8`.
+ type = 'text/plain;charset=UTF-8'
+ } else if (object instanceof URLSearchParams) {
+ // URLSearchParams
- block = stack[stack.length - 1];
- continue;
- }
+ // spec says to run application/x-www-form-urlencoded on body.list
+ // this is implemented in Node.js as apart of an URLSearchParams instance toString method
+ // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
+ // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
- /**
- * Comma: ','
- */
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
+ source = object.toString()
- if (value === CHAR_COMMA && depth > 0) {
- if (block.ranges > 0) {
- block.ranges = 0;
- let open = block.nodes.shift();
- block.nodes = [open, { type: 'text', value: stringify(block) }];
- }
+ // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
+ type = 'application/x-www-form-urlencoded;charset=UTF-8'
+ } else if (isArrayBuffer(object)) {
+ // BufferSource/ArrayBuffer
- push({ type: 'comma', value });
- block.commas++;
- continue;
- }
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.slice())
+ } else if (ArrayBuffer.isView(object)) {
+ // BufferSource/ArrayBufferView
- /**
- * Dot: '.'
- */
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
+ } else if (util.isFormDataLike(object)) {
+ const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
- if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
- let siblings = block.nodes;
+ /*! formdata-polyfill. MIT License. Jimmy Wärting */
+ const escape = (str) =>
+ str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
+ const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
- if (depth === 0 || siblings.length === 0) {
- push({ type: 'text', value });
- continue;
- }
+ // Set action to this step: run the multipart/form-data
+ // encoding algorithm, with object’s entry list and UTF-8.
+ // - This ensures that the body is immutable and can't be changed afterwords
+ // - That the content-length is calculated in advance.
+ // - And that all parts are pre-encoded and ready to be sent.
- if (prev.type === 'dot') {
- block.range = [];
- prev.value += value;
- prev.type = 'range';
+ const enc = new TextEncoder()
+ const blobParts = []
+ const rn = new Uint8Array([13, 10]) // '\r\n'
+ length = 0
+ let hasUnknownSizeValue = false
- if (block.nodes.length !== 3 && block.nodes.length !== 5) {
- block.invalid = true;
- block.ranges = 0;
- prev.type = 'text';
- continue;
+ for (const [name, value] of object) {
+ if (typeof value === 'string') {
+ const chunk = enc.encode(prefix +
+ `; name="${escape(normalizeLinefeeds(name))}"` +
+ `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ } else {
+ const chunk = enc.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
+ (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
+ `Content-Type: ${
+ value.type || 'application/octet-stream'
+ }\r\n\r\n`)
+ blobParts.push(chunk, value, rn)
+ if (typeof value.size === 'number') {
+ length += chunk.byteLength + value.size + rn.byteLength
+ } else {
+ hasUnknownSizeValue = true
}
-
- block.ranges++;
- block.args = [];
- continue;
}
-
- if (prev.type === 'range') {
- siblings.pop();
-
- let before = siblings[siblings.length - 1];
- before.value += prev.value + value;
- prev = before;
- block.ranges--;
- continue;
- }
-
- push({ type: 'dot', value });
- continue;
}
- /**
- * Text
- */
-
- push({ type: 'text', value });
- }
+ const chunk = enc.encode(`--${boundary}--`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ if (hasUnknownSizeValue) {
+ length = null
+ }
- // Mark imbalanced braces and brackets as invalid
- do {
- block = stack.pop();
+ // Set source to object.
+ source = object
- if (block.type !== 'root') {
- block.nodes.forEach(node => {
- if (!node.nodes) {
- if (node.type === 'open') node.isOpen = true;
- if (node.type === 'close') node.isClose = true;
- if (!node.nodes) node.type = 'text';
- node.invalid = true;
+ action = async function * () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield * part.stream()
+ } else {
+ yield part
}
- });
-
- // get the location of the block on parent.nodes (block's siblings)
- let parent = stack[stack.length - 1];
- let index = parent.nodes.indexOf(block);
- // replace the (invalid) block with it's nodes
- parent.nodes.splice(index, 1, ...block.nodes);
+ }
}
- } while (stack.length > 0);
-
- push({ type: 'eos' });
- return ast;
-};
-
-module.exports = parse;
-
-
-/***/ }),
-
-/***/ 38750:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+ // Set type to `multipart/form-data; boundary=`,
+ // followed by the multipart/form-data boundary string generated
+ // by the multipart/form-data encoding algorithm.
+ type = 'multipart/form-data; boundary=' + boundary
+ } else if (isBlobLike(object)) {
+ // Blob
-const utils = __nccwpck_require__(45207);
+ // Set source to object.
+ source = object
-module.exports = (ast, options = {}) => {
- let stringify = (node, parent = {}) => {
- let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let output = '';
+ // Set length to object’s size.
+ length = object.size
- if (node.value) {
- if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
- return '\\' + node.value;
- }
- return node.value;
+ // If object’s type attribute is not the empty byte sequence, set
+ // type to its value.
+ if (object.type) {
+ type = object.type
}
-
- if (node.value) {
- return node.value;
+ } else if (typeof object[Symbol.asyncIterator] === 'function') {
+ // If keepalive is true, then throw a TypeError.
+ if (keepalive) {
+ throw new TypeError('keepalive')
}
- if (node.nodes) {
- for (let child of node.nodes) {
- output += stringify(child);
- }
+ // If object is disturbed or locked, then throw a TypeError.
+ if (util.isDisturbed(object) || object.locked) {
+ throw new TypeError(
+ 'Response body object should not be disturbed or locked'
+ )
}
- return output;
- };
- return stringify(ast);
-};
+ stream =
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
+ }
+ // 11. If source is a byte sequence, then set action to a
+ // step that returns source and length to source’s length.
+ if (typeof source === 'string' || util.isBuffer(source)) {
+ length = Buffer.byteLength(source)
+ }
+ // 12. If action is non-null, then run these steps in in parallel:
+ if (action != null) {
+ // Run action.
+ let iterator
+ stream = new ReadableStream({
+ async start () {
+ iterator = action(object)[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { value, done } = await iterator.next()
+ if (done) {
+ // When running action is done, close stream.
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ // Whenever one or more bytes are available and stream is not errored,
+ // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
+ // bytes into stream.
+ if (!isErrored(stream)) {
+ controller.enqueue(new Uint8Array(value))
+ }
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ },
+ type: undefined
+ })
+ }
-/***/ }),
+ // 13. Let body be a body whose stream is stream, source is source,
+ // and length is length.
+ const body = { stream, source, length }
-/***/ 45207:
-/***/ ((__unused_webpack_module, exports) => {
+ // 14. Return (body, type).
+ return [body, type]
+}
-"use strict";
+// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
+function safelyExtractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ // istanbul ignore next
+ ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ }
+ // To safely extract a body and a `Content-Type` value from
+ // a byte sequence or BodyInit object object, run these steps:
-exports.isInteger = num => {
- if (typeof num === 'number') {
- return Number.isInteger(num);
- }
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isInteger(Number(num));
+ // 1. If object is a ReadableStream object, then:
+ if (object instanceof ReadableStream) {
+ // Assert: object is neither disturbed nor locked.
+ // istanbul ignore next
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
+ // istanbul ignore next
+ assert(!object.locked, 'The stream is locked.')
}
- return false;
-};
-
-/**
- * Find a node of the given type
- */
-exports.find = (node, type) => node.nodes.find(node => node.type === type);
+ // 2. Return the results of extracting object.
+ return extractBody(object, keepalive)
+}
-/**
- * Find a node of the given type
- */
+function cloneBody (body) {
+ // To clone a body body, run these steps:
-exports.exceedsLimit = (min, max, step = 1, limit) => {
- if (limit === false) return false;
- if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
- return ((Number(max) - Number(min)) / Number(step)) >= limit;
-};
+ // https://fetch.spec.whatwg.org/#concept-body-clone
-/**
- * Escape the given node with '\\' before node.value
- */
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
+ const [out1, out2] = body.stream.tee()
+ const out2Clone = structuredClone(out2, { transfer: [out2] })
+ // This, for whatever reasons, unrefs out2Clone which allows
+ // the process to exit by itself.
+ const [, finalClone] = out2Clone.tee()
-exports.escapeNode = (block, n = 0, type) => {
- let node = block.nodes[n];
- if (!node) return;
+ // 2. Set body’s stream to out1.
+ body.stream = out1
- if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
- if (node.escaped !== true) {
- node.value = '\\' + node.value;
- node.escaped = true;
- }
+ // 3. Return a body whose stream is out2 and other members are copied from body.
+ return {
+ stream: finalClone,
+ length: body.length,
+ source: body.source
}
-};
+}
-/**
- * Returns true if the given brace node should be enclosed in literal braces
- */
+async function * consumeBody (body) {
+ if (body) {
+ if (isUint8Array(body)) {
+ yield body
+ } else {
+ const stream = body.stream
-exports.encloseBrace = node => {
- if (node.type !== 'brace') return false;
- if ((node.commas >> 0 + node.ranges >> 0) === 0) {
- node.invalid = true;
- return true;
- }
- return false;
-};
+ if (util.isDisturbed(stream)) {
+ throw new TypeError('The body has already been consumed.')
+ }
-/**
- * Returns true if a brace node is invalid.
- */
+ if (stream.locked) {
+ throw new TypeError('The stream is locked.')
+ }
-exports.isInvalidBrace = block => {
- if (block.type !== 'brace') return false;
- if (block.invalid === true || block.dollar) return true;
- if ((block.commas >> 0 + block.ranges >> 0) === 0) {
- block.invalid = true;
- return true;
- }
- if (block.open !== true || block.close !== true) {
- block.invalid = true;
- return true;
- }
- return false;
-};
+ // Compat.
+ stream[kBodyUsed] = true
-/**
- * Returns true if a node is an open or close node
- */
+ yield * stream
+ }
+ }
+}
-exports.isOpenOrClose = node => {
- if (node.type === 'open' || node.type === 'close') {
- return true;
+function throwIfAborted (state) {
+ if (state.aborted) {
+ throw new DOMException('The operation was aborted.', 'AbortError')
}
- return node.open === true || node.close === true;
-};
+}
-/**
- * Reduce an array of text nodes.
- */
+function bodyMixinMethods (instance) {
+ const methods = {
+ blob () {
+ // The blob() method steps are to return the result of
+ // running consume body with this and the following step
+ // given a byte sequence bytes: return a Blob whose
+ // contents are bytes and whose type attribute is this’s
+ // MIME type.
+ return specConsumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(this)
-exports.reduce = nodes => nodes.reduce((acc, node) => {
- if (node.type === 'text') acc.push(node.value);
- if (node.type === 'range') node.type = 'text';
- return acc;
-}, []);
+ if (mimeType === 'failure') {
+ mimeType = ''
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType)
+ }
-/**
- * Flatten an array
- */
+ // Return a Blob whose contents are bytes and type attribute
+ // is mimeType.
+ return new Blob([bytes], { type: mimeType })
+ }, instance)
+ },
-exports.flatten = (...args) => {
- const result = [];
- const flat = arr => {
- for (let i = 0; i < arr.length; i++) {
- let ele = arr[i];
- Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele);
- }
- return result;
- };
- flat(args);
- return result;
-};
+ arrayBuffer () {
+ // The arrayBuffer() method steps are to return the result
+ // of running consume body with this and the following step
+ // given a byte sequence bytes: return a new ArrayBuffer
+ // whose contents are bytes.
+ return specConsumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer
+ }, instance)
+ },
+ text () {
+ // The text() method steps are to return the result of running
+ // consume body with this and UTF-8 decode.
+ return specConsumeBody(this, utf8DecodeBytes, instance)
+ },
-/***/ }),
+ json () {
+ // The json() method steps are to return the result of running
+ // consume body with this and parse JSON from bytes.
+ return specConsumeBody(this, parseJSONFromBytes, instance)
+ },
-/***/ 86966:
-/***/ ((module) => {
+ async formData () {
+ webidl.brandCheck(this, instance)
-"use strict";
-/*!
- * bytes
- * Copyright(c) 2012-2014 TJ Holowaychuk
- * Copyright(c) 2015 Jed Watson
- * MIT Licensed
- */
+ throwIfAborted(this[kState])
+ const contentType = this.headers.get('Content-Type')
+ // If mimeType’s essence is "multipart/form-data", then:
+ if (/multipart\/form-data/.test(contentType)) {
+ const headers = {}
+ for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
-/**
- * Module exports.
- * @public
- */
+ const responseFormData = new FormData()
-module.exports = bytes;
-module.exports.format = format;
-module.exports.parse = parse;
+ let busboy
-/**
- * Module variables.
- * @private
- */
+ try {
+ busboy = new Busboy({
+ headers,
+ preservePath: true
+ })
+ } catch (err) {
+ throw new DOMException(`${err}`, 'AbortError')
+ }
-var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
+ busboy.on('field', (name, value) => {
+ responseFormData.append(name, value)
+ })
+ busboy.on('file', (name, value, filename, encoding, mimeType) => {
+ const chunks = []
-var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
+ if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
+ let base64chunk = ''
-var map = {
- b: 1,
- kb: 1 << 10,
- mb: 1 << 20,
- gb: 1 << 30,
- tb: Math.pow(1024, 4),
- pb: Math.pow(1024, 5),
-};
+ value.on('data', (chunk) => {
+ base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
-var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
+ const end = base64chunk.length - base64chunk.length % 4
+ chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
-/**
- * Convert the given value in bytes into a string or parse to string to an integer in bytes.
- *
- * @param {string|number} value
- * @param {{
- * case: [string],
- * decimalPlaces: [number]
- * fixedDecimals: [boolean]
- * thousandsSeparator: [string]
- * unitSeparator: [string]
- * }} [options] bytes options.
- *
- * @returns {string|number|null}
- */
+ base64chunk = base64chunk.slice(end)
+ })
+ value.on('end', () => {
+ chunks.push(Buffer.from(base64chunk, 'base64'))
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ } else {
+ value.on('data', (chunk) => {
+ chunks.push(chunk)
+ })
+ value.on('end', () => {
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ }
+ })
-function bytes(value, options) {
- if (typeof value === 'string') {
- return parse(value);
- }
+ const busboyResolve = new Promise((resolve, reject) => {
+ busboy.on('finish', resolve)
+ busboy.on('error', (err) => reject(new TypeError(err)))
+ })
- if (typeof value === 'number') {
- return format(value, options);
- }
+ if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
+ busboy.end()
+ await busboyResolve
- return null;
-}
+ return responseFormData
+ } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
+ // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
-/**
- * Format the given value in bytes into a string.
- *
- * If the value is negative, it is kept as such. If it is a float,
- * it is rounded.
- *
- * @param {number} value
- * @param {object} [options]
- * @param {number} [options.decimalPlaces=2]
- * @param {number} [options.fixedDecimals=false]
- * @param {string} [options.thousandsSeparator=]
- * @param {string} [options.unit=]
- * @param {string} [options.unitSeparator=]
- *
- * @returns {string|null}
- * @public
- */
+ // 1. Let entries be the result of parsing bytes.
+ let entries
+ try {
+ let text = ''
+ // application/x-www-form-urlencoded parser will keep the BOM.
+ // https://url.spec.whatwg.org/#concept-urlencoded-parser
+ const textDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
+ for await (const chunk of consumeBody(this[kState].body)) {
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Expected Uint8Array chunk')
+ }
+ text += textDecoder.decode(chunk, { stream: true })
+ }
+ text += textDecoder.decode()
+ entries = new URLSearchParams(text)
+ } catch (err) {
+ // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
+ // 2. If entries is failure, then throw a TypeError.
+ throw Object.assign(new TypeError(), { cause: err })
+ }
-function format(value, options) {
- if (!Number.isFinite(value)) {
- return null;
- }
-
- var mag = Math.abs(value);
- var thousandsSeparator = (options && options.thousandsSeparator) || '';
- var unitSeparator = (options && options.unitSeparator) || '';
- var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
- var fixedDecimals = Boolean(options && options.fixedDecimals);
- var unit = (options && options.unit) || '';
-
- if (!unit || !map[unit.toLowerCase()]) {
- if (mag >= map.pb) {
- unit = 'PB';
- } else if (mag >= map.tb) {
- unit = 'TB';
- } else if (mag >= map.gb) {
- unit = 'GB';
- } else if (mag >= map.mb) {
- unit = 'MB';
- } else if (mag >= map.kb) {
- unit = 'KB';
- } else {
- unit = 'B';
- }
- }
+ // 3. Return a new FormData object whose entries are entries.
+ const formData = new FormData()
+ for (const [name, value] of entries) {
+ formData.append(name, value)
+ }
+ return formData
+ } else {
+ // Wait a tick before checking if the request has been aborted.
+ // Otherwise, a TypeError can be thrown when an AbortError should.
+ await Promise.resolve()
- var val = value / map[unit.toLowerCase()];
- var str = val.toFixed(decimalPlaces);
+ throwIfAborted(this[kState])
- if (!fixedDecimals) {
- str = str.replace(formatDecimalsRegExp, '$1');
+ // Otherwise, throw a TypeError.
+ throw webidl.errors.exception({
+ header: `${instance.name}.formData`,
+ message: 'Could not parse content as FormData.'
+ })
+ }
+ }
}
- if (thousandsSeparator) {
- str = str.split('.').map(function (s, i) {
- return i === 0
- ? s.replace(formatThousandsRegExp, thousandsSeparator)
- : s
- }).join('.');
- }
+ return methods
+}
- return str + unitSeparator + unit;
+function mixinBody (prototype) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
}
/**
- * Parse the string value into an integer in bytes.
- *
- * If no unit is given, it is assumed the value is in bytes.
- *
- * @param {number|string} val
- *
- * @returns {number|null}
- * @public
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
+ * @param {Response|Request} object
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
+ * @param {Response|Request} instance
*/
+async function specConsumeBody (object, convertBytesToJSValue, instance) {
+ webidl.brandCheck(object, instance)
-function parse(val) {
- if (typeof val === 'number' && !isNaN(val)) {
- return val;
- }
+ throwIfAborted(object[kState])
- if (typeof val !== 'string') {
- return null;
+ // 1. If object is unusable, then return a promise rejected
+ // with a TypeError.
+ if (bodyUnusable(object[kState].body)) {
+ throw new TypeError('Body is unusable')
}
- // Test if the string passed is valid
- var results = parseRegExp.exec(val);
- var floatValue;
- var unit = 'b';
+ // 2. Let promise be a new promise.
+ const promise = createDeferredPromise()
- if (!results) {
- // Nothing could be extracted from the given string
- floatValue = parseInt(val, 10);
- unit = 'b'
- } else {
- // Retrieve the value and the unit
- floatValue = parseFloat(results[1]);
- unit = results[4].toLowerCase();
+ // 3. Let errorSteps given error be to reject promise with error.
+ const errorSteps = (error) => promise.reject(error)
+
+ // 4. Let successSteps given a byte sequence data be to resolve
+ // promise with the result of running convertBytesToJSValue
+ // with data. If that threw an exception, then run errorSteps
+ // with that exception.
+ const successSteps = (data) => {
+ try {
+ promise.resolve(convertBytesToJSValue(data))
+ } catch (e) {
+ errorSteps(e)
+ }
}
- if (isNaN(floatValue)) {
- return null;
+ // 5. If object’s body is null, then run successSteps with an
+ // empty byte sequence.
+ if (object[kState].body == null) {
+ successSteps(new Uint8Array())
+ return promise.promise
}
- return Math.floor(map[unit] * floatValue);
+ // 6. Otherwise, fully read object’s body given successSteps,
+ // errorSteps, and object’s relevant global object.
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
+
+ // 7. Return promise.
+ return promise.promise
+}
+
+// https://fetch.spec.whatwg.org/#body-unusable
+function bodyUnusable (body) {
+ // An object including the Body interface mixin is
+ // said to be unusable if its body is non-null and
+ // its body’s stream is disturbed or locked.
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream))
}
+/**
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
+ * @param {Buffer} buffer
+ */
+function utf8DecodeBytes (buffer) {
+ if (buffer.length === 0) {
+ return ''
+ }
+
+ // 1. Let buffer be the result of peeking three bytes from
+ // ioQueue, converted to a byte sequence.
-/***/ }),
+ // 2. If buffer is 0xEF 0xBB 0xBF, then read three
+ // bytes from ioQueue. (Do nothing with those bytes.)
+ if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
+ buffer = buffer.subarray(3)
+ }
-/***/ 28803:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Process a queue with an instance of UTF-8’s
+ // decoder, ioQueue, output, and "replacement".
+ const output = new TextDecoder().decode(buffer)
-"use strict";
+ // 4. Return output.
+ return output
+}
+/**
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
+ * @param {Uint8Array} bytes
+ */
+function parseJSONFromBytes (bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes))
+}
-var GetIntrinsic = __nccwpck_require__(74538);
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
+ * @param {import('./response').Response|import('./request').Request} object
+ */
+function bodyMimeType (object) {
+ const { headersList } = object[kState]
+ const contentType = headersList.get('content-type')
-var callBind = __nccwpck_require__(62977);
+ if (contentType === null) {
+ return 'failure'
+ }
-var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
+ return parseMIMEType(contentType)
+}
-module.exports = function callBoundIntrinsic(name, allowMissing) {
- var intrinsic = GetIntrinsic(name, !!allowMissing);
- if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
- return callBind(intrinsic);
- }
- return intrinsic;
-};
+module.exports = {
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody
+}
/***/ }),
-/***/ 62977:
+/***/ 7326:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-
-
-var bind = __nccwpck_require__(88334);
-var GetIntrinsic = __nccwpck_require__(74538);
-
-var $apply = GetIntrinsic('%Function.prototype.apply%');
-var $call = GetIntrinsic('%Function.prototype.call%');
-var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
-
-var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
-var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
-var $max = GetIntrinsic('%Math.max%');
-
-if ($defineProperty) {
- try {
- $defineProperty({}, 'a', { value: 1 });
- } catch (e) {
- // IE 8 has a broken defineProperty
- $defineProperty = null;
- }
-}
-
-module.exports = function callBind(originalFunction) {
- var func = $reflectApply(bind, $call, arguments);
- if ($gOPD && $defineProperty) {
- var desc = $gOPD(func, 'length');
- if (desc.configurable) {
- // original length, plus the receiver, minus any additional arguments (after the receiver)
- $defineProperty(
- func,
- 'length',
- { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
- );
- }
- }
- return func;
-};
-
-var applyBind = function applyBind() {
- return $reflectApply(bind, $apply, arguments);
-};
-if ($defineProperty) {
- $defineProperty(module.exports, 'apply', { value: applyBind });
-} else {
- module.exports.apply = applyBind;
-}
+const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167)
-/***/ }),
+const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
-/***/ 8937:
-/***/ ((module, exports, __nccwpck_require__) => {
+const nullBodyStatus = [101, 204, 205, 304]
-"use strict";
+const redirectStatus = [301, 302, 303, 307, 308]
+// https://fetch.spec.whatwg.org/#block-bad-port
+const badPorts = [
+ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
+ '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
+ '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
+ '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
+ '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
+ '10080'
+]
-var objIsRegex = __nccwpck_require__(96403);
+// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
+const referrerPolicy = [
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+]
-exports = (module.exports = parse);
+const requestRedirect = ['follow', 'manual', 'error']
-var TOKEN_TYPES = exports.TOKEN_TYPES = {
- LINE_COMMENT: '//',
- BLOCK_COMMENT: '/**/',
- SINGLE_QUOTE: '\'',
- DOUBLE_QUOTE: '"',
- TEMPLATE_QUOTE: '`',
- REGEXP: '//g'
-}
+const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
-var BRACKETS = exports.BRACKETS = {
- '(': ')',
- '{': '}',
- '[': ']'
-};
-var BRACKETS_REVERSED = {
- ')': '(',
- '}': '{',
- ']': '['
-};
+const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
-exports.parse = parse;
-function parse(src, state, options) {
- options = options || {};
- state = state || exports.defaultState();
- var start = options.start || 0;
- var end = options.end || src.length;
- var index = start;
- while (index < end) {
- try {
- parseChar(src[index], state);
- } catch (ex) {
- ex.index = index;
- throw ex;
- }
- index++;
- }
- return state;
-}
-
-exports.parseUntil = parseUntil;
-function parseUntil(src, delimiter, options) {
- options = options || {};
- var start = options.start || 0;
- var index = start;
- var state = exports.defaultState();
- while (index < src.length) {
- if ((options.ignoreNesting || !state.isNesting(options)) && matches(src, delimiter, index)) {
- var end = index;
- return {
- start: start,
- end: end,
- src: src.substring(start, end)
- };
- }
- try {
- parseChar(src[index], state);
- } catch (ex) {
- ex.index = index;
- throw ex;
- }
- index++;
- }
- var err = new Error('The end of the string was reached with no closing bracket found.');
- err.code = 'CHARACTER_PARSER:END_OF_STRING_REACHED';
- err.index = index;
- throw err;
-}
+const requestCredentials = ['omit', 'same-origin', 'include']
-exports.parseChar = parseChar;
-function parseChar(character, state) {
- if (character.length !== 1) {
- var err = new Error('Character must be a string of length 1');
- err.name = 'InvalidArgumentError';
- err.code = 'CHARACTER_PARSER:CHAR_LENGTH_NOT_ONE';
- throw err;
- }
- state = state || exports.defaultState();
- state.src += character;
- var wasComment = state.isComment();
- var lastChar = state.history ? state.history[0] : '';
+const requestCache = [
+ 'default',
+ 'no-store',
+ 'reload',
+ 'no-cache',
+ 'force-cache',
+ 'only-if-cached'
+]
+// https://fetch.spec.whatwg.org/#request-body-header-name
+const requestBodyHeader = [
+ 'content-encoding',
+ 'content-language',
+ 'content-location',
+ 'content-type',
+ // See https://github.com/nodejs/undici/issues/2021
+ // 'Content-Length' is a forbidden header name, which is typically
+ // removed in the Headers implementation. However, undici doesn't
+ // filter out headers, so we add it here.
+ 'content-length'
+]
- if (state.regexpStart) {
- if (character === '/' || character == '*') {
- state.stack.pop();
- }
- state.regexpStart = false;
- }
- switch (state.current()) {
- case TOKEN_TYPES.LINE_COMMENT:
- if (character === '\n') {
- state.stack.pop();
- }
- break;
- case TOKEN_TYPES.BLOCK_COMMENT:
- if (state.lastChar === '*' && character === '/') {
- state.stack.pop();
- }
- break;
- case TOKEN_TYPES.SINGLE_QUOTE:
- if (character === '\'' && !state.escaped) {
- state.stack.pop();
- } else if (character === '\\' && !state.escaped) {
- state.escaped = true;
- } else {
- state.escaped = false;
- }
- break;
- case TOKEN_TYPES.DOUBLE_QUOTE:
- if (character === '"' && !state.escaped) {
- state.stack.pop();
- } else if (character === '\\' && !state.escaped) {
- state.escaped = true;
- } else {
- state.escaped = false;
- }
- break;
- case TOKEN_TYPES.TEMPLATE_QUOTE:
- if (character === '`' && !state.escaped) {
- state.stack.pop();
- state.hasDollar = false;
- } else if (character === '\\' && !state.escaped) {
- state.escaped = true;
- state.hasDollar = false;
- } else if (character === '$' && !state.escaped) {
- state.hasDollar = true;
- } else if (character === '{' && state.hasDollar) {
- state.stack.push(BRACKETS[character]);
- } else {
- state.escaped = false;
- state.hasDollar = false;
- }
- break;
- case TOKEN_TYPES.REGEXP:
- if (character === '/' && !state.escaped) {
- state.stack.pop();
- } else if (character === '\\' && !state.escaped) {
- state.escaped = true;
- } else {
- state.escaped = false;
- }
- break;
- default:
- if (character in BRACKETS) {
- state.stack.push(BRACKETS[character]);
- } else if (character in BRACKETS_REVERSED) {
- if (state.current() !== character) {
- var err = new SyntaxError('Mismatched Bracket: ' + character);
- err.code = 'CHARACTER_PARSER:MISMATCHED_BRACKET';
- throw err;
- };
- state.stack.pop();
- } else if (lastChar === '/' && character === '/') {
- // Don't include comments in history
- state.history = state.history.substr(1);
- state.stack.push(TOKEN_TYPES.LINE_COMMENT);
- } else if (lastChar === '/' && character === '*') {
- // Don't include comment in history
- state.history = state.history.substr(1);
- state.stack.push(TOKEN_TYPES.BLOCK_COMMENT);
- } else if (character === '/' && isRegexp(state.history)) {
- state.stack.push(TOKEN_TYPES.REGEXP);
- // N.B. if the next character turns out to be a `*` or a `/`
- // then this isn't actually a regexp
- state.regexpStart = true;
- } else if (character === '\'') {
- state.stack.push(TOKEN_TYPES.SINGLE_QUOTE);
- } else if (character === '"') {
- state.stack.push(TOKEN_TYPES.DOUBLE_QUOTE);
- } else if (character === '`') {
- state.stack.push(TOKEN_TYPES.TEMPLATE_QUOTE);
- }
- break;
- }
- if (!state.isComment() && !wasComment) {
- state.history = character + state.history;
- }
- state.lastChar = character; // store last character for ending block comments
- return state;
-}
+// https://fetch.spec.whatwg.org/#enumdef-requestduplex
+const requestDuplex = [
+ 'half'
+]
-exports.defaultState = function () { return new State() };
-function State() {
- this.stack = [];
+// http://fetch.spec.whatwg.org/#forbidden-method
+const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
- this.regexpStart = false;
- this.escaped = false;
- this.hasDollar = false;
+const subresource = [
+ 'audio',
+ 'audioworklet',
+ 'font',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'script',
+ 'style',
+ 'track',
+ 'video',
+ 'xslt',
+ ''
+]
- this.src = '';
- this.history = ''
- this.lastChar = ''
-}
-State.prototype.current = function () {
- return this.stack[this.stack.length - 1];
-};
-State.prototype.isString = function () {
- return (
- this.current() === TOKEN_TYPES.SINGLE_QUOTE ||
- this.current() === TOKEN_TYPES.DOUBLE_QUOTE ||
- this.current() === TOKEN_TYPES.TEMPLATE_QUOTE
- );
-}
-State.prototype.isComment = function () {
- return this.current() === TOKEN_TYPES.LINE_COMMENT || this.current() === TOKEN_TYPES.BLOCK_COMMENT;
-}
-State.prototype.isNesting = function (opts) {
- if (
- opts && opts.ignoreLineComment &&
- this.stack.length === 1 && this.stack[0] === TOKEN_TYPES.LINE_COMMENT
- ) {
- // if we are only inside a line comment, and line comments are ignored
- // don't count it as nesting
- return false;
+/** @type {globalThis['DOMException']} */
+const DOMException = globalThis.DOMException ?? (() => {
+ // DOMException was only made a global in Node v17.0.0,
+ // but fetch supports >= v16.8.
+ try {
+ atob('~')
+ } catch (err) {
+ return Object.getPrototypeOf(err).constructor
}
- return !!this.stack.length;
-}
+})()
-function matches(str, matcher, i) {
- if (objIsRegex(matcher)) {
- return matcher.test(str.substr(i || 0));
- } else {
- return str.substr(i || 0, matcher.length) === matcher;
- }
-}
-
-exports.isPunctuator = isPunctuator
-function isPunctuator(c) {
- if (!c) return true; // the start of a string is a punctuator
- var code = c.charCodeAt(0)
-
- switch (code) {
- case 46: // . dot
- case 40: // ( open bracket
- case 41: // ) close bracket
- case 59: // ; semicolon
- case 44: // , comma
- case 123: // { open curly brace
- case 125: // } close curly brace
- case 91: // [
- case 93: // ]
- case 58: // :
- case 63: // ?
- case 126: // ~
- case 37: // %
- case 38: // &
- case 42: // *:
- case 43: // +
- case 45: // -
- case 47: // /
- case 60: // <
- case 62: // >
- case 94: // ^
- case 124: // |
- case 33: // !
- case 61: // =
- return true;
- default:
- return false;
- }
-}
-
-exports.isKeyword = isKeyword
-function isKeyword(id) {
- return (id === 'if') || (id === 'in') || (id === 'do') || (id === 'var') || (id === 'for') || (id === 'new') ||
- (id === 'try') || (id === 'let') || (id === 'this') || (id === 'else') || (id === 'case') ||
- (id === 'void') || (id === 'with') || (id === 'enum') || (id === 'while') || (id === 'break') || (id === 'catch') ||
- (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super') ||
- (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') ||
- (id === 'import') || (id === 'default') || (id === 'finally') || (id === 'extends') || (id === 'function') ||
- (id === 'continue') || (id === 'debugger') || (id === 'package') || (id === 'private') || (id === 'interface') ||
- (id === 'instanceof') || (id === 'implements') || (id === 'protected') || (id === 'public') || (id === 'static');
-}
-
-function isRegexp(history) {
- //could be start of regexp or divide sign
-
- history = history.replace(/^\s*/, '');
-
- //unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide
- if (history[0] === ')') return false;
- //unless it's a function expression, it's a regexp, so we assume it's a regexp
- if (history[0] === '}') return true;
- //any punctuation means it's a regexp
- if (isPunctuator(history[0])) return true;
- //if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`)
- if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0].split('').reverse().join(''))) return true;
-
- return false;
-}
+let channel
+/** @type {globalThis['structuredClone']} */
+const structuredClone =
+ globalThis.structuredClone ??
+ // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
+ // structuredClone was added in v17.0.0, but fetch supports v16.8
+ function structuredClone (value, options = undefined) {
+ if (arguments.length === 0) {
+ throw new TypeError('missing argument')
+ }
-/***/ }),
+ if (!channel) {
+ channel = new MessageChannel()
+ }
+ channel.port1.unref()
+ channel.port2.unref()
+ channel.port1.postMessage(value, options?.transfer)
+ return receiveMessageOnPort(channel.port2).message
+ }
-/***/ 2101:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+module.exports = {
+ DOMException,
+ structuredClone,
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex
+}
-module.exports = __nccwpck_require__(16136);
/***/ }),
-/***/ 66168:
+/***/ 4322:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { info, debug } = __nccwpck_require__(65829);
-const utils = __nccwpck_require__(98911);
+const assert = __nccwpck_require__(2613)
+const { atob } = __nccwpck_require__(181)
+const { isomorphicDecode } = __nccwpck_require__(5523)
-class Cell {
- /**
- * A representation of a cell within the table.
- * Implementations must have `init` and `draw` methods,
- * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties.
- * @param options
- * @constructor
- */
- constructor(options) {
- this.setOptions(options);
+const encoder = new TextEncoder()
- /**
- * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to
- * `init` being called;
- * @type {Number}
- */
- this.x = null;
- this.y = null;
- }
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
+ */
+const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
+const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
+ */
+const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
- setOptions(options) {
- if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) {
- options = { content: '' + options };
- }
- options = options || {};
- this.options = options;
- let content = options.content;
- if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) {
- this.content = String(content);
- } else if (!content) {
- this.content = this.options.href || '';
- } else {
- throw new Error('Content needs to be a primitive, got: ' + typeof content);
- }
- this.colSpan = options.colSpan || 1;
- this.rowSpan = options.rowSpan || 1;
- if (this.options.href) {
- Object.defineProperty(this, 'href', {
- get() {
- return this.options.href;
- },
- });
- }
- }
+// https://fetch.spec.whatwg.org/#data-url-processor
+/** @param {URL} dataURL */
+function dataURLProcessor (dataURL) {
+ // 1. Assert: dataURL’s scheme is "data".
+ assert(dataURL.protocol === 'data:')
- mergeTableOptions(tableOptions, cells) {
- this.cells = cells;
+ // 2. Let input be the result of running the URL
+ // serializer on dataURL with exclude fragment
+ // set to true.
+ let input = URLSerializer(dataURL, true)
- let optionsChars = this.options.chars || {};
- let tableChars = tableOptions.chars;
- let chars = (this.chars = {});
- CHAR_NAMES.forEach(function (name) {
- setOption(optionsChars, tableChars, name, chars);
- });
+ // 3. Remove the leading "data:" string from input.
+ input = input.slice(5)
- this.truncate = this.options.truncate || tableOptions.truncate;
+ // 4. Let position point at the start of input.
+ const position = { position: 0 }
- let style = (this.options.style = this.options.style || {});
- let tableStyle = tableOptions.style;
- setOption(style, tableStyle, 'padding-left', this);
- setOption(style, tableStyle, 'padding-right', this);
- this.head = style.head || tableStyle.head;
- this.border = style.border || tableStyle.border;
+ // 5. Let mimeType be the result of collecting a
+ // sequence of code points that are not equal
+ // to U+002C (,), given position.
+ let mimeType = collectASequenceOfCodePointsFast(
+ ',',
+ input,
+ position
+ )
- this.fixedWidth = tableOptions.colWidths[this.x];
- this.lines = this.computeLines(tableOptions);
+ // 6. Strip leading and trailing ASCII whitespace
+ // from mimeType.
+ // Undici implementation note: we need to store the
+ // length because if the mimetype has spaces removed,
+ // the wrong amount will be sliced from the input in
+ // step #9
+ const mimeTypeLength = mimeType.length
+ mimeType = removeASCIIWhitespace(mimeType, true, true)
- this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight;
- this.desiredHeight = this.lines.length;
+ // 7. If position is past the end of input, then
+ // return failure
+ if (position.position >= input.length) {
+ return 'failure'
}
- computeLines(tableOptions) {
- const tableWordWrap = tableOptions.wordWrap || tableOptions.textWrap;
- const { wordWrap = tableWordWrap } = this.options;
- if (this.fixedWidth && wordWrap) {
- this.fixedWidth -= this.paddingLeft + this.paddingRight;
- if (this.colSpan) {
- let i = 1;
- while (i < this.colSpan) {
- this.fixedWidth += tableOptions.colWidths[this.x + i];
- i++;
- }
- }
- const { wrapOnWordBoundary: tableWrapOnWordBoundary = true } = tableOptions;
- const { wrapOnWordBoundary = tableWrapOnWordBoundary } = this.options;
- return this.wrapLines(utils.wordWrap(this.fixedWidth, this.content, wrapOnWordBoundary));
- }
- return this.wrapLines(this.content.split('\n'));
- }
+ // 8. Advance position by 1.
+ position.position++
- wrapLines(computedLines) {
- const lines = utils.colorizeLines(computedLines);
- if (this.href) {
- return lines.map((line) => utils.hyperlink(this.href, line));
- }
- return lines;
- }
+ // 9. Let encodedBody be the remainder of input.
+ const encodedBody = input.slice(mimeTypeLength + 1)
- /**
- * Initializes the Cells data structure.
- *
- * @param tableOptions - A fully populated set of tableOptions.
- * In addition to the standard default values, tableOptions must have fully populated the
- * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number
- * of columns or rows (respectively) in this table, and each array item must be a Number.
- *
- */
- init(tableOptions) {
- let x = this.x;
- let y = this.y;
- this.widths = tableOptions.colWidths.slice(x, x + this.colSpan);
- this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan);
- this.width = this.widths.reduce(sumPlusOne, -1);
- this.height = this.heights.reduce(sumPlusOne, -1);
+ // 10. Let body be the percent-decoding of encodedBody.
+ let body = stringPercentDecode(encodedBody)
- this.hAlign = this.options.hAlign || tableOptions.colAligns[x];
- this.vAlign = this.options.vAlign || tableOptions.rowAligns[y];
+ // 11. If mimeType ends with U+003B (;), followed by
+ // zero or more U+0020 SPACE, followed by an ASCII
+ // case-insensitive match for "base64", then:
+ if (/;(\u0020){0,}base64$/i.test(mimeType)) {
+ // 1. Let stringBody be the isomorphic decode of body.
+ const stringBody = isomorphicDecode(body)
- this.drawRight = x + this.colSpan == tableOptions.colWidths.length;
- }
+ // 2. Set body to the forgiving-base64 decode of
+ // stringBody.
+ body = forgivingBase64(stringBody)
- /**
- * Draws the given line of the cell.
- * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`.
- * @param lineNum - can be `top`, `bottom` or a numerical line number.
- * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how
- * many rows below it's being called from. Otherwise it's undefined.
- * @returns {String} The representation of this line.
- */
- draw(lineNum, spanningCell) {
- if (lineNum == 'top') return this.drawTop(this.drawRight);
- if (lineNum == 'bottom') return this.drawBottom(this.drawRight);
- let content = utils.truncate(this.content, 10, this.truncate);
- if (!lineNum) {
- info(`${this.y}-${this.x}: ${this.rowSpan - lineNum}x${this.colSpan} Cell ${content}`);
- } else {
- // debug(`${lineNum}-${this.x}: 1x${this.colSpan} RowSpanCell ${content}`);
- }
- let padLen = Math.max(this.height - this.lines.length, 0);
- let padTop;
- switch (this.vAlign) {
- case 'center':
- padTop = Math.ceil(padLen / 2);
- break;
- case 'bottom':
- padTop = padLen;
- break;
- default:
- padTop = 0;
- }
- if (lineNum < padTop || lineNum >= padTop + this.lines.length) {
- return this.drawEmpty(this.drawRight, spanningCell);
+ // 3. If body is failure, then return failure.
+ if (body === 'failure') {
+ return 'failure'
}
- let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height;
- return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell);
- }
- /**
- * Renders the top line of the cell.
- * @param drawRight - true if this method should render the right edge of the cell.
- * @returns {String}
- */
- drawTop(drawRight) {
- let content = [];
- if (this.cells) {
- //TODO: cells should always exist - some tests don't fill it in though
- this.widths.forEach(function (width, index) {
- content.push(this._topLeftChar(index));
- content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width));
- }, this);
- } else {
- content.push(this._topLeftChar(0));
- content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width));
- }
- if (drawRight) {
- content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']);
- }
- return this.wrapWithStyleColors('border', content.join(''));
- }
+ // 4. Remove the last 6 code points from mimeType.
+ mimeType = mimeType.slice(0, -6)
- _topLeftChar(offset) {
- let x = this.x + offset;
- let leftChar;
- if (this.y == 0) {
- leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top';
- } else {
- if (x == 0) {
- leftChar = 'leftMid';
- } else {
- leftChar = offset == 0 ? 'midMid' : 'bottomMid';
- if (this.cells) {
- //TODO: cells should always exist - some tests don't fill it in though
- let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell;
- if (spanAbove) {
- leftChar = offset == 0 ? 'topMid' : 'mid';
- }
- if (offset == 0) {
- let i = 1;
- while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) {
- i++;
- }
- if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) {
- leftChar = 'leftMid';
- }
- }
- }
- }
- }
- return this.chars[leftChar];
- }
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
+ // if any.
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
- wrapWithStyleColors(styleProperty, content) {
- if (this[styleProperty] && this[styleProperty].length) {
- try {
- let colors = __nccwpck_require__(59256);
- for (let i = this[styleProperty].length - 1; i >= 0; i--) {
- colors = colors[this[styleProperty][i]];
- }
- return colors(content);
- } catch (e) {
- return content;
- }
- } else {
- return content;
- }
+ // 6. Remove the last U+003B (;) code point from mimeType.
+ mimeType = mimeType.slice(0, -1)
}
- /**
- * Renders a line of text.
- * @param lineNum - Which line of text to render. This is not necessarily the line within the cell.
- * There may be top-padding above the first line of text.
- * @param drawRight - true if this method should render the right edge of the cell.
- * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even
- * if the text fits. This is used when the cell is vertically truncated. If `false` the text should
- * only include the truncation symbol if the text will not fit horizontally within the cell width.
- * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
- * @returns {String}
- */
- drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) {
- let left = this.chars[this.x == 0 ? 'left' : 'middle'];
- if (this.x && spanningCell && this.cells) {
- let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
- while (cellLeft instanceof ColSpanCell) {
- cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
- }
- if (!(cellLeft instanceof RowSpanCell)) {
- left = this.chars['rightMid'];
- }
- }
- let leftPadding = utils.repeat(' ', this.paddingLeft);
- let right = drawRight ? this.chars['right'] : '';
- let rightPadding = utils.repeat(' ', this.paddingRight);
- let line = this.lines[lineNum];
- let len = this.width - (this.paddingLeft + this.paddingRight);
- if (forceTruncationSymbol) line += this.truncate || '…';
- let content = utils.truncate(line, len, this.truncate);
- content = utils.pad(content, len, ' ', this.hAlign);
- content = leftPadding + content + rightPadding;
- return this.stylizeLine(left, content, right);
+ // 12. If mimeType starts with U+003B (;), then prepend
+ // "text/plain" to mimeType.
+ if (mimeType.startsWith(';')) {
+ mimeType = 'text/plain' + mimeType
}
- stylizeLine(left, content, right) {
- left = this.wrapWithStyleColors('border', left);
- right = this.wrapWithStyleColors('border', right);
- if (this.y === 0) {
- content = this.wrapWithStyleColors('head', content);
- }
- return left + content + right;
- }
+ // 13. Let mimeTypeRecord be the result of parsing
+ // mimeType.
+ let mimeTypeRecord = parseMIMEType(mimeType)
- /**
- * Renders the bottom line of the cell.
- * @param drawRight - true if this method should render the right edge of the cell.
- * @returns {String}
- */
- drawBottom(drawRight) {
- let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid'];
- let content = utils.repeat(this.chars.bottom, this.width);
- let right = drawRight ? this.chars['bottomRight'] : '';
- return this.wrapWithStyleColors('border', left + content + right);
+ // 14. If mimeTypeRecord is failure, then set
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
+ if (mimeTypeRecord === 'failure') {
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
}
- /**
- * Renders a blank line of text within the cell. Used for top and/or bottom padding.
- * @param drawRight - true if this method should render the right edge of the cell.
- * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined.
- * @returns {String}
- */
- drawEmpty(drawRight, spanningCell) {
- let left = this.chars[this.x == 0 ? 'left' : 'middle'];
- if (this.x && spanningCell && this.cells) {
- let cellLeft = this.cells[this.y + spanningCell][this.x - 1];
- while (cellLeft instanceof ColSpanCell) {
- cellLeft = this.cells[cellLeft.y][cellLeft.x - 1];
- }
- if (!(cellLeft instanceof RowSpanCell)) {
- left = this.chars['rightMid'];
- }
- }
- let right = drawRight ? this.chars['right'] : '';
- let content = utils.repeat(' ', this.width);
- return this.stylizeLine(left, content, right);
- }
+ // 15. Return a new data: URL struct whose MIME
+ // type is mimeTypeRecord and body is body.
+ // https://fetch.spec.whatwg.org/#data-url-struct
+ return { mimeType: mimeTypeRecord, body }
}
-class ColSpanCell {
- /**
- * A Cell that doesn't do anything. It just draws empty lines.
- * Used as a placeholder in column spanning.
- * @constructor
- */
- constructor() {}
+// https://url.spec.whatwg.org/#concept-url-serializer
+/**
+ * @param {URL} url
+ * @param {boolean} excludeFragment
+ */
+function URLSerializer (url, excludeFragment = false) {
+ const href = url.href
- draw(lineNum) {
- if (typeof lineNum === 'number') {
- debug(`${this.y}-${this.x}: 1x1 ColSpanCell`);
- }
- return '';
+ if (!excludeFragment) {
+ return href
}
- init() {}
-
- mergeTableOptions() {}
+ const hash = href.lastIndexOf('#')
+ if (hash === -1) {
+ return href
+ }
+ return href.slice(0, hash)
}
-class RowSpanCell {
- /**
- * A placeholder Cell for a Cell that spans multiple rows.
- * It delegates rendering to the original cell, but adds the appropriate offset.
- * @param originalCell
- * @constructor
- */
- constructor(originalCell) {
- this.originalCell = originalCell;
- }
+// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
+/**
+ * @param {(char: string) => boolean} condition
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePoints (condition, input, position) {
+ // 1. Let result be the empty string.
+ let result = ''
- init(tableOptions) {
- let y = this.y;
- let originalY = this.originalCell.y;
- this.cellOffset = y - originalY;
- this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset);
- }
+ // 2. While position doesn’t point past the end of input and the
+ // code point at position within input meets the condition condition:
+ while (position.position < input.length && condition(input[position.position])) {
+ // 1. Append that code point to the end of result.
+ result += input[position.position]
- draw(lineNum) {
- if (lineNum == 'top') {
- return this.originalCell.draw(this.offset, this.cellOffset);
- }
- if (lineNum == 'bottom') {
- return this.originalCell.draw('bottom');
- }
- debug(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`);
- return this.originalCell.draw(this.offset + 1 + lineNum);
+ // 2. Advance position by 1.
+ position.position++
}
- mergeTableOptions() {}
+ // 3. Return result.
+ return result
}
-function firstDefined(...args) {
- return args.filter((v) => v !== undefined && v !== null).shift();
-}
+/**
+ * A faster collectASequenceOfCodePoints that only works when comparing a single character.
+ * @param {string} char
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePointsFast (char, input, position) {
+ const idx = input.indexOf(char, position.position)
+ const start = position.position
-// HELPER FUNCTIONS
-function setOption(objA, objB, nameB, targetObj) {
- let nameA = nameB.split('-');
- if (nameA.length > 1) {
- nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1);
- nameA = nameA.join('');
- targetObj[nameA] = firstDefined(objA[nameA], objA[nameB], objB[nameA], objB[nameB]);
- } else {
- targetObj[nameB] = firstDefined(objA[nameB], objB[nameB]);
+ if (idx === -1) {
+ position.position = input.length
+ return input.slice(start)
}
-}
-function findDimension(dimensionTable, startingIndex, span) {
- let ret = dimensionTable[startingIndex];
- for (let i = 1; i < span; i++) {
- ret += 1 + dimensionTable[startingIndex + i];
- }
- return ret;
+ position.position = idx
+ return input.slice(start, position.position)
}
-function sumPlusOne(a, b) {
- return a + b + 1;
+// https://url.spec.whatwg.org/#string-percent-decode
+/** @param {string} input */
+function stringPercentDecode (input) {
+ // 1. Let bytes be the UTF-8 encoding of input.
+ const bytes = encoder.encode(input)
+
+ // 2. Return the percent-decoding of bytes.
+ return percentDecode(bytes)
}
-let CHAR_NAMES = [
- 'top',
- 'top-mid',
- 'top-left',
- 'top-right',
- 'bottom',
- 'bottom-mid',
- 'bottom-left',
- 'bottom-right',
- 'left',
- 'left-mid',
- 'mid',
- 'mid-mid',
- 'right',
- 'right-mid',
- 'middle',
-];
+// https://url.spec.whatwg.org/#percent-decode
+/** @param {Uint8Array} input */
+function percentDecode (input) {
+ // 1. Let output be an empty byte sequence.
+ /** @type {number[]} */
+ const output = []
-module.exports = Cell;
-module.exports.ColSpanCell = ColSpanCell;
-module.exports.RowSpanCell = RowSpanCell;
+ // 2. For each byte byte in input:
+ for (let i = 0; i < input.length; i++) {
+ const byte = input[i]
+ // 1. If byte is not 0x25 (%), then append byte to output.
+ if (byte !== 0x25) {
+ output.push(byte)
-/***/ }),
+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
+ // after byte in input are not in the ranges
+ // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
+ // and 0x61 (a) to 0x66 (f), all inclusive, append byte
+ // to output.
+ } else if (
+ byte === 0x25 &&
+ !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
+ ) {
+ output.push(0x25)
-/***/ 65829:
-/***/ ((module) => {
+ // 3. Otherwise:
+ } else {
+ // 1. Let bytePoint be the two bytes after byte in input,
+ // decoded, and then interpreted as hexadecimal number.
+ const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
+ const bytePoint = Number.parseInt(nextTwoBytes, 16)
-let messages = [];
-let level = 0;
+ // 2. Append a byte whose value is bytePoint to output.
+ output.push(bytePoint)
-const debug = (msg, min) => {
- if (level >= min) {
- messages.push(msg);
+ // 3. Skip the next two bytes in input.
+ i += 2
+ }
}
-};
-
-debug.WARN = 1;
-debug.INFO = 2;
-debug.DEBUG = 3;
-
-debug.reset = () => {
- messages = [];
-};
-
-debug.setDebugLevel = (v) => {
- level = v;
-};
-
-debug.warn = (msg) => debug(msg, debug.WARN);
-debug.info = (msg) => debug(msg, debug.INFO);
-debug.debug = (msg) => debug(msg, debug.DEBUG);
-
-debug.debugMessages = () => messages;
-
-module.exports = debug;
+ // 3. Return output.
+ return Uint8Array.from(output)
+}
-/***/ }),
+// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+/** @param {string} input */
+function parseMIMEType (input) {
+ // 1. Remove any leading and trailing HTTP whitespace
+ // from input.
+ input = removeHTTPWhitespace(input, true, true)
-/***/ 93875:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let position be a position variable for input,
+ // initially pointing at the start of input.
+ const position = { position: 0 }
-const { warn, debug } = __nccwpck_require__(65829);
-const Cell = __nccwpck_require__(66168);
-const { ColSpanCell, RowSpanCell } = Cell;
-
-(function () {
- function next(alloc, col) {
- if (alloc[col] > 0) {
- return next(alloc, col + 1);
- }
- return col;
- }
-
- function layoutTable(table) {
- let alloc = {};
- table.forEach(function (row, rowIndex) {
- let col = 0;
- row.forEach(function (cell) {
- cell.y = rowIndex;
- // Avoid erroneous call to next() on first row
- cell.x = rowIndex ? next(alloc, col) : col;
- const rowSpan = cell.rowSpan || 1;
- const colSpan = cell.colSpan || 1;
- if (rowSpan > 1) {
- for (let cs = 0; cs < colSpan; cs++) {
- alloc[cell.x + cs] = rowSpan;
- }
- }
- col = cell.x + colSpan;
- });
- Object.keys(alloc).forEach((idx) => {
- alloc[idx]--;
- if (alloc[idx] < 1) delete alloc[idx];
- });
- });
- }
+ // 3. Let type be the result of collecting a sequence
+ // of code points that are not U+002F (/) from
+ // input, given position.
+ const type = collectASequenceOfCodePointsFast(
+ '/',
+ input,
+ position
+ )
- function maxWidth(table) {
- let mw = 0;
- table.forEach(function (row) {
- row.forEach(function (cell) {
- mw = Math.max(mw, cell.x + (cell.colSpan || 1));
- });
- });
- return mw;
+ // 4. If type is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ // https://mimesniff.spec.whatwg.org/#http-token-code-point
+ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
+ return 'failure'
}
- function maxHeight(table) {
- return table.length;
+ // 5. If position is past the end of input, then return
+ // failure
+ if (position.position > input.length) {
+ return 'failure'
}
- function cellsConflict(cell1, cell2) {
- let yMin1 = cell1.y;
- let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1);
- let yMin2 = cell2.y;
- let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1);
- let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1);
-
- let xMin1 = cell1.x;
- let xMax1 = cell1.x - 1 + (cell1.colSpan || 1);
- let xMin2 = cell2.x;
- let xMax2 = cell2.x - 1 + (cell2.colSpan || 1);
- let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1);
-
- return yConflict && xConflict;
- }
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position.position++
- function conflictExists(rows, x, y) {
- let i_max = Math.min(rows.length - 1, y);
- let cell = { x: x, y: y };
- for (let i = 0; i <= i_max; i++) {
- let row = rows[i];
- for (let j = 0; j < row.length; j++) {
- if (cellsConflict(cell, row[j])) {
- return true;
- }
- }
- }
- return false;
- }
+ // 7. Let subtype be the result of collecting a sequence of
+ // code points that are not U+003B (;) from input, given
+ // position.
+ let subtype = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- function allBlank(rows, y, xMin, xMax) {
- for (let x = xMin; x < xMax; x++) {
- if (conflictExists(rows, x, y)) {
- return false;
- }
- }
- return true;
- }
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ subtype = removeHTTPWhitespace(subtype, false, true)
- function addRowSpanCells(table) {
- table.forEach(function (row, rowIndex) {
- row.forEach(function (cell) {
- for (let i = 1; i < cell.rowSpan; i++) {
- let rowSpanCell = new RowSpanCell(cell);
- rowSpanCell.x = cell.x;
- rowSpanCell.y = cell.y + i;
- rowSpanCell.colSpan = cell.colSpan;
- insertCell(rowSpanCell, table[rowIndex + i]);
- }
- });
- });
+ // 9. If subtype is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
+ return 'failure'
}
- function addColSpanCells(cellRows) {
- for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) {
- let cellColumns = cellRows[rowIndex];
- for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) {
- let cell = cellColumns[columnIndex];
- for (let k = 1; k < cell.colSpan; k++) {
- let colSpanCell = new ColSpanCell();
- colSpanCell.x = cell.x + k;
- colSpanCell.y = cell.y;
- cellColumns.splice(columnIndex + 1, 0, colSpanCell);
- }
- }
- }
- }
+ const typeLowercase = type.toLowerCase()
+ const subtypeLowercase = subtype.toLowerCase()
- function insertCell(cell, row) {
- let x = 0;
- while (x < row.length && row[x].x < cell.x) {
- x++;
- }
- row.splice(x, 0, cell);
+ // 10. Let mimeType be a new MIME type record whose type
+ // is type, in ASCII lowercase, and subtype is subtype,
+ // in ASCII lowercase.
+ // https://mimesniff.spec.whatwg.org/#mime-type
+ const mimeType = {
+ type: typeLowercase,
+ subtype: subtypeLowercase,
+ /** @type {Map} */
+ parameters: new Map(),
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
+ essence: `${typeLowercase}/${subtypeLowercase}`
}
- function fillInTable(table) {
- let h_max = maxHeight(table);
- let w_max = maxWidth(table);
- debug(`Max rows: ${h_max}; Max cols: ${w_max}`);
- for (let y = 0; y < h_max; y++) {
- for (let x = 0; x < w_max; x++) {
- if (!conflictExists(table, x, y)) {
- let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 };
- x++;
- while (x < w_max && !conflictExists(table, x, y)) {
- opts.colSpan++;
- x++;
- }
- let y2 = y + 1;
- while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) {
- opts.rowSpan++;
- y2++;
- }
- let cell = new Cell(opts);
- cell.x = opts.x;
- cell.y = opts.y;
- warn(`Missing cell at ${cell.y}-${cell.x}.`);
- insertCell(cell, table[y]);
- }
- }
- }
- }
+ // 11. While position is not past the end of input:
+ while (position.position < input.length) {
+ // 1. Advance position by 1. (This skips past U+003B (;).)
+ position.position++
- function generateCells(rows) {
- return rows.map(function (row) {
- if (!Array.isArray(row)) {
- let key = Object.keys(row)[0];
- row = row[key];
- if (Array.isArray(row)) {
- row = row.slice();
- row.unshift(key);
- } else {
- row = [key, row];
- }
- }
- return row.map(function (cell) {
- return new Cell(cell);
- });
- });
- }
+ // 2. Collect a sequence of code points that are HTTP
+ // whitespace from input given position.
+ collectASequenceOfCodePoints(
+ // https://fetch.spec.whatwg.org/#http-whitespace
+ char => HTTP_WHITESPACE_REGEX.test(char),
+ input,
+ position
+ )
- function makeTableLayout(rows) {
- let cellRows = generateCells(rows);
- layoutTable(cellRows);
- fillInTable(cellRows);
- addRowSpanCells(cellRows);
- addColSpanCells(cellRows);
- return cellRows;
- }
-
- module.exports = {
- makeTableLayout: makeTableLayout,
- layoutTable: layoutTable,
- addRowSpanCells: addRowSpanCells,
- maxWidth: maxWidth,
- fillInTable: fillInTable,
- computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1),
- computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1),
- };
-})();
-
-function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) {
- return function (vals, table) {
- let result = [];
- let spanners = [];
- let auto = {};
- table.forEach(function (row) {
- row.forEach(function (cell) {
- if ((cell[colSpan] || 1) > 1) {
- spanners.push(cell);
- } else {
- result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin);
- }
- });
- });
+ // 3. Let parameterName be the result of collecting a
+ // sequence of code points that are not U+003B (;)
+ // or U+003D (=) from input, given position.
+ let parameterName = collectASequenceOfCodePoints(
+ (char) => char !== ';' && char !== '=',
+ input,
+ position
+ )
- vals.forEach(function (val, index) {
- if (typeof val === 'number') {
- result[index] = val;
- }
- });
+ // 4. Set parameterName to parameterName, in ASCII
+ // lowercase.
+ parameterName = parameterName.toLowerCase()
- //spanners.forEach(function(cell){
- for (let k = spanners.length - 1; k >= 0; k--) {
- let cell = spanners[k];
- let span = cell[colSpan];
- let col = cell[x];
- let existingWidth = result[col];
- let editableCols = typeof vals[col] === 'number' ? 0 : 1;
- if (typeof existingWidth === 'number') {
- for (let i = 1; i < span; i++) {
- existingWidth += 1 + result[col + i];
- if (typeof vals[col + i] !== 'number') {
- editableCols++;
- }
- }
- } else {
- existingWidth = desiredWidth === 'desiredWidth' ? cell.desiredWidth - 1 : 1;
- if (!auto[col] || auto[col] < existingWidth) {
- auto[col] = existingWidth;
- }
+ // 5. If position is not past the end of input, then:
+ if (position.position < input.length) {
+ // 1. If the code point at position within input is
+ // U+003B (;), then continue.
+ if (input[position.position] === ';') {
+ continue
}
- if (cell[desiredWidth] > existingWidth) {
- let i = 0;
- while (editableCols > 0 && cell[desiredWidth] > existingWidth) {
- if (typeof vals[col + i] !== 'number') {
- let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols);
- existingWidth += dif;
- result[col + i] += dif;
- editableCols--;
- }
- i++;
- }
- }
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position.position++
}
- Object.assign(vals, result, auto);
- for (let j = 0; j < vals.length; j++) {
- vals[j] = Math.max(forcedMin, vals[j] || 0);
+ // 6. If position is past the end of input, then break.
+ if (position.position > input.length) {
+ break
}
- };
-}
-
-/***/ }),
+ // 7. Let parameterValue be null.
+ let parameterValue = null
-/***/ 16136:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 8. If the code point at position within input is
+ // U+0022 ("), then:
+ if (input[position.position] === '"') {
+ // 1. Set parameterValue to the result of collecting
+ // an HTTP quoted string from input, given position
+ // and the extract-value flag.
+ parameterValue = collectAnHTTPQuotedString(input, position, true)
-const debug = __nccwpck_require__(65829);
-const utils = __nccwpck_require__(98911);
-const tableLayout = __nccwpck_require__(93875);
+ // 2. Collect a sequence of code points that are not
+ // U+003B (;) from input, given position.
+ collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
-class Table extends Array {
- constructor(opts) {
- super();
+ // 9. Otherwise:
+ } else {
+ // 1. Set parameterValue to the result of collecting
+ // a sequence of code points that are not U+003B (;)
+ // from input, given position.
+ parameterValue = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- const options = utils.mergeOptions(opts);
- Object.defineProperty(this, 'options', {
- value: options,
- enumerable: options.debug,
- });
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true)
- if (options.debug) {
- switch (typeof options.debug) {
- case 'boolean':
- debug.setDebugLevel(debug.WARN);
- break;
- case 'number':
- debug.setDebugLevel(options.debug);
- break;
- case 'string':
- debug.setDebugLevel(parseInt(options.debug, 10));
- break;
- default:
- debug.setDebugLevel(debug.WARN);
- debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`);
+ // 3. If parameterValue is the empty string, then continue.
+ if (parameterValue.length === 0) {
+ continue
}
- Object.defineProperty(this, 'messages', {
- get() {
- return debug.debugMessages();
- },
- });
}
- }
- toString() {
- let array = this;
- let headersPresent = this.options.head && this.options.head.length;
- if (headersPresent) {
- array = [this.options.head];
- if (this.length) {
- array.push.apply(array, this);
- }
- } else {
- this.options.style.head = [];
+ // 10. If all of the following are true
+ // - parameterName is not the empty string
+ // - parameterName solely contains HTTP token code points
+ // - parameterValue solely contains HTTP quoted-string token code points
+ // - mimeType’s parameters[parameterName] does not exist
+ // then set mimeType’s parameters[parameterName] to parameterValue.
+ if (
+ parameterName.length !== 0 &&
+ HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
+ (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
+ !mimeType.parameters.has(parameterName)
+ ) {
+ mimeType.parameters.set(parameterName, parameterValue)
}
+ }
- let cells = tableLayout.makeTableLayout(array);
-
- cells.forEach(function (row) {
- row.forEach(function (cell) {
- cell.mergeTableOptions(this.options, cells);
- }, this);
- }, this);
-
- tableLayout.computeWidths(this.options.colWidths, cells);
- tableLayout.computeHeights(this.options.rowHeights, cells);
-
- cells.forEach(function (row) {
- row.forEach(function (cell) {
- cell.init(this.options);
- }, this);
- }, this);
-
- let result = [];
-
- for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) {
- let row = cells[rowIndex];
- let heightOfRow = this.options.rowHeights[rowIndex];
-
- if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) {
- doDraw(row, 'top', result);
- }
+ // 12. Return mimeType.
+ return mimeType
+}
- for (let lineNum = 0; lineNum < heightOfRow; lineNum++) {
- doDraw(row, lineNum, result);
- }
+// https://infra.spec.whatwg.org/#forgiving-base64-decode
+/** @param {string} data */
+function forgivingBase64 (data) {
+ // 1. Remove all ASCII whitespace from data.
+ data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
- if (rowIndex + 1 == cells.length) {
- doDraw(row, 'bottom', result);
- }
- }
+ // 2. If data’s code point length divides by 4 leaving
+ // no remainder, then:
+ if (data.length % 4 === 0) {
+ // 1. If data ends with one or two U+003D (=) code points,
+ // then remove them from data.
+ data = data.replace(/=?=$/, '')
+ }
- return result.join('\n');
+ // 3. If data’s code point length divides by 4 leaving
+ // a remainder of 1, then return failure.
+ if (data.length % 4 === 1) {
+ return 'failure'
}
- get width() {
- let str = this.toString().split('\n');
- return str[0].length;
+ // 4. If data contains a code point that is not one of
+ // U+002B (+)
+ // U+002F (/)
+ // ASCII alphanumeric
+ // then return failure.
+ if (/[^+/0-9A-Za-z]/.test(data)) {
+ return 'failure'
}
-}
-Table.reset = () => debug.reset();
+ const binary = atob(data)
+ const bytes = new Uint8Array(binary.length)
-function doDraw(row, lineNum, result) {
- let line = [];
- row.forEach(function (cell) {
- line.push(cell.draw(lineNum));
- });
- let str = line.join('');
- if (str.length) result.push(str);
+ for (let byte = 0; byte < binary.length; byte++) {
+ bytes[byte] = binary.charCodeAt(byte)
+ }
+
+ return bytes
}
-module.exports = Table;
+// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
+// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
+/**
+ * @param {string} input
+ * @param {{ position: number }} position
+ * @param {boolean?} extractValue
+ */
+function collectAnHTTPQuotedString (input, position, extractValue) {
+ // 1. Let positionStart be position.
+ const positionStart = position.position
+ // 2. Let value be the empty string.
+ let value = ''
-/***/ }),
+ // 3. Assert: the code point at position within input
+ // is U+0022 (").
+ assert(input[position.position] === '"')
-/***/ 98911:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Advance position by 1.
+ position.position++
-const stringWidth = __nccwpck_require__(42577);
+ // 5. While true:
+ while (true) {
+ // 1. Append the result of collecting a sequence of code points
+ // that are not U+0022 (") or U+005C (\) from input, given
+ // position, to value.
+ value += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== '\\',
+ input,
+ position
+ )
-function codeRegex(capture) {
- return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g;
-}
+ // 2. If position is past the end of input, then break.
+ if (position.position >= input.length) {
+ break
+ }
-function strlen(str) {
- let code = codeRegex();
- let stripped = ('' + str).replace(code, '');
- let split = stripped.split('\n');
- return split.reduce(function (memo, s) {
- return stringWidth(s) > memo ? stringWidth(s) : memo;
- }, 0);
-}
+ // 3. Let quoteOrBackslash be the code point at position within
+ // input.
+ const quoteOrBackslash = input[position.position]
-function repeat(str, times) {
- return Array(times + 1).join(str);
-}
+ // 4. Advance position by 1.
+ position.position++
-function pad(str, len, pad, dir) {
- let length = strlen(str);
- if (len + 1 >= length) {
- let padlen = len - length;
- switch (dir) {
- case 'right': {
- str = repeat(pad, padlen) + str;
- break;
- }
- case 'center': {
- let right = Math.ceil(padlen / 2);
- let left = padlen - right;
- str = repeat(pad, left) + str + repeat(pad, right);
- break;
- }
- default: {
- str = str + repeat(pad, padlen);
- break;
+ // 5. If quoteOrBackslash is U+005C (\), then:
+ if (quoteOrBackslash === '\\') {
+ // 1. If position is past the end of input, then append
+ // U+005C (\) to value and break.
+ if (position.position >= input.length) {
+ value += '\\'
+ break
}
- }
- }
- return str;
-}
-let codeCache = {};
+ // 2. Append the code point at position within input to value.
+ value += input[position.position]
-function addToCodeCache(name, on, off) {
- on = '\u001b[' + on + 'm';
- off = '\u001b[' + off + 'm';
- codeCache[on] = { set: name, to: true };
- codeCache[off] = { set: name, to: false };
- codeCache[name] = { on: on, off: off };
-}
+ // 3. Advance position by 1.
+ position.position++
-//https://github.com/Marak/colors.js/blob/master/lib/styles.js
-addToCodeCache('bold', 1, 22);
-addToCodeCache('italics', 3, 23);
-addToCodeCache('underline', 4, 24);
-addToCodeCache('inverse', 7, 27);
-addToCodeCache('strikethrough', 9, 29);
+ // 6. Otherwise:
+ } else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert(quoteOrBackslash === '"')
-function updateState(state, controlChars) {
- let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0;
- if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) {
- state.lastForegroundAdded = controlChars[0];
- return;
- }
- if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) {
- state.lastBackgroundAdded = controlChars[0];
- return;
- }
- if (controlCode === 0) {
- for (let i in state) {
- /* istanbul ignore else */
- if (Object.prototype.hasOwnProperty.call(state, i)) {
- delete state[i];
- }
+ // 2. Break.
+ break
}
- return;
- }
- let info = codeCache[controlChars[0]];
- if (info) {
- state[info.set] = info.to;
}
-}
-function readState(line) {
- let code = codeRegex(true);
- let controlChars = code.exec(line);
- let state = {};
- while (controlChars !== null) {
- updateState(state, controlChars);
- controlChars = code.exec(line);
+ // 6. If the extract-value flag is set, then return value.
+ if (extractValue) {
+ return value
}
- return state;
+
+ // 7. Return the code points from positionStart to position,
+ // inclusive, within input.
+ return input.slice(positionStart, position.position)
}
-function unwindState(state, ret) {
- let lastBackgroundAdded = state.lastBackgroundAdded;
- let lastForegroundAdded = state.lastForegroundAdded;
+/**
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+function serializeAMimeType (mimeType) {
+ assert(mimeType !== 'failure')
+ const { parameters, essence } = mimeType
- delete state.lastBackgroundAdded;
- delete state.lastForegroundAdded;
+ // 1. Let serialization be the concatenation of mimeType’s
+ // type, U+002F (/), and mimeType’s subtype.
+ let serialization = essence
- Object.keys(state).forEach(function (key) {
- if (state[key]) {
- ret += codeCache[key].off;
- }
- });
+ // 2. For each name → value of mimeType’s parameters:
+ for (let [name, value] of parameters.entries()) {
+ // 1. Append U+003B (;) to serialization.
+ serialization += ';'
- if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') {
- ret += '\u001b[49m';
- }
- if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') {
- ret += '\u001b[39m';
- }
+ // 2. Append name to serialization.
+ serialization += name
- return ret;
-}
+ // 3. Append U+003D (=) to serialization.
+ serialization += '='
-function rewindState(state, ret) {
- let lastBackgroundAdded = state.lastBackgroundAdded;
- let lastForegroundAdded = state.lastForegroundAdded;
+ // 4. If value does not solely contain HTTP token code
+ // points or value is the empty string, then:
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
+ // 1. Precede each occurence of U+0022 (") or
+ // U+005C (\) in value with U+005C (\).
+ value = value.replace(/(\\|")/g, '\\$1')
- delete state.lastBackgroundAdded;
- delete state.lastForegroundAdded;
+ // 2. Prepend U+0022 (") to value.
+ value = '"' + value
- Object.keys(state).forEach(function (key) {
- if (state[key]) {
- ret = codeCache[key].on + ret;
+ // 3. Append U+0022 (") to value.
+ value += '"'
}
- });
- if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') {
- ret = lastBackgroundAdded + ret;
- }
- if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') {
- ret = lastForegroundAdded + ret;
+ // 5. Append value to serialization.
+ serialization += value
}
- return ret;
+ // 3. Return serialization.
+ return serialization
}
-function truncateWidth(str, desiredLength) {
- if (str.length === strlen(str)) {
- return str.substr(0, desiredLength);
- }
-
- while (strlen(str) > desiredLength) {
- str = str.slice(0, -1);
- }
-
- return str;
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} char
+ */
+function isHTTPWhiteSpace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === ' '
}
-function truncateWidthWithAnsi(str, desiredLength) {
- let code = codeRegex(true);
- let split = str.split(codeRegex());
- let splitIndex = 0;
- let retLen = 0;
- let ret = '';
- let myArray;
- let state = {};
-
- while (retLen < desiredLength) {
- myArray = code.exec(str);
- let toAdd = split[splitIndex];
- splitIndex++;
- if (retLen + strlen(toAdd) > desiredLength) {
- toAdd = truncateWidth(toAdd, desiredLength - retLen);
- }
- ret += toAdd;
- retLen += strlen(toAdd);
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} str
+ */
+function removeHTTPWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- if (retLen < desiredLength) {
- if (!myArray) {
- break;
- } // full-width chars may cause a whitespace which cannot be filled
- ret += myArray[0];
- updateState(state, myArray);
- }
+ if (leading) {
+ for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
}
- return unwindState(state, ret);
-}
-
-function truncate(str, desiredLength, truncateChar) {
- truncateChar = truncateChar || '…';
- let lengthOfStr = strlen(str);
- if (lengthOfStr <= desiredLength) {
- return str;
+ if (trailing) {
+ for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
}
- desiredLength -= strlen(truncateChar);
- let ret = truncateWidthWithAnsi(str, desiredLength);
-
- return ret + truncateChar;
+ return str.slice(lead, trail + 1)
}
-function defaultOptions() {
- return {
- chars: {
- top: '─',
- 'top-mid': '┬',
- 'top-left': '┌',
- 'top-right': '┐',
- bottom: '─',
- 'bottom-mid': '┴',
- 'bottom-left': '└',
- 'bottom-right': '┘',
- left: '│',
- 'left-mid': '├',
- mid: '─',
- 'mid-mid': '┼',
- right: '│',
- 'right-mid': '┤',
- middle: '│',
- },
- truncate: '…',
- colWidths: [],
- rowHeights: [],
- colAligns: [],
- rowAligns: [],
- style: {
- 'padding-left': 1,
- 'padding-right': 1,
- head: ['red'],
- border: ['grey'],
- compact: false,
- },
- head: [],
- };
-}
-
-function mergeOptions(options, defaults) {
- options = options || {};
- defaults = defaults || defaultOptions();
- let ret = Object.assign({}, defaults, options);
- ret.chars = Object.assign({}, defaults.chars, options.chars);
- ret.style = Object.assign({}, defaults.style, options.style);
- return ret;
-}
-
-// Wrap on word boundary
-function wordWrap(maxLength, input) {
- let lines = [];
- let split = input.split(/(\s+)/g);
- let line = [];
- let lineLength = 0;
- let whitespace;
- for (let i = 0; i < split.length; i += 2) {
- let word = split[i];
- let newLength = lineLength + strlen(word);
- if (lineLength > 0 && whitespace) {
- newLength += whitespace.length;
- }
- if (newLength > maxLength) {
- if (lineLength !== 0) {
- lines.push(line.join(''));
- }
- line = [word];
- lineLength = strlen(word);
- } else {
- line.push(whitespace || '', word);
- lineLength = newLength;
- }
- whitespace = split[i + 1];
- }
- if (lineLength) {
- lines.push(line.join(''));
- }
- return lines;
+/**
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
+ * @param {string} char
+ */
+function isASCIIWhitespace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
}
-// Wrap text (ignoring word boundaries)
-function textWrap(maxLength, input) {
- let lines = [];
- let line = '';
- function pushLine(str, ws) {
- if (line.length && ws) line += ws;
- line += str;
- while (line.length > maxLength) {
- lines.push(line.slice(0, maxLength));
- line = line.slice(maxLength);
- }
- }
- let split = input.split(/(\s+)/g);
- for (let i = 0; i < split.length; i += 2) {
- pushLine(split[i], i && split[i - 1]);
- }
- if (line.length) lines.push(line);
- return lines;
-}
+/**
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ */
+function removeASCIIWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
-function multiLineWordWrap(maxLength, input, wrapOnWordBoundary = true) {
- let output = [];
- input = input.split('\n');
- const handler = wrapOnWordBoundary ? wordWrap : textWrap;
- for (let i = 0; i < input.length; i++) {
- output.push.apply(output, handler(maxLength, input[i]));
+ if (leading) {
+ for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
}
- return output;
-}
-function colorizeLines(input) {
- let state = {};
- let output = [];
- for (let i = 0; i < input.length; i++) {
- let line = rewindState(state, input[i]);
- state = readState(line);
- let temp = Object.assign({}, state);
- output.push(unwindState(temp, line));
+ if (trailing) {
+ for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
}
- return output;
-}
-
-/**
- * Credit: Matheus Sampaio https://github.com/matheussampaio
- */
-function hyperlink(url, text) {
- const OSC = '\u001B]';
- const BEL = '\u0007';
- const SEP = ';';
-
- return [OSC, '8', SEP, SEP, url || text, BEL, text, OSC, '8', SEP, SEP, BEL].join('');
+
+ return str.slice(lead, trail + 1)
}
module.exports = {
- strlen: strlen,
- repeat: repeat,
- pad: pad,
- truncate: truncate,
- mergeOptions: mergeOptions,
- wordWrap: multiLineWordWrap,
- colorizeLines: colorizeLines,
- hyperlink,
-};
+ dataURLProcessor,
+ URLSerializer,
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType
+}
/***/ }),
-/***/ 43595:
+/***/ 3041:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/*
-The MIT License (MIT)
-Original Library
- - Copyright (c) Marak Squires
+const { Blob, File: NativeFile } = __nccwpck_require__(181)
+const { types } = __nccwpck_require__(9023)
+const { kState } = __nccwpck_require__(9710)
+const { isBlobLike } = __nccwpck_require__(5523)
+const { webidl } = __nccwpck_require__(4222)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
-Additional functionality
- - Copyright (c) Sindre Sorhus (sindresorhus.com)
+class File extends Blob {
+ constructor (fileBits, fileName, options = {}) {
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
+ webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
-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:
+ fileBits = webidl.converters['sequence'](fileBits)
+ fileName = webidl.converters.USVString(fileName)
+ options = webidl.converters.FilePropertyBag(options)
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
+ // Note: Blob handles this for us
-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.
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
-*/
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
-var colors = {};
-module['exports'] = colors;
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // 2. Convert every character in t to ASCII lowercase.
+ let t = options.type
+ let d
-colors.themes = {};
+ // eslint-disable-next-line no-labels
+ substep: {
+ if (t) {
+ t = parseMIMEType(t)
-var util = __nccwpck_require__(73837);
-var ansiStyles = colors.styles = __nccwpck_require__(73104);
-var defineProps = Object.defineProperties;
-var newLineRegex = new RegExp(/[\r\n]+/g);
+ if (t === 'failure') {
+ t = ''
+ // eslint-disable-next-line no-labels
+ break substep
+ }
-colors.supportsColor = (__nccwpck_require__(10662).supportsColor);
+ t = serializeAMimeType(t).toLowerCase()
+ }
-if (typeof colors.enabled === 'undefined') {
- colors.enabled = colors.supportsColor() !== false;
-}
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ d = options.lastModified
+ }
-colors.enable = function() {
- colors.enabled = true;
-};
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
-colors.disable = function() {
- colors.enabled = false;
-};
+ super(processBlobParts(fileBits, options), { type: t })
+ this[kState] = {
+ name: n,
+ lastModified: d,
+ type: t
+ }
+ }
-colors.stripColors = colors.strip = function(str) {
- return ('' + str).replace(/\x1B\[\d+m/g, '');
-};
+ get name () {
+ webidl.brandCheck(this, File)
-// eslint-disable-next-line no-unused-vars
-var stylize = colors.stylize = function stylize(str, style) {
- if (!colors.enabled) {
- return str+'';
+ return this[kState].name
}
- var styleMap = ansiStyles[style];
+ get lastModified () {
+ webidl.brandCheck(this, File)
- // Stylize should work for non-ANSI styles, too
- if(!styleMap && style in colors){
- // Style maps like trap operate as functions on strings;
- // they don't have properties like open or close.
- return colors[style](str);
+ return this[kState].lastModified
}
- return styleMap.open + str + styleMap.close;
-};
+ get type () {
+ webidl.brandCheck(this, File)
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-var escapeStringRegexp = function(str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
+ return this[kState].type
}
- return str.replace(matchOperatorsRe, '\\$&');
-};
+}
-function build(_styles) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- // __proto__ is used because we must return a function, but there is
- // no way to create a function with a different prototype.
- builder.__proto__ = proto;
- return builder;
-}
-
-var styles = (function() {
- var ret = {};
- ansiStyles.grey = ansiStyles.gray;
- Object.keys(ansiStyles).forEach(function(key) {
- ansiStyles[key].closeRe =
- new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- ret[key] = {
- get: function() {
- return build(this._styles.concat(key));
- },
- };
- });
- return ret;
-})();
+class FileLike {
+ constructor (blobLike, fileName, options = {}) {
+ // TODO: argument idl type check
-var proto = defineProps(function colors() {}, styles);
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
-function applyStyle() {
- var args = Array.prototype.slice.call(arguments);
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
- var str = args.map(function(arg) {
- // Use weak equality check so we can colorize null/undefined in safe mode
- if (arg != null && arg.constructor === String) {
- return arg;
- } else {
- return util.inspect(arg);
- }
- }).join(' ');
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- if (!colors.enabled || !str) {
- return str;
- }
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- var newLinesPresent = str.indexOf('\n') != -1;
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // TODO
+ const t = options.type
- var nestedStyles = this._styles;
+ // 2. Convert every character in t to ASCII lowercase.
+ // TODO
- var i = nestedStyles.length;
- while (i--) {
- var code = ansiStyles[nestedStyles[i]];
- str = code.open + str.replace(code.closeRe, code.open) + code.close;
- if (newLinesPresent) {
- str = str.replace(newLineRegex, function(match) {
- return code.close + match + code.open;
- });
- }
- }
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ const d = options.lastModified ?? Date.now()
- return str;
-}
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
-colors.setTheme = function(theme) {
- if (typeof theme === 'string') {
- console.log('colors.setTheme now only accepts an object, not a string. ' +
- 'If you are trying to set a theme from a file, it is now your (the ' +
- 'caller\'s) responsibility to require the file. The old syntax ' +
- 'looked like colors.setTheme(__dirname + ' +
- '\'/../themes/generic-logging.js\'); The new syntax looks like '+
- 'colors.setTheme(require(__dirname + ' +
- '\'/../themes/generic-logging.js\'));');
- return;
- }
- for (var style in theme) {
- (function(style) {
- colors[style] = function(str) {
- if (typeof theme[style] === 'object') {
- var out = str;
- for (var i in theme[style]) {
- out = colors[theme[style][i]](out);
- }
- return out;
- }
- return colors[theme[style]](str);
- };
- })(style);
+ this[kState] = {
+ blobLike,
+ name: n,
+ type: t,
+ lastModified: d
+ }
}
-};
-
-function init() {
- var ret = {};
- Object.keys(styles).forEach(function(name) {
- ret[name] = {
- get: function() {
- return build([name]);
- },
- };
- });
- return ret;
-}
-var sequencer = function sequencer(map, str) {
- var exploded = str.split('');
- exploded = exploded.map(map);
- return exploded.join('');
-};
+ stream (...args) {
+ webidl.brandCheck(this, FileLike)
-// custom formatter methods
-colors.trap = __nccwpck_require__(31302);
-colors.zalgo = __nccwpck_require__(97743);
-
-// maps
-colors.maps = {};
-colors.maps.america = __nccwpck_require__(76936)(colors);
-colors.maps.zebra = __nccwpck_require__(12989)(colors);
-colors.maps.rainbow = __nccwpck_require__(75210)(colors);
-colors.maps.random = __nccwpck_require__(13441)(colors);
-
-for (var map in colors.maps) {
- (function(map) {
- colors[map] = function(str) {
- return sequencer(colors.maps[map], str);
- };
- })(map);
-}
+ return this[kState].blobLike.stream(...args)
+ }
-defineProps(colors, init());
+ arrayBuffer (...args) {
+ webidl.brandCheck(this, FileLike)
+ return this[kState].blobLike.arrayBuffer(...args)
+ }
-/***/ }),
+ slice (...args) {
+ webidl.brandCheck(this, FileLike)
-/***/ 31302:
-/***/ ((module) => {
+ return this[kState].blobLike.slice(...args)
+ }
-module['exports'] = function runTheTrap(text, options) {
- var result = '';
- text = text || 'Run the trap, drop the bass';
- text = text.split('');
- var trap = {
- a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
- b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
- c: ['\u00a9', '\u023b', '\u03fe'],
- d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
- e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
- '\u0a6c'],
- f: ['\u04fa'],
- g: ['\u0262'],
- h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
- i: ['\u0f0f'],
- j: ['\u0134'],
- k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
- l: ['\u0139'],
- m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
- n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
- o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
- '\u06dd', '\u0e4f'],
- p: ['\u01f7', '\u048e'],
- q: ['\u09cd'],
- r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
- s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
- t: ['\u0141', '\u0166', '\u0373'],
- u: ['\u01b1', '\u054d'],
- v: ['\u05d8'],
- w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
- x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
- y: ['\u00a5', '\u04b0', '\u04cb'],
- z: ['\u01b5', '\u0240'],
- };
- text.forEach(function(c) {
- c = c.toLowerCase();
- var chars = trap[c] || [' '];
- var rand = Math.floor(Math.random() * chars.length);
- if (typeof trap[c] !== 'undefined') {
- result += trap[c][rand];
- } else {
- result += c;
- }
- });
- return result;
-};
+ text (...args) {
+ webidl.brandCheck(this, FileLike)
+ return this[kState].blobLike.text(...args)
+ }
-/***/ }),
+ get size () {
+ webidl.brandCheck(this, FileLike)
-/***/ 97743:
-/***/ ((module) => {
+ return this[kState].blobLike.size
+ }
-// please no
-module['exports'] = function zalgo(text, options) {
- text = text || ' he is here ';
- var soul = {
- 'up': [
- '̍', '̎', '̄', '̅',
- '̿', '̑', '̆', '̐',
- '͒', '͗', '͑', '̇',
- '̈', '̊', '͂', '̓',
- '̈', '͊', '͋', '͌',
- '̃', '̂', '̌', '͐',
- '̀', '́', '̋', '̏',
- '̒', '̓', '̔', '̽',
- '̉', 'ͣ', 'ͤ', 'ͥ',
- 'ͦ', 'ͧ', 'ͨ', 'ͩ',
- 'ͪ', 'ͫ', 'ͬ', 'ͭ',
- 'ͮ', 'ͯ', '̾', '͛',
- '͆', '̚',
- ],
- 'down': [
- '̖', '̗', '̘', '̙',
- '̜', '̝', '̞', '̟',
- '̠', '̤', '̥', '̦',
- '̩', '̪', '̫', '̬',
- '̭', '̮', '̯', '̰',
- '̱', '̲', '̳', '̹',
- '̺', '̻', '̼', 'ͅ',
- '͇', '͈', '͉', '͍',
- '͎', '͓', '͔', '͕',
- '͖', '͙', '͚', '̣',
- ],
- 'mid': [
- '̕', '̛', '̀', '́',
- '͘', '̡', '̢', '̧',
- '̨', '̴', '̵', '̶',
- '͜', '͝', '͞',
- '͟', '͠', '͢', '̸',
- '̷', '͡', ' ҉',
- ],
- };
- var all = [].concat(soul.up, soul.down, soul.mid);
-
- function randomNumber(range) {
- var r = Math.floor(Math.random() * range);
- return r;
- }
-
- function isChar(character) {
- var bool = false;
- all.filter(function(i) {
- bool = (i === character);
- });
- return bool;
- }
-
-
- function heComes(text, options) {
- var result = '';
- var counts;
- var l;
- options = options || {};
- options['up'] =
- typeof options['up'] !== 'undefined' ? options['up'] : true;
- options['mid'] =
- typeof options['mid'] !== 'undefined' ? options['mid'] : true;
- options['down'] =
- typeof options['down'] !== 'undefined' ? options['down'] : true;
- options['size'] =
- typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
- text = text.split('');
- for (l in text) {
- if (isChar(l)) {
- continue;
- }
- result = result + text[l];
- counts = {'up': 0, 'down': 0, 'mid': 0};
- switch (options.size) {
- case 'mini':
- counts.up = randomNumber(8);
- counts.mid = randomNumber(2);
- counts.down = randomNumber(8);
- break;
- case 'maxi':
- counts.up = randomNumber(16) + 3;
- counts.mid = randomNumber(4) + 1;
- counts.down = randomNumber(64) + 3;
- break;
- default:
- counts.up = randomNumber(8) + 1;
- counts.mid = randomNumber(6) / 2;
- counts.down = randomNumber(8) + 1;
- break;
- }
+ get type () {
+ webidl.brandCheck(this, FileLike)
- var arr = ['up', 'mid', 'down'];
- for (var d in arr) {
- var index = arr[d];
- for (var i = 0; i <= counts[index]; i++) {
- if (options[index]) {
- result = result + soul[index][randomNumber(soul[index].length)];
- }
- }
- }
- }
- return result;
+ return this[kState].blobLike.type
}
- // don't summon him
- return heComes(text, options);
-};
+ get name () {
+ webidl.brandCheck(this, FileLike)
+ return this[kState].name
+ }
-/***/ }),
+ get lastModified () {
+ webidl.brandCheck(this, FileLike)
-/***/ 76936:
-/***/ ((module) => {
+ return this[kState].lastModified
+ }
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- if (letter === ' ') return letter;
- switch (i%3) {
- case 0: return colors.red(letter);
- case 1: return colors.white(letter);
- case 2: return colors.blue(letter);
- }
- };
-};
+ get [Symbol.toStringTag] () {
+ return 'File'
+ }
+}
+Object.defineProperties(File.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'File',
+ configurable: true
+ },
+ name: kEnumerableProperty,
+ lastModified: kEnumerableProperty
+})
-/***/ }),
+webidl.converters.Blob = webidl.interfaceConverter(Blob)
-/***/ 75210:
-/***/ ((module) => {
+webidl.converters.BlobPart = function (V, opts) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
+ }
-module['exports'] = function(colors) {
- // RoY G BiV
- var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
- return function(letter, i, exploded) {
- if (letter === ' ') {
- return letter;
- } else {
- return colors[rainbowColors[i++ % rainbowColors.length]](letter);
+ if (
+ ArrayBuffer.isView(V) ||
+ types.isAnyArrayBuffer(V)
+ ) {
+ return webidl.converters.BufferSource(V, opts)
}
- };
-};
+ }
+ return webidl.converters.USVString(V, opts)
+}
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.BlobPart
+)
-/***/ }),
+// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
+webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
+ {
+ key: 'lastModified',
+ converter: webidl.converters['long long'],
+ get defaultValue () {
+ return Date.now()
+ }
+ },
+ {
+ key: 'type',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'endings',
+ converter: (value) => {
+ value = webidl.converters.DOMString(value)
+ value = value.toLowerCase()
-/***/ 13441:
-/***/ ((module) => {
+ if (value !== 'native') {
+ value = 'transparent'
+ }
-module['exports'] = function(colors) {
- var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
- 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
- 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
- return function(letter, i, exploded) {
- return letter === ' ' ? letter :
- colors[
- available[Math.round(Math.random() * (available.length - 2))]
- ](letter);
- };
-};
+ return value
+ },
+ defaultValue: 'transparent'
+ }
+])
+/**
+ * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
+ * @param {(NodeJS.TypedArray|Blob|string)[]} parts
+ * @param {{ type: string, endings: string }} options
+ */
+function processBlobParts (parts, options) {
+ // 1. Let bytes be an empty sequence of bytes.
+ /** @type {NodeJS.TypedArray[]} */
+ const bytes = []
-/***/ }),
+ // 2. For each element in parts:
+ for (const element of parts) {
+ // 1. If element is a USVString, run the following substeps:
+ if (typeof element === 'string') {
+ // 1. Let s be element.
+ let s = element
-/***/ 12989:
-/***/ ((module) => {
+ // 2. If the endings member of options is "native", set s
+ // to the result of converting line endings to native
+ // of element.
+ if (options.endings === 'native') {
+ s = convertLineEndingsNative(s)
+ }
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- return i % 2 === 0 ? letter : colors.inverse(letter);
- };
-};
+ // 3. Append the result of UTF-8 encoding s to bytes.
+ bytes.push(new TextEncoder().encode(s))
+ } else if (
+ types.isAnyArrayBuffer(element) ||
+ types.isTypedArray(element)
+ ) {
+ // 2. If element is a BufferSource, get a copy of the
+ // bytes held by the buffer source, and append those
+ // bytes to bytes.
+ if (!element.buffer) { // ArrayBuffer
+ bytes.push(new Uint8Array(element))
+ } else {
+ bytes.push(
+ new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
+ )
+ }
+ } else if (isBlobLike(element)) {
+ // 3. If element is a Blob, append the bytes it represents
+ // to bytes.
+ bytes.push(element)
+ }
+ }
+ // 3. Return bytes.
+ return bytes
+}
-/***/ }),
+/**
+ * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
+ * @param {string} s
+ */
+function convertLineEndingsNative (s) {
+ // 1. Let native line ending be be the code point U+000A LF.
+ let nativeLineEnding = '\n'
-/***/ 73104:
-/***/ ((module) => {
+ // 2. If the underlying platform’s conventions are to
+ // represent newlines as a carriage return and line feed
+ // sequence, set native line ending to the code point
+ // U+000D CR followed by the code point U+000A LF.
+ if (process.platform === 'win32') {
+ nativeLineEnding = '\r\n'
+ }
-/*
-The MIT License (MIT)
-
-Copyright (c) Sindre Sorhus (sindresorhus.com)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-
-*/
-
-var styles = {};
-module['exports'] = styles;
-
-var codes = {
- reset: [0, 0],
-
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29],
-
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- grey: [90, 39],
-
- brightRed: [91, 39],
- brightGreen: [92, 39],
- brightYellow: [93, 39],
- brightBlue: [94, 39],
- brightMagenta: [95, 39],
- brightCyan: [96, 39],
- brightWhite: [97, 39],
-
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgGray: [100, 49],
- bgGrey: [100, 49],
-
- bgBrightRed: [101, 49],
- bgBrightGreen: [102, 49],
- bgBrightYellow: [103, 49],
- bgBrightBlue: [104, 49],
- bgBrightMagenta: [105, 49],
- bgBrightCyan: [106, 49],
- bgBrightWhite: [107, 49],
-
- // legacy styles for colors pre v1.0.0
- blackBG: [40, 49],
- redBG: [41, 49],
- greenBG: [42, 49],
- yellowBG: [43, 49],
- blueBG: [44, 49],
- magentaBG: [45, 49],
- cyanBG: [46, 49],
- whiteBG: [47, 49],
+ return s.replace(/\r?\n/g, nativeLineEnding)
+}
-};
+// If this function is moved to ./util.js, some tools (such as
+// rollup) will warn about circular dependencies. See:
+// https://github.com/nodejs/undici/issues/1629
+function isFileLike (object) {
+ return (
+ (NativeFile && object instanceof NativeFile) ||
+ object instanceof File || (
+ object &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ object[Symbol.toStringTag] === 'File'
+ )
+ )
+}
-Object.keys(codes).forEach(function(key) {
- var val = codes[key];
- var style = styles[key] = [];
- style.open = '\u001b[' + val[0] + 'm';
- style.close = '\u001b[' + val[1] + 'm';
-});
+module.exports = { File, FileLike, isFileLike }
/***/ }),
-/***/ 10223:
-/***/ ((module) => {
+/***/ 3073:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-/*
-MIT License
-Copyright (c) Sindre Sorhus (sindresorhus.com)
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
+const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523)
+const { kState } = __nccwpck_require__(9710)
+const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041)
+const { webidl } = __nccwpck_require__(4222)
+const { Blob, File: NativeFile } = __nccwpck_require__(181)
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
-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.
-*/
+// https://xhr.spec.whatwg.org/#formdata
+class FormData {
+ constructor (form) {
+ if (form !== undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix: 'FormData constructor',
+ argument: 'Argument 1',
+ types: ['undefined']
+ })
+ }
+ this[kState] = []
+ }
+ append (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
-module.exports = function(flag, argv) {
- argv = argv || process.argv;
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
- var terminatorPos = argv.indexOf('--');
- var prefix = /^-{1,2}/.test(flag) ? '' : '--';
- var pos = argv.indexOf(prefix + flag);
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
+ }
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
-};
+ // 1. Let value be value if given; otherwise blobValue.
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename)
+ : undefined
-/***/ }),
+ // 2. Let entry be the result of creating an entry with
+ // name, value, and filename if given.
+ const entry = makeEntry(name, value, filename)
-/***/ 10662:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Append entry to this’s entry list.
+ this[kState].push(entry)
+ }
-"use strict";
-/*
-The MIT License (MIT)
+ delete (name) {
+ webidl.brandCheck(this, FormData)
-Copyright (c) Sindre Sorhus (sindresorhus.com)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
+
+ name = webidl.converters.USVString(name)
-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 delete(name) method steps are to remove all entries whose name
+ // is name from this’s entry list.
+ this[kState] = this[kState].filter(entry => entry.name !== name)
+ }
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
+ get (name) {
+ webidl.brandCheck(this, FormData)
-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.
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
-*/
+ name = webidl.converters.USVString(name)
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return null.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx === -1) {
+ return null
+ }
+ // 2. Return the value of the first entry whose name is name from
+ // this’s entry list.
+ return this[kState][idx].value
+ }
-var os = __nccwpck_require__(22037);
-var hasFlag = __nccwpck_require__(10223);
+ getAll (name) {
+ webidl.brandCheck(this, FormData)
-var env = process.env;
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
-var forceColor = void 0;
-if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor = false;
-} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
- || hasFlag('color=always')) {
- forceColor = true;
-}
-if ('FORCE_COLOR' in env) {
- forceColor = env.FORCE_COLOR.length === 0
- || parseInt(env.FORCE_COLOR, 10) !== 0;
-}
+ name = webidl.converters.USVString(name)
-function translateLevel(level) {
- if (level === 0) {
- return false;
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return the empty list.
+ // 2. Return the values of all entries whose name is name, in order,
+ // from this’s entry list.
+ return this[kState]
+ .filter((entry) => entry.name === name)
+ .map((entry) => entry.value)
}
- return {
- level: level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3,
- };
-}
+ has (name) {
+ webidl.brandCheck(this, FormData)
-function supportsColor(stream) {
- if (forceColor === false) {
- return 0;
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
- if (hasFlag('color=16m') || hasFlag('color=full')
- || hasFlag('color=truecolor')) {
- return 3;
- }
+ name = webidl.converters.USVString(name)
- if (hasFlag('color=256')) {
- return 2;
+ // The has(name) method steps are to return true if there is an entry
+ // whose name is name in this’s entry list; otherwise false.
+ return this[kState].findIndex((entry) => entry.name === name) !== -1
}
- if (stream && !stream.isTTY && forceColor !== true) {
- return 0;
- }
+ set (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- var min = forceColor ? 1 : 0;
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first
- // Windows release that supports 256 colors. Windows 10 build 14931 is the
- // first release that supports 16m/TrueColor.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8
- && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
}
- return 1;
- }
-
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
- return sign in env;
- }) || env.CI_NAME === 'codeship') {
- return 1;
- }
+ // The set(name, value) and set(name, blobValue, filename) method steps
+ // are:
- return min;
- }
+ // 1. Let value be value if given; otherwise blobValue.
- if ('TEAMCITY_VERSION' in env) {
- return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
- );
- }
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? toUSVString(filename)
+ : undefined
- if ('TERM_PROGRAM' in env) {
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
+ // 2. Let entry be the result of creating an entry with name, value, and
+ // filename if given.
+ const entry = makeEntry(name, value, filename)
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Hyper':
- return 3;
- case 'Apple_Terminal':
- return 2;
- // No default
+ // 3. If there are entries in this’s entry list whose name is name, then
+ // replace the first such entry with entry and remove the others.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx !== -1) {
+ this[kState] = [
+ ...this[kState].slice(0, idx),
+ entry,
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
+ ]
+ } else {
+ // 4. Otherwise, append entry to this’s entry list.
+ this[kState].push(entry)
}
}
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
+ entries () {
+ webidl.brandCheck(this, FormData)
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key+value'
+ )
}
- if ('COLORTERM' in env) {
- return 1;
- }
+ keys () {
+ webidl.brandCheck(this, FormData)
- if (env.TERM === 'dumb') {
- return min;
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key'
+ )
}
- return min;
-}
-
-function getSupportLevel(stream) {
- var level = supportsColor(stream);
- return translateLevel(level);
-}
-
-module.exports = {
- supportsColor: getSupportLevel,
- stdout: getSupportLevel(process.stdout),
- stderr: getSupportLevel(process.stderr),
-};
+ values () {
+ webidl.brandCheck(this, FormData)
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'value'
+ )
+ }
-/***/ }),
+ /**
+ * @param {(value: string, key: string, self: FormData) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, FormData)
-/***/ 41997:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
-//
-// Remark: Requiring this file will use the "safe" colors API,
-// which will not touch String.prototype.
-//
-// var colors = require('colors/safe');
-// colors.red("foo")
-//
-//
-var colors = __nccwpck_require__(43595);
-module['exports'] = colors;
-
-
-/***/ }),
-
-/***/ 86891:
-/***/ ((module) => {
-
-module.exports = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray(x)) res.push.apply(res, x);
- else res.push(x);
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
+ )
}
- return res;
-};
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
-
-
-/***/ }),
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
+ }
+ }
+}
-/***/ 84322:
-/***/ ((__unused_webpack_module, exports) => {
+FormData.prototype[Symbol.iterator] = FormData.prototype.entries
-"use strict";
-
-exports.__esModule = true;
-function binaryOperation(operator, left, right) {
- switch (operator) {
- case '+':
- return left + right;
- case '-':
- return left - right;
- case '/':
- return left / right;
- case '%':
- return left % right;
- case '*':
- return left * right;
- case '**':
- return Math.pow(left, right);
- case '&':
- return left & right;
- case '|':
- return left | right;
- case '>>':
- return left >> right;
- case '>>>':
- return left >>> right;
- case '<<':
- return left << right;
- case '^':
- return left ^ right;
- case '==':
- return left == right;
- case '===':
- return left === right;
- case '!=':
- return left != right;
- case '!==':
- return left !== right;
- case 'in':
- return left in right;
- case 'instanceof':
- return left instanceof right;
- case '>':
- return left > right;
- case '<':
- return left < right;
- case '>=':
- return left >= right;
- case '<=':
- return left <= right;
- }
-}
-exports["default"] = binaryOperation;
+Object.defineProperties(FormData.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'FormData',
+ configurable: true
+ }
+})
+/**
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+ * @param {string} name
+ * @param {string|Blob} value
+ * @param {?string} filename
+ * @returns
+ */
+function makeEntry (name, value, filename) {
+ // 1. Set name to the result of converting name into a scalar value string.
+ // "To convert a string into a scalar value string, replace any surrogates
+ // with U+FFFD."
+ // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
+ name = Buffer.from(name).toString('utf8')
-/***/ }),
+ // 2. If value is a string, then set value to the result of converting
+ // value into a scalar value string.
+ if (typeof value === 'string') {
+ value = Buffer.from(value).toString('utf8')
+ } else {
+ // 3. Otherwise:
-/***/ 40953:
-/***/ ((module, exports, __nccwpck_require__) => {
+ // 1. If value is not a File object, then set value to a new File object,
+ // representing the same bytes, whose name attribute value is "blob"
+ if (!isFileLike(value)) {
+ value = value instanceof Blob
+ ? new File([value], 'blob', { type: value.type })
+ : new FileLike(value, 'blob', { type: value.type })
+ }
-"use strict";
+ // 2. If filename is given, then set value to a new File object,
+ // representing the same bytes, whose name attribute is filename.
+ if (filename !== undefined) {
+ /** @type {FilePropertyBag} */
+ const options = {
+ type: value.type,
+ lastModified: value.lastModified
+ }
-exports.__esModule = true;
-var parser_1 = __nccwpck_require__(85026);
-var b = __nccwpck_require__(7912);
-var binaryOperation_1 = __nccwpck_require__(84322);
-function expressionToConstant(expression, options) {
- if (options === void 0) { options = {}; }
- var constant = true;
- function toConstant(expression) {
- if (!constant)
- return;
- if (b.isArrayExpression(expression)) {
- var result_1 = [];
- for (var i = 0; constant && i < expression.elements.length; i++) {
- var element = expression.elements[i];
- if (b.isSpreadElement(element)) {
- var spread = toConstant(element.argument);
- if (!(isSpreadable(spread) && constant)) {
- constant = false;
- }
- else {
- result_1.push.apply(result_1, spread);
- }
- }
- else if (b.isExpression(element)) {
- result_1.push(toConstant(element));
- }
- else {
- constant = false;
- }
- }
- return result_1;
- }
- if (b.isBinaryExpression(expression)) {
- var left = toConstant(expression.left);
- var right = toConstant(expression.right);
- return constant && binaryOperation_1["default"](expression.operator, left, right);
- }
- if (b.isBooleanLiteral(expression)) {
- return expression.value;
- }
- if (b.isCallExpression(expression)) {
- var args = [];
- for (var i = 0; constant && i < expression.arguments.length; i++) {
- var arg = expression.arguments[i];
- if (b.isSpreadElement(arg)) {
- var spread = toConstant(arg.argument);
- if (!(isSpreadable(spread) && constant)) {
- constant = false;
- }
- else {
- args.push.apply(args, spread);
- }
- }
- else if (b.isExpression(arg)) {
- args.push(toConstant(arg));
- }
- else {
- constant = false;
- }
- }
- if (!constant)
- return;
- if (b.isMemberExpression(expression.callee)) {
- var object = toConstant(expression.callee.object);
- if (!object || !constant) {
- constant = false;
- return;
- }
- var member = expression.callee.computed
- ? toConstant(expression.callee.property)
- : b.isIdentifier(expression.callee.property)
- ? expression.callee.property.name
- : undefined;
- if (member === undefined && !expression.callee.computed) {
- constant = false;
- }
- if (!constant)
- return;
- if (canCallMethod(object, '' + member)) {
- return object[member].apply(object, args);
- }
- }
- else {
- if (!b.isExpression(expression.callee)) {
- constant = false;
- return;
- }
- var callee = toConstant(expression.callee);
- if (!constant)
- return;
- return callee.apply(null, args);
- }
- }
- if (b.isConditionalExpression(expression)) {
- var test = toConstant(expression.test);
- return test
- ? toConstant(expression.consequent)
- : toConstant(expression.alternate);
- }
- if (b.isIdentifier(expression)) {
- if (options.constants &&
- {}.hasOwnProperty.call(options.constants, expression.name)) {
- return options.constants[expression.name];
- }
- }
- if (b.isLogicalExpression(expression)) {
- var left = toConstant(expression.left);
- var right = toConstant(expression.right);
- if (constant && expression.operator === '&&') {
- return left && right;
- }
- if (constant && expression.operator === '||') {
- return left || right;
- }
- }
- if (b.isMemberExpression(expression)) {
- var object = toConstant(expression.object);
- if (!object || !constant) {
- constant = false;
- return;
- }
- var member = expression.computed
- ? toConstant(expression.property)
- : b.isIdentifier(expression.property)
- ? expression.property.name
- : undefined;
- if (member === undefined && !expression.computed) {
- constant = false;
- }
- if (!constant)
- return;
- if ({}.hasOwnProperty.call(object, '' + member) && member[0] !== '_') {
- return object[member];
- }
- }
- if (b.isNullLiteral(expression)) {
- return null;
- }
- if (b.isNumericLiteral(expression)) {
- return expression.value;
- }
- if (b.isObjectExpression(expression)) {
- var result_2 = {};
- for (var i = 0; constant && i < expression.properties.length; i++) {
- var property = expression.properties[i];
- if (b.isObjectProperty(property)) {
- if (property.shorthand) {
- constant = false;
- return;
- }
- var key = property.computed
- ? toConstant(property.key)
- : b.isIdentifier(property.key)
- ? property.key.name
- : b.isStringLiteral(property.key)
- ? property.key.value
- : undefined;
- if (!key || key[0] === '_') {
- constant = false;
- }
- if (!constant)
- return;
- if (b.isExpression(property.value)) {
- var value = toConstant(property.value);
- if (!constant)
- return;
- result_2[key] = value;
- }
- else {
- constant = false;
- }
- }
- else if (b.isObjectMethod(property)) {
- constant = false;
- }
- else if (b.isSpreadProperty(property)) {
- var argument = toConstant(property.argument);
- if (!argument)
- constant = false;
- if (!constant)
- return;
- Object.assign(result_2, argument);
- }
- }
- return result_2;
- }
- if (b.isParenthesizedExpression(expression)) {
- return toConstant(expression.expression);
- }
- if (b.isRegExpLiteral(expression)) {
- return new RegExp(expression.pattern, expression.flags);
- }
- if (b.isSequenceExpression(expression)) {
- for (var i = 0; i < expression.expressions.length - 1 && constant; i++) {
- toConstant(expression.expressions[i]);
- }
- return toConstant(expression.expressions[expression.expressions.length - 1]);
- }
- if (b.isStringLiteral(expression)) {
- return expression.value;
- }
- // TODO: TaggedTemplateExpression
- if (b.isTemplateLiteral(expression)) {
- var result_3 = '';
- for (var i = 0; i < expression.quasis.length; i++) {
- var quasi = expression.quasis[i];
- result_3 += quasi.value.cooked;
- if (i < expression.expressions.length) {
- result_3 += '' + toConstant(expression.expressions[i]);
- }
- }
- return result_3;
- }
- if (b.isUnaryExpression(expression)) {
- var argument = toConstant(expression.argument);
- if (!constant) {
- return;
- }
- switch (expression.operator) {
- case '-':
- return -argument;
- case '+':
- return +argument;
- case '!':
- return !argument;
- case '~':
- return ~argument;
- case 'typeof':
- return typeof argument;
- case 'void':
- return void argument;
- }
- }
- constant = false;
- }
- var result = toConstant(expression);
- return constant ? { constant: true, result: result } : { constant: false };
-}
-exports.expressionToConstant = expressionToConstant;
-function isSpreadable(value) {
- return (typeof value === 'string' ||
- Array.isArray(value) ||
- (typeof Set !== 'undefined' && value instanceof Set) ||
- (typeof Map !== 'undefined' && value instanceof Map));
-}
-function shallowEqual(a, b) {
- if (a === b)
- return true;
- if (a && b && typeof a === 'object' && typeof b === 'object') {
- for (var key in a) {
- if (a[key] !== b[key]) {
- return false;
- }
- }
- for (var key in b) {
- if (a[key] !== b[key]) {
- return false;
- }
- }
- return true;
- }
- return false;
-}
-function canCallMethod(object, member) {
- switch (typeof object) {
- case 'boolean':
- switch (member) {
- case 'toString':
- return true;
- default:
- return false;
- }
- case 'number':
- switch (member) {
- case 'toExponential':
- case 'toFixed':
- case 'toPrecision':
- case 'toString':
- return true;
- default:
- return false;
- }
- case 'string':
- switch (member) {
- case 'charAt':
- case 'charCodeAt':
- case 'codePointAt':
- case 'concat':
- case 'endsWith':
- case 'includes':
- case 'indexOf':
- case 'lastIndexOf':
- case 'match':
- case 'normalize':
- case 'padEnd':
- case 'padStart':
- case 'repeat':
- case 'replace':
- case 'search':
- case 'slice':
- case 'split':
- case 'startsWith':
- case 'substr':
- case 'substring':
- case 'toLowerCase':
- case 'toUpperCase':
- case 'trim':
- return true;
- default:
- return false;
- }
- default:
- if (object instanceof RegExp) {
- switch (member) {
- case 'test':
- case 'exec':
- return true;
- default:
- return false;
- }
- }
- return {}.hasOwnProperty.call(object, member) && member[0] !== '_';
- }
-}
-var EMPTY_OBJECT = {};
-var lastSrc = '';
-var lastConstants = EMPTY_OBJECT;
-var lastOptions = EMPTY_OBJECT;
-var lastResult = null;
-var lastWasConstant = false;
-function isConstant(src, constants, options) {
- if (constants === void 0) { constants = EMPTY_OBJECT; }
- if (options === void 0) { options = EMPTY_OBJECT; }
- if (lastSrc === src &&
- shallowEqual(lastConstants, constants) &&
- shallowEqual(lastOptions, options)) {
- return lastWasConstant;
- }
- lastSrc = src;
- lastConstants = constants;
- var ast;
- try {
- ast = parser_1.parseExpression(src, options);
- }
- catch (ex) {
- return (lastWasConstant = false);
- }
- var _a = expressionToConstant(ast, { constants: constants }), result = _a.result, constant = _a.constant;
- lastResult = result;
- return (lastWasConstant = constant);
-}
-exports.isConstant = isConstant;
-function toConstant(src, constants, options) {
- if (constants === void 0) { constants = EMPTY_OBJECT; }
- if (options === void 0) { options = EMPTY_OBJECT; }
- if (!isConstant(src, constants, options)) {
- throw new Error(JSON.stringify(src) + ' is not constant.');
+ value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
+ ? new File([value], filename, options)
+ : new FileLike(value, filename, options)
}
- return lastResult;
-}
-exports.toConstant = toConstant;
-exports["default"] = isConstant;
-module.exports = isConstant;
-module.exports["default"] = isConstant;
-module.exports.expressionToConstant = expressionToConstant;
-module.exports.isConstant = isConstant;
-module.exports.toConstant = toConstant;
-
+ }
-/***/ }),
+ // 4. Return an entry whose name is name and whose value is value.
+ return { name, value }
+}
-/***/ 72746:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+module.exports = { FormData }
-"use strict";
+/***/ }),
-const cp = __nccwpck_require__(32081);
-const parse = __nccwpck_require__(66855);
-const enoent = __nccwpck_require__(44101);
+/***/ 5628:
+/***/ ((module) => {
-function spawn(command, args, options) {
- // Parse the arguments
- const parsed = parse(command, args, options);
- // Spawn the child process
- const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
- // Hook into child process "exit" event to emit an error if the command
- // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
- enoent.hookChildProcess(spawned, parsed);
+// In case of breaking changes, increase the version
+// number to avoid conflicts.
+const globalOrigin = Symbol.for('undici.globalOrigin.1')
- return spawned;
+function getGlobalOrigin () {
+ return globalThis[globalOrigin]
}
-function spawnSync(command, args, options) {
- // Parse the arguments
- const parsed = parse(command, args, options);
+function setGlobalOrigin (newOrigin) {
+ if (newOrigin === undefined) {
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: undefined,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
- // Spawn the child process
- const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
+ return
+ }
- // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
- result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
+ const parsedURL = new URL(newOrigin)
- return result;
-}
+ if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ }
-module.exports = spawn;
-module.exports.spawn = spawn;
-module.exports.sync = spawnSync;
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: parsedURL,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
-module.exports._parse = parse;
-module.exports._enoent = enoent;
+module.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
+}
/***/ }),
-/***/ 44101:
-/***/ ((module) => {
-
-"use strict";
-
+/***/ 6349:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const isWin = process.platform === 'win32';
+// https://github.com/Ethan-Arrowood/undici-fetch
-function notFoundError(original, syscall) {
- return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
- code: 'ENOENT',
- errno: 'ENOENT',
- syscall: `${syscall} ${original.command}`,
- path: original.command,
- spawnargs: original.args,
- });
-}
-function hookChildProcess(cp, parsed) {
- if (!isWin) {
- return;
- }
- const originalEmit = cp.emit;
+const { kHeadersList } = __nccwpck_require__(6443)
+const { kGuard } = __nccwpck_require__(9710)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const {
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue
+} = __nccwpck_require__(5523)
+const { webidl } = __nccwpck_require__(4222)
+const assert = __nccwpck_require__(2613)
- cp.emit = function (name, arg1) {
- // If emitting "exit" event and exit code is 1, we need to check if
- // the command exists and emit an "error" instead
- // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
- if (name === 'exit') {
- const err = verifyENOENT(arg1, parsed, 'spawn');
+const kHeadersMap = Symbol('headers map')
+const kHeadersSortedMap = Symbol('headers map sorted')
- if (err) {
- return originalEmit.call(cp, 'error', err);
- }
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
+ * @param {string} potentialValue
+ */
+function headerValueNormalize (potentialValue) {
+ // To normalize a byte sequence potentialValue, remove
+ // any leading and trailing HTTP whitespace bytes from
+ // potentialValue.
- return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
- };
+ // Trimming the end with `.replace()` and a RegExp is typically subject to
+ // ReDoS. This is safer and faster.
+ let i = potentialValue.length
+ while (/[\r\n\t ]/.test(potentialValue.charAt(--i)));
+ return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, '')
}
-function verifyENOENT(status, parsed) {
- if (isWin && status === 1 && !parsed.file) {
- return notFoundError(parsed.original, 'spawn');
- }
+function fill (headers, object) {
+ // To fill a Headers object headers with a given object object, run these steps:
- return null;
-}
+ // 1. If object is a sequence, then for each header in object:
+ // Note: webidl conversion to array has already been done.
+ if (Array.isArray(object)) {
+ for (const header of object) {
+ // 1. If header does not contain exactly two items, then throw a TypeError.
+ if (header.length !== 2) {
+ throw webidl.errors.exception({
+ header: 'Headers constructor',
+ message: `expected name/value pair to be length 2, found ${header.length}.`
+ })
+ }
-function verifyENOENTSync(status, parsed) {
- if (isWin && status === 1 && !parsed.file) {
- return notFoundError(parsed.original, 'spawnSync');
+ // 2. Append (header’s first item, header’s second item) to headers.
+ headers.append(header[0], header[1])
}
+ } else if (typeof object === 'object' && object !== null) {
+ // Note: null should throw
- return null;
+ // 2. Otherwise, object is a record, then for each key → value in object,
+ // append (key, value) to headers
+ for (const [key, value] of Object.entries(object)) {
+ headers.append(key, value)
+ }
+ } else {
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+ }
}
-module.exports = {
- hookChildProcess,
- verifyENOENT,
- verifyENOENTSync,
- notFoundError,
-};
-
-
-/***/ }),
-
-/***/ 66855:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+class HeadersList {
+ /** @type {[string, string][]|null} */
+ cookies = null
-"use strict";
+ constructor (init) {
+ if (init instanceof HeadersList) {
+ this[kHeadersMap] = new Map(init[kHeadersMap])
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
+ this.cookies = init.cookies
+ } else {
+ this[kHeadersMap] = new Map(init)
+ this[kHeadersSortedMap] = null
+ }
+ }
+ // https://fetch.spec.whatwg.org/#header-list-contains
+ contains (name) {
+ // A header list list contains a header name name if list
+ // contains a header whose name is a byte-case-insensitive
+ // match for name.
+ name = name.toLowerCase()
-const path = __nccwpck_require__(71017);
-const resolveCommand = __nccwpck_require__(87274);
-const escape = __nccwpck_require__(34274);
-const readShebang = __nccwpck_require__(41252);
+ return this[kHeadersMap].has(name)
+ }
-const isWin = process.platform === 'win32';
-const isExecutableRegExp = /\.(?:com|exe)$/i;
-const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
+ clear () {
+ this[kHeadersMap].clear()
+ this[kHeadersSortedMap] = null
+ this.cookies = null
+ }
-function detectShebang(parsed) {
- parsed.file = resolveCommand(parsed);
+ // https://fetch.spec.whatwg.org/#concept-header-list-append
+ append (name, value) {
+ this[kHeadersSortedMap] = null
- const shebang = parsed.file && readShebang(parsed.file);
+ // 1. If list contains name, then set name to the first such
+ // header’s name.
+ const lowercaseName = name.toLowerCase()
+ const exists = this[kHeadersMap].get(lowercaseName)
- if (shebang) {
- parsed.args.unshift(parsed.file);
- parsed.command = shebang;
+ // 2. Append (name, value) to list.
+ if (exists) {
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
+ this[kHeadersMap].set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ })
+ } else {
+ this[kHeadersMap].set(lowercaseName, { name, value })
+ }
- return resolveCommand(parsed);
+ if (lowercaseName === 'set-cookie') {
+ this.cookies ??= []
+ this.cookies.push(value)
}
+ }
- return parsed.file;
-}
+ // https://fetch.spec.whatwg.org/#concept-header-list-set
+ set (name, value) {
+ this[kHeadersSortedMap] = null
+ const lowercaseName = name.toLowerCase()
-function parseNonShell(parsed) {
- if (!isWin) {
- return parsed;
+ if (lowercaseName === 'set-cookie') {
+ this.cookies = [value]
}
- // Detect & add support for shebangs
- const commandFile = detectShebang(parsed);
-
- // We don't need a shell if the command filename is an executable
- const needsShell = !isExecutableRegExp.test(commandFile);
+ // 1. If list contains name, then set the value of
+ // the first such header to value and remove the
+ // others.
+ // 2. Otherwise, append header (name, value) to list.
+ return this[kHeadersMap].set(lowercaseName, { name, value })
+ }
- // If a shell is required, use cmd.exe and take care of escaping everything correctly
- // Note that `forceShell` is an hidden option used only in tests
- if (parsed.options.forceShell || needsShell) {
- // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
- // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
- // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
- // we need to double escape them
- const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
+ // https://fetch.spec.whatwg.org/#concept-header-list-delete
+ delete (name) {
+ this[kHeadersSortedMap] = null
- // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
- // This is necessary otherwise it will always fail with ENOENT in those cases
- parsed.command = path.normalize(parsed.command);
+ name = name.toLowerCase()
- // Escape command & arguments
- parsed.command = escape.command(parsed.command);
- parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
+ if (name === 'set-cookie') {
+ this.cookies = null
+ }
- const shellCommand = [parsed.command].concat(parsed.args).join(' ');
+ return this[kHeadersMap].delete(name)
+ }
- parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
- parsed.command = process.env.comspec || 'cmd.exe';
- parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
+ // https://fetch.spec.whatwg.org/#concept-header-list-get
+ get (name) {
+ // 1. If list does not contain name, then return null.
+ if (!this.contains(name)) {
+ return null
}
- return parsed;
-}
+ // 2. Return the values of all headers in list whose name
+ // is a byte-case-insensitive match for name,
+ // separated from each other by 0x2C 0x20, in order.
+ return this[kHeadersMap].get(name.toLowerCase())?.value ?? null
+ }
-function parse(command, args, options) {
- // Normalize arguments, similar to nodejs
- if (args && !Array.isArray(args)) {
- options = args;
- args = null;
+ * [Symbol.iterator] () {
+ // use the lowercased name
+ for (const [name, { value }] of this[kHeadersMap]) {
+ yield [name, value]
}
+ }
- args = args ? args.slice(0) : []; // Clone array to avoid changing the original
- options = Object.assign({}, options); // Clone object to avoid changing the original
+ get entries () {
+ const headers = {}
- // Build our parsed object
- const parsed = {
- command,
- args,
- options,
- file: undefined,
- original: {
- command,
- args,
- },
- };
+ if (this[kHeadersMap].size) {
+ for (const { name, value } of this[kHeadersMap].values()) {
+ headers[name] = value
+ }
+ }
- // Delegate further parsing to shell or non-shell
- return options.shell ? parsed : parseNonShell(parsed);
+ return headers
+ }
}
-module.exports = parse;
-
+// https://fetch.spec.whatwg.org/#headers-class
+class Headers {
+ constructor (init = undefined) {
+ this[kHeadersList] = new HeadersList()
-/***/ }),
+ // The new Headers(init) constructor steps are:
-/***/ 34274:
-/***/ ((module) => {
+ // 1. Set this’s guard to "none".
+ this[kGuard] = 'none'
-"use strict";
+ // 2. If init is given, then fill this with init.
+ if (init !== undefined) {
+ init = webidl.converters.HeadersInit(init)
+ fill(this, init)
+ }
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append (name, value) {
+ webidl.brandCheck(this, Headers)
-// See http://www.robvanderwoude.com/escapechars.php
-const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
-function escapeCommand(arg) {
- // Escape meta chars
- arg = arg.replace(metaCharsRegExp, '^$1');
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
- return arg;
-}
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
-function escapeArgument(arg, doubleEscapeMetaChars) {
- // Convert to string
- arg = `${arg}`;
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value,
+ type: 'header value'
+ })
+ }
- // Algorithm below is based on https://qntm.org/cmd
+ // 3. If headers’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if headers’s guard is "request" and name is a
+ // forbidden header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
+ // TODO
+ }
- // Sequence of backslashes followed by a double quote:
- // double up all the backslashes and escape the double quote
- arg = arg.replace(/(\\*)"/g, '$1$1\\"');
+ // 6. Otherwise, if headers’s guard is "response" and name is a
+ // forbidden response-header name, return.
- // Sequence of backslashes followed by the end of the string
- // (which will become a double quote later):
- // double up all the backslashes
- arg = arg.replace(/(\\*)$/, '$1$1');
+ // 7. Append (name, value) to headers’s header list.
+ // 8. If headers’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from headers
+ return this[kHeadersList].append(name, value)
+ }
- // All other backslashes occur literally
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete (name) {
+ webidl.brandCheck(this, Headers)
- // Quote the whole thing:
- arg = `"${arg}"`;
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
- // Escape meta chars
- arg = arg.replace(metaCharsRegExp, '^$1');
+ name = webidl.converters.ByteString(name)
- // Double escape meta chars if necessary
- if (doubleEscapeMetaChars) {
- arg = arg.replace(metaCharsRegExp, '^$1');
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.delete',
+ value: name,
+ type: 'header name'
+ })
}
- return arg;
-}
-
-module.exports.command = escapeCommand;
-module.exports.argument = escapeArgument;
-
-
-/***/ }),
+ // 2. If this’s guard is "immutable", then throw a TypeError.
+ // 3. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 4. Otherwise, if this’s guard is "request-no-cors", name
+ // is not a no-CORS-safelisted request-header name, and
+ // name is not a privileged no-CORS request-header name,
+ // return.
+ // 5. Otherwise, if this’s guard is "response" and name is
+ // a forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
+ }
-/***/ 41252:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 6. If this’s header list does not contain name, then
+ // return.
+ if (!this[kHeadersList].contains(name)) {
+ return
+ }
-"use strict";
+ // 7. Delete name from this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this.
+ return this[kHeadersList].delete(name)
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get (name) {
+ webidl.brandCheck(this, Headers)
-const fs = __nccwpck_require__(57147);
-const shebangCommand = __nccwpck_require__(67032);
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
-function readShebang(command) {
- // Read the first 150 bytes from the file
- const size = 150;
- const buffer = Buffer.alloc(size);
+ name = webidl.converters.ByteString(name)
- let fd;
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.get',
+ value: name,
+ type: 'header name'
+ })
+ }
- try {
- fd = fs.openSync(command, 'r');
- fs.readSync(fd, buffer, 0, size, 0);
- fs.closeSync(fd);
- } catch (e) { /* Empty */ }
+ // 2. Return the result of getting name from this’s header
+ // list.
+ return this[kHeadersList].get(name)
+ }
- // Attempt to extract shebang (null is returned if not a shebang)
- return shebangCommand(buffer.toString());
-}
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has (name) {
+ webidl.brandCheck(this, Headers)
-module.exports = readShebang;
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
+ name = webidl.converters.ByteString(name)
-/***/ }),
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.has',
+ value: name,
+ type: 'header name'
+ })
+ }
-/***/ 87274:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Return true if this’s header list contains name;
+ // otherwise false.
+ return this[kHeadersList].contains(name)
+ }
-"use strict";
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set (name, value) {
+ webidl.brandCheck(this, Headers)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
-const path = __nccwpck_require__(71017);
-const which = __nccwpck_require__(34207);
-const getPathKey = __nccwpck_require__(20539);
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
-function resolveCommandAttempt(parsed, withoutPathExt) {
- const env = parsed.options.env || process.env;
- const cwd = process.cwd();
- const hasCustomCwd = parsed.options.cwd != null;
- // Worker threads do not have process.chdir()
- const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- // If a custom `cwd` was specified, we need to change the process cwd
- // because `which` will do stat calls but does not support a custom cwd
- if (shouldSwitchCwd) {
- try {
- process.chdir(parsed.options.cwd);
- } catch (err) {
- /* Empty */
- }
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value,
+ type: 'header value'
+ })
}
- let resolved;
-
- try {
- resolved = which.sync(parsed.command, {
- path: env[getPathKey({ env })],
- pathExt: withoutPathExt ? path.delimiter : undefined,
- });
- } catch (e) {
- /* Empty */
- } finally {
- if (shouldSwitchCwd) {
- process.chdir(cwd);
- }
+ // 3. If this’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 5. Otherwise, if this’s guard is "request-no-cors" and
+ // name/value is not a no-CORS-safelisted request-header,
+ // return.
+ // 6. Otherwise, if this’s guard is "response" and name is a
+ // forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- // If we successfully resolved, ensure that an absolute path is returned
- // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
- if (resolved) {
- resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
- }
+ // 7. Set (name, value) in this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this
+ return this[kHeadersList].set(name, value)
+ }
- return resolved;
-}
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie () {
+ webidl.brandCheck(this, Headers)
-function resolveCommand(parsed) {
- return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
-}
+ // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
+ // 2. Return the values of all headers in this’s header list whose name is
+ // a byte-case-insensitive match for `Set-Cookie`, in order.
-module.exports = resolveCommand;
+ const list = this[kHeadersList].cookies
+ if (list) {
+ return [...list]
+ }
-/***/ }),
+ return []
+ }
-/***/ 56323:
-/***/ ((module) => {
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ get [kHeadersSortedMap] () {
+ if (this[kHeadersList][kHeadersSortedMap]) {
+ return this[kHeadersList][kHeadersSortedMap]
+ }
-"use strict";
+ // 1. Let headers be an empty list of headers with the key being the name
+ // and value the value.
+ const headers = []
+ // 2. Let names be the result of convert header names to a sorted-lowercase
+ // set with all the names of the headers in list.
+ const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
+ const cookies = this[kHeadersList].cookies
-var isMergeableObject = function isMergeableObject(value) {
- return isNonNullObject(value)
- && !isSpecial(value)
-};
+ // 3. For each name of names:
+ for (const [name, value] of names) {
+ // 1. If name is `set-cookie`, then:
+ if (name === 'set-cookie') {
+ // 1. Let values be a list of all values of headers in list whose name
+ // is a byte-case-insensitive match for name, in order.
-function isNonNullObject(value) {
- return !!value && typeof value === 'object'
-}
+ // 2. For each value of values:
+ // 1. Append (name, value) to headers.
+ for (const value of cookies) {
+ headers.push([name, value])
+ }
+ } else {
+ // 2. Otherwise:
-function isSpecial(value) {
- var stringValue = Object.prototype.toString.call(value);
+ // 1. Let value be the result of getting name from list.
- return stringValue === '[object RegExp]'
- || stringValue === '[object Date]'
- || isReactElement(value)
-}
+ // 2. Assert: value is non-null.
+ assert(value !== null)
-// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
-var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
-var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
+ // 3. Append (name, value) to headers.
+ headers.push([name, value])
+ }
+ }
-function isReactElement(value) {
- return value.$$typeof === REACT_ELEMENT_TYPE
-}
+ this[kHeadersList][kHeadersSortedMap] = headers
-function emptyTarget(val) {
- return Array.isArray(val) ? [] : {}
-}
+ // 4. Return headers.
+ return headers
+ }
-function cloneUnlessOtherwiseSpecified(value, options) {
- return (options.clone !== false && options.isMergeableObject(value))
- ? deepmerge(emptyTarget(value), value, options)
- : value
-}
+ keys () {
+ webidl.brandCheck(this, Headers)
-function defaultArrayMerge(target, source, options) {
- return target.concat(source).map(function(element) {
- return cloneUnlessOtherwiseSpecified(element, options)
- })
-}
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key'
+ )
+ }
-function getMergeFunction(key, options) {
- if (!options.customMerge) {
- return deepmerge
- }
- var customMerge = options.customMerge(key);
- return typeof customMerge === 'function' ? customMerge : deepmerge
-}
+ values () {
+ webidl.brandCheck(this, Headers)
-function getEnumerableOwnPropertySymbols(target) {
- return Object.getOwnPropertySymbols
- ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
- return Object.propertyIsEnumerable.call(target, symbol)
- })
- : []
-}
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'value'
+ )
+ }
-function getKeys(target) {
- return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
-}
+ entries () {
+ webidl.brandCheck(this, Headers)
-function propertyIsOnObject(object, property) {
- try {
- return property in object
- } catch(_) {
- return false
- }
-}
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key+value'
+ )
+ }
-// Protects from prototype poisoning and unexpected merging up the prototype chain.
-function propertyIsUnsafe(target, key) {
- return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
- && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
- && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
-}
+ /**
+ * @param {(value: string, key: string, self: Headers) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, Headers)
-function mergeObject(target, source, options) {
- var destination = {};
- if (options.isMergeableObject(target)) {
- getKeys(target).forEach(function(key) {
- destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
- });
- }
- getKeys(source).forEach(function(key) {
- if (propertyIsUnsafe(target, key)) {
- return
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
- if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
- destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
- } else {
- destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
- }
- });
- return destination
-}
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
+ )
+ }
-function deepmerge(target, source, options) {
- options = options || {};
- options.arrayMerge = options.arrayMerge || defaultArrayMerge;
- options.isMergeableObject = options.isMergeableObject || isMergeableObject;
- // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
- // implementations can use it. The caller may not replace it.
- options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
+ }
+ }
- var sourceIsArray = Array.isArray(source);
- var targetIsArray = Array.isArray(target);
- var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
+ [Symbol.for('nodejs.util.inspect.custom')] () {
+ webidl.brandCheck(this, Headers)
- if (!sourceAndTargetTypesMatch) {
- return cloneUnlessOtherwiseSpecified(source, options)
- } else if (sourceIsArray) {
- return options.arrayMerge(target, source, options)
- } else {
- return mergeObject(target, source, options)
- }
+ return this[kHeadersList]
+ }
}
-deepmerge.all = function deepmergeAll(array, options) {
- if (!Array.isArray(array)) {
- throw new Error('first argument should be an array')
- }
-
- return array.reduce(function(prev, next) {
- return deepmerge(prev, next, options)
- }, {})
-};
-
-var deepmerge_1 = deepmerge;
-
-module.exports = deepmerge_1;
-
-
-/***/ }),
-
-/***/ 58932:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
-class Deprecation extends Error {
- constructor(message) {
- super(message); // Maintains proper stack trace (only available on V8)
+Headers.prototype[Symbol.iterator] = Headers.prototype.entries
- /* istanbul ignore next */
+Object.defineProperties(Headers.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ keys: kEnumerableProperty,
+ values: kEnumerableProperty,
+ entries: kEnumerableProperty,
+ forEach: kEnumerableProperty,
+ [Symbol.iterator]: { enumerable: false },
+ [Symbol.toStringTag]: {
+ value: 'Headers',
+ configurable: true
+ }
+})
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
+webidl.converters.HeadersInit = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (V[Symbol.iterator]) {
+ return webidl.converters['sequence>'](V)
}
- this.name = 'Deprecation';
+ return webidl.converters['record'](V)
}
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
}
-exports.Deprecation = Deprecation;
-
-
-/***/ }),
-
-/***/ 3194:
-/***/ ((module) => {
-
-"use strict";
-
-
module.exports = {
- 'html': '',
- 'xml': '',
- 'transitional': '',
- 'strict': '',
- 'frameset': '',
- '1.1': '',
- 'basic': '',
- 'mobile': '',
- 'plist': ''
-};
+ fill,
+ Headers,
+ HeadersList
+}
/***/ }),
-/***/ 81205:
+/***/ 2315:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var once = __nccwpck_require__(1223);
-
-var noop = function() {};
+// https://github.com/Ethan-Arrowood/undici-fetch
-var isRequest = function(stream) {
- return stream.setHeader && typeof stream.abort === 'function';
-};
-var isChildProcess = function(stream) {
- return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
-};
-var eos = function(stream, opts, callback) {
- if (typeof opts === 'function') return eos(stream, null, opts);
- if (!opts) opts = {};
-
- callback = once(callback || noop);
-
- var ws = stream._writableState;
- var rs = stream._readableState;
- var readable = opts.readable || (opts.readable !== false && stream.readable);
- var writable = opts.writable || (opts.writable !== false && stream.writable);
- var cancelled = false;
-
- var onlegacyfinish = function() {
- if (!stream.writable) onfinish();
- };
-
- var onfinish = function() {
- writable = false;
- if (!readable) callback.call(stream);
- };
-
- var onend = function() {
- readable = false;
- if (!writable) callback.call(stream);
- };
-
- var onexit = function(exitCode) {
- callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
- };
-
- var onerror = function(err) {
- callback.call(stream, err);
- };
-
- var onclose = function() {
- process.nextTick(onclosenexttick);
- };
-
- var onclosenexttick = function() {
- if (cancelled) return;
- if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
- if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
- };
-
- var onrequest = function() {
- stream.req.on('finish', onfinish);
- };
-
- if (isRequest(stream)) {
- stream.on('complete', onfinish);
- stream.on('abort', onclose);
- if (stream.req) onrequest();
- else stream.on('request', onrequest);
- } else if (writable && !ws) { // legacy streams
- stream.on('end', onlegacyfinish);
- stream.on('close', onlegacyfinish);
- }
-
- if (isChildProcess(stream)) stream.on('exit', onexit);
-
- stream.on('end', onend);
- stream.on('finish', onfinish);
- if (opts.error !== false) stream.on('error', onerror);
- stream.on('close', onclose);
-
- return function() {
- cancelled = true;
- stream.removeListener('complete', onfinish);
- stream.removeListener('abort', onclose);
- stream.removeListener('request', onrequest);
- if (stream.req) stream.req.removeListener('finish', onfinish);
- stream.removeListener('end', onlegacyfinish);
- stream.removeListener('close', onlegacyfinish);
- stream.removeListener('finish', onfinish);
- stream.removeListener('exit', onexit);
- stream.removeListener('end', onend);
- stream.removeListener('error', onerror);
- stream.removeListener('close', onclose);
- };
-};
+const {
+ Response,
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse
+} = __nccwpck_require__(8676)
+const { Headers } = __nccwpck_require__(6349)
+const { Request, makeRequest } = __nccwpck_require__(5194)
+const zlib = __nccwpck_require__(3106)
+const {
+ bytesMatch,
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ createDeferredPromise,
+ isBlobLike,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme
+} = __nccwpck_require__(5523)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
+const assert = __nccwpck_require__(2613)
+const { safelyExtractBody } = __nccwpck_require__(8923)
+const {
+ redirectStatus,
+ nullBodyStatus,
+ safeMethods,
+ requestBodyHeader,
+ subresource,
+ DOMException
+} = __nccwpck_require__(7326)
+const { kHeadersList } = __nccwpck_require__(6443)
+const EE = __nccwpck_require__(4434)
+const { Readable, pipeline } = __nccwpck_require__(2203)
+const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440)
+const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322)
+const { TransformStream } = __nccwpck_require__(3774)
+const { getGlobalDispatcher } = __nccwpck_require__(2581)
+const { webidl } = __nccwpck_require__(4222)
+const { STATUS_CODES } = __nccwpck_require__(8611)
-module.exports = eos;
+/** @type {import('buffer').resolveObjectURL} */
+let resolveObjectURL
+let ReadableStream = globalThis.ReadableStream
+class Fetch extends EE {
+ constructor (dispatcher) {
+ super()
-/***/ }),
+ this.dispatcher = dispatcher
+ this.connection = null
+ this.dump = false
+ this.state = 'ongoing'
+ // 2 terminated listeners get added per request,
+ // but only 1 gets removed. If there are 20 redirects,
+ // 21 listeners will be added.
+ // See https://github.com/nodejs/undici/issues/1711
+ // TODO (fix): Find and fix root cause for leaked listener.
+ this.setMaxListeners(21)
+ }
-/***/ 11848:
-/***/ ((module) => {
+ terminate (reason) {
+ if (this.state !== 'ongoing') {
+ return
+ }
-"use strict";
+ this.state = 'terminated'
+ this.connection?.destroy(reason)
+ this.emit('terminated', reason)
+ }
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort (error) {
+ if (this.state !== 'ongoing') {
+ return
+ }
-var has = Object.prototype.hasOwnProperty
- , prefix = '~';
+ // 1. Set controller’s state to "aborted".
+ this.state = 'aborted'
-/**
- * Constructor to create a storage for our `EE` objects.
- * An `Events` instance is a plain object whose properties are event names.
- *
- * @constructor
- * @private
- */
-function Events() {}
+ // 2. Let fallbackError be an "AbortError" DOMException.
+ // 3. Set error to fallbackError if it is not given.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
+ }
-//
-// We try to not inherit from `Object.prototype`. In some engines creating an
-// instance in this way is faster than calling `Object.create(null)` directly.
-// If `Object.create(null)` is not supported we prefix the event names with a
-// character to make sure that the built-in object properties are not
-// overridden or used as an attack vector.
-//
-if (Object.create) {
- Events.prototype = Object.create(null);
+ // 4. Let serializedError be StructuredSerialize(error).
+ // If that threw an exception, catch it, and let
+ // serializedError be StructuredSerialize(fallbackError).
- //
- // This hack is needed because the `__proto__` property is still inherited in
- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
- //
- if (!new Events().__proto__) prefix = false;
-}
+ // 5. Set controller’s serialized abort reason to serializedError.
+ this.serializedAbortReason = error
-/**
- * Representation of a single event listener.
- *
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
- * @constructor
- * @private
- */
-function EE(fn, context, once) {
- this.fn = fn;
- this.context = context;
- this.once = once || false;
+ this.connection?.destroy(error)
+ this.emit('terminated', error)
+ }
}
-/**
- * Add a listener for a given event.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} once Specify if the listener is a one-time listener.
- * @returns {EventEmitter}
- * @private
- */
-function addListener(emitter, event, fn, context, once) {
- if (typeof fn !== 'function') {
- throw new TypeError('The listener must be a function');
- }
+// https://fetch.spec.whatwg.org/#fetch-method
+async function fetch (input, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
- var listener = new EE(fn, context || emitter, once)
- , evt = prefix ? prefix + event : event;
+ // 1. Let p be a new promise.
+ const p = createDeferredPromise()
- if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
- else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
- else emitter._events[evt] = [emitter._events[evt], listener];
+ // 2. Let requestObject be the result of invoking the initial value of
+ // Request as constructor with input and init as arguments. If this throws
+ // an exception, reject p with it and return p.
+ let requestObject
- return emitter;
-}
+ try {
+ requestObject = new Request(input, init)
+ } catch (e) {
+ p.reject(e)
+ return p.promise
+ }
-/**
- * Clear event by name.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} evt The Event name.
- * @private
- */
-function clearEvent(emitter, evt) {
- if (--emitter._eventsCount === 0) emitter._events = new Events();
- else delete emitter._events[evt];
-}
+ // 3. Let request be requestObject’s request.
+ const request = requestObject[kState]
-/**
- * Minimal `EventEmitter` interface that is molded against the Node.js
- * `EventEmitter` interface.
- *
- * @constructor
- * @public
- */
-function EventEmitter() {
- this._events = new Events();
- this._eventsCount = 0;
-}
+ // 4. If requestObject’s signal’s aborted flag is set, then:
+ if (requestObject.signal.aborted) {
+ // 1. Abort the fetch() call with p, request, null, and
+ // requestObject’s signal’s abort reason.
+ abortFetch(p, request, null, requestObject.signal.reason)
-/**
- * Return an array listing the events for which the emitter has registered
- * listeners.
- *
- * @returns {Array}
- * @public
- */
-EventEmitter.prototype.eventNames = function eventNames() {
- var names = []
- , events
- , name;
+ // 2. Return p.
+ return p.promise
+ }
- if (this._eventsCount === 0) return names;
+ // 5. Let globalObject be request’s client’s global object.
+ const globalObject = request.client.globalObject
- for (name in (events = this._events)) {
- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
+ // request’s service-workers mode to "none".
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
+ request.serviceWorkers = 'none'
}
- if (Object.getOwnPropertySymbols) {
- return names.concat(Object.getOwnPropertySymbols(events));
- }
+ // 7. Let responseObject be null.
+ let responseObject = null
- return names;
-};
+ // 8. Let relevantRealm be this’s relevant Realm.
+ const relevantRealm = null
-/**
- * Return the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Array} The registered listeners.
- * @public
- */
-EventEmitter.prototype.listeners = function listeners(event) {
- var evt = prefix ? prefix + event : event
- , handlers = this._events[evt];
+ // 9. Let locallyAborted be false.
+ let locallyAborted = false
- if (!handlers) return [];
- if (handlers.fn) return [handlers.fn];
+ // 10. Let controller be null.
+ let controller = null
- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
- ee[i] = handlers[i].fn;
- }
+ // 11. Add the following abort steps to requestObject’s signal:
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ // 1. Set locallyAborted to true.
+ locallyAborted = true
- return ee;
-};
+ // 2. Assert: controller is non-null.
+ assert(controller != null)
-/**
- * Return the number of listeners listening to a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Number} The number of listeners.
- * @public
- */
-EventEmitter.prototype.listenerCount = function listenerCount(event) {
- var evt = prefix ? prefix + event : event
- , listeners = this._events[evt];
+ // 3. Abort controller with requestObject’s signal’s abort reason.
+ controller.abort(requestObject.signal.reason)
- if (!listeners) return 0;
- if (listeners.fn) return 1;
- return listeners.length;
-};
+ // 4. Abort the fetch() call with p, request, responseObject,
+ // and requestObject’s signal’s abort reason.
+ abortFetch(p, request, responseObject, requestObject.signal.reason)
+ }
+ )
-/**
- * Calls each of the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Boolean} `true` if the event had listeners, else `false`.
- * @public
- */
-EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
- var evt = prefix ? prefix + event : event;
+ // 12. Let handleFetchDone given response response be to finalize and
+ // report timing with response, globalObject, and "fetch".
+ const handleFetchDone = (response) =>
+ finalizeAndReportTiming(response, 'fetch')
+
+ // 13. Set controller to the result of calling fetch given request,
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
+ // given response being these substeps:
- if (!this._events[evt]) return false;
+ const processResponse = (response) => {
+ // 1. If locallyAborted is true, terminate these substeps.
+ if (locallyAborted) {
+ return
+ }
- var listeners = this._events[evt]
- , len = arguments.length
- , args
- , i;
+ // 2. If response’s aborted flag is set, then:
+ if (response.aborted) {
+ // 1. Let deserializedError be the result of deserialize a serialized
+ // abort reason given controller’s serialized abort reason and
+ // relevantRealm.
- if (listeners.fn) {
- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
+ // 2. Abort the fetch() call with p, request, responseObject, and
+ // deserializedError.
- switch (len) {
- case 1: return listeners.fn.call(listeners.context), true;
- case 2: return listeners.fn.call(listeners.context, a1), true;
- case 3: return listeners.fn.call(listeners.context, a1, a2), true;
- case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
- case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
- case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ return
}
- for (i = 1, args = new Array(len -1); i < len; i++) {
- args[i - 1] = arguments[i];
+ // 3. If response is a network error, then reject p with a TypeError
+ // and terminate these substeps.
+ if (response.type === 'error') {
+ p.reject(
+ Object.assign(new TypeError('fetch failed'), { cause: response.error })
+ )
+ return
}
- listeners.fn.apply(listeners.context, args);
- } else {
- var length = listeners.length
- , j;
-
- for (i = 0; i < length; i++) {
- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
-
- switch (len) {
- case 1: listeners[i].fn.call(listeners[i].context); break;
- case 2: listeners[i].fn.call(listeners[i].context, a1); break;
- case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
- case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
- default:
- if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
- args[j - 1] = arguments[j];
- }
+ // 4. Set responseObject to the result of creating a Response object,
+ // given response, "immutable", and relevantRealm.
+ responseObject = new Response()
+ responseObject[kState] = response
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- listeners[i].fn.apply(listeners[i].context, args);
- }
- }
+ // 5. Resolve p with responseObject.
+ p.resolve(responseObject)
}
- return true;
-};
-
-/**
- * Add a listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
-EventEmitter.prototype.on = function on(event, fn, context) {
- return addListener(this, event, fn, context, false);
-};
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
+ })
-/**
- * Add a one-time listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
-EventEmitter.prototype.once = function once(event, fn, context) {
- return addListener(this, event, fn, context, true);
-};
+ // 14. Return p.
+ return p.promise
+}
-/**
- * Remove the listeners of a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn Only remove the listeners that match this function.
- * @param {*} context Only remove the listeners that have this context.
- * @param {Boolean} once Only remove one-time listeners.
- * @returns {EventEmitter} `this`.
- * @public
- */
-EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
- var evt = prefix ? prefix + event : event;
+// https://fetch.spec.whatwg.org/#finalize-and-report-timing
+function finalizeAndReportTiming (response, initiatorType = 'other') {
+ // 1. If response is an aborted network error, then return.
+ if (response.type === 'error' && response.aborted) {
+ return
+ }
- if (!this._events[evt]) return this;
- if (!fn) {
- clearEvent(this, evt);
- return this;
+ // 2. If response’s URL list is null or empty, then return.
+ if (!response.urlList?.length) {
+ return
}
- var listeners = this._events[evt];
+ // 3. Let originalURL be response’s URL list[0].
+ const originalURL = response.urlList[0]
- if (listeners.fn) {
- if (
- listeners.fn === fn &&
- (!once || listeners.once) &&
- (!context || listeners.context === context)
- ) {
- clearEvent(this, evt);
- }
- } else {
- for (var i = 0, events = [], length = listeners.length; i < length; i++) {
- if (
- listeners[i].fn !== fn ||
- (once && !listeners[i].once) ||
- (context && listeners[i].context !== context)
- ) {
- events.push(listeners[i]);
- }
- }
+ // 4. Let timingInfo be response’s timing info.
+ let timingInfo = response.timingInfo
- //
- // Reset the array, or remove it completely if we have no more listeners.
- //
- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
- else clearEvent(this, evt);
+ // 5. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
+
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return
}
- return this;
-};
+ // 7. If timingInfo is null, then return.
+ if (timingInfo === null) {
+ return
+ }
-/**
- * Remove all listeners, or those of the specified event.
- *
- * @param {(String|Symbol)} [event] The event name.
- * @returns {EventEmitter} `this`.
- * @public
- */
-EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
- var evt;
+ // 8. If response’s timing allow passed flag is not set, then:
+ if (!timingInfo.timingAllowPassed) {
+ // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
+ timingInfo = createOpaqueTimingInfo({
+ startTime: timingInfo.startTime
+ })
- if (event) {
- evt = prefix ? prefix + event : event;
- if (this._events[evt]) clearEvent(this, evt);
- } else {
- this._events = new Events();
- this._eventsCount = 0;
+ // 2. Set cacheState to the empty string.
+ cacheState = ''
}
- return this;
-};
+ // 9. Set timingInfo’s end time to the coarsened shared current time
+ // given global’s relevant settings object’s cross-origin isolated
+ // capability.
+ // TODO: given global’s relevant settings object’s cross-origin isolated
+ // capability?
+ timingInfo.endTime = coarsenedSharedCurrentTime()
-//
-// Alias methods names because people roll like that.
-//
-EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
-EventEmitter.prototype.addListener = EventEmitter.prototype.on;
-
-//
-// Expose the prefix.
-//
-EventEmitter.prefixed = prefix;
-
-//
-// Allow `EventEmitter` to be imported as module namespace.
-//
-EventEmitter.EventEmitter = EventEmitter;
+ // 10. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
-//
-// Expose the module.
-//
-if (true) {
- module.exports = EventEmitter;
+ // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
+ // global, and cacheState.
+ markResourceTiming(
+ timingInfo,
+ originalURL,
+ initiatorType,
+ globalThis,
+ cacheState
+ )
}
-
-/***/ }),
-
-/***/ 43664:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-const taskManager = __nccwpck_require__(42708);
-const async_1 = __nccwpck_require__(95679);
-const stream_1 = __nccwpck_require__(94630);
-const sync_1 = __nccwpck_require__(42405);
-const settings_1 = __nccwpck_require__(10952);
-const utils = __nccwpck_require__(45444);
-async function FastGlob(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, async_1.default, options);
- const result = await Promise.all(works);
- return utils.array.flatten(result);
-}
-// https://github.com/typescript-eslint/typescript-eslint/issues/60
-// eslint-disable-next-line no-redeclare
-(function (FastGlob) {
- FastGlob.glob = FastGlob;
- FastGlob.globSync = sync;
- FastGlob.globStream = stream;
- FastGlob.async = FastGlob;
- function sync(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, sync_1.default, options);
- return utils.array.flatten(works);
- }
- FastGlob.sync = sync;
- function stream(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, stream_1.default, options);
- /**
- * The stream returned by the provider cannot work with an asynchronous iterator.
- * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
- * This affects performance (+25%). I don't see best solution right now.
- */
- return utils.stream.merge(works);
- }
- FastGlob.stream = stream;
- function generateTasks(source, options) {
- assertPatternsInput(source);
- const patterns = [].concat(source);
- const settings = new settings_1.default(options);
- return taskManager.generate(patterns, settings);
- }
- FastGlob.generateTasks = generateTasks;
- function isDynamicPattern(source, options) {
- assertPatternsInput(source);
- const settings = new settings_1.default(options);
- return utils.pattern.isDynamicPattern(source, settings);
- }
- FastGlob.isDynamicPattern = isDynamicPattern;
- function escapePath(source) {
- assertPatternsInput(source);
- return utils.path.escape(source);
- }
- FastGlob.escapePath = escapePath;
- function convertPathToPattern(source) {
- assertPatternsInput(source);
- return utils.path.convertPathToPattern(source);
- }
- FastGlob.convertPathToPattern = convertPathToPattern;
- let posix;
- (function (posix) {
- function escapePath(source) {
- assertPatternsInput(source);
- return utils.path.escapePosixPath(source);
- }
- posix.escapePath = escapePath;
- function convertPathToPattern(source) {
- assertPatternsInput(source);
- return utils.path.convertPosixPathToPattern(source);
- }
- posix.convertPathToPattern = convertPathToPattern;
- })(posix = FastGlob.posix || (FastGlob.posix = {}));
- let win32;
- (function (win32) {
- function escapePath(source) {
- assertPatternsInput(source);
- return utils.path.escapeWindowsPath(source);
- }
- win32.escapePath = escapePath;
- function convertPathToPattern(source) {
- assertPatternsInput(source);
- return utils.path.convertWindowsPathToPattern(source);
- }
- win32.convertPathToPattern = convertPathToPattern;
- })(win32 = FastGlob.win32 || (FastGlob.win32 = {}));
-})(FastGlob || (FastGlob = {}));
-function getWorks(source, _Provider, options) {
- const patterns = [].concat(source);
- const settings = new settings_1.default(options);
- const tasks = taskManager.generate(patterns, settings);
- const provider = new _Provider(settings);
- return tasks.map(provider.read, provider);
-}
-function assertPatternsInput(input) {
- const source = [].concat(input);
- const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
- if (!isValidSource) {
- throw new TypeError('Patterns must be a string (non empty) or an array of strings');
- }
+// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
+function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
+ if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
+ performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
+ }
}
-module.exports = FastGlob;
-
-
-/***/ }),
-
-/***/ 42708:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
-const utils = __nccwpck_require__(45444);
-function generate(input, settings) {
- const patterns = processPatterns(input, settings);
- const ignore = processPatterns(settings.ignore, settings);
- const positivePatterns = getPositivePatterns(patterns);
- const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
- const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings));
- const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings));
- const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
- const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
- return staticTasks.concat(dynamicTasks);
-}
-exports.generate = generate;
-function processPatterns(input, settings) {
- let patterns = input;
- /**
- * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry
- * and some problems with the micromatch package (see fast-glob issues: #365, #394).
- *
- * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown
- * in matching in the case of a large set of patterns after expansion.
- */
- if (settings.braceExpansion) {
- patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns);
- }
- /**
- * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used
- * at any nesting level.
- *
- * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change
- * the pattern in the filter before creating a regular expression. There is no need to change the patterns
- * in the application. Only on the input.
- */
- if (settings.baseNameMatch) {
- patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`);
- }
- /**
- * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion.
- */
- return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern));
-}
-/**
- * Returns tasks grouped by basic pattern directories.
- *
- * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
- * This is necessary because directory traversal starts at the base directory and goes deeper.
- */
-function convertPatternsToTasks(positive, negative, dynamic) {
- const tasks = [];
- const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive);
- const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive);
- const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
- const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
- tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
- /*
- * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
- * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
- */
- if ('.' in insideCurrentDirectoryGroup) {
- tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
- }
- else {
- tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
- }
- return tasks;
-}
-exports.convertPatternsToTasks = convertPatternsToTasks;
-function getPositivePatterns(patterns) {
- return utils.pattern.getPositivePatterns(patterns);
-}
-exports.getPositivePatterns = getPositivePatterns;
-function getNegativePatternsAsPositive(patterns, ignore) {
- const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore);
- const positive = negative.map(utils.pattern.convertToPositivePattern);
- return positive;
-}
-exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
-function groupPatternsByBaseDirectory(patterns) {
- const group = {};
- return patterns.reduce((collection, pattern) => {
- const base = utils.pattern.getBaseDirectory(pattern);
- if (base in collection) {
- collection[base].push(pattern);
- }
- else {
- collection[base] = [pattern];
- }
- return collection;
- }, group);
-}
-exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
-function convertPatternGroupsToTasks(positive, negative, dynamic) {
- return Object.keys(positive).map((base) => {
- return convertPatternGroupToTask(base, positive[base], negative, dynamic);
- });
-}
-exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
-function convertPatternGroupToTask(base, positive, negative, dynamic) {
- return {
- dynamic,
- positive,
- negative,
- base,
- patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern))
- };
-}
-exports.convertPatternGroupToTask = convertPatternGroupToTask;
+// https://fetch.spec.whatwg.org/#abort-fetch
+function abortFetch (p, request, responseObject, error) {
+ // Note: AbortSignal.reason was added in node v17.2.0
+ // which would give us an undefined error to reject with.
+ // Remove this once node v16 is no longer supported.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
+ }
+ // 1. Reject promise with error.
+ p.reject(error)
-/***/ }),
+ // 2. If request’s body is not null and is readable, then cancel request’s
+ // body with error.
+ if (request.body != null && isReadable(request.body?.stream)) {
+ request.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
+ }
-/***/ 95679:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 3. If responseObject is null, then return.
+ if (responseObject == null) {
+ return
+ }
-"use strict";
+ // 4. Let response be responseObject’s response.
+ const response = responseObject[kState]
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const async_1 = __nccwpck_require__(97747);
-const provider_1 = __nccwpck_require__(60257);
-class ProviderAsync extends provider_1.default {
- constructor() {
- super(...arguments);
- this._reader = new async_1.default(this._settings);
- }
- async read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const entries = await this.api(root, task, options);
- return entries.map((entry) => options.transform(entry));
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
- return this._reader.static(task.patterns, options);
- }
+ // 5. If response’s body is not null and is readable, then error response’s
+ // body with error.
+ if (response.body != null && isReadable(response.body?.stream)) {
+ response.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
+ }
}
-exports["default"] = ProviderAsync;
-
-
-/***/ }),
-/***/ 36983:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+// https://fetch.spec.whatwg.org/#fetching
+function fetching ({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher // undici
+}) {
+ // 1. Let taskDestination be null.
+ let taskDestination = null
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const utils = __nccwpck_require__(45444);
-const partial_1 = __nccwpck_require__(35295);
-class DeepFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- }
- getFilter(basePath, positive, negative) {
- const matcher = this._getMatcher(positive);
- const negativeRe = this._getNegativePatternsRe(negative);
- return (entry) => this._filter(basePath, entry, matcher, negativeRe);
- }
- _getMatcher(patterns) {
- return new partial_1.default(patterns, this._settings, this._micromatchOptions);
- }
- _getNegativePatternsRe(patterns) {
- const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern);
- return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
- }
- _filter(basePath, entry, matcher, negativeRe) {
- if (this._isSkippedByDeep(basePath, entry.path)) {
- return false;
- }
- if (this._isSkippedSymbolicLink(entry)) {
- return false;
- }
- const filepath = utils.path.removeLeadingDotSegment(entry.path);
- if (this._isSkippedByPositivePatterns(filepath, matcher)) {
- return false;
- }
- return this._isSkippedByNegativePatterns(filepath, negativeRe);
- }
- _isSkippedByDeep(basePath, entryPath) {
- /**
- * Avoid unnecessary depth calculations when it doesn't matter.
- */
- if (this._settings.deep === Infinity) {
- return false;
- }
- return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
- }
- _getEntryLevel(basePath, entryPath) {
- const entryPathDepth = entryPath.split('/').length;
- if (basePath === '') {
- return entryPathDepth;
- }
- const basePathDepth = basePath.split('/').length;
- return entryPathDepth - basePathDepth;
- }
- _isSkippedSymbolicLink(entry) {
- return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
- }
- _isSkippedByPositivePatterns(entryPath, matcher) {
- return !this._settings.baseNameMatch && !matcher.match(entryPath);
- }
- _isSkippedByNegativePatterns(entryPath, patternsRe) {
- return !utils.pattern.matchAny(entryPath, patternsRe);
- }
-}
-exports["default"] = DeepFilter;
+ // 2. Let crossOriginIsolatedCapability be false.
+ let crossOriginIsolatedCapability = false
+ // 3. If request’s client is non-null, then:
+ if (request.client != null) {
+ // 1. Set taskDestination to request’s client’s global object.
+ taskDestination = request.client.globalObject
-/***/ }),
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
+ // isolated capability.
+ crossOriginIsolatedCapability =
+ request.client.crossOriginIsolatedCapability
+ }
-/***/ 71343:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
+ // starting a new parallel queue.
+ // TODO
-"use strict";
+ // 5. Let timingInfo be a new fetch timing info whose start time and
+ // post-redirect start time are the coarsened shared current time given
+ // crossOriginIsolatedCapability.
+ const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currenTime
+ })
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const utils = __nccwpck_require__(45444);
-class EntryFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this.index = new Map();
- }
- getFilter(positive, negative) {
- const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions);
- const negativeRe = utils.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }));
- return (entry) => this._filter(entry, positiveRe, negativeRe);
- }
- _filter(entry, positiveRe, negativeRe) {
- const filepath = utils.path.removeLeadingDotSegment(entry.path);
- if (this._settings.unique && this._isDuplicateEntry(filepath)) {
- return false;
- }
- if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
- return false;
- }
- if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) {
- return false;
- }
- const isDirectory = entry.dirent.isDirectory();
- const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory);
- if (this._settings.unique && isMatched) {
- this._createIndexRecord(filepath);
- }
- return isMatched;
- }
- _isDuplicateEntry(filepath) {
- return this.index.has(filepath);
- }
- _createIndexRecord(filepath) {
- this.index.set(filepath, undefined);
- }
- _onlyFileFilter(entry) {
- return this._settings.onlyFiles && !entry.dirent.isFile();
- }
- _onlyDirectoryFilter(entry) {
- return this._settings.onlyDirectories && !entry.dirent.isDirectory();
- }
- _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
- if (!this._settings.absolute) {
- return false;
- }
- const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath);
- return utils.pattern.matchAny(fullpath, patternsRe);
- }
- _isMatchToPatterns(filepath, patternsRe, isDirectory) {
- // Trying to match files and directories by patterns.
- const isMatched = utils.pattern.matchAny(filepath, patternsRe);
- // A pattern with a trailling slash can be used for directory matching.
- // To apply such pattern, we need to add a tralling slash to the path.
- if (!isMatched && isDirectory) {
- return utils.pattern.matchAny(filepath + '/', patternsRe);
- }
- return isMatched;
- }
-}
-exports["default"] = EntryFilter;
+ // 6. Let fetchParams be a new fetch params whose
+ // request is request,
+ // timing info is timingInfo,
+ // process request body chunk length is processRequestBodyChunkLength,
+ // process request end-of-body is processRequestEndOfBody,
+ // process response is processResponse,
+ // process response consume body is processResponseConsumeBody,
+ // process response end-of-body is processResponseEndOfBody,
+ // task destination is taskDestination,
+ // and cross-origin isolated capability is crossOriginIsolatedCapability.
+ const fetchParams = {
+ controller: new Fetch(dispatcher),
+ request,
+ timingInfo,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseConsumeBody,
+ processResponseEndOfBody,
+ taskDestination,
+ crossOriginIsolatedCapability
+ }
+ // 7. If request’s body is a byte sequence, then set request’s body to
+ // request’s body as a body.
+ // NOTE: Since fetching is only called from fetch, body should already be
+ // extracted.
+ assert(!request.body || request.body.stream)
-/***/ }),
+ // 8. If request’s window is "client", then set request’s window to request’s
+ // client, if request’s client’s global object is a Window object; otherwise
+ // "no-window".
+ if (request.window === 'client') {
+ // TODO: What if request.client is null?
+ request.window =
+ request.client?.globalObject?.constructor?.name === 'Window'
+ ? request.client
+ : 'no-window'
+ }
-/***/ 36654:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 9. If request’s origin is "client", then set request’s origin to request’s
+ // client’s origin.
+ if (request.origin === 'client') {
+ // TODO: What if request.client is null?
+ request.origin = request.client?.origin
+ }
-"use strict";
+ // 10. If all of the following conditions are true:
+ // TODO
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const utils = __nccwpck_require__(45444);
-class ErrorFilter {
- constructor(_settings) {
- this._settings = _settings;
- }
- getFilter() {
- return (error) => this._isNonFatalError(error);
- }
- _isNonFatalError(error) {
- return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
+ // 11. If request’s policy container is "client", then:
+ if (request.policyContainer === 'client') {
+ // 1. If request’s client is non-null, then set request’s policy
+ // container to a clone of request’s client’s policy container. [HTML]
+ if (request.client != null) {
+ request.policyContainer = clonePolicyContainer(
+ request.client.policyContainer
+ )
+ } else {
+ // 2. Otherwise, set request’s policy container to a new policy
+ // container.
+ request.policyContainer = makePolicyContainer()
}
-}
-exports["default"] = ErrorFilter;
-
-
-/***/ }),
+ }
-/***/ 32576:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 12. If request’s header list does not contain `Accept`, then:
+ if (!request.headersList.contains('accept')) {
+ // 1. Let value be `*/*`.
+ const value = '*/*'
-"use strict";
+ // 2. A user agent should set value to the first matching statement, if
+ // any, switching on request’s destination:
+ // "document"
+ // "frame"
+ // "iframe"
+ // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
+ // "image"
+ // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
+ // "style"
+ // `text/css,*/*;q=0.1`
+ // TODO
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const utils = __nccwpck_require__(45444);
-class Matcher {
- constructor(_patterns, _settings, _micromatchOptions) {
- this._patterns = _patterns;
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this._storage = [];
- this._fillStorage();
- }
- _fillStorage() {
- for (const pattern of this._patterns) {
- const segments = this._getPatternSegments(pattern);
- const sections = this._splitSegmentsIntoSections(segments);
- this._storage.push({
- complete: sections.length <= 1,
- pattern,
- segments,
- sections
- });
- }
- }
- _getPatternSegments(pattern) {
- const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions);
- return parts.map((part) => {
- const dynamic = utils.pattern.isDynamicPattern(part, this._settings);
- if (!dynamic) {
- return {
- dynamic: false,
- pattern: part
- };
- }
- return {
- dynamic: true,
- pattern: part,
- patternRe: utils.pattern.makeRe(part, this._micromatchOptions)
- };
- });
- }
- _splitSegmentsIntoSections(segments) {
- return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern));
- }
-}
-exports["default"] = Matcher;
+ // 3. Append `Accept`/value to request’s header list.
+ request.headersList.append('accept', value)
+ }
+ // 13. If request’s header list does not contain `Accept-Language`, then
+ // user agents should append `Accept-Language`/an appropriate value to
+ // request’s header list.
+ if (!request.headersList.contains('accept-language')) {
+ request.headersList.append('accept-language', '*')
+ }
-/***/ }),
+ // 14. If request’s priority is null, then use request’s initiator and
+ // destination appropriately in setting request’s priority to a
+ // user-agent-defined object.
+ if (request.priority === null) {
+ // TODO
+ }
-/***/ 35295:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 15. If request is a subresource request, then:
+ if (subresource.includes(request.destination)) {
+ // TODO
+ }
-"use strict";
+ // 16. Run main fetch given fetchParams.
+ mainFetch(fetchParams)
+ .catch(err => {
+ fetchParams.controller.terminate(err)
+ })
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const matcher_1 = __nccwpck_require__(32576);
-class PartialMatcher extends matcher_1.default {
- match(filepath) {
- const parts = filepath.split('/');
- const levels = parts.length;
- const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
- for (const pattern of patterns) {
- const section = pattern.sections[0];
- /**
- * In this case, the pattern has a globstar and we must read all directories unconditionally,
- * but only if the level has reached the end of the first group.
- *
- * fixtures/{a,b}/**
- * ^ true/false ^ always true
- */
- if (!pattern.complete && levels > section.length) {
- return true;
- }
- const match = parts.every((part, index) => {
- const segment = pattern.segments[index];
- if (segment.dynamic && segment.patternRe.test(part)) {
- return true;
- }
- if (!segment.dynamic && segment.pattern === part) {
- return true;
- }
- return false;
- });
- if (match) {
- return true;
- }
- }
- return false;
- }
+ // 17. Return fetchParam's controller
+ return fetchParams.controller
}
-exports["default"] = PartialMatcher;
+// https://fetch.spec.whatwg.org/#concept-main-fetch
+async function mainFetch (fetchParams, recursive = false) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-/***/ }),
+ // 2. Let response be null.
+ let response = null
-/***/ 60257:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 3. If request’s local-URLs-only flag is set and request’s current URL is
+ // not local, then set response to a network error.
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
+ response = makeNetworkError('local URLs only')
+ }
-"use strict";
+ // 4. Run report Content Security Policy violations for request.
+ // TODO
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(71017);
-const deep_1 = __nccwpck_require__(36983);
-const entry_1 = __nccwpck_require__(71343);
-const error_1 = __nccwpck_require__(36654);
-const entry_2 = __nccwpck_require__(94029);
-class Provider {
- constructor(_settings) {
- this._settings = _settings;
- this.errorFilter = new error_1.default(this._settings);
- this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
- this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
- this.entryTransformer = new entry_2.default(this._settings);
- }
- _getRootDirectory(task) {
- return path.resolve(this._settings.cwd, task.base);
- }
- _getReaderOptions(task) {
- const basePath = task.base === '.' ? '' : task.base;
- return {
- basePath,
- pathSegmentSeparator: '/',
- concurrency: this._settings.concurrency,
- deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
- entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
- errorFilter: this.errorFilter.getFilter(),
- followSymbolicLinks: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- stats: this._settings.stats,
- throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
- transform: this.entryTransformer.getTransformer()
- };
- }
- _getMicromatchOptions() {
- return {
- dot: this._settings.dot,
- matchBase: this._settings.baseNameMatch,
- nobrace: !this._settings.braceExpansion,
- nocase: !this._settings.caseSensitiveMatch,
- noext: !this._settings.extglob,
- noglobstar: !this._settings.globstar,
- posix: true,
- strictSlashes: false
- };
- }
-}
-exports["default"] = Provider;
+ // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
+ // 6. If should request be blocked due to a bad port, should fetching request
+ // be blocked as mixed content, or should request be blocked by Content
+ // Security Policy returns blocked, then set response to a network error.
+ if (requestBadPort(request) === 'blocked') {
+ response = makeNetworkError('bad port')
+ }
+ // TODO: should fetching request be blocked as mixed content?
+ // TODO: should request be blocked by Content Security Policy?
-/***/ }),
+ // 7. If request’s referrer policy is the empty string, then set request’s
+ // referrer policy to request’s policy container’s referrer policy.
+ if (request.referrerPolicy === '') {
+ request.referrerPolicy = request.policyContainer.referrerPolicy
+ }
-/***/ 94630:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 8. If request’s referrer is not "no-referrer", then set request’s
+ // referrer to the result of invoking determine request’s referrer.
+ if (request.referrer !== 'no-referrer') {
+ request.referrer = determineRequestsReferrer(request)
+ }
-"use strict";
+ // 9. Set request’s current URL’s scheme to "https" if all of the following
+ // conditions are true:
+ // - request’s current URL’s scheme is "http"
+ // - request’s current URL’s host is a domain
+ // - Matching request’s current URL’s host per Known HSTS Host Domain Name
+ // Matching results in either a superdomain match with an asserted
+ // includeSubDomains directive or a congruent match (with or without an
+ // asserted includeSubDomains directive). [HSTS]
+ // TODO
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(12781);
-const stream_2 = __nccwpck_require__(12083);
-const provider_1 = __nccwpck_require__(60257);
-class ProviderStream extends provider_1.default {
- constructor() {
- super(...arguments);
- this._reader = new stream_2.default(this._settings);
- }
- read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const source = this.api(root, task, options);
- const destination = new stream_1.Readable({ objectMode: true, read: () => { } });
- source
- .once('error', (error) => destination.emit('error', error))
- .on('data', (entry) => destination.emit('data', options.transform(entry)))
- .once('end', () => destination.emit('end'));
- destination
- .once('close', () => source.destroy());
- return destination;
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
- return this._reader.static(task.patterns, options);
- }
-}
-exports["default"] = ProviderStream;
+ // 10. If recursive is false, then run the remaining steps in parallel.
+ // TODO
+ // 11. If response is null, then set response to the result of running
+ // the steps corresponding to the first matching statement:
+ if (response === null) {
+ response = await (async () => {
+ const currentURL = requestCurrentURL(request)
-/***/ }),
+ if (
+ // - request’s current URL’s origin is same origin with request’s origin,
+ // and request’s response tainting is "basic"
+ (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
+ // request’s current URL’s scheme is "data"
+ (currentURL.protocol === 'data:') ||
+ // - request’s mode is "navigate" or "websocket"
+ (request.mode === 'navigate' || request.mode === 'websocket')
+ ) {
+ // 1. Set request’s response tainting to "basic".
+ request.responseTainting = 'basic'
-/***/ 42405:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
-"use strict";
+ // request’s mode is "same-origin"
+ if (request.mode === 'same-origin') {
+ // 1. Return a network error.
+ return makeNetworkError('request mode cannot be "same-origin"')
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const sync_1 = __nccwpck_require__(76234);
-const provider_1 = __nccwpck_require__(60257);
-class ProviderSync extends provider_1.default {
- constructor() {
- super(...arguments);
- this._reader = new sync_1.default(this._settings);
- }
- read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const entries = this.api(root, task, options);
- return entries.map(options.transform);
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
+ // request’s mode is "no-cors"
+ if (request.mode === 'no-cors') {
+ // 1. If request’s redirect mode is not "follow", then return a network
+ // error.
+ if (request.redirect !== 'follow') {
+ return makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" request'
+ )
}
- return this._reader.static(task.patterns, options);
- }
-}
-exports["default"] = ProviderSync;
-
-/***/ }),
-
-/***/ 94029:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2. Set request’s response tainting to "opaque".
+ request.responseTainting = 'opaque'
-"use strict";
+ // 3. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const utils = __nccwpck_require__(45444);
-class EntryTransformer {
- constructor(_settings) {
- this._settings = _settings;
- }
- getTransformer() {
- return (entry) => this._transform(entry);
- }
- _transform(entry) {
- let filepath = entry.path;
- if (this._settings.absolute) {
- filepath = utils.path.makeAbsolute(this._settings.cwd, filepath);
- filepath = utils.path.unixify(filepath);
- }
- if (this._settings.markDirectories && entry.dirent.isDirectory()) {
- filepath += '/';
- }
- if (!this._settings.objectMode) {
- return filepath;
- }
- return Object.assign(Object.assign({}, entry), { path: filepath });
- }
-}
-exports["default"] = EntryTransformer;
+ // request’s current URL’s scheme is not an HTTP(S) scheme
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ // Return a network error.
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ }
+ // - request’s use-CORS-preflight flag is set
+ // - request’s unsafe-request flag is set and either request’s method is
+ // not a CORS-safelisted method or CORS-unsafe request-header names with
+ // request’s header list is not empty
+ // 1. Set request’s response tainting to "cors".
+ // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
+ // given fetchParams and true.
+ // 3. If corsWithPreflightResponse is a network error, then clear cache
+ // entries using request.
+ // 4. Return corsWithPreflightResponse.
+ // TODO
-/***/ }),
+ // Otherwise
+ // 1. Set request’s response tainting to "cors".
+ request.responseTainting = 'cors'
-/***/ 97747:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2. Return the result of running HTTP fetch given fetchParams.
+ return await httpFetch(fetchParams)
+ })()
+ }
-"use strict";
+ // 12. If recursive is true, then return response.
+ if (recursive) {
+ return response
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fsWalk = __nccwpck_require__(26026);
-const reader_1 = __nccwpck_require__(65582);
-const stream_1 = __nccwpck_require__(12083);
-class ReaderAsync extends reader_1.default {
- constructor() {
- super(...arguments);
- this._walkAsync = fsWalk.walk;
- this._readerStream = new stream_1.default(this._settings);
- }
- dynamic(root, options) {
- return new Promise((resolve, reject) => {
- this._walkAsync(root, options, (error, entries) => {
- if (error === null) {
- resolve(entries);
- }
- else {
- reject(error);
- }
- });
- });
- }
- async static(patterns, options) {
- const entries = [];
- const stream = this._readerStream.static(patterns, options);
- // After #235, replace it with an asynchronous iterator.
- return new Promise((resolve, reject) => {
- stream.once('error', reject);
- stream.on('data', (entry) => entries.push(entry));
- stream.once('end', () => resolve(entries));
- });
+ // 13. If response is not a network error and response is not a filtered
+ // response, then:
+ if (response.status !== 0 && !response.internalResponse) {
+ // If request’s response tainting is "cors", then:
+ if (request.responseTainting === 'cors') {
+ // 1. Let headerNames be the result of extracting header list values
+ // given `Access-Control-Expose-Headers` and response’s header list.
+ // TODO
+ // 2. If request’s credentials mode is not "include" and headerNames
+ // contains `*`, then set response’s CORS-exposed header-name list to
+ // all unique header names in response’s header list.
+ // TODO
+ // 3. Otherwise, if headerNames is not null or failure, then set
+ // response’s CORS-exposed header-name list to headerNames.
+ // TODO
}
-}
-exports["default"] = ReaderAsync;
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (request.responseTainting === 'basic') {
+ response = filterResponse(response, 'basic')
+ } else if (request.responseTainting === 'cors') {
+ response = filterResponse(response, 'cors')
+ } else if (request.responseTainting === 'opaque') {
+ response = filterResponse(response, 'opaque')
+ } else {
+ assert(false)
+ }
+ }
-/***/ }),
+ // 14. Let internalResponse be response, if response is a network error,
+ // and response’s internal response otherwise.
+ let internalResponse =
+ response.status === 0 ? response : response.internalResponse
-/***/ 65582:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 15. If internalResponse’s URL list is empty, then set it to a clone of
+ // request’s URL list.
+ if (internalResponse.urlList.length === 0) {
+ internalResponse.urlList.push(...request.urlList)
+ }
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(71017);
-const fsStat = __nccwpck_require__(70109);
-const utils = __nccwpck_require__(45444);
-class Reader {
- constructor(_settings) {
- this._settings = _settings;
- this._fsStatSettings = new fsStat.Settings({
- followSymbolicLink: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
- });
- }
- _getFullEntryPath(filepath) {
- return path.resolve(this._settings.cwd, filepath);
- }
- _makeEntry(stats, pattern) {
- const entry = {
- name: pattern,
- path: pattern,
- dirent: utils.fs.createDirentFromStats(pattern, stats)
- };
- if (this._settings.stats) {
- entry.stats = stats;
- }
- return entry;
- }
- _isFatalError(error) {
- return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
- }
-}
-exports["default"] = Reader;
+ // 16. If request’s timing allow failed flag is unset, then set
+ // internalResponse’s timing allow passed flag.
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true
+ }
+ // 17. If response is not a network error and any of the following returns
+ // blocked
+ // - should internalResponse to request be blocked as mixed content
+ // - should internalResponse to request be blocked by Content Security Policy
+ // - should internalResponse to request be blocked due to its MIME type
+ // - should internalResponse to request be blocked due to nosniff
+ // TODO
-/***/ }),
+ // 18. If response’s type is "opaque", internalResponse’s status is 206,
+ // internalResponse’s range-requested flag is set, and request’s header
+ // list does not contain `Range`, then set response and internalResponse
+ // to a network error.
+ if (
+ response.type === 'opaque' &&
+ internalResponse.status === 206 &&
+ internalResponse.rangeRequested &&
+ !request.headers.contains('range')
+ ) {
+ response = internalResponse = makeNetworkError()
+ }
-/***/ 12083:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 19. If response is not a network error and either request’s method is
+ // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
+ // set internalResponse’s body to null and disregard any enqueuing toward
+ // it (if any).
+ if (
+ response.status !== 0 &&
+ (request.method === 'HEAD' ||
+ request.method === 'CONNECT' ||
+ nullBodyStatus.includes(internalResponse.status))
+ ) {
+ internalResponse.body = null
+ fetchParams.controller.dump = true
+ }
-"use strict";
+ // 20. If request’s integrity metadata is not the empty string, then:
+ if (request.integrity) {
+ // 1. Let processBodyError be this step: run fetch finale given fetchParams
+ // and a network error.
+ const processBodyError = (reason) =>
+ fetchFinale(fetchParams, makeNetworkError(reason))
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(12781);
-const fsStat = __nccwpck_require__(70109);
-const fsWalk = __nccwpck_require__(26026);
-const reader_1 = __nccwpck_require__(65582);
-class ReaderStream extends reader_1.default {
- constructor() {
- super(...arguments);
- this._walkStream = fsWalk.walkStream;
- this._stat = fsStat.stat;
- }
- dynamic(root, options) {
- return this._walkStream(root, options);
- }
- static(patterns, options) {
- const filepaths = patterns.map(this._getFullEntryPath, this);
- const stream = new stream_1.PassThrough({ objectMode: true });
- stream._write = (index, _enc, done) => {
- return this._getEntry(filepaths[index], patterns[index], options)
- .then((entry) => {
- if (entry !== null && options.entryFilter(entry)) {
- stream.push(entry);
- }
- if (index === filepaths.length - 1) {
- stream.end();
- }
- done();
- })
- .catch(done);
- };
- for (let i = 0; i < filepaths.length; i++) {
- stream.write(i);
- }
- return stream;
- }
- _getEntry(filepath, pattern, options) {
- return this._getStat(filepath)
- .then((stats) => this._makeEntry(stats, pattern))
- .catch((error) => {
- if (options.errorFilter(error)) {
- return null;
- }
- throw error;
- });
- }
- _getStat(filepath) {
- return new Promise((resolve, reject) => {
- this._stat(filepath, this._fsStatSettings, (error, stats) => {
- return error === null ? resolve(stats) : reject(error);
- });
- });
+ // 2. If request’s response tainting is "opaque", or response’s body is null,
+ // then run processBodyError and abort these steps.
+ if (request.responseTainting === 'opaque' || response.body == null) {
+ processBodyError(response.error)
+ return
}
-}
-exports["default"] = ReaderStream;
+ // 3. Let processBody given bytes be these steps:
+ const processBody = (bytes) => {
+ // 1. If bytes do not match request’s integrity metadata,
+ // then run processBodyError and abort these steps. [SRI]
+ if (!bytesMatch(bytes, request.integrity)) {
+ processBodyError('integrity mismatch')
+ return
+ }
-/***/ }),
-
-/***/ 76234:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+ // 2. Set response’s body to bytes as a body.
+ response.body = safelyExtractBody(bytes)[0]
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const fsStat = __nccwpck_require__(70109);
-const fsWalk = __nccwpck_require__(26026);
-const reader_1 = __nccwpck_require__(65582);
-class ReaderSync extends reader_1.default {
- constructor() {
- super(...arguments);
- this._walkSync = fsWalk.walkSync;
- this._statSync = fsStat.statSync;
- }
- dynamic(root, options) {
- return this._walkSync(root, options);
- }
- static(patterns, options) {
- const entries = [];
- for (const pattern of patterns) {
- const filepath = this._getFullEntryPath(pattern);
- const entry = this._getEntry(filepath, pattern, options);
- if (entry === null || !options.entryFilter(entry)) {
- continue;
- }
- entries.push(entry);
- }
- return entries;
- }
- _getEntry(filepath, pattern, options) {
- try {
- const stats = this._getStat(filepath);
- return this._makeEntry(stats, pattern);
- }
- catch (error) {
- if (options.errorFilter(error)) {
- return null;
- }
- throw error;
- }
- }
- _getStat(filepath) {
- return this._statSync(filepath, this._fsStatSettings);
+ // 3. Run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
-}
-exports["default"] = ReaderSync;
-
-
-/***/ }),
-
-/***/ 10952:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(57147);
-const os = __nccwpck_require__(22037);
-/**
- * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
- * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
- */
-const CPU_COUNT = Math.max(os.cpus().length, 1);
-exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
- lstat: fs.lstat,
- lstatSync: fs.lstatSync,
- stat: fs.stat,
- statSync: fs.statSync,
- readdir: fs.readdir,
- readdirSync: fs.readdirSync
-};
-class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.absolute = this._getValue(this._options.absolute, false);
- this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
- this.braceExpansion = this._getValue(this._options.braceExpansion, true);
- this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
- this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
- this.cwd = this._getValue(this._options.cwd, process.cwd());
- this.deep = this._getValue(this._options.deep, Infinity);
- this.dot = this._getValue(this._options.dot, false);
- this.extglob = this._getValue(this._options.extglob, true);
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
- this.fs = this._getFileSystemMethods(this._options.fs);
- this.globstar = this._getValue(this._options.globstar, true);
- this.ignore = this._getValue(this._options.ignore, []);
- this.markDirectories = this._getValue(this._options.markDirectories, false);
- this.objectMode = this._getValue(this._options.objectMode, false);
- this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
- this.onlyFiles = this._getValue(this._options.onlyFiles, true);
- this.stats = this._getValue(this._options.stats, false);
- this.suppressErrors = this._getValue(this._options.suppressErrors, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
- this.unique = this._getValue(this._options.unique, true);
- if (this.onlyDirectories) {
- this.onlyFiles = false;
- }
- if (this.stats) {
- this.objectMode = true;
- }
- // Remove the cast to the array in the next major (#404).
- this.ignore = [].concat(this.ignore);
- }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
- _getFileSystemMethods(methods = {}) {
- return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
- }
+ // 4. Fully read response’s body given processBody and processBodyError.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ } else {
+ // 21. Otherwise, run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
+ }
}
-exports["default"] = Settings;
+// https://fetch.spec.whatwg.org/#concept-scheme-fetch
+// given a fetch params fetchParams
+async function schemeFetch (fetchParams) {
+ // Note: since the connection is destroyed on redirect, which sets fetchParams to a
+ // cancelled state, we do not want this condition to trigger *unless* there have been
+ // no redirects. See https://github.com/nodejs/undici/issues/1776
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
-/***/ }),
+ // 2. Let request be fetchParams’s request.
+ const { request } = fetchParams
-/***/ 85325:
-/***/ ((__unused_webpack_module, exports) => {
+ const { protocol: scheme } = requestCurrentURL(request)
-"use strict";
+ // 3. Switch on request’s current URL’s scheme and run the associated steps:
+ switch (scheme) {
+ case 'about:': {
+ // If request’s current URL’s path is the string "blank", then return a new response
+ // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
+ // and body is the empty byte sequence as a body.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.splitWhen = exports.flatten = void 0;
-function flatten(items) {
- return items.reduce((collection, item) => [].concat(collection, item), []);
-}
-exports.flatten = flatten;
-function splitWhen(items, predicate) {
- const result = [[]];
- let groupIndex = 0;
- for (const item of items) {
- if (predicate(item)) {
- groupIndex++;
- result[groupIndex] = [];
- }
- else {
- result[groupIndex].push(item);
- }
+ // Otherwise, return a network error.
+ return makeNetworkError('about scheme is not supported')
}
- return result;
-}
-exports.splitWhen = splitWhen;
-
-
-/***/ }),
-
-/***/ 41230:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isEnoentCodeError = void 0;
-function isEnoentCodeError(error) {
- return error.code === 'ENOENT';
-}
-exports.isEnoentCodeError = isEnoentCodeError;
-
-
-/***/ }),
-
-/***/ 17543:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
+ case 'blob:': {
+ if (!resolveObjectURL) {
+ resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL)
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createDirentFromStats = void 0;
-class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
- }
-}
-function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
-}
-exports.createDirentFromStats = createDirentFromStats;
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
+ const blobURLEntry = requestCurrentURL(request)
+ // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
+ // Buffer.resolveObjectURL does not ignore URL queries.
+ if (blobURLEntry.search.length !== 0) {
+ return makeNetworkError('NetworkError when attempting to fetch resource.')
+ }
-/***/ }),
+ const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
-/***/ 45444:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
+ // object is not a Blob object, then return a network error.
+ if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
+ return makeNetworkError('invalid method')
+ }
-"use strict";
+ // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
+ const bodyWithType = safelyExtractBody(blobURLEntryObject)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
-const array = __nccwpck_require__(85325);
-exports.array = array;
-const errno = __nccwpck_require__(41230);
-exports.errno = errno;
-const fs = __nccwpck_require__(17543);
-exports.fs = fs;
-const path = __nccwpck_require__(63873);
-exports.path = path;
-const pattern = __nccwpck_require__(81221);
-exports.pattern = pattern;
-const stream = __nccwpck_require__(18382);
-exports.stream = stream;
-const string = __nccwpck_require__(52203);
-exports.string = string;
+ // 4. Let body be bodyWithType’s body.
+ const body = bodyWithType[0]
+ // 5. Let length be body’s length, serialized and isomorphic encoded.
+ const length = isomorphicEncode(`${body.length}`)
-/***/ }),
+ // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
+ const type = bodyWithType[1] ?? ''
-/***/ 63873:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 7. Return a new response whose status message is `OK`, header list is
+ // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
+ const response = makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-length', { name: 'Content-Length', value: length }],
+ ['content-type', { name: 'Content-Type', value: type }]
+ ]
+ })
-"use strict";
+ response.body = body
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0;
-const os = __nccwpck_require__(22037);
-const path = __nccwpck_require__(71017);
-const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
-const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
-/**
- * All non-escaped special characters.
- * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
- * Windows: (){}, !+@ before (, ! at the beginning.
- */
-const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
-const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g;
-/**
- * The device path (\\.\ or \\?\).
- * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
- */
-const DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
-/**
- * All backslashes except those escaping special characters.
- * Windows: !()+@{}
- * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
- */
-const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g;
-/**
- * Designed to work only with simple paths: `dir\\file`.
- */
-function unixify(filepath) {
- return filepath.replace(/\\/g, '/');
-}
-exports.unixify = unixify;
-function makeAbsolute(cwd, filepath) {
- return path.resolve(cwd, filepath);
-}
-exports.makeAbsolute = makeAbsolute;
-function removeLeadingDotSegment(entry) {
- // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
- if (entry.charAt(0) === '.') {
- const secondCharactery = entry.charAt(1);
- if (secondCharactery === '/' || secondCharactery === '\\') {
- return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
- }
+ return response
}
- return entry;
-}
-exports.removeLeadingDotSegment = removeLeadingDotSegment;
-exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
-function escapeWindowsPath(pattern) {
- return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
-}
-exports.escapeWindowsPath = escapeWindowsPath;
-function escapePosixPath(pattern) {
- return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
-}
-exports.escapePosixPath = escapePosixPath;
-exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
-function convertWindowsPathToPattern(filepath) {
- return escapeWindowsPath(filepath)
- .replace(DOS_DEVICE_PATH_RE, '//$1')
- .replace(WINDOWS_BACKSLASHES_RE, '/');
-}
-exports.convertWindowsPathToPattern = convertWindowsPathToPattern;
-function convertPosixPathToPattern(filepath) {
- return escapePosixPath(filepath);
-}
-exports.convertPosixPathToPattern = convertPosixPathToPattern;
-
-
-/***/ }),
+ case 'data:': {
+ // 1. Let dataURLStruct be the result of running the
+ // data: URL processor on request’s current URL.
+ const currentURL = requestCurrentURL(request)
+ const dataURLStruct = dataURLProcessor(currentURL)
-/***/ 81221:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // 2. If dataURLStruct is failure, then return a
+ // network error.
+ if (dataURLStruct === 'failure') {
+ return makeNetworkError('failed to fetch the data URL')
+ }
-"use strict";
+ // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType)
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
-const path = __nccwpck_require__(71017);
-const globParent = __nccwpck_require__(54655);
-const micromatch = __nccwpck_require__(76228);
-const GLOBSTAR = '**';
-const ESCAPE_SYMBOL = '\\';
-const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
-const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
-const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
-const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
-const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
-/**
- * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
- * The latter is due to the presence of the device path at the beginning of the UNC path.
- */
-const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g;
-function isStaticPattern(pattern, options = {}) {
- return !isDynamicPattern(pattern, options);
-}
-exports.isStaticPattern = isStaticPattern;
-function isDynamicPattern(pattern, options = {}) {
- /**
- * A special case with an empty string is necessary for matching patterns that start with a forward slash.
- * An empty string cannot be a dynamic pattern.
- * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
- */
- if (pattern === '') {
- return false;
- }
- /**
- * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
- * filepath directly (without read directory).
- */
- if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
- return true;
- }
- if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
- return true;
- }
- if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
- return true;
- }
- if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
- return true;
- }
- return false;
-}
-exports.isDynamicPattern = isDynamicPattern;
-function hasBraceExpansion(pattern) {
- const openingBraceIndex = pattern.indexOf('{');
- if (openingBraceIndex === -1) {
- return false;
+ // 4. Return a response whose status message is `OK`,
+ // header list is « (`Content-Type`, mimeType) »,
+ // and body is dataURLStruct’s body as a body.
+ return makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-type', { name: 'Content-Type', value: mimeType }]
+ ],
+ body: safelyExtractBody(dataURLStruct.body)[0]
+ })
}
- const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
- if (closingBraceIndex === -1) {
- return false;
+ case 'file:': {
+ // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
+ // When in doubt, return a network error.
+ return makeNetworkError('not implemented... yet...')
}
- const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
- return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
-}
-function convertToPositivePattern(pattern) {
- return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
-}
-exports.convertToPositivePattern = convertToPositivePattern;
-function convertToNegativePattern(pattern) {
- return '!' + pattern;
-}
-exports.convertToNegativePattern = convertToNegativePattern;
-function isNegativePattern(pattern) {
- return pattern.startsWith('!') && pattern[1] !== '(';
-}
-exports.isNegativePattern = isNegativePattern;
-function isPositivePattern(pattern) {
- return !isNegativePattern(pattern);
-}
-exports.isPositivePattern = isPositivePattern;
-function getNegativePatterns(patterns) {
- return patterns.filter(isNegativePattern);
-}
-exports.getNegativePatterns = getNegativePatterns;
-function getPositivePatterns(patterns) {
- return patterns.filter(isPositivePattern);
-}
-exports.getPositivePatterns = getPositivePatterns;
-/**
- * Returns patterns that can be applied inside the current directory.
- *
- * @example
- * // ['./*', '*', 'a/*']
- * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
- */
-function getPatternsInsideCurrentDirectory(patterns) {
- return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
-}
-exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
-/**
- * Returns patterns to be expanded relative to (outside) the current directory.
- *
- * @example
- * // ['../*', './../*']
- * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
- */
-function getPatternsOutsideCurrentDirectory(patterns) {
- return patterns.filter(isPatternRelatedToParentDirectory);
-}
-exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
-function isPatternRelatedToParentDirectory(pattern) {
- return pattern.startsWith('..') || pattern.startsWith('./..');
-}
-exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
-function getBaseDirectory(pattern) {
- return globParent(pattern, { flipBackslashes: false });
-}
-exports.getBaseDirectory = getBaseDirectory;
-function hasGlobStar(pattern) {
- return pattern.includes(GLOBSTAR);
-}
-exports.hasGlobStar = hasGlobStar;
-function endsWithSlashGlobStar(pattern) {
- return pattern.endsWith('/' + GLOBSTAR);
-}
-exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
-function isAffectDepthOfReadingPattern(pattern) {
- const basename = path.basename(pattern);
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
-}
-exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
-function expandPatternsWithBraceExpansion(patterns) {
- return patterns.reduce((collection, pattern) => {
- return collection.concat(expandBraceExpansion(pattern));
- }, []);
-}
-exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
-function expandBraceExpansion(pattern) {
- const patterns = micromatch.braces(pattern, { expand: true, nodupes: true });
- /**
- * Sort the patterns by length so that the same depth patterns are processed side by side.
- * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
- */
- patterns.sort((a, b) => a.length - b.length);
- /**
- * Micromatch can return an empty string in the case of patterns like `{a,}`.
- */
- return patterns.filter((pattern) => pattern !== '');
-}
-exports.expandBraceExpansion = expandBraceExpansion;
-function getPatternParts(pattern, options) {
- let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
- /**
- * The scan method returns an empty array in some cases.
- * See micromatch/picomatch#58 for more details.
- */
- if (parts.length === 0) {
- parts = [pattern];
+ case 'http:':
+ case 'https:': {
+ // Return the result of running HTTP fetch given fetchParams.
+
+ return await httpFetch(fetchParams)
+ .catch((err) => makeNetworkError(err))
}
- /**
- * The scan method does not return an empty part for the pattern with a forward slash.
- * This is another part of micromatch/picomatch#58.
- */
- if (parts[0].startsWith('/')) {
- parts[0] = parts[0].slice(1);
- parts.unshift('');
+ default: {
+ return makeNetworkError('unknown scheme')
}
- return parts;
-}
-exports.getPatternParts = getPatternParts;
-function makeRe(pattern, options) {
- return micromatch.makeRe(pattern, options);
-}
-exports.makeRe = makeRe;
-function convertPatternsToRe(patterns, options) {
- return patterns.map((pattern) => makeRe(pattern, options));
-}
-exports.convertPatternsToRe = convertPatternsToRe;
-function matchAny(entry, patternsRe) {
- return patternsRe.some((patternRe) => patternRe.test(entry));
-}
-exports.matchAny = matchAny;
-/**
- * This package only works with forward slashes as a path separator.
- * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
- */
-function removeDuplicateSlashes(pattern) {
- return pattern.replace(DOUBLE_SLASH_RE, '/');
+ }
}
-exports.removeDuplicateSlashes = removeDuplicateSlashes;
-
-
-/***/ }),
-/***/ 18382:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+// https://fetch.spec.whatwg.org/#finalize-response
+function finalizeResponse (fetchParams, response) {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.merge = void 0;
-const merge2 = __nccwpck_require__(82578);
-function merge(streams) {
- const mergedStream = merge2(streams);
- streams.forEach((stream) => {
- stream.once('error', (error) => mergedStream.emit('error', error));
- });
- mergedStream.once('close', () => propagateCloseEventToSources(streams));
- mergedStream.once('end', () => propagateCloseEventToSources(streams));
- return mergedStream;
-}
-exports.merge = merge;
-function propagateCloseEventToSources(streams) {
- streams.forEach((stream) => stream.emit('close'));
+ // 2, If fetchParams’s process response done is not null, then queue a fetch
+ // task to run fetchParams’s process response done given response, with
+ // fetchParams’s task destination.
+ if (fetchParams.processResponseDone != null) {
+ queueMicrotask(() => fetchParams.processResponseDone(response))
+ }
}
+// https://fetch.spec.whatwg.org/#fetch-finale
+async function fetchFinale (fetchParams, response) {
+ // 1. If response is a network error, then:
+ if (response.type === 'error') {
+ // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
+ response.urlList = [fetchParams.request.urlList[0]]
-/***/ }),
-
-/***/ 52203:
-/***/ ((__unused_webpack_module, exports) => {
+ // 2. Set response’s timing info to the result of creating an opaque timing
+ // info for fetchParams’s timing info.
+ response.timingInfo = createOpaqueTimingInfo({
+ startTime: fetchParams.timingInfo.startTime
+ })
+ }
-"use strict";
+ // 2. Let processResponseEndOfBody be the following steps:
+ const processResponseEndOfBody = () => {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isEmpty = exports.isString = void 0;
-function isString(input) {
- return typeof input === 'string';
-}
-exports.isString = isString;
-function isEmpty(input) {
- return input === '';
-}
-exports.isEmpty = isEmpty;
+ // If fetchParams’s process response end-of-body is not null,
+ // then queue a fetch task to run fetchParams’s process response
+ // end-of-body given response with fetchParams’s task destination.
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
+ }
+ }
+ // 3. If fetchParams’s process response is non-null, then queue a fetch task
+ // to run fetchParams’s process response given response, with fetchParams’s
+ // task destination.
+ if (fetchParams.processResponse != null) {
+ queueMicrotask(() => fetchParams.processResponse(response))
+ }
-/***/ }),
+ // 4. If response’s body is null, then run processResponseEndOfBody.
+ if (response.body == null) {
+ processResponseEndOfBody()
+ } else {
+ // 5. Otherwise:
-/***/ 7340:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. Let transformStream be a new a TransformStream.
-"use strict";
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
+ // enqueues chunk in transformStream.
+ const identityTransformAlgorithm = (chunk, controller) => {
+ controller.enqueue(chunk)
+ }
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
+ // and flushAlgorithm set to processResponseEndOfBody.
+ const transformStream = new TransformStream({
+ start () {},
+ transform: identityTransformAlgorithm,
+ flush: processResponseEndOfBody
+ }, {
+ size () {
+ return 1
+ }
+ }, {
+ size () {
+ return 1
+ }
+ })
-/* eslint-disable no-var */
+ // 4. Set response’s body to the result of piping response’s body through transformStream.
+ response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+ }
-var reusify = __nccwpck_require__(32113)
+ // 6. If fetchParams’s process response consume body is non-null, then:
+ if (fetchParams.processResponseConsumeBody != null) {
+ // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
+ // process response consume body given response and nullOrBytes.
+ const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
-function fastqueue (context, worker, concurrency) {
- if (typeof context === 'function') {
- concurrency = worker
- worker = context
- context = null
- }
+ // 2. Let processBodyError be this step: run fetchParams’s process
+ // response consume body given response and failure.
+ const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
- if (concurrency < 1) {
- throw new Error('fastqueue concurrency must be greater than 1')
+ // 3. If response’s body is null, then queue a fetch task to run processBody
+ // given null, with fetchParams’s task destination.
+ if (response.body == null) {
+ queueMicrotask(() => processBody(null))
+ } else {
+ // 4. Otherwise, fully read response’s body given processBody, processBodyError,
+ // and fetchParams’s task destination.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ }
}
+}
- var cache = reusify(Task)
- var queueHead = null
- var queueTail = null
- var _running = 0
- var errorHandler = null
+// https://fetch.spec.whatwg.org/#http-fetch
+async function httpFetch (fetchParams) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- var self = {
- push: push,
- drain: noop,
- saturated: noop,
- pause: pause,
- paused: false,
- concurrency: concurrency,
- running: running,
- resume: resume,
- idle: idle,
- length: length,
- getQueue: getQueue,
- unshift: unshift,
- empty: noop,
- kill: kill,
- killAndDrain: killAndDrain,
- error: error
- }
+ // 2. Let response be null.
+ let response = null
- return self
+ // 3. Let actualResponse be null.
+ let actualResponse = null
- function running () {
- return _running
- }
+ // 4. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- function pause () {
- self.paused = true
+ // 5. If request’s service-workers mode is "all", then:
+ if (request.serviceWorkers === 'all') {
+ // TODO
}
- function length () {
- var current = queueHead
- var counter = 0
+ // 6. If response is null, then:
+ if (response === null) {
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
+ // TODO
- while (current) {
- current = current.next
- counter++
+ // 2. If request’s redirect mode is "follow", then set request’s
+ // service-workers mode to "none".
+ if (request.redirect === 'follow') {
+ request.serviceWorkers = 'none'
}
- return counter
- }
-
- function getQueue () {
- var current = queueHead
- var tasks = []
+ // 3. Set response and actualResponse to the result of running
+ // HTTP-network-or-cache fetch given fetchParams.
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
- while (current) {
- tasks.push(current.value)
- current = current.next
+ // 4. If request’s response tainting is "cors" and a CORS check
+ // for request and response returns failure, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ corsCheck(request, response) === 'failure'
+ ) {
+ return makeNetworkError('cors failure')
}
- return tasks
- }
-
- function resume () {
- if (!self.paused) return
- self.paused = false
- for (var i = 0; i < self.concurrency; i++) {
- _running++
- release()
+ // 5. If the TAO check for request and response returns failure, then set
+ // request’s timing allow failed flag.
+ if (TAOCheck(request, response) === 'failure') {
+ request.timingAllowFailed = true
}
}
- function idle () {
- return _running === 0 && self.length() === 0
+ // 7. If either request’s response tainting or response’s type
+ // is "opaque", and the cross-origin resource policy check with
+ // request’s origin, request’s client, request’s destination,
+ // and actualResponse returns blocked, then return a network error.
+ if (
+ (request.responseTainting === 'opaque' || response.type === 'opaque') &&
+ crossOriginResourcePolicyCheck(
+ request.origin,
+ request.client,
+ request.destination,
+ actualResponse
+ ) === 'blocked'
+ ) {
+ return makeNetworkError('blocked')
}
- function push (value, done) {
- var current = cache.get()
-
- current.context = context
- current.release = release
- current.value = value
- current.callback = done || noop
- current.errorHandler = errorHandler
-
- if (_running === self.concurrency || self.paused) {
- if (queueTail) {
- queueTail.next = current
- queueTail = current
- } else {
- queueHead = current
- queueTail = current
- self.saturated()
- }
- } else {
- _running++
- worker.call(context, current.value, current.worked)
+ // 8. If actualResponse’s status is a redirect status, then:
+ if (redirectStatus.includes(actualResponse.status)) {
+ // 1. If actualResponse’s status is not 303, request’s body is not null,
+ // and the connection uses HTTP/2, then user agents may, and are even
+ // encouraged to, transmit an RST_STREAM frame.
+ // See, https://github.com/whatwg/fetch/issues/1288
+ if (request.redirect !== 'manual') {
+ fetchParams.controller.connection.destroy()
}
- }
-
- function unshift (value, done) {
- var current = cache.get()
- current.context = context
- current.release = release
- current.value = value
- current.callback = done || noop
-
- if (_running === self.concurrency || self.paused) {
- if (queueHead) {
- current.next = queueHead
- queueHead = current
- } else {
- queueHead = current
- queueTail = current
- self.saturated()
- }
+ // 2. Switch on request’s redirect mode:
+ if (request.redirect === 'error') {
+ // Set response to a network error.
+ response = makeNetworkError('unexpected redirect')
+ } else if (request.redirect === 'manual') {
+ // Set response to an opaque-redirect filtered response whose internal
+ // response is actualResponse.
+ // NOTE(spec): On the web this would return an `opaqueredirect` response,
+ // but that doesn't make sense server side.
+ // See https://github.com/nodejs/undici/issues/1193.
+ response = actualResponse
+ } else if (request.redirect === 'follow') {
+ // Set response to the result of running HTTP-redirect fetch given
+ // fetchParams and response.
+ response = await httpRedirectFetch(fetchParams, response)
} else {
- _running++
- worker.call(context, current.value, current.worked)
- }
- }
-
- function release (holder) {
- if (holder) {
- cache.release(holder)
- }
- var next = queueHead
- if (next) {
- if (!self.paused) {
- if (queueTail === queueHead) {
- queueTail = null
- }
- queueHead = next.next
- next.next = null
- worker.call(context, next.value, next.worked)
- if (queueTail === null) {
- self.empty()
- }
- } else {
- _running--
- }
- } else if (--_running === 0) {
- self.drain()
+ assert(false)
}
}
- function kill () {
- queueHead = null
- queueTail = null
- self.drain = noop
- }
+ // 9. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- function killAndDrain () {
- queueHead = null
- queueTail = null
- self.drain()
- self.drain = noop
- }
+ // 10. Return response.
+ return response
+}
- function error (handler) {
- errorHandler = handler
- }
-}
+// https://fetch.spec.whatwg.org/#http-redirect-fetch
+async function httpRedirectFetch (fetchParams, response) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-function noop () {}
+ // 2. Let actualResponse be response, if response is not a filtered response,
+ // and response’s internal response otherwise.
+ const actualResponse = response.internalResponse
+ ? response.internalResponse
+ : response
-function Task () {
- this.value = null
- this.callback = noop
- this.next = null
- this.release = noop
- this.context = null
- this.errorHandler = null
+ // 3. Let locationURL be actualResponse’s location URL given request’s current
+ // URL’s fragment.
+ let locationURL
- var self = this
+ try {
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ )
- this.worked = function worked (err, result) {
- var callback = self.callback
- var errorHandler = self.errorHandler
- var val = self.value
- self.value = null
- self.callback = noop
- if (self.errorHandler) {
- errorHandler(err, val)
+ // 4. If locationURL is null, then return response.
+ if (locationURL == null) {
+ return response
}
- callback.call(self.context, err, result)
- self.release(self)
+ } catch (err) {
+ // 5. If locationURL is failure, then return a network error.
+ return makeNetworkError(err)
}
-}
-function queueAsPromised (context, worker, concurrency) {
- if (typeof context === 'function') {
- concurrency = worker
- worker = context
- context = null
+ // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
+ // error.
+ if (!urlIsHttpHttpsScheme(locationURL)) {
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
}
- function asyncWrapper (arg, cb) {
- worker.call(this, arg)
- .then(function (res) {
- cb(null, res)
- }, cb)
+ // 7. If request’s redirect count is 20, then return a network error.
+ if (request.redirectCount === 20) {
+ return makeNetworkError('redirect count exceeded')
}
- var queue = fastqueue(context, asyncWrapper, concurrency)
-
- var pushCb = queue.push
- var unshiftCb = queue.unshift
+ // 8. Increase request’s redirect count by 1.
+ request.redirectCount += 1
- queue.push = push
- queue.unshift = unshift
- queue.drained = drained
+ // 9. If request’s mode is "cors", locationURL includes credentials, and
+ // request’s origin is not same origin with locationURL’s origin, then return
+ // a network error.
+ if (
+ request.mode === 'cors' &&
+ (locationURL.username || locationURL.password) &&
+ !sameOrigin(request, locationURL)
+ ) {
+ return makeNetworkError('cross origin not allowed for request mode "cors"')
+ }
- return queue
+ // 10. If request’s response tainting is "cors" and locationURL includes
+ // credentials, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ (locationURL.username || locationURL.password)
+ ) {
+ return makeNetworkError(
+ 'URL cannot contain credentials for request mode "cors"'
+ )
+ }
- function push (value) {
- var p = new Promise(function (resolve, reject) {
- pushCb(value, function (err, result) {
- if (err) {
- reject(err)
- return
- }
- resolve(result)
- })
- })
+ // 11. If actualResponse’s status is not 303, request’s body is non-null,
+ // and request’s body’s source is null, then return a network error.
+ if (
+ actualResponse.status !== 303 &&
+ request.body != null &&
+ request.body.source == null
+ ) {
+ return makeNetworkError()
+ }
- // Let's fork the promise chain to
- // make the error bubble up to the user but
- // not lead to a unhandledRejection
- p.catch(noop)
+ // 12. If one of the following is true
+ // - actualResponse’s status is 301 or 302 and request’s method is `POST`
+ // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
+ if (
+ ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
+ (actualResponse.status === 303 &&
+ !['GET', 'HEAD'].includes(request.method))
+ ) {
+ // then:
+ // 1. Set request’s method to `GET` and request’s body to null.
+ request.method = 'GET'
+ request.body = null
- return p
+ // 2. For each headerName of request-body-header name, delete headerName from
+ // request’s header list.
+ for (const headerName of requestBodyHeader) {
+ request.headersList.delete(headerName)
+ }
}
- function unshift (value) {
- var p = new Promise(function (resolve, reject) {
- unshiftCb(value, function (err, result) {
- if (err) {
- reject(err)
- return
- }
- resolve(result)
- })
- })
-
- // Let's fork the promise chain to
- // make the error bubble up to the user but
- // not lead to a unhandledRejection
- p.catch(noop)
+ // 13. If request’s current URL’s origin is not same origin with locationURL’s
+ // origin, then for each headerName of CORS non-wildcard request-header name,
+ // delete headerName from request’s header list.
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
+ // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
+ request.headersList.delete('authorization')
+ }
- return p
+ // 14. If request’s body is non-null, then set request’s body to the first return
+ // value of safely extracting request’s body’s source.
+ if (request.body != null) {
+ assert(request.body.source != null)
+ request.body = safelyExtractBody(request.body.source)[0]
}
- function drained () {
- var previousDrain = queue.drain
+ // 15. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- var p = new Promise(function (resolve) {
- queue.drain = function () {
- previousDrain()
- resolve()
- }
- })
+ // 16. Set timingInfo’s redirect end time and post-redirect start time to the
+ // coarsened shared current time given fetchParams’s cross-origin isolated
+ // capability.
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
+ coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- return p
+ // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
+ // redirect start time to timingInfo’s start time.
+ if (timingInfo.redirectStartTime === 0) {
+ timingInfo.redirectStartTime = timingInfo.startTime
}
-}
-
-module.exports = fastqueue
-module.exports.promise = queueAsPromised
+ // 18. Append locationURL to request’s URL list.
+ request.urlList.push(locationURL)
-/***/ }),
+ // 19. Invoke set request’s referrer policy on redirect on request and
+ // actualResponse.
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
-/***/ 6330:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 20. Return the result of running main fetch given fetchParams and true.
+ return mainFetch(fetchParams, true)
+}
-"use strict";
-/*!
- * fill-range
- *
- * Copyright (c) 2014-present, Jon Schlinkert.
- * Licensed under the MIT License.
- */
+// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
+async function httpNetworkOrCacheFetch (
+ fetchParams,
+ isAuthenticationFetch = false,
+ isNewConnectionFetch = false
+) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
+ // 2. Let httpFetchParams be null.
+ let httpFetchParams = null
+ // 3. Let httpRequest be null.
+ let httpRequest = null
-const util = __nccwpck_require__(73837);
-const toRegexRange = __nccwpck_require__(1861);
+ // 4. Let response be null.
+ let response = null
-const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+ // 5. Let storedResponse be null.
+ // TODO: cache
-const transform = toNumber => {
- return value => toNumber === true ? Number(value) : String(value);
-};
+ // 6. Let httpCache be null.
+ const httpCache = null
-const isValidValue = value => {
- return typeof value === 'number' || (typeof value === 'string' && value !== '');
-};
+ // 7. Let the revalidatingFlag be unset.
+ const revalidatingFlag = false
-const isNumber = num => Number.isInteger(+num);
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
-const zeros = input => {
- let value = `${input}`;
- let index = -1;
- if (value[0] === '-') value = value.slice(1);
- if (value === '0') return false;
- while (value[++index] === '0');
- return index > 0;
-};
+ // 1. If request’s window is "no-window" and request’s redirect mode is
+ // "error", then set httpFetchParams to fetchParams and httpRequest to
+ // request.
+ if (request.window === 'no-window' && request.redirect === 'error') {
+ httpFetchParams = fetchParams
+ httpRequest = request
+ } else {
+ // Otherwise:
-const stringify = (start, end, options) => {
- if (typeof start === 'string' || typeof end === 'string') {
- return true;
- }
- return options.stringify === true;
-};
+ // 1. Set httpRequest to a clone of request.
+ httpRequest = makeRequest(request)
-const pad = (input, maxLength, toNumber) => {
- if (maxLength > 0) {
- let dash = input[0] === '-' ? '-' : '';
- if (dash) input = input.slice(1);
- input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
- }
- if (toNumber === false) {
- return String(input);
- }
- return input;
-};
+ // 2. Set httpFetchParams to a copy of fetchParams.
+ httpFetchParams = { ...fetchParams }
-const toMaxLen = (input, maxLength) => {
- let negative = input[0] === '-' ? '-' : '';
- if (negative) {
- input = input.slice(1);
- maxLength--;
+ // 3. Set httpFetchParams’s request to httpRequest.
+ httpFetchParams.request = httpRequest
}
- while (input.length < maxLength) input = '0' + input;
- return negative ? ('-' + input) : input;
-};
-const toSequence = (parts, options) => {
- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+ // 3. Let includeCredentials be true if one of
+ const includeCredentials =
+ request.credentials === 'include' ||
+ (request.credentials === 'same-origin' &&
+ request.responseTainting === 'basic')
- let prefix = options.capture ? '' : '?:';
- let positives = '';
- let negatives = '';
- let result;
+ // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
+ // body is non-null; otherwise null.
+ const contentLength = httpRequest.body ? httpRequest.body.length : null
- if (parts.positives.length) {
- positives = parts.positives.join('|');
- }
+ // 5. Let contentLengthHeaderValue be null.
+ let contentLengthHeaderValue = null
- if (parts.negatives.length) {
- negatives = `-(${prefix}${parts.negatives.join('|')})`;
+ // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
+ // `PUT`, then set contentLengthHeaderValue to `0`.
+ if (
+ httpRequest.body == null &&
+ ['POST', 'PUT'].includes(httpRequest.method)
+ ) {
+ contentLengthHeaderValue = '0'
}
- if (positives && negatives) {
- result = `${positives}|${negatives}`;
- } else {
- result = positives || negatives;
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
+ // contentLength, serialized and isomorphic encoded.
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
}
- if (options.wrap) {
- return `(${prefix}${result})`;
+ // 8. If contentLengthHeaderValue is non-null, then append
+ // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
+ // list.
+ if (contentLengthHeaderValue != null) {
+ httpRequest.headersList.append('content-length', contentLengthHeaderValue)
}
- return result;
-};
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
+ // contentLengthHeaderValue) to httpRequest’s header list.
-const toRange = (a, b, isNumbers, options) => {
- if (isNumbers) {
- return toRegexRange(a, b, { wrap: false, ...options });
+ // 10. If contentLength is non-null and httpRequest’s keepalive is true,
+ // then:
+ if (contentLength != null && httpRequest.keepalive) {
+ // NOTE: keepalive is a noop outside of browser context.
}
- let start = String.fromCharCode(a);
- if (a === b) return start;
-
- let stop = String.fromCharCode(b);
- return `[${start}-${stop}]`;
-};
-
-const toRegex = (start, end, options) => {
- if (Array.isArray(start)) {
- let wrap = options.wrap === true;
- let prefix = options.capture ? '' : '?:';
- return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
+ // 11. If httpRequest’s referrer is a URL, then append
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
+ // to httpRequest’s header list.
+ if (httpRequest.referrer instanceof URL) {
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
}
- return toRegexRange(start, end, options);
-};
-const rangeError = (...args) => {
- return new RangeError('Invalid range arguments: ' + util.inspect(...args));
-};
+ // 12. Append a request `Origin` header for httpRequest.
+ appendRequestOriginHeader(httpRequest)
-const invalidRange = (start, end, options) => {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
-};
+ // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
+ appendFetchMetadata(httpRequest)
-const invalidStep = (step, options) => {
- if (options.strictRanges === true) {
- throw new TypeError(`Expected step "${step}" to be a number`);
+ // 14. If httpRequest’s header list does not contain `User-Agent`, then
+ // user agents should append `User-Agent`/default `User-Agent` value to
+ // httpRequest’s header list.
+ if (!httpRequest.headersList.contains('user-agent')) {
+ httpRequest.headersList.append('user-agent', 'undici')
}
- return [];
-};
-
-const fillNumbers = (start, end, step = 1, options = {}) => {
- let a = Number(start);
- let b = Number(end);
- if (!Number.isInteger(a) || !Number.isInteger(b)) {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
+ // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
+ // list contains `If-Modified-Since`, `If-None-Match`,
+ // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
+ // httpRequest’s cache mode to "no-store".
+ if (
+ httpRequest.cache === 'default' &&
+ (httpRequest.headersList.contains('if-modified-since') ||
+ httpRequest.headersList.contains('if-none-match') ||
+ httpRequest.headersList.contains('if-unmodified-since') ||
+ httpRequest.headersList.contains('if-match') ||
+ httpRequest.headersList.contains('if-range'))
+ ) {
+ httpRequest.cache = 'no-store'
}
- // fix negative zero
- if (a === 0) a = 0;
- if (b === 0) b = 0;
-
- let descending = a > b;
- let startString = String(start);
- let endString = String(end);
- let stepString = String(step);
- step = Math.max(Math.abs(step), 1);
-
- let padded = zeros(startString) || zeros(endString) || zeros(stepString);
- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
- let toNumber = padded === false && stringify(start, end, options) === false;
- let format = options.transform || transform(toNumber);
-
- if (options.toRegex && step === 1) {
- return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
+ // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
+ // no-cache cache-control header modification flag is unset, and
+ // httpRequest’s header list does not contain `Cache-Control`, then append
+ // `Cache-Control`/`max-age=0` to httpRequest’s header list.
+ if (
+ httpRequest.cache === 'no-cache' &&
+ !httpRequest.preventNoCacheCacheControlHeaderModification &&
+ !httpRequest.headersList.contains('cache-control')
+ ) {
+ httpRequest.headersList.append('cache-control', 'max-age=0')
}
- let parts = { negatives: [], positives: [] };
- let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
- let range = [];
- let index = 0;
+ // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
+ if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
+ // 1. If httpRequest’s header list does not contain `Pragma`, then append
+ // `Pragma`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('pragma')) {
+ httpRequest.headersList.append('pragma', 'no-cache')
+ }
- while (descending ? a >= b : a <= b) {
- if (options.toRegex === true && step > 1) {
- push(a);
- } else {
- range.push(pad(format(a, index), maxLen, toNumber));
+ // 2. If httpRequest’s header list does not contain `Cache-Control`,
+ // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('cache-control')) {
+ httpRequest.headersList.append('cache-control', 'no-cache')
}
- a = descending ? a - step : a + step;
- index++;
}
- if (options.toRegex === true) {
- return step > 1
- ? toSequence(parts, options)
- : toRegex(range, null, { wrap: false, ...options });
+ // 18. If httpRequest’s header list contains `Range`, then append
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
+ if (httpRequest.headersList.contains('range')) {
+ httpRequest.headersList.append('accept-encoding', 'identity')
}
- return range;
-};
-
-const fillLetters = (start, end, step = 1, options = {}) => {
- if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
- return invalidRange(start, end, options);
+ // 19. Modify httpRequest’s header list per HTTP. Do not append a given
+ // header if httpRequest’s header list contains that header’s name.
+ // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
+ if (!httpRequest.headersList.contains('accept-encoding')) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
+ } else {
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
+ }
}
-
- let format = options.transform || (val => String.fromCharCode(val));
- let a = `${start}`.charCodeAt(0);
- let b = `${end}`.charCodeAt(0);
-
- let descending = a > b;
- let min = Math.min(a, b);
- let max = Math.max(a, b);
-
- if (options.toRegex && step === 1) {
- return toRange(min, max, false, options);
+ // 20. If includeCredentials is true, then:
+ if (includeCredentials) {
+ // 1. If the user agent is not configured to block cookies for httpRequest
+ // (see section 7 of [COOKIES]), then:
+ // TODO: credentials
+ // 2. If httpRequest’s header list does not contain `Authorization`, then:
+ // TODO: credentials
}
- let range = [];
- let index = 0;
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
+ // TODO: proxy-authentication
- while (descending ? a >= b : a <= b) {
- range.push(format(a, index));
- a = descending ? a - step : a + step;
- index++;
- }
+ // 22. Set httpCache to the result of determining the HTTP cache
+ // partition, given httpRequest.
+ // TODO: cache
- if (options.toRegex === true) {
- return toRegex(range, null, { wrap: false, options });
+ // 23. If httpCache is null, then set httpRequest’s cache mode to
+ // "no-store".
+ if (httpCache == null) {
+ httpRequest.cache = 'no-store'
}
- return range;
-};
-
-const fill = (start, end, step, options = {}) => {
- if (end == null && isValidValue(start)) {
- return [start];
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
+ // then:
+ if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
+ // TODO: cache
}
- if (!isValidValue(start) || !isValidValue(end)) {
- return invalidRange(start, end, options);
- }
+ // 9. If aborted, then return the appropriate network error for fetchParams.
+ // TODO
- if (typeof step === 'function') {
- return fill(start, end, 1, { transform: step });
- }
+ // 10. If response is null, then:
+ if (response == null) {
+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a
+ // network error.
+ if (httpRequest.mode === 'only-if-cached') {
+ return makeNetworkError('only if cached')
+ }
- if (isObject(step)) {
- return fill(start, end, 0, step);
- }
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ )
+
+ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
+ // in the range 200 to 399, inclusive, invalidate appropriate stored
+ // responses in httpCache, as per the "Invalidation" chapter of HTTP
+ // Caching, and set storedResponse to null. [HTTP-CACHING]
+ if (
+ !safeMethods.includes(httpRequest.method) &&
+ forwardResponse.status >= 200 &&
+ forwardResponse.status <= 399
+ ) {
+ // TODO: cache
+ }
- let opts = { ...options };
- if (opts.capture === true) opts.wrap = true;
- step = step || opts.step || 1;
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
+ // then:
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ // TODO: cache
+ }
- if (!isNumber(step)) {
- if (step != null && !isObject(step)) return invalidStep(step, opts);
- return fill(start, end, 1, step);
- }
+ // 5. If response is null, then:
+ if (response == null) {
+ // 1. Set response to forwardResponse.
+ response = forwardResponse
- if (isNumber(start) && isNumber(end)) {
- return fillNumbers(start, end, step, opts);
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
+ // TODO: cache
+ }
}
- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
-};
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
+ response.urlList = [...httpRequest.urlList]
-module.exports = fill;
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
+ // range-requested flag.
+ if (httpRequest.headersList.contains('range')) {
+ response.rangeRequested = true
+ }
+ // 13. Set response’s request-includes-credentials to includeCredentials.
+ response.requestIncludesCredentials = includeCredentials
-/***/ }),
+ // 14. If response’s status is 401, httpRequest’s response tainting is not
+ // "cors", includeCredentials is true, and request’s window is an environment
+ // settings object, then:
+ // TODO
-/***/ 43338:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 15. If response’s status is 407, then:
+ if (response.status === 407) {
+ // 1. If request’s window is "no-window", then return a network error.
+ if (request.window === 'no-window') {
+ return makeNetworkError()
+ }
-"use strict";
+ // 2. ???
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const mkdirsSync = (__nccwpck_require__(98605).mkdirsSync)
-const utimesMillisSync = (__nccwpck_require__(52548).utimesMillisSync)
-const stat = __nccwpck_require__(73901)
+ // 4. Prompt the end user as appropriate in request’s window and store
+ // the result as a proxy-authentication entry. [HTTP-AUTH]
+ // TODO: Invoke some kind of callback?
-function copySync (src, dest, opts) {
- if (typeof opts === 'function') {
- opts = { filter: opts }
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
+ // fetchParams.
+ // TODO
+ return makeNetworkError('proxy authentication required')
}
- opts = opts || {}
- opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
+ // 16. If all of the following are true
+ if (
+ // response’s status is 421
+ response.status === 421 &&
+ // isNewConnectionFetch is false
+ !isNewConnectionFetch &&
+ // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
+ (request.body == null || request.body.source != null)
+ ) {
+ // then:
- // Warn about using preserveTimestamps on 32-bit node
- if (opts.preserveTimestamps && process.arch === 'ia32') {
- console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
- see https://github.com/jprichardson/node-fs-extra/issues/269`)
- }
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
- const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy')
- stat.checkParentPathsSync(src, srcStat, dest, 'copy')
- return handleFilterAndCopy(destStat, src, dest, opts)
-}
+ // 2. Set response to the result of running HTTP-network-or-cache
+ // fetch given fetchParams, isAuthenticationFetch, and true.
-function handleFilterAndCopy (destStat, src, dest, opts) {
- if (opts.filter && !opts.filter(src, dest)) return
- const destParent = path.dirname(dest)
- if (!fs.existsSync(destParent)) mkdirsSync(destParent)
- return startCopy(destStat, src, dest, opts)
-}
+ // TODO (spec): The spec doesn't specify this but we need to cancel
+ // the active response before we can start a new one.
+ // https://github.com/whatwg/fetch/issues/1293
+ fetchParams.controller.connection.destroy()
-function startCopy (destStat, src, dest, opts) {
- if (opts.filter && !opts.filter(src, dest)) return
- return getStats(destStat, src, dest, opts)
-}
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ )
+ }
-function getStats (destStat, src, dest, opts) {
- const statSync = opts.dereference ? fs.statSync : fs.lstatSync
- const srcStat = statSync(src)
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
+ if (isAuthenticationFetch) {
+ // TODO
+ }
- if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
- else if (srcStat.isFile() ||
- srcStat.isCharacterDevice() ||
- srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
- else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
+ // 18. Return response.
+ return response
}
-function onFile (srcStat, destStat, src, dest, opts) {
- if (!destStat) return copyFile(srcStat, src, dest, opts)
- return mayCopyFile(srcStat, src, dest, opts)
-}
+// https://fetch.spec.whatwg.org/#http-network-fetch
+async function httpNetworkFetch (
+ fetchParams,
+ includeCredentials = false,
+ forceNewConnection = false
+) {
+ assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
-function mayCopyFile (srcStat, src, dest, opts) {
- if (opts.overwrite) {
- fs.unlinkSync(dest)
- return copyFile(srcStat, src, dest, opts)
- } else if (opts.errorOnExist) {
- throw new Error(`'${dest}' already exists`)
+ fetchParams.controller.connection = {
+ abort: null,
+ destroyed: false,
+ destroy (err) {
+ if (!this.destroyed) {
+ this.destroyed = true
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
+ }
+ }
}
-}
-function copyFile (srcStat, src, dest, opts) {
- fs.copyFileSync(src, dest)
- if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
- return setDestMode(dest, srcStat.mode)
-}
-
-function handleTimestamps (srcMode, src, dest) {
- // Make sure the file is writable before setting the timestamp
- // otherwise open fails with EPERM when invoked with 'r+'
- // (through utimes call)
- if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)
- return setDestTimestamps(src, dest)
-}
-
-function fileIsNotWritable (srcMode) {
- return (srcMode & 0o200) === 0
-}
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-function makeFileWritable (dest, srcMode) {
- return setDestMode(dest, srcMode | 0o200)
-}
+ // 2. Let response be null.
+ let response = null
-function setDestMode (dest, srcMode) {
- return fs.chmodSync(dest, srcMode)
-}
+ // 3. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
-function setDestTimestamps (src, dest) {
- // The initial srcStat.atime cannot be trusted
- // because it is modified by the read(2) system call
- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
- const updatedSrcStat = fs.statSync(src)
- return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
-}
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
+ // given request.
+ // TODO: cache
+ const httpCache = null
-function onDir (srcStat, destStat, src, dest, opts) {
- if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
- if (destStat && !destStat.isDirectory()) {
- throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
+ if (httpCache == null) {
+ request.cache = 'no-store'
}
- return copyDir(src, dest, opts)
-}
-
-function mkDirAndCopy (srcMode, src, dest, opts) {
- fs.mkdirSync(dest)
- copyDir(src, dest, opts)
- return setDestMode(dest, srcMode)
-}
-function copyDir (src, dest, opts) {
- fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
-}
-
-function copyDirItem (item, src, dest, opts) {
- const srcItem = path.join(src, item)
- const destItem = path.join(dest, item)
- const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy')
- return startCopy(destStat, srcItem, destItem, opts)
-}
+ // 6. Let networkPartitionKey be the result of determining the network
+ // partition key given request.
+ // TODO
-function onLink (destStat, src, dest, opts) {
- let resolvedSrc = fs.readlinkSync(src)
- if (opts.dereference) {
- resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
- }
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
+ // "no".
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
- if (!destStat) {
- return fs.symlinkSync(resolvedSrc, dest)
+ // 8. Switch on request’s mode:
+ if (request.mode === 'websocket') {
+ // Let connection be the result of obtaining a WebSocket connection,
+ // given request’s current URL.
+ // TODO
} else {
- let resolvedDest
- try {
- resolvedDest = fs.readlinkSync(dest)
- } catch (err) {
- // dest exists and is a regular file or directory,
- // Windows may throw UNKNOWN error. If dest already exists,
- // fs throws error anyway, so no need to guard against it here.
- if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
- throw err
- }
- if (opts.dereference) {
- resolvedDest = path.resolve(process.cwd(), resolvedDest)
- }
- if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
- throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
- }
-
- // prevent copy if src is a subdir of dest since unlinking
- // dest in this case would result in removing src contents
- // and therefore a broken symlink would be created.
- if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
- throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
- }
- return copyLink(resolvedSrc, dest)
+ // Let connection be the result of obtaining a connection, given
+ // networkPartitionKey, request’s current URL’s origin,
+ // includeCredentials, and forceNewConnection.
+ // TODO
}
-}
-function copyLink (resolvedSrc, dest) {
- fs.unlinkSync(dest)
- return fs.symlinkSync(resolvedSrc, dest)
-}
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
-module.exports = copySync
+ // 1. If connection is failure, then return a network error.
+ // 2. Set timingInfo’s final connection timing info to the result of
+ // calling clamp and coarsen connection timing info with connection’s
+ // timing info, timingInfo’s post-redirect start time, and fetchParams’s
+ // cross-origin isolated capability.
-/***/ }),
-
-/***/ 11135:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-module.exports = {
- copySync: __nccwpck_require__(43338)
-}
+ // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
+ // and request’s body’s source is null, then append (`Transfer-Encoding`,
+ // `chunked`) to request’s header list.
+ // 4. Set timingInfo’s final network-request start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated
+ // capability.
-/***/ }),
+ // 5. Set response to the result of making an HTTP request over connection
+ // using request with the following caveats:
-/***/ 38834:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
-"use strict";
+ // - If request’s body is non-null, and request’s body’s source is null,
+ // then the user agent may have a buffer of up to 64 kibibytes and store
+ // a part of request’s body in that buffer. If the user agent reads from
+ // request’s body beyond that buffer’s size and the user agent needs to
+ // resend request, then instead return a network error.
+ // - Set timingInfo’s final network-response start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated capability,
+ // immediately after the user agent’s HTTP parser receives the first byte
+ // of the response (e.g., frame header bytes for HTTP/2 or response status
+ // line for HTTP/1.x).
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const mkdirs = (__nccwpck_require__(98605).mkdirs)
-const pathExists = (__nccwpck_require__(43835).pathExists)
-const utimesMillis = (__nccwpck_require__(52548).utimesMillis)
-const stat = __nccwpck_require__(73901)
+ // - Wait until all the headers are transmitted.
-function copy (src, dest, opts, cb) {
- if (typeof opts === 'function' && !cb) {
- cb = opts
- opts = {}
- } else if (typeof opts === 'function') {
- opts = { filter: opts }
- }
+ // - Any responses whose status is in the range 100 to 199, inclusive,
+ // and is not 101, are to be ignored, except for the purposes of setting
+ // timingInfo’s final network-response start time above.
- cb = cb || function () {}
- opts = opts || {}
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
+ // response is transferred via HTTP/1.0 or older, then return a network
+ // error.
- opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
+ // - If the HTTP request results in a TLS client certificate dialog, then:
- // Warn about using preserveTimestamps on 32-bit node
- if (opts.preserveTimestamps && process.arch === 'ia32') {
- console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
- see https://github.com/jprichardson/node-fs-extra/issues/269`)
- }
+ // 1. If request’s window is an environment settings object, make the
+ // dialog available in request’s window.
- stat.checkPaths(src, dest, 'copy', (err, stats) => {
- if (err) return cb(err)
- const { srcStat, destStat } = stats
- stat.checkParentPaths(src, srcStat, dest, 'copy', err => {
- if (err) return cb(err)
- if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)
- return checkParentDir(destStat, src, dest, opts, cb)
- })
- })
-}
+ // 2. Otherwise, return a network error.
-function checkParentDir (destStat, src, dest, opts, cb) {
- const destParent = path.dirname(dest)
- pathExists(destParent, (err, dirExists) => {
- if (err) return cb(err)
- if (dirExists) return startCopy(destStat, src, dest, opts, cb)
- mkdirs(destParent, err => {
- if (err) return cb(err)
- return startCopy(destStat, src, dest, opts, cb)
- })
- })
-}
+ // To transmit request’s body body, run these steps:
+ let requestBody = null
+ // 1. If body is null and fetchParams’s process request end-of-body is
+ // non-null, then queue a fetch task given fetchParams’s process request
+ // end-of-body and fetchParams’s task destination.
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
+ queueMicrotask(() => fetchParams.processRequestEndOfBody())
+ } else if (request.body != null) {
+ // 2. Otherwise, if body is non-null:
-function handleFilter (onInclude, destStat, src, dest, opts, cb) {
- Promise.resolve(opts.filter(src, dest)).then(include => {
- if (include) return onInclude(destStat, src, dest, opts, cb)
- return cb()
- }, error => cb(error))
-}
+ // 1. Let processBodyChunk given bytes be these steps:
+ const processBodyChunk = async function * (bytes) {
+ // 1. If the ongoing fetch is terminated, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
-function startCopy (destStat, src, dest, opts, cb) {
- if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb)
- return getStats(destStat, src, dest, opts, cb)
-}
+ // 2. Run this step in parallel: transmit bytes.
+ yield bytes
-function getStats (destStat, src, dest, opts, cb) {
- const stat = opts.dereference ? fs.stat : fs.lstat
- stat(src, (err, srcStat) => {
- if (err) return cb(err)
+ // 3. If fetchParams’s process request body is non-null, then run
+ // fetchParams’s process request body given bytes’s length.
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
+ }
- if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb)
- else if (srcStat.isFile() ||
- srcStat.isCharacterDevice() ||
- srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb)
- else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb)
- })
-}
+ // 2. Let processEndOfBody be these steps:
+ const processEndOfBody = () => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
-function onFile (srcStat, destStat, src, dest, opts, cb) {
- if (!destStat) return copyFile(srcStat, src, dest, opts, cb)
- return mayCopyFile(srcStat, src, dest, opts, cb)
-}
+ // 2. If fetchParams’s process request end-of-body is non-null,
+ // then run fetchParams’s process request end-of-body.
+ if (fetchParams.processRequestEndOfBody) {
+ fetchParams.processRequestEndOfBody()
+ }
+ }
-function mayCopyFile (srcStat, src, dest, opts, cb) {
- if (opts.overwrite) {
- fs.unlink(dest, err => {
- if (err) return cb(err)
- return copyFile(srcStat, src, dest, opts, cb)
- })
- } else if (opts.errorOnExist) {
- return cb(new Error(`'${dest}' already exists`))
- } else return cb()
-}
+ // 3. Let processBodyError given e be these steps:
+ const processBodyError = (e) => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
-function copyFile (srcStat, src, dest, opts, cb) {
- fs.copyFile(src, dest, err => {
- if (err) return cb(err)
- if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)
- return setDestMode(dest, srcStat.mode, cb)
- })
-}
+ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
+ if (e.name === 'AbortError') {
+ fetchParams.controller.abort()
+ } else {
+ fetchParams.controller.terminate(e)
+ }
+ }
-function handleTimestampsAndMode (srcMode, src, dest, cb) {
- // Make sure the file is writable before setting the timestamp
- // otherwise open fails with EPERM when invoked with 'r+'
- // (through utimes call)
- if (fileIsNotWritable(srcMode)) {
- return makeFileWritable(dest, srcMode, err => {
- if (err) return cb(err)
- return setDestTimestampsAndMode(srcMode, src, dest, cb)
- })
+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
+ // processBodyError, and fetchParams’s task destination.
+ requestBody = (async function * () {
+ try {
+ for await (const bytes of request.body.stream) {
+ yield * processBodyChunk(bytes)
+ }
+ processEndOfBody()
+ } catch (err) {
+ processBodyError(err)
+ }
+ })()
}
- return setDestTimestampsAndMode(srcMode, src, dest, cb)
-}
-function fileIsNotWritable (srcMode) {
- return (srcMode & 0o200) === 0
-}
+ try {
+ // socket is only provided for websockets
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
-function makeFileWritable (dest, srcMode, cb) {
- return setDestMode(dest, srcMode | 0o200, cb)
-}
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket })
+ } else {
+ const iterator = body[Symbol.asyncIterator]()
+ fetchParams.controller.next = () => iterator.next()
-function setDestTimestampsAndMode (srcMode, src, dest, cb) {
- setDestTimestamps(src, dest, err => {
- if (err) return cb(err)
- return setDestMode(dest, srcMode, cb)
- })
-}
+ response = makeResponse({ status, statusText, headersList })
+ }
+ } catch (err) {
+ // 10. If aborted, then:
+ if (err.name === 'AbortError') {
+ // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ fetchParams.controller.connection.destroy()
-function setDestMode (dest, srcMode, cb) {
- return fs.chmod(dest, srcMode, cb)
-}
+ // 2. Return the appropriate network error for fetchParams.
+ return makeAppropriateNetworkError(fetchParams, err)
+ }
-function setDestTimestamps (src, dest, cb) {
- // The initial srcStat.atime cannot be trusted
- // because it is modified by the read(2) system call
- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
- fs.stat(src, (err, updatedSrcStat) => {
- if (err) return cb(err)
- return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)
- })
-}
+ return makeNetworkError(err)
+ }
-function onDir (srcStat, destStat, src, dest, opts, cb) {
- if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb)
- if (destStat && !destStat.isDirectory()) {
- return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
+ // if it is suspended.
+ const pullAlgorithm = () => {
+ fetchParams.controller.resume()
}
- return copyDir(src, dest, opts, cb)
-}
-function mkDirAndCopy (srcMode, src, dest, opts, cb) {
- fs.mkdir(dest, err => {
- if (err) return cb(err)
- copyDir(src, dest, opts, err => {
- if (err) return cb(err)
- return setDestMode(dest, srcMode, cb)
- })
- })
-}
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
+ // controller with reason, given reason.
+ const cancelAlgorithm = (reason) => {
+ fetchParams.controller.abort(reason)
+ }
-function copyDir (src, dest, opts, cb) {
- fs.readdir(src, (err, items) => {
- if (err) return cb(err)
- return copyDirItems(items, src, dest, opts, cb)
- })
-}
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
+ // the user agent.
+ // TODO
-function copyDirItems (items, src, dest, opts, cb) {
- const item = items.pop()
- if (!item) return cb()
- return copyDirItem(items, item, src, dest, opts, cb)
-}
+ // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
+ // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
+ // TODO
-function copyDirItem (items, item, src, dest, opts, cb) {
- const srcItem = path.join(src, item)
- const destItem = path.join(dest, item)
- stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => {
- if (err) return cb(err)
- const { destStat } = stats
- startCopy(destStat, srcItem, destItem, opts, err => {
- if (err) return cb(err)
- return copyDirItems(items, src, dest, opts, cb)
- })
- })
-}
+ // 15. Let stream be a new ReadableStream.
+ // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
+ // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
+ // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(3774).ReadableStream)
+ }
-function onLink (destStat, src, dest, opts, cb) {
- fs.readlink(src, (err, resolvedSrc) => {
- if (err) return cb(err)
- if (opts.dereference) {
- resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
+ const stream = new ReadableStream(
+ {
+ async start (controller) {
+ fetchParams.controller.controller = controller
+ },
+ async pull (controller) {
+ await pullAlgorithm(controller)
+ },
+ async cancel (reason) {
+ await cancelAlgorithm(reason)
+ }
+ },
+ {
+ highWaterMark: 0,
+ size () {
+ return 1
+ }
}
+ )
- if (!destStat) {
- return fs.symlink(resolvedSrc, dest, cb)
- } else {
- fs.readlink(dest, (err, resolvedDest) => {
- if (err) {
- // dest exists and is a regular file or directory,
- // Windows may throw UNKNOWN error. If dest already exists,
- // fs throws error anyway, so no need to guard against it here.
- if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb)
- return cb(err)
- }
- if (opts.dereference) {
- resolvedDest = path.resolve(process.cwd(), resolvedDest)
- }
- if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
- return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))
- }
-
- // do not copy if src is a subdir of dest since unlinking
- // dest in this case would result in removing src contents
- // and therefore a broken symlink would be created.
- if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
- return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
- }
- return copyLink(resolvedSrc, dest, cb)
- })
- }
- })
-}
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
-function copyLink (resolvedSrc, dest, cb) {
- fs.unlink(dest, err => {
- if (err) return cb(err)
- return fs.symlink(resolvedSrc, dest, cb)
- })
-}
+ // 1. Set response’s body to a new body whose stream is stream.
+ response.body = { stream }
-module.exports = copy
+ // 2. If response is not a network error and request’s cache mode is
+ // not "no-store", then update response in httpCache for request.
+ // TODO
+ // 3. If includeCredentials is true and the user agent is not configured
+ // to block cookies for request (see section 7 of [COOKIES]), then run the
+ // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
+ // the value of each header whose name is a byte-case-insensitive match for
+ // `Set-Cookie` in response’s header list, if any, and request’s current URL.
+ // TODO
-/***/ }),
+ // 18. If aborted, then:
+ // TODO
-/***/ 61335:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 19. Run these steps in parallel:
-"use strict";
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ fetchParams.controller.on('terminated', onAborted)
+ fetchParams.controller.resume = async () => {
+ // 1. While true
+ while (true) {
+ // 1-3. See onData...
+ // 4. Set bytes to the result of handling content codings given
+ // codings and bytes.
+ let bytes
+ let isFailure
+ try {
+ const { done, value } = await fetchParams.controller.next()
-const u = (__nccwpck_require__(9046).fromCallback)
-module.exports = {
- copy: u(__nccwpck_require__(38834))
-}
+ if (isAborted(fetchParams)) {
+ break
+ }
+ bytes = done ? undefined : value
+ } catch (err) {
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
+ // zlib doesn't like empty streams.
+ bytes = undefined
+ } else {
+ bytes = err
-/***/ }),
+ // err may be propagated from the result of calling readablestream.cancel,
+ // which might not be an error. https://github.com/nodejs/undici/issues/2009
+ isFailure = true
+ }
+ }
-/***/ 96970:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (bytes === undefined) {
+ // 2. Otherwise, if the bytes transmission for response’s message
+ // body is done normally and stream is readable, then close
+ // stream, finalize response for fetchParams and response, and
+ // abort these in-parallel steps.
+ readableStreamClose(fetchParams.controller.controller)
-"use strict";
+ finalizeResponse(fetchParams, response)
+ return
+ }
-const u = (__nccwpck_require__(9046).fromCallback)
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const mkdir = __nccwpck_require__(98605)
-const remove = __nccwpck_require__(47357)
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
-const emptyDir = u(function emptyDir (dir, callback) {
- callback = callback || function () {}
- fs.readdir(dir, (err, items) => {
- if (err) return mkdir.mkdirs(dir, callback)
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes)
+ return
+ }
- items = items.map(item => path.join(dir, item))
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
+ // into stream.
+ fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
- deleteItem()
+ // 8. If stream is errored, then terminate the ongoing fetch.
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate()
+ return
+ }
- function deleteItem () {
- const item = items.pop()
- if (!item) return callback()
- remove.remove(item, err => {
- if (err) return callback(err)
- deleteItem()
- })
+ // 9. If stream doesn’t need more data ask the user agent to suspend
+ // the ongoing fetch.
+ if (!fetchParams.controller.controller.desiredSize) {
+ return
+ }
}
- })
-})
-
-function emptyDirSync (dir) {
- let items
- try {
- items = fs.readdirSync(dir)
- } catch {
- return mkdir.mkdirsSync(dir)
}
- items.forEach(item => {
- item = path.join(dir, item)
- remove.removeSync(item)
- })
-}
-
-module.exports = {
- emptyDirSync,
- emptydirSync: emptyDirSync,
- emptyDir,
- emptydir: emptyDir
-}
-
-
-/***/ }),
+ // 2. If aborted, then:
+ function onAborted (reason) {
+ // 2. If fetchParams is aborted, then:
+ if (isAborted(fetchParams)) {
+ // 1. Set response’s aborted flag.
+ response.aborted = true
-/***/ 2164:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If stream is readable, then error stream with the result of
+ // deserialize a serialized abort reason given fetchParams’s
+ // controller’s serialized abort reason and an
+ // implementation-defined realm.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(
+ fetchParams.controller.serializedAbortReason
+ )
+ }
+ } else {
+ // 3. Otherwise, if stream is readable, error stream with a TypeError.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(new TypeError('terminated', {
+ cause: isErrorLike(reason) ? reason : undefined
+ }))
+ }
+ }
-"use strict";
+ // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
+ fetchParams.controller.connection.destroy()
+ }
+ // 20. Return response.
+ return response
-const u = (__nccwpck_require__(9046).fromCallback)
-const path = __nccwpck_require__(71017)
-const fs = __nccwpck_require__(14178)
-const mkdir = __nccwpck_require__(98605)
+ async function dispatch ({ body }) {
+ const url = requestCurrentURL(request)
+ /** @type {import('../..').Agent} */
+ const agent = fetchParams.controller.dispatcher
-function createFile (file, callback) {
- function makeFile () {
- fs.writeFile(file, '', err => {
- if (err) return callback(err)
- callback()
- })
- }
+ return new Promise((resolve, reject) => agent.dispatch(
+ {
+ path: url.pathname + url.search,
+ origin: url.origin,
+ method: request.method,
+ body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body,
+ headers: request.headersList.entries,
+ maxRedirections: 0,
+ upgrade: request.mode === 'websocket' ? 'websocket' : undefined
+ },
+ {
+ body: null,
+ abort: null,
- fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
- if (!err && stats.isFile()) return callback()
- const dir = path.dirname(file)
- fs.stat(dir, (err, stats) => {
- if (err) {
- // if the directory doesn't exist, make it
- if (err.code === 'ENOENT') {
- return mkdir.mkdirs(dir, err => {
- if (err) return callback(err)
- makeFile()
- })
- }
- return callback(err)
- }
+ onConnect (abort) {
+ // TODO (fix): Do we need connection here?
+ const { connection } = fetchParams.controller
- if (stats.isDirectory()) makeFile()
- else {
- // parent is not a directory
- // This is just to cause an internal ENOTDIR error to be thrown
- fs.readdir(dir, err => {
- if (err) return callback(err)
- })
- }
- })
- })
-}
+ if (connection.destroyed) {
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
+ } else {
+ fetchParams.controller.on('terminated', abort)
+ this.abort = connection.abort = abort
+ }
+ },
-function createFileSync (file) {
- let stats
- try {
- stats = fs.statSync(file)
- } catch {}
- if (stats && stats.isFile()) return
+ onHeaders (status, headersList, resume, statusText) {
+ if (status < 200) {
+ return
+ }
- const dir = path.dirname(file)
- try {
- if (!fs.statSync(dir).isDirectory()) {
- // parent is not a directory
- // This is just to cause an internal ENOTDIR error to be thrown
- fs.readdirSync(dir)
- }
- } catch (err) {
- // If the stat call above failed because the directory doesn't exist, create it
- if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
- else throw err
- }
+ let codings = []
+ let location = ''
- fs.writeFileSync(file, '')
-}
+ const headers = new Headers()
-module.exports = {
- createFile: u(createFile),
- createFileSync
-}
+ // For H2, the headers are a plain JS object
+ // We distinguish between them and iterate accordingly
+ if (Array.isArray(headersList)) {
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim())
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
+ headers.append(key, val)
+ }
+ } else {
+ const keys = Object.keys(headersList)
+ for (const key of keys) {
+ const val = headersList[key]
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
-/***/ }),
+ headers.append(key, val)
+ }
+ }
-/***/ 40055:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.body = new Readable({ read: resume })
-"use strict";
+ const decoders = []
+ const willFollow = request.redirect === 'follow' &&
+ location &&
+ redirectStatus.includes(status)
-const file = __nccwpck_require__(2164)
-const link = __nccwpck_require__(53797)
-const symlink = __nccwpck_require__(72549)
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
+ for (const coding of codings) {
+ // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
+ if (coding === 'x-gzip' || coding === 'gzip') {
+ decoders.push(zlib.createGunzip({
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }))
+ } else if (coding === 'deflate') {
+ decoders.push(zlib.createInflate())
+ } else if (coding === 'br') {
+ decoders.push(zlib.createBrotliDecompress())
+ } else {
+ decoders.length = 0
+ break
+ }
+ }
+ }
-module.exports = {
- // file
- createFile: file.createFile,
- createFileSync: file.createFileSync,
- ensureFile: file.createFile,
- ensureFileSync: file.createFileSync,
- // link
- createLink: link.createLink,
- createLinkSync: link.createLinkSync,
- ensureLink: link.createLink,
- ensureLinkSync: link.createLinkSync,
- // symlink
- createSymlink: symlink.createSymlink,
- createSymlinkSync: symlink.createSymlinkSync,
- ensureSymlink: symlink.createSymlink,
- ensureSymlinkSync: symlink.createSymlinkSync
-}
+ resolve({
+ status,
+ statusText,
+ headersList: headers[kHeadersList],
+ body: decoders.length
+ ? pipeline(this.body, ...decoders, () => { })
+ : this.body.on('error', () => {})
+ })
+ return true
+ },
-/***/ }),
+ onData (chunk) {
+ if (fetchParams.controller.dump) {
+ return
+ }
-/***/ 53797:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. If one or more bytes have been transmitted from response’s
+ // message body, then:
-"use strict";
+ // 1. Let bytes be the transmitted bytes.
+ const bytes = chunk
+ // 2. Let codings be the result of extracting header list values
+ // given `Content-Encoding` and response’s header list.
+ // See pullAlgorithm.
-const u = (__nccwpck_require__(9046).fromCallback)
-const path = __nccwpck_require__(71017)
-const fs = __nccwpck_require__(14178)
-const mkdir = __nccwpck_require__(98605)
-const pathExists = (__nccwpck_require__(43835).pathExists)
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
+ timingInfo.encodedBodySize += bytes.byteLength
-function createLink (srcpath, dstpath, callback) {
- function makeLink (srcpath, dstpath) {
- fs.link(srcpath, dstpath, err => {
- if (err) return callback(err)
- callback(null)
- })
- }
+ // 4. See pullAlgorithm...
- pathExists(dstpath, (err, destinationExists) => {
- if (err) return callback(err)
- if (destinationExists) return callback(null)
- fs.lstat(srcpath, (err) => {
- if (err) {
- err.message = err.message.replace('lstat', 'ensureLink')
- return callback(err)
- }
+ return this.body.push(bytes)
+ },
- const dir = path.dirname(dstpath)
- pathExists(dir, (err, dirExists) => {
- if (err) return callback(err)
- if (dirExists) return makeLink(srcpath, dstpath)
- mkdir.mkdirs(dir, err => {
- if (err) return callback(err)
- makeLink(srcpath, dstpath)
- })
- })
- })
- })
-}
+ onComplete () {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
-function createLinkSync (srcpath, dstpath) {
- const destinationExists = fs.existsSync(dstpath)
- if (destinationExists) return undefined
+ fetchParams.controller.ended = true
- try {
- fs.lstatSync(srcpath)
- } catch (err) {
- err.message = err.message.replace('lstat', 'ensureLink')
- throw err
- }
+ this.body.push(null)
+ },
- const dir = path.dirname(dstpath)
- const dirExists = fs.existsSync(dir)
- if (dirExists) return fs.linkSync(srcpath, dstpath)
- mkdir.mkdirsSync(dir)
+ onError (error) {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- return fs.linkSync(srcpath, dstpath)
-}
+ this.body?.destroy(error)
-module.exports = {
- createLink: u(createLink),
- createLinkSync
-}
+ fetchParams.controller.terminate(error)
+ reject(error)
+ },
-/***/ }),
+ onUpgrade (status, headersList, socket) {
+ if (status !== 101) {
+ return
+ }
-/***/ 53727:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const headers = new Headers()
-"use strict";
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
+ headers.append(key, val)
+ }
-const path = __nccwpck_require__(71017)
-const fs = __nccwpck_require__(14178)
-const pathExists = (__nccwpck_require__(43835).pathExists)
+ resolve({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList: headers[kHeadersList],
+ socket
+ })
-/**
- * Function that returns two types of paths, one relative to symlink, and one
- * relative to the current working directory. Checks if path is absolute or
- * relative. If the path is relative, this function checks if the path is
- * relative to symlink or relative to current working directory. This is an
- * initiative to find a smarter `srcpath` to supply when building symlinks.
- * This allows you to determine which path to use out of one of three possible
- * types of source paths. The first is an absolute path. This is detected by
- * `path.isAbsolute()`. When an absolute path is provided, it is checked to
- * see if it exists. If it does it's used, if not an error is returned
- * (callback)/ thrown (sync). The other two options for `srcpath` are a
- * relative url. By default Node's `fs.symlink` works by creating a symlink
- * using `dstpath` and expects the `srcpath` to be relative to the newly
- * created symlink. If you provide a `srcpath` that does not exist on the file
- * system it results in a broken symlink. To minimize this, the function
- * checks to see if the 'relative to symlink' source file exists, and if it
- * does it will use it. If it does not, it checks if there's a file that
- * exists that is relative to the current working directory, if does its used.
- * This preserves the expectations of the original fs.symlink spec and adds
- * the ability to pass in `relative to current working direcotry` paths.
- */
-
-function symlinkPaths (srcpath, dstpath, callback) {
- if (path.isAbsolute(srcpath)) {
- return fs.lstat(srcpath, (err) => {
- if (err) {
- err.message = err.message.replace('lstat', 'ensureSymlink')
- return callback(err)
- }
- return callback(null, {
- toCwd: srcpath,
- toDst: srcpath
- })
- })
- } else {
- const dstdir = path.dirname(dstpath)
- const relativeToDst = path.join(dstdir, srcpath)
- return pathExists(relativeToDst, (err, exists) => {
- if (err) return callback(err)
- if (exists) {
- return callback(null, {
- toCwd: relativeToDst,
- toDst: srcpath
- })
- } else {
- return fs.lstat(srcpath, (err) => {
- if (err) {
- err.message = err.message.replace('lstat', 'ensureSymlink')
- return callback(err)
- }
- return callback(null, {
- toCwd: srcpath,
- toDst: path.relative(dstdir, srcpath)
- })
- })
- }
- })
- }
-}
-
-function symlinkPathsSync (srcpath, dstpath) {
- let exists
- if (path.isAbsolute(srcpath)) {
- exists = fs.existsSync(srcpath)
- if (!exists) throw new Error('absolute srcpath does not exist')
- return {
- toCwd: srcpath,
- toDst: srcpath
- }
- } else {
- const dstdir = path.dirname(dstpath)
- const relativeToDst = path.join(dstdir, srcpath)
- exists = fs.existsSync(relativeToDst)
- if (exists) {
- return {
- toCwd: relativeToDst,
- toDst: srcpath
- }
- } else {
- exists = fs.existsSync(srcpath)
- if (!exists) throw new Error('relative srcpath does not exist')
- return {
- toCwd: srcpath,
- toDst: path.relative(dstdir, srcpath)
+ return true
+ }
}
- }
- }
-}
-
-module.exports = {
- symlinkPaths,
- symlinkPathsSync
-}
-
-
-/***/ }),
-
-/***/ 18254:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const fs = __nccwpck_require__(14178)
-
-function symlinkType (srcpath, type, callback) {
- callback = (typeof type === 'function') ? type : callback
- type = (typeof type === 'function') ? false : type
- if (type) return callback(null, type)
- fs.lstat(srcpath, (err, stats) => {
- if (err) return callback(null, 'file')
- type = (stats && stats.isDirectory()) ? 'dir' : 'file'
- callback(null, type)
- })
-}
-
-function symlinkTypeSync (srcpath, type) {
- let stats
-
- if (type) return type
- try {
- stats = fs.lstatSync(srcpath)
- } catch {
- return 'file'
+ ))
}
- return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
- symlinkType,
- symlinkTypeSync
+ fetch,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
}
/***/ }),
-/***/ 72549:
+/***/ 5194:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-"use strict";
-
-
-const u = (__nccwpck_require__(9046).fromCallback)
-const path = __nccwpck_require__(71017)
-const fs = __nccwpck_require__(14178)
-const _mkdirs = __nccwpck_require__(98605)
-const mkdirs = _mkdirs.mkdirs
-const mkdirsSync = _mkdirs.mkdirsSync
-
-const _symlinkPaths = __nccwpck_require__(53727)
-const symlinkPaths = _symlinkPaths.symlinkPaths
-const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
-
-const _symlinkType = __nccwpck_require__(18254)
-const symlinkType = _symlinkType.symlinkType
-const symlinkTypeSync = _symlinkType.symlinkTypeSync
-
-const pathExists = (__nccwpck_require__(43835).pathExists)
-
-function createSymlink (srcpath, dstpath, type, callback) {
- callback = (typeof type === 'function') ? type : callback
- type = (typeof type === 'function') ? false : type
-
- pathExists(dstpath, (err, destinationExists) => {
- if (err) return callback(err)
- if (destinationExists) return callback(null)
- symlinkPaths(srcpath, dstpath, (err, relative) => {
- if (err) return callback(err)
- srcpath = relative.toDst
- symlinkType(relative.toCwd, type, (err, type) => {
- if (err) return callback(err)
- const dir = path.dirname(dstpath)
- pathExists(dir, (err, dirExists) => {
- if (err) return callback(err)
- if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
- mkdirs(dir, err => {
- if (err) return callback(err)
- fs.symlink(srcpath, dstpath, type, callback)
- })
- })
- })
- })
- })
-}
-
-function createSymlinkSync (srcpath, dstpath, type) {
- const destinationExists = fs.existsSync(dstpath)
- if (destinationExists) return undefined
-
- const relative = symlinkPathsSync(srcpath, dstpath)
- srcpath = relative.toDst
- type = symlinkTypeSync(relative.toCwd, type)
- const dir = path.dirname(dstpath)
- const exists = fs.existsSync(dir)
- if (exists) return fs.symlinkSync(srcpath, dstpath, type)
- mkdirsSync(dir)
- return fs.symlinkSync(srcpath, dstpath, type)
-}
-
-module.exports = {
- createSymlink: u(createSymlink),
- createSymlinkSync
-}
+/* globals AbortController */
-/***/ }),
-/***/ 61176:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923)
+const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349)
+const { FinalizationRegistry } = __nccwpck_require__(3194)()
+const util = __nccwpck_require__(3440)
+const {
+ isValidHTTPToken,
+ sameOrigin,
+ normalizeMethod,
+ makePolicyContainer
+} = __nccwpck_require__(5523)
+const {
+ forbiddenMethods,
+ corsSafeListedMethods,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+} = __nccwpck_require__(7326)
+const { kEnumerableProperty } = util
+const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710)
+const { webidl } = __nccwpck_require__(4222)
+const { getGlobalOrigin } = __nccwpck_require__(5628)
+const { URLSerializer } = __nccwpck_require__(4322)
+const { kHeadersList } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(2613)
+const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434)
-"use strict";
-
-// This is adapted from https://github.com/normalize/mz
-// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
-const u = (__nccwpck_require__(9046).fromCallback)
-const fs = __nccwpck_require__(14178)
-
-const api = [
- 'access',
- 'appendFile',
- 'chmod',
- 'chown',
- 'close',
- 'copyFile',
- 'fchmod',
- 'fchown',
- 'fdatasync',
- 'fstat',
- 'fsync',
- 'ftruncate',
- 'futimes',
- 'lchmod',
- 'lchown',
- 'link',
- 'lstat',
- 'mkdir',
- 'mkdtemp',
- 'open',
- 'opendir',
- 'readdir',
- 'readFile',
- 'readlink',
- 'realpath',
- 'rename',
- 'rm',
- 'rmdir',
- 'stat',
- 'symlink',
- 'truncate',
- 'unlink',
- 'utimes',
- 'writeFile'
-].filter(key => {
- // Some commands are not available on some systems. Ex:
- // fs.opendir was added in Node.js v12.12.0
- // fs.rm was added in Node.js v14.14.0
- // fs.lchown is not available on at least some Linux
- return typeof fs[key] === 'function'
-})
+let TransformStream = globalThis.TransformStream
-// Export all keys:
-Object.keys(fs).forEach(key => {
- if (key === 'promises') {
- // fs.promises is a getter property that triggers ExperimentalWarning
- // Don't re-export it here, the getter is defined in "lib/index.js"
- return
- }
- exports[key] = fs[key]
-})
+const kInit = Symbol('init')
+const kAbortController = Symbol('abortController')
-// Universalify async methods:
-api.forEach(method => {
- exports[method] = u(fs[method])
+const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener('abort', abort)
})
-// We differ from mz/fs in that we still ship the old, broken, fs.exists()
-// since we are a drop-in replacement for the native module
-exports.exists = function (filename, callback) {
- if (typeof callback === 'function') {
- return fs.exists(filename, callback)
- }
- return new Promise(resolve => {
- return fs.exists(filename, resolve)
- })
-}
-
-// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args
-
-exports.read = function (fd, buffer, offset, length, position, callback) {
- if (typeof callback === 'function') {
- return fs.read(fd, buffer, offset, length, position, callback)
- }
- return new Promise((resolve, reject) => {
- fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
- if (err) return reject(err)
- resolve({ bytesRead, buffer })
- })
- })
-}
-
-// Function signature can be
-// fs.write(fd, buffer[, offset[, length[, position]]], callback)
-// OR
-// fs.write(fd, string[, position[, encoding]], callback)
-// We need to handle both cases, so we use ...args
-exports.write = function (fd, buffer, ...args) {
- if (typeof args[args.length - 1] === 'function') {
- return fs.write(fd, buffer, ...args)
- }
-
- return new Promise((resolve, reject) => {
- fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
- if (err) return reject(err)
- resolve({ bytesWritten, buffer })
- })
- })
-}
-
-// fs.writev only available in Node v12.9.0+
-if (typeof fs.writev === 'function') {
- // Function signature is
- // s.writev(fd, buffers[, position], callback)
- // We need to handle the optional arg, so we use ...args
- exports.writev = function (fd, buffers, ...args) {
- if (typeof args[args.length - 1] === 'function') {
- return fs.writev(fd, buffers, ...args)
+// https://fetch.spec.whatwg.org/#request-class
+class Request {
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor (input, init = {}) {
+ if (input === kInit) {
+ return
}
- return new Promise((resolve, reject) => {
- fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
- if (err) return reject(err)
- resolve({ bytesWritten, buffers })
- })
- })
- }
-}
-
-// fs.realpath.native only available in Node v9.2+
-if (typeof fs.realpath.native === 'function') {
- exports.realpath.native = u(fs.realpath.native)
-}
-
-
-/***/ }),
-
-/***/ 5630:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-module.exports = {
- // Export promiseified graceful-fs:
- ...__nccwpck_require__(61176),
- // Export extra methods:
- ...__nccwpck_require__(11135),
- ...__nccwpck_require__(61335),
- ...__nccwpck_require__(96970),
- ...__nccwpck_require__(40055),
- ...__nccwpck_require__(40213),
- ...__nccwpck_require__(98605),
- ...__nccwpck_require__(69665),
- ...__nccwpck_require__(41497),
- ...__nccwpck_require__(16570),
- ...__nccwpck_require__(43835),
- ...__nccwpck_require__(47357)
-}
-
-// Export fs.promises as a getter property so that we don't trigger
-// ExperimentalWarning before fs.promises is actually accessed.
-const fs = __nccwpck_require__(57147)
-if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
- Object.defineProperty(module.exports, "promises", ({
- get () { return fs.promises }
- }))
-}
-
-
-/***/ }),
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
-/***/ 40213:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ input = webidl.converters.RequestInfo(input)
+ init = webidl.converters.RequestInit(init)
-"use strict";
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
+ this[kRealm] = {
+ settingsObject: {
+ baseUrl: getGlobalOrigin(),
+ get origin () {
+ return this.baseUrl?.origin
+ },
+ policyContainer: makePolicyContainer()
+ }
+ }
+ // 1. Let request be null.
+ let request = null
-const u = (__nccwpck_require__(9046).fromPromise)
-const jsonFile = __nccwpck_require__(18970)
+ // 2. Let fallbackMode be null.
+ let fallbackMode = null
-jsonFile.outputJson = u(__nccwpck_require__(60531))
-jsonFile.outputJsonSync = __nccwpck_require__(19421)
-// aliases
-jsonFile.outputJSON = jsonFile.outputJson
-jsonFile.outputJSONSync = jsonFile.outputJsonSync
-jsonFile.writeJSON = jsonFile.writeJson
-jsonFile.writeJSONSync = jsonFile.writeJsonSync
-jsonFile.readJSON = jsonFile.readJson
-jsonFile.readJSONSync = jsonFile.readJsonSync
+ // 3. Let baseURL be this’s relevant settings object’s API base URL.
+ const baseUrl = this[kRealm].settingsObject.baseUrl
-module.exports = jsonFile
+ // 4. Let signal be null.
+ let signal = null
+ // 5. If input is a string, then:
+ if (typeof input === 'string') {
+ // 1. Let parsedURL be the result of parsing input with baseURL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsedURL
+ try {
+ parsedURL = new URL(input, baseUrl)
+ } catch (err) {
+ throw new TypeError('Failed to parse URL from ' + input, { cause: err })
+ }
-/***/ }),
+ // 3. If parsedURL includes credentials, then throw a TypeError.
+ if (parsedURL.username || parsedURL.password) {
+ throw new TypeError(
+ 'Request cannot be constructed from a URL that includes credentials: ' +
+ input
+ )
+ }
-/***/ 18970:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Set request to a new request whose URL is parsedURL.
+ request = makeRequest({ urlList: [parsedURL] })
-"use strict";
+ // 5. Set fallbackMode to "cors".
+ fallbackMode = 'cors'
+ } else {
+ // 6. Otherwise:
+ // 7. Assert: input is a Request object.
+ assert(input instanceof Request)
-const jsonFile = __nccwpck_require__(26160)
+ // 8. Set request to input’s request.
+ request = input[kState]
-module.exports = {
- // jsonfile exports
- readJson: jsonFile.readFile,
- readJsonSync: jsonFile.readFileSync,
- writeJson: jsonFile.writeFile,
- writeJsonSync: jsonFile.writeFileSync
-}
+ // 9. Set signal to input’s signal.
+ signal = input[kSignal]
+ }
+ // 7. Let origin be this’s relevant settings object’s origin.
+ const origin = this[kRealm].settingsObject.origin
-/***/ }),
+ // 8. Let window be "client".
+ let window = 'client'
-/***/ 19421:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 9. If request’s window is an environment settings object and its origin
+ // is same origin with origin, then set window to request’s window.
+ if (
+ request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
+ sameOrigin(request.window, origin)
+ ) {
+ window = request.window
+ }
-"use strict";
+ // 10. If init["window"] exists and is non-null, then throw a TypeError.
+ if (init.window != null) {
+ throw new TypeError(`'window' option '${window}' must be null`)
+ }
+ // 11. If init["window"] exists, then set window to "no-window".
+ if ('window' in init) {
+ window = 'no-window'
+ }
-const { stringify } = __nccwpck_require__(35902)
-const { outputFileSync } = __nccwpck_require__(16570)
+ // 12. Set request to a new request with the following properties:
+ request = makeRequest({
+ // URL request’s URL.
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
+ // method request’s method.
+ method: request.method,
+ // header list A copy of request’s header list.
+ // undici implementation note: headersList is cloned in makeRequest
+ headersList: request.headersList,
+ // unsafe-request flag Set.
+ unsafeRequest: request.unsafeRequest,
+ // client This’s relevant settings object.
+ client: this[kRealm].settingsObject,
+ // window window.
+ window,
+ // priority request’s priority.
+ priority: request.priority,
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
+ // being handled by a service worker. In this scenario a request can have an origin that is different
+ // from the current client.
+ origin: request.origin,
+ // referrer request’s referrer.
+ referrer: request.referrer,
+ // referrer policy request’s referrer policy.
+ referrerPolicy: request.referrerPolicy,
+ // mode request’s mode.
+ mode: request.mode,
+ // credentials mode request’s credentials mode.
+ credentials: request.credentials,
+ // cache mode request’s cache mode.
+ cache: request.cache,
+ // redirect mode request’s redirect mode.
+ redirect: request.redirect,
+ // integrity metadata request’s integrity metadata.
+ integrity: request.integrity,
+ // keepalive request’s keepalive.
+ keepalive: request.keepalive,
+ // reload-navigation flag request’s reload-navigation flag.
+ reloadNavigation: request.reloadNavigation,
+ // history-navigation flag request’s history-navigation flag.
+ historyNavigation: request.historyNavigation,
+ // URL list A clone of request’s URL list.
+ urlList: [...request.urlList]
+ })
-function outputJsonSync (file, data, options) {
- const str = stringify(data, options)
+ // 13. If init is not empty, then:
+ if (Object.keys(init).length > 0) {
+ // 1. If request’s mode is "navigate", then set it to "same-origin".
+ if (request.mode === 'navigate') {
+ request.mode = 'same-origin'
+ }
- outputFileSync(file, str, options)
-}
+ // 2. Unset request’s reload-navigation flag.
+ request.reloadNavigation = false
-module.exports = outputJsonSync
+ // 3. Unset request’s history-navigation flag.
+ request.historyNavigation = false
+ // 4. Set request’s origin to "client".
+ request.origin = 'client'
-/***/ }),
+ // 5. Set request’s referrer to "client"
+ request.referrer = 'client'
-/***/ 60531:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 6. Set request’s referrer policy to the empty string.
+ request.referrerPolicy = ''
-"use strict";
+ // 7. Set request’s URL to request’s current URL.
+ request.url = request.urlList[request.urlList.length - 1]
+ // 8. Set request’s URL list to « request’s URL ».
+ request.urlList = [request.url]
+ }
-const { stringify } = __nccwpck_require__(35902)
-const { outputFile } = __nccwpck_require__(16570)
+ // 14. If init["referrer"] exists, then:
+ if (init.referrer !== undefined) {
+ // 1. Let referrer be init["referrer"].
+ const referrer = init.referrer
-async function outputJson (file, data, options = {}) {
- const str = stringify(data, options)
+ // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
+ if (referrer === '') {
+ request.referrer = 'no-referrer'
+ } else {
+ // 1. Let parsedReferrer be the result of parsing referrer with
+ // baseURL.
+ // 2. If parsedReferrer is failure, then throw a TypeError.
+ let parsedReferrer
+ try {
+ parsedReferrer = new URL(referrer, baseUrl)
+ } catch (err) {
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
+ }
- await outputFile(file, str, options)
-}
+ // 3. If one of the following is true
+ // - parsedReferrer’s scheme is "about" and path is the string "client"
+ // - parsedReferrer’s origin is not same origin with origin
+ // then set request’s referrer to "client".
+ if (
+ (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
+ (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
+ ) {
+ request.referrer = 'client'
+ } else {
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
+ request.referrer = parsedReferrer
+ }
+ }
+ }
-module.exports = outputJson
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
+ // to it.
+ if (init.referrerPolicy !== undefined) {
+ request.referrerPolicy = init.referrerPolicy
+ }
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
+ let mode
+ if (init.mode !== undefined) {
+ mode = init.mode
+ } else {
+ mode = fallbackMode
+ }
-/***/ }),
+ // 17. If mode is "navigate", then throw a TypeError.
+ if (mode === 'navigate') {
+ throw webidl.errors.exception({
+ header: 'Request constructor',
+ message: 'invalid request mode navigate.'
+ })
+ }
-/***/ 98605:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 18. If mode is non-null, set request’s mode to mode.
+ if (mode != null) {
+ request.mode = mode
+ }
-"use strict";
+ // 19. If init["credentials"] exists, then set request’s credentials mode
+ // to it.
+ if (init.credentials !== undefined) {
+ request.credentials = init.credentials
+ }
-const u = (__nccwpck_require__(9046).fromPromise)
-const { makeDir: _makeDir, makeDirSync } = __nccwpck_require__(52751)
-const makeDir = u(_makeDir)
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
+ if (init.cache !== undefined) {
+ request.cache = init.cache
+ }
-module.exports = {
- mkdirs: makeDir,
- mkdirsSync: makeDirSync,
- // alias
- mkdirp: makeDir,
- mkdirpSync: makeDirSync,
- ensureDir: makeDir,
- ensureDirSync: makeDirSync
-}
+ // 21. If request’s cache mode is "only-if-cached" and request’s mode is
+ // not "same-origin", then throw a TypeError.
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ throw new TypeError(
+ "'only-if-cached' can be set only with 'same-origin' mode"
+ )
+ }
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
+ if (init.redirect !== undefined) {
+ request.redirect = init.redirect
+ }
-/***/ }),
+ // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
+ if (init.integrity !== undefined && init.integrity != null) {
+ request.integrity = String(init.integrity)
+ }
-/***/ 52751:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 24. If init["keepalive"] exists, then set request’s keepalive to it.
+ if (init.keepalive !== undefined) {
+ request.keepalive = Boolean(init.keepalive)
+ }
-"use strict";
-// Adapted from https://github.com/sindresorhus/make-dir
-// Copyright (c) Sindre Sorhus (sindresorhus.com)
-// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ // 25. If init["method"] exists, then:
+ if (init.method !== undefined) {
+ // 1. Let method be init["method"].
+ let method = init.method
-const fs = __nccwpck_require__(61176)
-const path = __nccwpck_require__(71017)
-const atLeastNode = __nccwpck_require__(25995)
+ // 2. If method is not a method or method is a forbidden method, then
+ // throw a TypeError.
+ if (!isValidHTTPToken(init.method)) {
+ throw TypeError(`'${init.method}' is not a valid HTTP method.`)
+ }
-const useNativeRecursiveOption = atLeastNode('10.12.0')
+ if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) {
+ throw TypeError(`'${init.method}' HTTP method is unsupported.`)
+ }
-// https://github.com/nodejs/node/issues/8987
-// https://github.com/libuv/libuv/pull/1088
-const checkPath = pth => {
- if (process.platform === 'win32') {
- const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
+ // 3. Normalize method.
+ method = normalizeMethod(init.method)
- if (pathHasInvalidWinCharacters) {
- const error = new Error(`Path contains invalid characters: ${pth}`)
- error.code = 'EINVAL'
- throw error
+ // 4. Set request’s method to method.
+ request.method = method
}
- }
-}
-
-const processOptions = options => {
- const defaults = { mode: 0o777 }
- if (typeof options === 'number') options = { mode: options }
- return { ...defaults, ...options }
-}
-
-const permissionError = pth => {
- // This replicates the exception of `fs.mkdir` with native the
- // `recusive` option when run on an invalid drive under Windows.
- const error = new Error(`operation not permitted, mkdir '${pth}'`)
- error.code = 'EPERM'
- error.errno = -4048
- error.path = pth
- error.syscall = 'mkdir'
- return error
-}
-module.exports.makeDir = async (input, options) => {
- checkPath(input)
- options = processOptions(options)
+ // 26. If init["signal"] exists, then set signal to it.
+ if (init.signal !== undefined) {
+ signal = init.signal
+ }
- if (useNativeRecursiveOption) {
- const pth = path.resolve(input)
+ // 27. Set this’s request to request.
+ this[kState] = request
- return fs.mkdir(pth, {
- mode: options.mode,
- recursive: true
- })
- }
+ // 28. Set this’s signal to a new AbortSignal object with this’s relevant
+ // Realm.
+ // TODO: could this be simplified with AbortSignal.any
+ // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
+ const ac = new AbortController()
+ this[kSignal] = ac.signal
+ this[kSignal][kRealm] = this[kRealm]
- const make = async pth => {
- try {
- await fs.mkdir(pth, options.mode)
- } catch (error) {
- if (error.code === 'EPERM') {
- throw error
+ // 29. If signal is not null, then make this’s signal follow signal.
+ if (signal != null) {
+ if (
+ !signal ||
+ typeof signal.aborted !== 'boolean' ||
+ typeof signal.addEventListener !== 'function'
+ ) {
+ throw new TypeError(
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
+ )
}
- if (error.code === 'ENOENT') {
- if (path.dirname(pth) === pth) {
- throw permissionError(pth)
- }
+ if (signal.aborted) {
+ ac.abort(signal.reason)
+ } else {
+ // Keep a strong ref to ac while request object
+ // is alive. This is needed to prevent AbortController
+ // from being prematurely garbage collected.
+ // See, https://github.com/nodejs/undici/issues/1926.
+ this[kAbortController] = ac
- if (error.message.includes('null bytes')) {
- throw error
+ const acRef = new WeakRef(ac)
+ const abort = function () {
+ const ac = acRef.deref()
+ if (ac !== undefined) {
+ ac.abort(this.reason)
+ }
}
- await make(path.dirname(pth))
- return make(pth)
- }
+ // Third-party AbortControllers may not work with these.
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
+ try {
+ // If the max amount of listeners is equal to the default, increase it
+ // This is only available in node >= v19.9.0
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ }
+ } catch {}
- try {
- const stats = await fs.stat(pth)
- if (!stats.isDirectory()) {
- // This error is never exposed to the user
- // it is caught below, and the original error is thrown
- throw new Error('The path is not a directory')
- }
- } catch {
- throw error
+ util.addAbortListener(signal, abort)
+ requestFinalizer.register(ac, { signal, abort })
}
}
- }
-
- return make(path.resolve(input))
-}
-module.exports.makeDirSync = (input, options) => {
- checkPath(input)
- options = processOptions(options)
-
- if (useNativeRecursiveOption) {
- const pth = path.resolve(input)
-
- return fs.mkdirSync(pth, {
- mode: options.mode,
- recursive: true
- })
- }
+ // 30. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is request’s header list and guard is
+ // "request".
+ this[kHeaders] = new Headers()
+ this[kHeaders][kHeadersList] = request.headersList
+ this[kHeaders][kGuard] = 'request'
+ this[kHeaders][kRealm] = this[kRealm]
- const make = pth => {
- try {
- fs.mkdirSync(pth, options.mode)
- } catch (error) {
- if (error.code === 'EPERM') {
- throw error
+ // 31. If this’s request’s mode is "no-cors", then:
+ if (mode === 'no-cors') {
+ // 1. If this’s request’s method is not a CORS-safelisted method,
+ // then throw a TypeError.
+ if (!corsSafeListedMethods.includes(request.method)) {
+ throw new TypeError(
+ `'${request.method} is unsupported in no-cors mode.`
+ )
}
- if (error.code === 'ENOENT') {
- if (path.dirname(pth) === pth) {
- throw permissionError(pth)
- }
+ // 2. Set this’s headers’s guard to "request-no-cors".
+ this[kHeaders][kGuard] = 'request-no-cors'
+ }
- if (error.message.includes('null bytes')) {
- throw error
- }
+ // 32. If init is not empty, then:
+ if (Object.keys(init).length !== 0) {
+ // 1. Let headers be a copy of this’s headers and its associated header
+ // list.
+ let headers = new Headers(this[kHeaders])
- make(path.dirname(pth))
- return make(pth)
+ // 2. If init["headers"] exists, then set headers to init["headers"].
+ if (init.headers !== undefined) {
+ headers = init.headers
}
- try {
- if (!fs.statSync(pth).isDirectory()) {
- // This error is never exposed to the user
- // it is caught below, and the original error is thrown
- throw new Error('The path is not a directory')
+ // 3. Empty this’s headers’s header list.
+ this[kHeaders][kHeadersList].clear()
+
+ // 4. If headers is a Headers object, then for each header in its header
+ // list, append header’s name/header’s value to this’s headers.
+ if (headers.constructor.name === 'Headers') {
+ for (const [key, val] of headers) {
+ this[kHeaders].append(key, val)
}
- } catch {
- throw error
+ } else {
+ // 5. Otherwise, fill this’s headers with headers.
+ fillHeaders(this[kHeaders], headers)
}
}
- }
- return make(path.resolve(input))
-}
+ // 33. Let inputBody be input’s request’s body if input is a Request
+ // object; otherwise null.
+ const inputBody = input instanceof Request ? input[kState].body : null
+ // 34. If either init["body"] exists and is non-null or inputBody is
+ // non-null, and request’s method is `GET` or `HEAD`, then throw a
+ // TypeError.
+ if (
+ (init.body != null || inputBody != null) &&
+ (request.method === 'GET' || request.method === 'HEAD')
+ ) {
+ throw new TypeError('Request with GET/HEAD method cannot have body.')
+ }
-/***/ }),
-
-/***/ 69665:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+ // 35. Let initBody be null.
+ let initBody = null
+ // 36. If init["body"] exists and is non-null, then:
+ if (init.body != null) {
+ // 1. Let Content-Type be null.
+ // 2. Set initBody and Content-Type to the result of extracting
+ // init["body"], with keepalive set to request’s keepalive.
+ const [extractedBody, contentType] = extractBody(
+ init.body,
+ request.keepalive
+ )
+ initBody = extractedBody
-module.exports = {
- moveSync: __nccwpck_require__(96445)
-}
+ // 3, If Content-Type is non-null and this’s headers’s header list does
+ // not contain `Content-Type`, then append `Content-Type`/Content-Type to
+ // this’s headers.
+ if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
+ this[kHeaders].append('content-type', contentType)
+ }
+ }
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
+ // inputBody.
+ const inputOrInitBody = initBody ?? inputBody
-/***/ }),
+ // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
+ // null, then:
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
+ // 1. If initBody is non-null and init["duplex"] does not exist,
+ // then throw a TypeError.
+ if (initBody != null && init.duplex == null) {
+ throw new TypeError('RequestInit: duplex option is required when sending a body.')
+ }
-/***/ 96445:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If this’s request’s mode is neither "same-origin" nor "cors",
+ // then throw a TypeError.
+ if (request.mode !== 'same-origin' && request.mode !== 'cors') {
+ throw new TypeError(
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
+ )
+ }
-"use strict";
+ // 3. Set this’s request’s use-CORS-preflight flag.
+ request.useCORSPreflightFlag = true
+ }
+ // 39. Let finalBody be inputOrInitBody.
+ let finalBody = inputOrInitBody
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const copySync = (__nccwpck_require__(11135).copySync)
-const removeSync = (__nccwpck_require__(47357).removeSync)
-const mkdirpSync = (__nccwpck_require__(98605).mkdirpSync)
-const stat = __nccwpck_require__(73901)
+ // 40. If initBody is null and inputBody is non-null, then:
+ if (initBody == null && inputBody != null) {
+ // 1. If input is unusable, then throw a TypeError.
+ if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
+ throw new TypeError(
+ 'Cannot construct a Request with a Request object that has already been used.'
+ )
+ }
-function moveSync (src, dest, opts) {
- opts = opts || {}
- const overwrite = opts.overwrite || opts.clobber || false
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
+ if (!TransformStream) {
+ TransformStream = (__nccwpck_require__(3774).TransformStream)
+ }
- const { srcStat } = stat.checkPathsSync(src, dest, 'move')
- stat.checkParentPathsSync(src, srcStat, dest, 'move')
- mkdirpSync(path.dirname(dest))
- return doRename(src, dest, overwrite)
-}
+ // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
+ const identityTransform = new TransformStream()
+ inputBody.stream.pipeThrough(identityTransform)
+ finalBody = {
+ source: inputBody.source,
+ length: inputBody.length,
+ stream: identityTransform.readable
+ }
+ }
-function doRename (src, dest, overwrite) {
- if (overwrite) {
- removeSync(dest)
- return rename(src, dest, overwrite)
+ // 41. Set this’s request’s body to finalBody.
+ this[kState].body = finalBody
}
- if (fs.existsSync(dest)) throw new Error('dest already exists.')
- return rename(src, dest, overwrite)
-}
-function rename (src, dest, overwrite) {
- try {
- fs.renameSync(src, dest)
- } catch (err) {
- if (err.code !== 'EXDEV') throw err
- return moveAcrossDevice(src, dest, overwrite)
- }
-}
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method () {
+ webidl.brandCheck(this, Request)
-function moveAcrossDevice (src, dest, overwrite) {
- const opts = {
- overwrite,
- errorOnExist: true
+ // The method getter steps are to return this’s request’s method.
+ return this[kState].method
}
- copySync(src, dest, opts)
- return removeSync(src)
-}
-
-module.exports = moveSync
-
-
-/***/ }),
-
-/***/ 41497:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const u = (__nccwpck_require__(9046).fromCallback)
-module.exports = {
- move: u(__nccwpck_require__(72231))
-}
-
-/***/ }),
-
-/***/ 72231:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const copy = (__nccwpck_require__(61335).copy)
-const remove = (__nccwpck_require__(47357).remove)
-const mkdirp = (__nccwpck_require__(98605).mkdirp)
-const pathExists = (__nccwpck_require__(43835).pathExists)
-const stat = __nccwpck_require__(73901)
+ // Returns the URL of request as a string.
+ get url () {
+ webidl.brandCheck(this, Request)
-function move (src, dest, opts, cb) {
- if (typeof opts === 'function') {
- cb = opts
- opts = {}
+ // The url getter steps are to return this’s request’s URL, serialized.
+ return URLSerializer(this[kState].url)
}
- const overwrite = opts.overwrite || opts.clobber || false
-
- stat.checkPaths(src, dest, 'move', (err, stats) => {
- if (err) return cb(err)
- const { srcStat } = stats
- stat.checkParentPaths(src, srcStat, dest, 'move', err => {
- if (err) return cb(err)
- mkdirp(path.dirname(dest), err => {
- if (err) return cb(err)
- return doRename(src, dest, overwrite, cb)
- })
- })
- })
-}
+ // Returns a Headers object consisting of the headers associated with request.
+ // Note that headers added in the network layer by the user agent will not
+ // be accounted for in this object, e.g., the "Host" header.
+ get headers () {
+ webidl.brandCheck(this, Request)
-function doRename (src, dest, overwrite, cb) {
- if (overwrite) {
- return remove(dest, err => {
- if (err) return cb(err)
- return rename(src, dest, overwrite, cb)
- })
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
- pathExists(dest, (err, destExists) => {
- if (err) return cb(err)
- if (destExists) return cb(new Error('dest already exists.'))
- return rename(src, dest, overwrite, cb)
- })
-}
-function rename (src, dest, overwrite, cb) {
- fs.rename(src, dest, err => {
- if (!err) return cb()
- if (err.code !== 'EXDEV') return cb(err)
- return moveAcrossDevice(src, dest, overwrite, cb)
- })
-}
+ // Returns the kind of resource requested by request, e.g., "document"
+ // or "script".
+ get destination () {
+ webidl.brandCheck(this, Request)
-function moveAcrossDevice (src, dest, overwrite, cb) {
- const opts = {
- overwrite,
- errorOnExist: true
+ // The destination getter are to return this’s request’s destination.
+ return this[kState].destination
}
- copy(src, dest, opts, err => {
- if (err) return cb(err)
- return remove(src, cb)
- })
-}
-
-module.exports = move
-
-
-/***/ }),
-/***/ 16570:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+ // Returns the referrer of request. Its value can be a same-origin URL if
+ // explicitly set in init, the empty string to indicate no referrer, and
+ // "about:client" when defaulting to the global’s default. This is used
+ // during fetching to determine the value of the `Referer` header of the
+ // request being made.
+ get referrer () {
+ webidl.brandCheck(this, Request)
+ // 1. If this’s request’s referrer is "no-referrer", then return the
+ // empty string.
+ if (this[kState].referrer === 'no-referrer') {
+ return ''
+ }
-const u = (__nccwpck_require__(9046).fromCallback)
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const mkdir = __nccwpck_require__(98605)
-const pathExists = (__nccwpck_require__(43835).pathExists)
+ // 2. If this’s request’s referrer is "client", then return
+ // "about:client".
+ if (this[kState].referrer === 'client') {
+ return 'about:client'
+ }
-function outputFile (file, data, encoding, callback) {
- if (typeof encoding === 'function') {
- callback = encoding
- encoding = 'utf8'
+ // Return this’s request’s referrer, serialized.
+ return this[kState].referrer.toString()
}
- const dir = path.dirname(file)
- pathExists(dir, (err, itDoes) => {
- if (err) return callback(err)
- if (itDoes) return fs.writeFile(file, data, encoding, callback)
-
- mkdir.mkdirs(dir, err => {
- if (err) return callback(err)
-
- fs.writeFile(file, data, encoding, callback)
- })
- })
-}
+ // Returns the referrer policy associated with request.
+ // This is used during fetching to compute the value of the request’s
+ // referrer.
+ get referrerPolicy () {
+ webidl.brandCheck(this, Request)
-function outputFileSync (file, ...args) {
- const dir = path.dirname(file)
- if (fs.existsSync(dir)) {
- return fs.writeFileSync(file, ...args)
+ // The referrerPolicy getter steps are to return this’s request’s referrer policy.
+ return this[kState].referrerPolicy
}
- mkdir.mkdirsSync(dir)
- fs.writeFileSync(file, ...args)
-}
-
-module.exports = {
- outputFile: u(outputFile),
- outputFileSync
-}
-
-
-/***/ }),
-
-/***/ 43835:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-const u = (__nccwpck_require__(9046).fromPromise)
-const fs = __nccwpck_require__(61176)
-
-function pathExists (path) {
- return fs.access(path).then(() => true).catch(() => false)
-}
-
-module.exports = {
- pathExists: u(pathExists),
- pathExistsSync: fs.existsSync
-}
-
-
-/***/ }),
-
-/***/ 47357:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const u = (__nccwpck_require__(9046).fromCallback)
-const rimraf = __nccwpck_require__(38761)
-
-module.exports = {
- remove: u(rimraf),
- removeSync: rimraf.sync
-}
-
-
-/***/ }),
-
-/***/ 38761:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+ // Returns the mode associated with request, which is a string indicating
+ // whether the request will use CORS, or will be restricted to same-origin
+ // URLs.
+ get mode () {
+ webidl.brandCheck(this, Request)
-const fs = __nccwpck_require__(14178)
-const path = __nccwpck_require__(71017)
-const assert = __nccwpck_require__(39491)
+ // The mode getter steps are to return this’s request’s mode.
+ return this[kState].mode
+ }
-const isWindows = (process.platform === 'win32')
+ // Returns the credentials mode associated with request,
+ // which is a string indicating whether credentials will be sent with the
+ // request always, never, or only when sent to a same-origin URL.
+ get credentials () {
+ // The credentials getter steps are to return this’s request’s credentials mode.
+ return this[kState].credentials
+ }
-function defaults (options) {
- const methods = [
- 'unlink',
- 'chmod',
- 'stat',
- 'lstat',
- 'rmdir',
- 'readdir'
- ]
- methods.forEach(m => {
- options[m] = options[m] || fs[m]
- m = m + 'Sync'
- options[m] = options[m] || fs[m]
- })
+ // Returns the cache mode associated with request,
+ // which is a string indicating how the request will
+ // interact with the browser’s cache when fetching.
+ get cache () {
+ webidl.brandCheck(this, Request)
- options.maxBusyTries = options.maxBusyTries || 3
-}
+ // The cache getter steps are to return this’s request’s cache mode.
+ return this[kState].cache
+ }
-function rimraf (p, options, cb) {
- let busyTries = 0
+ // Returns the redirect mode associated with request,
+ // which is a string indicating how redirects for the
+ // request will be handled during fetching. A request
+ // will follow redirects by default.
+ get redirect () {
+ webidl.brandCheck(this, Request)
- if (typeof options === 'function') {
- cb = options
- options = {}
+ // The redirect getter steps are to return this’s request’s redirect mode.
+ return this[kState].redirect
}
- assert(p, 'rimraf: missing path')
- assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
- assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required')
- assert(options, 'rimraf: invalid options argument provided')
- assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
-
- defaults(options)
+ // Returns request’s subresource integrity metadata, which is a
+ // cryptographic hash of the resource being fetched. Its value
+ // consists of multiple hashes separated by whitespace. [SRI]
+ get integrity () {
+ webidl.brandCheck(this, Request)
- rimraf_(p, options, function CB (er) {
- if (er) {
- if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
- busyTries < options.maxBusyTries) {
- busyTries++
- const time = busyTries * 100
- // try again, with the same exact callback as this one.
- return setTimeout(() => rimraf_(p, options, CB), time)
- }
+ // The integrity getter steps are to return this’s request’s integrity
+ // metadata.
+ return this[kState].integrity
+ }
- // already gone
- if (er.code === 'ENOENT') er = null
- }
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive () {
+ webidl.brandCheck(this, Request)
- cb(er)
- })
-}
+ // The keepalive getter steps are to return this’s request’s keepalive.
+ return this[kState].keepalive
+ }
-// Two possible strategies.
-// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
-// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
-//
-// Both result in an extra syscall when you guess wrong. However, there
-// are likely far more normal files in the world than directories. This
-// is based on the assumption that a the average number of files per
-// directory is >= 1.
-//
-// If anyone ever complains about this, then I guess the strategy could
-// be made configurable somehow. But until then, YAGNI.
-function rimraf_ (p, options, cb) {
- assert(p)
- assert(options)
- assert(typeof cb === 'function')
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation () {
+ webidl.brandCheck(this, Request)
- // sunos lets the root user unlink directories, which is... weird.
- // so we have to lstat here and make sure it's not a dir.
- options.lstat(p, (er, st) => {
- if (er && er.code === 'ENOENT') {
- return cb(null)
- }
+ // The isReloadNavigation getter steps are to return true if this’s
+ // request’s reload-navigation flag is set; otherwise false.
+ return this[kState].reloadNavigation
+ }
- // Windows can EPERM on stat. Life is suffering.
- if (er && er.code === 'EPERM' && isWindows) {
- return fixWinEPERM(p, options, er, cb)
- }
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-foward navigation).
+ get isHistoryNavigation () {
+ webidl.brandCheck(this, Request)
- if (st && st.isDirectory()) {
- return rmdir(p, options, er, cb)
- }
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
+ // history-navigation flag is set; otherwise false.
+ return this[kState].historyNavigation
+ }
- options.unlink(p, er => {
- if (er) {
- if (er.code === 'ENOENT') {
- return cb(null)
- }
- if (er.code === 'EPERM') {
- return (isWindows)
- ? fixWinEPERM(p, options, er, cb)
- : rmdir(p, options, er, cb)
- }
- if (er.code === 'EISDIR') {
- return rmdir(p, options, er, cb)
- }
- }
- return cb(er)
- })
- })
-}
+ // Returns the signal associated with request, which is an AbortSignal
+ // object indicating whether or not request has been aborted, and its
+ // abort event handler.
+ get signal () {
+ webidl.brandCheck(this, Request)
-function fixWinEPERM (p, options, er, cb) {
- assert(p)
- assert(options)
- assert(typeof cb === 'function')
+ // The signal getter steps are to return this’s signal.
+ return this[kSignal]
+ }
- options.chmod(p, 0o666, er2 => {
- if (er2) {
- cb(er2.code === 'ENOENT' ? null : er)
- } else {
- options.stat(p, (er3, stats) => {
- if (er3) {
- cb(er3.code === 'ENOENT' ? null : er)
- } else if (stats.isDirectory()) {
- rmdir(p, options, er, cb)
- } else {
- options.unlink(p, cb)
- }
- })
- }
- })
-}
+ get body () {
+ webidl.brandCheck(this, Request)
-function fixWinEPERMSync (p, options, er) {
- let stats
+ return this[kState].body ? this[kState].body.stream : null
+ }
- assert(p)
- assert(options)
+ get bodyUsed () {
+ webidl.brandCheck(this, Request)
- try {
- options.chmodSync(p, 0o666)
- } catch (er2) {
- if (er2.code === 'ENOENT') {
- return
- } else {
- throw er
- }
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
- try {
- stats = options.statSync(p)
- } catch (er3) {
- if (er3.code === 'ENOENT') {
- return
- } else {
- throw er
- }
- }
+ get duplex () {
+ webidl.brandCheck(this, Request)
- if (stats.isDirectory()) {
- rmdirSync(p, options, er)
- } else {
- options.unlinkSync(p)
+ return 'half'
}
-}
-function rmdir (p, options, originalEr, cb) {
- assert(p)
- assert(options)
- assert(typeof cb === 'function')
+ // Returns a clone of request.
+ clone () {
+ webidl.brandCheck(this, Request)
- // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
- // if we guessed wrong, and it's not a directory, then
- // raise the original error.
- options.rmdir(p, er => {
- if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
- rmkids(p, options, cb)
- } else if (er && er.code === 'ENOTDIR') {
- cb(originalEr)
- } else {
- cb(er)
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || this.body?.locked) {
+ throw new TypeError('unusable')
}
- })
-}
-
-function rmkids (p, options, cb) {
- assert(p)
- assert(options)
- assert(typeof cb === 'function')
-
- options.readdir(p, (er, files) => {
- if (er) return cb(er)
- let n = files.length
- let errState
+ // 2. Let clonedRequest be the result of cloning this’s request.
+ const clonedRequest = cloneRequest(this[kState])
- if (n === 0) return options.rmdir(p, cb)
+ // 3. Let clonedRequestObject be the result of creating a Request object,
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
+ const clonedRequestObject = new Request(kInit)
+ clonedRequestObject[kState] = clonedRequest
+ clonedRequestObject[kRealm] = this[kRealm]
+ clonedRequestObject[kHeaders] = new Headers()
+ clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
+ clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- files.forEach(f => {
- rimraf(path.join(p, f), options, er => {
- if (errState) {
- return
- }
- if (er) return cb(errState = er)
- if (--n === 0) {
- options.rmdir(p, cb)
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
+ const ac = new AbortController()
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason)
+ } else {
+ util.addAbortListener(
+ this.signal,
+ () => {
+ ac.abort(this.signal.reason)
}
- })
- })
- })
-}
-
-// this looks simpler, and is strictly *faster*, but will
-// tie up the JavaScript thread and fail on excessively
-// deep directory trees.
-function rimrafSync (p, options) {
- let st
-
- options = options || {}
- defaults(options)
-
- assert(p, 'rimraf: missing path')
- assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
- assert(options, 'rimraf: missing options')
- assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
-
- try {
- st = options.lstatSync(p)
- } catch (er) {
- if (er.code === 'ENOENT') {
- return
- }
-
- // Windows can EPERM on stat. Life is suffering.
- if (er.code === 'EPERM' && isWindows) {
- fixWinEPERMSync(p, options, er)
+ )
}
- }
+ clonedRequestObject[kSignal] = ac.signal
- try {
- // sunos lets the root user unlink directories, which is... weird.
- if (st && st.isDirectory()) {
- rmdirSync(p, options, null)
- } else {
- options.unlinkSync(p)
- }
- } catch (er) {
- if (er.code === 'ENOENT') {
- return
- } else if (er.code === 'EPERM') {
- return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
- } else if (er.code !== 'EISDIR') {
- throw er
- }
- rmdirSync(p, options, er)
+ // 4. Return clonedRequestObject.
+ return clonedRequestObject
}
}
-function rmdirSync (p, options, originalEr) {
- assert(p)
- assert(options)
+mixinBody(Request)
- try {
- options.rmdirSync(p)
- } catch (er) {
- if (er.code === 'ENOTDIR') {
- throw originalEr
- } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
- rmkidsSync(p, options)
- } else if (er.code !== 'ENOENT') {
- throw er
- }
- }
-}
-
-function rmkidsSync (p, options) {
- assert(p)
- assert(options)
- options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
-
- if (isWindows) {
- // We only end up here once we got ENOTEMPTY at least once, and
- // at this point, we are guaranteed to have removed all the kids.
- // So, we know that it won't be ENOENT or ENOTDIR or anything else.
- // try really hard to delete stuff on windows, because it has a
- // PROFOUNDLY annoying habit of not closing handles promptly when
- // files are deleted, resulting in spurious ENOTEMPTY errors.
- const startTime = Date.now()
- do {
- try {
- const ret = options.rmdirSync(p, options)
- return ret
- } catch {}
- } while (Date.now() - startTime < 500) // give up after 500ms
- } else {
- const ret = options.rmdirSync(p, options)
- return ret
+function makeRequest (init) {
+ // https://fetch.spec.whatwg.org/#requests
+ const request = {
+ method: 'GET',
+ localURLsOnly: false,
+ unsafeRequest: false,
+ body: null,
+ client: null,
+ reservedClient: null,
+ replacesClientId: '',
+ window: 'client',
+ keepalive: false,
+ serviceWorkers: 'all',
+ initiator: '',
+ destination: '',
+ priority: null,
+ origin: 'client',
+ policyContainer: 'client',
+ referrer: 'client',
+ referrerPolicy: '',
+ mode: 'no-cors',
+ useCORSPreflightFlag: false,
+ credentials: 'same-origin',
+ useCredentials: false,
+ cache: 'default',
+ redirect: 'follow',
+ integrity: '',
+ cryptoGraphicsNonceMetadata: '',
+ parserMetadata: '',
+ reloadNavigation: false,
+ historyNavigation: false,
+ userActivation: false,
+ taintedOrigin: false,
+ redirectCount: 0,
+ responseTainting: 'basic',
+ preventNoCacheCacheControlHeaderModification: false,
+ done: false,
+ timingAllowFailed: false,
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList()
}
+ request.url = request.urlList[0]
+ return request
}
-module.exports = rimraf
-rimraf.sync = rimrafSync
-
-
-/***/ }),
-
-/***/ 73901:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const fs = __nccwpck_require__(61176)
-const path = __nccwpck_require__(71017)
-const util = __nccwpck_require__(73837)
-const atLeastNode = __nccwpck_require__(25995)
-
-const nodeSupportsBigInt = atLeastNode('10.5.0')
-const stat = (file) => nodeSupportsBigInt ? fs.stat(file, { bigint: true }) : fs.stat(file)
-const statSync = (file) => nodeSupportsBigInt ? fs.statSync(file, { bigint: true }) : fs.statSync(file)
+// https://fetch.spec.whatwg.org/#concept-request-clone
+function cloneRequest (request) {
+ // To clone a request request, run these steps:
-function getStats (src, dest) {
- return Promise.all([
- stat(src),
- stat(dest).catch(err => {
- if (err.code === 'ENOENT') return null
- throw err
- })
- ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
-}
+ // 1. Let newRequest be a copy of request, except for its body.
+ const newRequest = makeRequest({ ...request, body: null })
-function getStatsSync (src, dest) {
- let destStat
- const srcStat = statSync(src)
- try {
- destStat = statSync(dest)
- } catch (err) {
- if (err.code === 'ENOENT') return { srcStat, destStat: null }
- throw err
+ // 2. If request’s body is non-null, set newRequest’s body to the
+ // result of cloning request’s body.
+ if (request.body != null) {
+ newRequest.body = cloneBody(request.body)
}
- return { srcStat, destStat }
-}
-function checkPaths (src, dest, funcName, cb) {
- util.callbackify(getStats)(src, dest, (err, stats) => {
- if (err) return cb(err)
- const { srcStat, destStat } = stats
- if (destStat && areIdentical(srcStat, destStat)) {
- return cb(new Error('Source and destination must not be the same.'))
- }
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
- return cb(new Error(errMsg(src, dest, funcName)))
- }
- return cb(null, { srcStat, destStat })
- })
+ // 3. Return newRequest.
+ return newRequest
}
-function checkPathsSync (src, dest, funcName) {
- const { srcStat, destStat } = getStatsSync(src, dest)
- if (destStat && areIdentical(srcStat, destStat)) {
- throw new Error('Source and destination must not be the same.')
- }
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
- throw new Error(errMsg(src, dest, funcName))
+Object.defineProperties(Request.prototype, {
+ method: kEnumerableProperty,
+ url: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ signal: kEnumerableProperty,
+ duplex: kEnumerableProperty,
+ destination: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ isHistoryNavigation: kEnumerableProperty,
+ isReloadNavigation: kEnumerableProperty,
+ keepalive: kEnumerableProperty,
+ integrity: kEnumerableProperty,
+ cache: kEnumerableProperty,
+ credentials: kEnumerableProperty,
+ attribute: kEnumerableProperty,
+ referrerPolicy: kEnumerableProperty,
+ referrer: kEnumerableProperty,
+ mode: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Request',
+ configurable: true
}
- return { srcStat, destStat }
-}
+})
-// recursively check if dest parent is a subdirectory of src.
-// It works for all file types including symlinks since it
-// checks the src and dest inodes. It starts from the deepest
-// parent and stops once it reaches the src parent or the root path.
-function checkParentPaths (src, srcStat, dest, funcName, cb) {
- const srcParent = path.resolve(path.dirname(src))
- const destParent = path.resolve(path.dirname(dest))
- if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
- const callback = (err, destStat) => {
- if (err) {
- if (err.code === 'ENOENT') return cb()
- return cb(err)
- }
- if (areIdentical(srcStat, destStat)) {
- return cb(new Error(errMsg(src, dest, funcName)))
- }
- return checkParentPaths(src, srcStat, destParent, funcName, cb)
- }
- if (nodeSupportsBigInt) fs.stat(destParent, { bigint: true }, callback)
- else fs.stat(destParent, callback)
-}
+webidl.converters.Request = webidl.interfaceConverter(
+ Request
+)
-function checkParentPathsSync (src, srcStat, dest, funcName) {
- const srcParent = path.resolve(path.dirname(src))
- const destParent = path.resolve(path.dirname(dest))
- if (destParent === srcParent || destParent === path.parse(destParent).root) return
- let destStat
- try {
- destStat = statSync(destParent)
- } catch (err) {
- if (err.code === 'ENOENT') return
- throw err
- }
- if (areIdentical(srcStat, destStat)) {
- throw new Error(errMsg(src, dest, funcName))
+// https://fetch.spec.whatwg.org/#requestinfo
+webidl.converters.RequestInfo = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
}
- return checkParentPathsSync(src, srcStat, destParent, funcName)
-}
-function areIdentical (srcStat, destStat) {
- if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) {
- if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) {
- // definitive answer
- return true
- }
- // Use additional heuristics if we can't use 'bigint'.
- // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER
- // See issue 657
- if (destStat.size === srcStat.size &&
- destStat.mode === srcStat.mode &&
- destStat.nlink === srcStat.nlink &&
- destStat.atimeMs === srcStat.atimeMs &&
- destStat.mtimeMs === srcStat.mtimeMs &&
- destStat.ctimeMs === srcStat.ctimeMs &&
- destStat.birthtimeMs === srcStat.birthtimeMs) {
- // heuristic answer
- return true
- }
+ if (V instanceof Request) {
+ return webidl.converters.Request(V)
}
- return false
-}
-// return true if dest is a subdir of src, otherwise false.
-// It only checks the path strings.
-function isSrcSubdir (src, dest) {
- const srcArr = path.resolve(src).split(path.sep).filter(i => i)
- const destArr = path.resolve(dest).split(path.sep).filter(i => i)
- return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
+ return webidl.converters.USVString(V)
}
-function errMsg (src, dest, funcName) {
- return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
-}
+webidl.converters.AbortSignal = webidl.interfaceConverter(
+ AbortSignal
+)
-module.exports = {
- checkPaths,
- checkPathsSync,
- checkParentPaths,
- checkParentPathsSync,
- isSrcSubdir
-}
-
-
-/***/ }),
-
-/***/ 52548:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const fs = __nccwpck_require__(14178)
-
-function utimesMillis (path, atime, mtime, callback) {
- // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
- fs.open(path, 'r+', (err, fd) => {
- if (err) return callback(err)
- fs.futimes(fd, atime, mtime, futimesErr => {
- fs.close(fd, closeErr => {
- if (callback) callback(futimesErr || closeErr)
- })
- })
- })
-}
-
-function utimesMillisSync (path, atime, mtime) {
- const fd = fs.openSync(path, 'r+')
- fs.futimesSync(fd, atime, mtime)
- return fs.closeSync(fd)
-}
+// https://fetch.spec.whatwg.org/#requestinit
+webidl.converters.RequestInit = webidl.dictionaryConverter([
+ {
+ key: 'method',
+ converter: webidl.converters.ByteString
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ },
+ {
+ key: 'body',
+ converter: webidl.nullableConverter(
+ webidl.converters.BodyInit
+ )
+ },
+ {
+ key: 'referrer',
+ converter: webidl.converters.USVString
+ },
+ {
+ key: 'referrerPolicy',
+ converter: webidl.converters.DOMString,
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
+ allowedValues: referrerPolicy
+ },
+ {
+ key: 'mode',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#concept-request-mode
+ allowedValues: requestMode
+ },
+ {
+ key: 'credentials',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcredentials
+ allowedValues: requestCredentials
+ },
+ {
+ key: 'cache',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcache
+ allowedValues: requestCache
+ },
+ {
+ key: 'redirect',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestredirect
+ allowedValues: requestRedirect
+ },
+ {
+ key: 'integrity',
+ converter: webidl.converters.DOMString
+ },
+ {
+ key: 'keepalive',
+ converter: webidl.converters.boolean
+ },
+ {
+ key: 'signal',
+ converter: webidl.nullableConverter(
+ (signal) => webidl.converters.AbortSignal(
+ signal,
+ { strict: false }
+ )
+ )
+ },
+ {
+ key: 'window',
+ converter: webidl.converters.any
+ },
+ {
+ key: 'duplex',
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
+ }
+])
-module.exports = {
- utimesMillis,
- utimesMillisSync
-}
+module.exports = { Request, makeRequest }
/***/ }),
-/***/ 25086:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = clone
+/***/ 8676:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var getPrototypeOf = Object.getPrototypeOf || function (obj) {
- return obj.__proto__
-}
-function clone (obj) {
- if (obj === null || typeof obj !== 'object')
- return obj
- if (obj instanceof Object)
- var copy = { __proto__: getPrototypeOf(obj) }
- else
- var copy = Object.create(null)
+const { Headers, HeadersList, fill } = __nccwpck_require__(6349)
+const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923)
+const util = __nccwpck_require__(3440)
+const { kEnumerableProperty } = util
+const {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isBlobLike,
+ serializeJavascriptValueToJSONString,
+ isErrorLike,
+ isomorphicEncode
+} = __nccwpck_require__(5523)
+const {
+ redirectStatus,
+ nullBodyStatus,
+ DOMException
+} = __nccwpck_require__(7326)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710)
+const { webidl } = __nccwpck_require__(4222)
+const { FormData } = __nccwpck_require__(3073)
+const { getGlobalOrigin } = __nccwpck_require__(5628)
+const { URLSerializer } = __nccwpck_require__(4322)
+const { kHeadersList } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(2613)
+const { types } = __nccwpck_require__(9023)
+
+const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream)
- Object.getOwnPropertyNames(obj).forEach(function (key) {
- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
- })
+// https://fetch.spec.whatwg.org/#response-class
+class Response {
+ // Creates network error Response.
+ static error () {
+ // TODO
+ const relevantRealm = { settingsObject: {} }
- return copy
-}
+ // The static error() method steps are to return the result of creating a
+ // Response object, given a new network error, "immutable", and this’s
+ // relevant Realm.
+ const responseObject = new Response()
+ responseObject[kState] = makeNetworkError()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
+ return responseObject
+ }
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json (data, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
-/***/ }),
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init)
+ }
-/***/ 14178:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
+ const bytes = new TextEncoder('utf-8').encode(
+ serializeJavascriptValueToJSONString(data)
+ )
-var fs = __nccwpck_require__(57147)
-var polyfills = __nccwpck_require__(35027)
-var legacy = __nccwpck_require__(73836)
-var clone = __nccwpck_require__(25086)
+ // 2. Let body be the result of extracting bytes.
+ const body = extractBody(bytes)
-var util = __nccwpck_require__(73837)
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
+ // "response", and this’s relevant Realm.
+ const relevantRealm = { settingsObject: {} }
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'response'
+ responseObject[kHeaders][kRealm] = relevantRealm
-/* istanbul ignore next - node 0.x polyfill */
-var gracefulQueue
-var previousSymbol
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
-/* istanbul ignore else - node 0.x polyfill */
-if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
- gracefulQueue = Symbol.for('graceful-fs.queue')
- // This is used in testing by future versions
- previousSymbol = Symbol.for('graceful-fs.previous')
-} else {
- gracefulQueue = '___graceful-fs.queue'
- previousSymbol = '___graceful-fs.previous'
-}
+ // 5. Return responseObject.
+ return responseObject
+ }
-function noop () {}
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect (url, status = 302) {
+ const relevantRealm = { settingsObject: {} }
-function publishQueue(context, queue) {
- Object.defineProperty(context, gracefulQueue, {
- get: function() {
- return queue
- }
- })
-}
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
-var debug = noop
-if (util.debuglog)
- debug = util.debuglog('gfs4')
-else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
- debug = function() {
- var m = util.format.apply(util, arguments)
- m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
- console.error(m)
- }
-
-// Once time initialization
-if (!fs[gracefulQueue]) {
- // This queue can be shared by multiple loaded instances
- var queue = global[gracefulQueue] || []
- publishQueue(fs, queue)
-
- // Patch fs.close/closeSync to shared queue version, because we need
- // to retry() whenever a close happens *anywhere* in the program.
- // This is essential when multiple graceful-fs instances are
- // in play at the same time.
- fs.close = (function (fs$close) {
- function close (fd, cb) {
- return fs$close.call(fs, fd, function (err) {
- // This function uses the graceful-fs shared queue
- if (!err) {
- resetQueue()
- }
+ url = webidl.converters.USVString(url)
+ status = webidl.converters['unsigned short'](status)
- if (typeof cb === 'function')
- cb.apply(this, arguments)
+ // 1. Let parsedURL be the result of parsing url with current settings
+ // object’s API base URL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ // TODO: base-URL?
+ let parsedURL
+ try {
+ parsedURL = new URL(url, getGlobalOrigin())
+ } catch (err) {
+ throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
+ cause: err
})
}
- Object.defineProperty(close, previousSymbol, {
- value: fs$close
- })
- return close
- })(fs.close)
-
- fs.closeSync = (function (fs$closeSync) {
- function closeSync (fd) {
- // This function uses the graceful-fs shared queue
- fs$closeSync.apply(fs, arguments)
- resetQueue()
+ // 3. If status is not a redirect status, then throw a RangeError.
+ if (!redirectStatus.includes(status)) {
+ throw new RangeError('Invalid status code ' + status)
}
- Object.defineProperty(closeSync, previousSymbol, {
- value: fs$closeSync
- })
- return closeSync
- })(fs.closeSync)
-
- if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
- process.on('exit', function() {
- debug(fs[gracefulQueue])
- __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0)
- })
- }
-}
-
-if (!global[gracefulQueue]) {
- publishQueue(global, fs[gracefulQueue]);
-}
+ // 4. Let responseObject be the result of creating a Response object,
+ // given a new response, "immutable", and this’s relevant Realm.
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
-module.exports = patch(clone(fs))
-if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
- module.exports = patch(fs)
- fs.__patched = true;
-}
+ // 5. Set responseObject’s response’s status to status.
+ responseObject[kState].status = status
-function patch (fs) {
- // Everything that references the open() function needs to be in here
- polyfills(fs)
- fs.gracefulify = patch
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
+ const value = isomorphicEncode(URLSerializer(parsedURL))
- fs.createReadStream = createReadStream
- fs.createWriteStream = createWriteStream
- var fs$readFile = fs.readFile
- fs.readFile = readFile
- function readFile (path, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ // 7. Append `Location`/value to responseObject’s response’s header list.
+ responseObject[kState].headersList.append('location', value)
- return go$readFile(path, options, cb)
+ // 8. Return responseObject.
+ return responseObject
+ }
- function go$readFile (path, options, cb, startTime) {
- return fs$readFile(path, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- }
- })
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor (body = null, init = {}) {
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body)
}
- }
- var fs$writeFile = fs.writeFile
- fs.writeFile = writeFile
- function writeFile (path, data, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ init = webidl.converters.ResponseInit(init)
- return go$writeFile(path, data, options, cb)
+ // TODO
+ this[kRealm] = { settingsObject: {} }
- function go$writeFile (path, data, options, cb, startTime) {
- return fs$writeFile(path, data, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- }
- })
- }
- }
+ // 1. Set this’s response to a new response.
+ this[kState] = makeResponse({})
- var fs$appendFile = fs.appendFile
- if (fs$appendFile)
- fs.appendFile = appendFile
- function appendFile (path, data, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ // 2. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is this’s response’s header list and guard
+ // is "response".
+ this[kHeaders] = new Headers()
+ this[kHeaders][kGuard] = 'response'
+ this[kHeaders][kHeadersList] = this[kState].headersList
+ this[kHeaders][kRealm] = this[kRealm]
- return go$appendFile(path, data, options, cb)
+ // 3. Let bodyWithType be null.
+ let bodyWithType = null
- function go$appendFile (path, data, options, cb, startTime) {
- return fs$appendFile(path, data, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- }
- })
+ // 4. If body is non-null, then set bodyWithType to the result of extracting body.
+ if (body != null) {
+ const [extractedBody, type] = extractBody(body)
+ bodyWithType = { body: extractedBody, type }
}
+
+ // 5. Perform initialize a response given this, init, and bodyWithType.
+ initializeResponse(this, init, bodyWithType)
}
- var fs$copyFile = fs.copyFile
- if (fs$copyFile)
- fs.copyFile = copyFile
- function copyFile (src, dest, flags, cb) {
- if (typeof flags === 'function') {
- cb = flags
- flags = 0
- }
- return go$copyFile(src, dest, flags, cb)
+ // Returns response’s type, e.g., "cors".
+ get type () {
+ webidl.brandCheck(this, Response)
- function go$copyFile (src, dest, flags, cb, startTime) {
- return fs$copyFile(src, dest, flags, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- }
- })
- }
+ // The type getter steps are to return this’s response’s type.
+ return this[kState].type
}
- var fs$readdir = fs.readdir
- fs.readdir = readdir
- var noReaddirOptionVersions = /^v[0-5]\./
- function readdir (path, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url () {
+ webidl.brandCheck(this, Response)
- var go$readdir = noReaddirOptionVersions.test(process.version)
- ? function go$readdir (path, options, cb, startTime) {
- return fs$readdir(path, fs$readdirCallback(
- path, options, cb, startTime
- ))
- }
- : function go$readdir (path, options, cb, startTime) {
- return fs$readdir(path, options, fs$readdirCallback(
- path, options, cb, startTime
- ))
- }
+ const urlList = this[kState].urlList
- return go$readdir(path, options, cb)
-
- function fs$readdirCallback (path, options, cb, startTime) {
- return function (err, files) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([
- go$readdir,
- [path, options, cb],
- err,
- startTime || Date.now(),
- Date.now()
- ])
- else {
- if (files && files.sort)
- files.sort()
+ // The url getter steps are to return the empty string if this’s
+ // response’s URL is null; otherwise this’s response’s URL,
+ // serialized with exclude fragment set to true.
+ const url = urlList[urlList.length - 1] ?? null
- if (typeof cb === 'function')
- cb.call(this, err, files)
- }
- }
+ if (url === null) {
+ return ''
}
- }
- if (process.version.substr(0, 4) === 'v0.8') {
- var legStreams = legacy(fs)
- ReadStream = legStreams.ReadStream
- WriteStream = legStreams.WriteStream
+ return URLSerializer(url, true)
}
- var fs$ReadStream = fs.ReadStream
- if (fs$ReadStream) {
- ReadStream.prototype = Object.create(fs$ReadStream.prototype)
- ReadStream.prototype.open = ReadStream$open
- }
+ // Returns whether response was obtained through a redirect.
+ get redirected () {
+ webidl.brandCheck(this, Response)
- var fs$WriteStream = fs.WriteStream
- if (fs$WriteStream) {
- WriteStream.prototype = Object.create(fs$WriteStream.prototype)
- WriteStream.prototype.open = WriteStream$open
+ // The redirected getter steps are to return true if this’s response’s URL
+ // list has more than one item; otherwise false.
+ return this[kState].urlList.length > 1
}
- Object.defineProperty(fs, 'ReadStream', {
- get: function () {
- return ReadStream
- },
- set: function (val) {
- ReadStream = val
- },
- enumerable: true,
- configurable: true
- })
- Object.defineProperty(fs, 'WriteStream', {
- get: function () {
- return WriteStream
- },
- set: function (val) {
- WriteStream = val
- },
- enumerable: true,
- configurable: true
- })
-
- // legacy names
- var FileReadStream = ReadStream
- Object.defineProperty(fs, 'FileReadStream', {
- get: function () {
- return FileReadStream
- },
- set: function (val) {
- FileReadStream = val
- },
- enumerable: true,
- configurable: true
- })
- var FileWriteStream = WriteStream
- Object.defineProperty(fs, 'FileWriteStream', {
- get: function () {
- return FileWriteStream
- },
- set: function (val) {
- FileWriteStream = val
- },
- enumerable: true,
- configurable: true
- })
+ // Returns response’s status.
+ get status () {
+ webidl.brandCheck(this, Response)
- function ReadStream (path, options) {
- if (this instanceof ReadStream)
- return fs$ReadStream.apply(this, arguments), this
- else
- return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
+ // The status getter steps are to return this’s response’s status.
+ return this[kState].status
}
- function ReadStream$open () {
- var that = this
- open(that.path, that.flags, that.mode, function (err, fd) {
- if (err) {
- if (that.autoClose)
- that.destroy()
+ // Returns whether response’s status is an ok status.
+ get ok () {
+ webidl.brandCheck(this, Response)
- that.emit('error', err)
- } else {
- that.fd = fd
- that.emit('open', fd)
- that.read()
- }
- })
+ // The ok getter steps are to return true if this’s response’s status is an
+ // ok status; otherwise false.
+ return this[kState].status >= 200 && this[kState].status <= 299
}
- function WriteStream (path, options) {
- if (this instanceof WriteStream)
- return fs$WriteStream.apply(this, arguments), this
- else
- return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
- }
+ // Returns response’s status message.
+ get statusText () {
+ webidl.brandCheck(this, Response)
- function WriteStream$open () {
- var that = this
- open(that.path, that.flags, that.mode, function (err, fd) {
- if (err) {
- that.destroy()
- that.emit('error', err)
- } else {
- that.fd = fd
- that.emit('open', fd)
- }
- })
+ // The statusText getter steps are to return this’s response’s status
+ // message.
+ return this[kState].statusText
}
- function createReadStream (path, options) {
- return new fs.ReadStream(path, options)
- }
+ // Returns response’s headers as Headers.
+ get headers () {
+ webidl.brandCheck(this, Response)
- function createWriteStream (path, options) {
- return new fs.WriteStream(path, options)
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
- var fs$open = fs.open
- fs.open = open
- function open (path, flags, mode, cb) {
- if (typeof mode === 'function')
- cb = mode, mode = null
-
- return go$open(path, flags, mode, cb)
+ get body () {
+ webidl.brandCheck(this, Response)
- function go$open (path, flags, mode, cb, startTime) {
- return fs$open(path, flags, mode, function (err, fd) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- }
- })
- }
+ return this[kState].body ? this[kState].body.stream : null
}
- return fs
-}
+ get bodyUsed () {
+ webidl.brandCheck(this, Response)
-function enqueue (elem) {
- debug('ENQUEUE', elem[0].name, elem[1])
- fs[gracefulQueue].push(elem)
- retry()
-}
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
-// keep track of the timeout between retry() calls
-var retryTimer
+ // Returns a clone of response.
+ clone () {
+ webidl.brandCheck(this, Response)
-// reset the startTime and lastTime to now
-// this resets the start of the 60 second overall timeout as well as the
-// delay between attempts so that we'll retry these jobs sooner
-function resetQueue () {
- var now = Date.now()
- for (var i = 0; i < fs[gracefulQueue].length; ++i) {
- // entries that are only a length of 2 are from an older version, don't
- // bother modifying those since they'll be retried anyway.
- if (fs[gracefulQueue][i].length > 2) {
- fs[gracefulQueue][i][3] = now // startTime
- fs[gracefulQueue][i][4] = now // lastTime
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || (this.body && this.body.locked)) {
+ throw webidl.errors.exception({
+ header: 'Response.clone',
+ message: 'Body has already been consumed.'
+ })
}
- }
- // call retry to make sure we're actively processing the queue
- retry()
-}
-function retry () {
- // clear the timer and remove it to help prevent unintended concurrency
- clearTimeout(retryTimer)
- retryTimer = undefined
-
- if (fs[gracefulQueue].length === 0)
- return
+ // 2. Let clonedResponse be the result of cloning this’s response.
+ const clonedResponse = cloneResponse(this[kState])
- var elem = fs[gracefulQueue].shift()
- var fn = elem[0]
- var args = elem[1]
- // these items may be unset if they were added by an older graceful-fs
- var err = elem[2]
- var startTime = elem[3]
- var lastTime = elem[4]
-
- // if we don't have a startTime we have no way of knowing if we've waited
- // long enough, so go ahead and retry this item now
- if (startTime === undefined) {
- debug('RETRY', fn.name, args)
- fn.apply(null, args)
- } else if (Date.now() - startTime >= 60000) {
- // it's been more than 60 seconds total, bail now
- debug('TIMEOUT', fn.name, args)
- var cb = args.pop()
- if (typeof cb === 'function')
- cb.call(null, err)
- } else {
- // the amount of time between the last attempt and right now
- var sinceAttempt = Date.now() - lastTime
- // the amount of time between when we first tried, and when we last tried
- // rounded up to at least 1
- var sinceStart = Math.max(lastTime - startTime, 1)
- // backoff. wait longer than the total time we've been retrying, but only
- // up to a maximum of 100ms
- var desiredDelay = Math.min(sinceStart * 1.2, 100)
- // it's been long enough since the last retry, do it again
- if (sinceAttempt >= desiredDelay) {
- debug('RETRY', fn.name, args)
- fn.apply(null, args.concat([startTime]))
- } else {
- // if we can't do this job yet, push it to the end of the queue
- // and let the next iteration check again
- fs[gracefulQueue].push(elem)
- }
- }
+ // 3. Return the result of creating a Response object, given
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
+ const clonedResponseObject = new Response()
+ clonedResponseObject[kState] = clonedResponse
+ clonedResponseObject[kRealm] = this[kRealm]
+ clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
+ clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- // schedule our next run if one isn't already scheduled
- if (retryTimer === undefined) {
- retryTimer = setTimeout(retry, 0)
+ return clonedResponseObject
}
}
+mixinBody(Response)
-/***/ }),
-
-/***/ 73836:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var Stream = (__nccwpck_require__(12781).Stream)
-
-module.exports = legacy
-
-function legacy (fs) {
- return {
- ReadStream: ReadStream,
- WriteStream: WriteStream
+Object.defineProperties(Response.prototype, {
+ type: kEnumerableProperty,
+ url: kEnumerableProperty,
+ status: kEnumerableProperty,
+ ok: kEnumerableProperty,
+ redirected: kEnumerableProperty,
+ statusText: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Response',
+ configurable: true
}
+})
- function ReadStream (path, options) {
- if (!(this instanceof ReadStream)) return new ReadStream(path, options);
-
- Stream.call(this);
+Object.defineProperties(Response, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- var self = this;
+// https://fetch.spec.whatwg.org/#concept-response-clone
+function cloneResponse (response) {
+ // To clone a response response, run these steps:
- this.path = path;
- this.fd = null;
- this.readable = true;
- this.paused = false;
+ // 1. If response is a filtered response, then return a new identical
+ // filtered response whose internal response is a clone of response’s
+ // internal response.
+ if (response.internalResponse) {
+ return filterResponse(
+ cloneResponse(response.internalResponse),
+ response.type
+ )
+ }
- this.flags = 'r';
- this.mode = 438; /*=0666*/
- this.bufferSize = 64 * 1024;
+ // 2. Let newResponse be a copy of response, except for its body.
+ const newResponse = makeResponse({ ...response, body: null })
- options = options || {};
+ // 3. If response’s body is non-null, then set newResponse’s body to the
+ // result of cloning response’s body.
+ if (response.body != null) {
+ newResponse.body = cloneBody(response.body)
+ }
- // Mixin options into this
- var keys = Object.keys(options);
- for (var index = 0, length = keys.length; index < length; index++) {
- var key = keys[index];
- this[key] = options[key];
- }
+ // 4. Return newResponse.
+ return newResponse
+}
- if (this.encoding) this.setEncoding(this.encoding);
+function makeResponse (init) {
+ return {
+ aborted: false,
+ rangeRequested: false,
+ timingAllowPassed: false,
+ requestIncludesCredentials: false,
+ type: 'default',
+ status: 200,
+ timingInfo: null,
+ cacheState: '',
+ statusText: '',
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList(),
+ urlList: init.urlList ? [...init.urlList] : []
+ }
+}
- if (this.start !== undefined) {
- if ('number' !== typeof this.start) {
- throw TypeError('start must be a Number');
- }
- if (this.end === undefined) {
- this.end = Infinity;
- } else if ('number' !== typeof this.end) {
- throw TypeError('end must be a Number');
- }
+function makeNetworkError (reason) {
+ const isError = isErrorLike(reason)
+ return makeResponse({
+ type: 'error',
+ status: 0,
+ error: isError
+ ? reason
+ : new Error(reason ? String(reason) : reason),
+ aborted: reason && reason.name === 'AbortError'
+ })
+}
- if (this.start > this.end) {
- throw new Error('start must be <= end');
- }
+function makeFilteredResponse (response, state) {
+ state = {
+ internalResponse: response,
+ ...state
+ }
- this.pos = this.start;
+ return new Proxy(response, {
+ get (target, p) {
+ return p in state ? state[p] : target[p]
+ },
+ set (target, p, value) {
+ assert(!(p in state))
+ target[p] = value
+ return true
}
+ })
+}
- if (this.fd !== null) {
- process.nextTick(function() {
- self._read();
- });
- return;
- }
+// https://fetch.spec.whatwg.org/#concept-filtered-response
+function filterResponse (response, type) {
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (type === 'basic') {
+ // A basic filtered response is a filtered response whose type is "basic"
+ // and header list excludes any headers in internal response’s header list
+ // whose name is a forbidden response-header name.
- fs.open(this.path, this.flags, this.mode, function (err, fd) {
- if (err) {
- self.emit('error', err);
- self.readable = false;
- return;
- }
+ // Note: undici does not implement forbidden response-header names
+ return makeFilteredResponse(response, {
+ type: 'basic',
+ headersList: response.headersList
+ })
+ } else if (type === 'cors') {
+ // A CORS filtered response is a filtered response whose type is "cors"
+ // and header list excludes any headers in internal response’s header
+ // list whose name is not a CORS-safelisted response-header name, given
+ // internal response’s CORS-exposed header-name list.
- self.fd = fd;
- self.emit('open', fd);
- self._read();
+ // Note: undici does not implement CORS-safelisted response-header names
+ return makeFilteredResponse(response, {
+ type: 'cors',
+ headersList: response.headersList
})
- }
+ } else if (type === 'opaque') {
+ // An opaque filtered response is a filtered response whose type is
+ // "opaque", URL list is the empty list, status is 0, status message
+ // is the empty byte sequence, header list is empty, and body is null.
- function WriteStream (path, options) {
- if (!(this instanceof WriteStream)) return new WriteStream(path, options);
+ return makeFilteredResponse(response, {
+ type: 'opaque',
+ urlList: Object.freeze([]),
+ status: 0,
+ statusText: '',
+ body: null
+ })
+ } else if (type === 'opaqueredirect') {
+ // An opaque-redirect filtered response is a filtered response whose type
+ // is "opaqueredirect", status is 0, status message is the empty byte
+ // sequence, header list is empty, and body is null.
- Stream.call(this);
-
- this.path = path;
- this.fd = null;
- this.writable = true;
-
- this.flags = 'w';
- this.encoding = 'binary';
- this.mode = 438; /*=0666*/
- this.bytesWritten = 0;
-
- options = options || {};
-
- // Mixin options into this
- var keys = Object.keys(options);
- for (var index = 0, length = keys.length; index < length; index++) {
- var key = keys[index];
- this[key] = options[key];
- }
-
- if (this.start !== undefined) {
- if ('number' !== typeof this.start) {
- throw TypeError('start must be a Number');
- }
- if (this.start < 0) {
- throw new Error('start must be >= zero');
- }
-
- this.pos = this.start;
- }
-
- this.busy = false;
- this._queue = [];
-
- if (this.fd === null) {
- this._open = fs.open;
- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
- this.flush();
- }
+ return makeFilteredResponse(response, {
+ type: 'opaqueredirect',
+ status: 0,
+ statusText: '',
+ headersList: [],
+ body: null
+ })
+ } else {
+ assert(false)
}
}
+// https://fetch.spec.whatwg.org/#appropriate-network-error
+function makeAppropriateNetworkError (fetchParams, err = null) {
+ // 1. Assert: fetchParams is canceled.
+ assert(isCancelled(fetchParams))
-/***/ }),
-
-/***/ 35027:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var constants = __nccwpck_require__(22057)
-
-var origCwd = process.cwd
-var cwd = null
-
-var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
-
-process.cwd = function() {
- if (!cwd)
- cwd = origCwd.call(process)
- return cwd
+ // 2. Return an aborted network error if fetchParams is aborted;
+ // otherwise return a network error.
+ return isAborted(fetchParams)
+ ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
+ : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
}
-try {
- process.cwd()
-} catch (er) {}
-
-// This check is needed until node.js 12 is required
-if (typeof process.chdir === 'function') {
- var chdir = process.chdir
- process.chdir = function (d) {
- cwd = null
- chdir.call(process, d)
- }
- if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir)
-}
-
-module.exports = patch
-
-function patch (fs) {
- // (re-)implement some things that are known busted or missing.
-
- // lchmod, broken prior to 0.6.2
- // back-port the fix here.
- if (constants.hasOwnProperty('O_SYMLINK') &&
- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
- patchLchmod(fs)
- }
-
- // lutimes implementation, or no-op
- if (!fs.lutimes) {
- patchLutimes(fs)
- }
-
- // https://github.com/isaacs/node-graceful-fs/issues/4
- // Chown should not fail on einval or eperm if non-root.
- // It should not fail on enosys ever, as this just indicates
- // that a fs doesn't support the intended operation.
-
- fs.chown = chownFix(fs.chown)
- fs.fchown = chownFix(fs.fchown)
- fs.lchown = chownFix(fs.lchown)
-
- fs.chmod = chmodFix(fs.chmod)
- fs.fchmod = chmodFix(fs.fchmod)
- fs.lchmod = chmodFix(fs.lchmod)
-
- fs.chownSync = chownFixSync(fs.chownSync)
- fs.fchownSync = chownFixSync(fs.fchownSync)
- fs.lchownSync = chownFixSync(fs.lchownSync)
-
- fs.chmodSync = chmodFixSync(fs.chmodSync)
- fs.fchmodSync = chmodFixSync(fs.fchmodSync)
- fs.lchmodSync = chmodFixSync(fs.lchmodSync)
-
- fs.stat = statFix(fs.stat)
- fs.fstat = statFix(fs.fstat)
- fs.lstat = statFix(fs.lstat)
-
- fs.statSync = statFixSync(fs.statSync)
- fs.fstatSync = statFixSync(fs.fstatSync)
- fs.lstatSync = statFixSync(fs.lstatSync)
-
- // if lchmod/lchown do not exist, then make them no-ops
- if (fs.chmod && !fs.lchmod) {
- fs.lchmod = function (path, mode, cb) {
- if (cb) process.nextTick(cb)
- }
- fs.lchmodSync = function () {}
- }
- if (fs.chown && !fs.lchown) {
- fs.lchown = function (path, uid, gid, cb) {
- if (cb) process.nextTick(cb)
- }
- fs.lchownSync = function () {}
- }
-
- // on Windows, A/V software can lock the directory, causing this
- // to fail with an EACCES or EPERM if the directory contains newly
- // created files. Try again on failure, for up to 60 seconds.
-
- // Set the timeout this long because some Windows Anti-Virus, such as Parity
- // bit9, may lock files for up to a minute, causing npm package install
- // failures. Also, take care to yield the scheduler. Windows scheduling gives
- // CPU to a busy looping process, which can cause the program causing the lock
- // contention to be starved of CPU by node, so the contention doesn't resolve.
- if (platform === "win32") {
- fs.rename = typeof fs.rename !== 'function' ? fs.rename
- : (function (fs$rename) {
- function rename (from, to, cb) {
- var start = Date.now()
- var backoff = 0;
- fs$rename(from, to, function CB (er) {
- if (er
- && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
- && Date.now() - start < 60000) {
- setTimeout(function() {
- fs.stat(to, function (stater, st) {
- if (stater && stater.code === "ENOENT")
- fs$rename(from, to, CB);
- else
- cb(er)
- })
- }, backoff)
- if (backoff < 100)
- backoff += 10;
- return;
- }
- if (cb) cb(er)
- })
- }
- if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename)
- return rename
- })(fs.rename)
- }
-
- // if read() returns EAGAIN, then just try it again.
- fs.read = typeof fs.read !== 'function' ? fs.read
- : (function (fs$read) {
- function read (fd, buffer, offset, length, position, callback_) {
- var callback
- if (callback_ && typeof callback_ === 'function') {
- var eagCounter = 0
- callback = function (er, _, __) {
- if (er && er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
- }
- callback_.apply(this, arguments)
- }
- }
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
- }
-
- // This ensures `util.promisify` works as it does for native `fs.read`.
- if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read)
- return read
- })(fs.read)
-
- fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
- : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
- var eagCounter = 0
- while (true) {
- try {
- return fs$readSync.call(fs, fd, buffer, offset, length, position)
- } catch (er) {
- if (er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- continue
- }
- throw er
- }
- }
- }})(fs.readSync)
-
- function patchLchmod (fs) {
- fs.lchmod = function (path, mode, callback) {
- fs.open( path
- , constants.O_WRONLY | constants.O_SYMLINK
- , mode
- , function (err, fd) {
- if (err) {
- if (callback) callback(err)
- return
- }
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- fs.fchmod(fd, mode, function (err) {
- fs.close(fd, function(err2) {
- if (callback) callback(err || err2)
- })
- })
- })
- }
- fs.lchmodSync = function (path, mode) {
- var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
-
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- var threw = true
- var ret
- try {
- ret = fs.fchmodSync(fd, mode)
- threw = false
- } finally {
- if (threw) {
- try {
- fs.closeSync(fd)
- } catch (er) {}
- } else {
- fs.closeSync(fd)
- }
- }
- return ret
- }
- }
-
- function patchLutimes (fs) {
- if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
- fs.lutimes = function (path, at, mt, cb) {
- fs.open(path, constants.O_SYMLINK, function (er, fd) {
- if (er) {
- if (cb) cb(er)
- return
- }
- fs.futimes(fd, at, mt, function (er) {
- fs.close(fd, function (er2) {
- if (cb) cb(er || er2)
- })
- })
- })
- }
-
- fs.lutimesSync = function (path, at, mt) {
- var fd = fs.openSync(path, constants.O_SYMLINK)
- var ret
- var threw = true
- try {
- ret = fs.futimesSync(fd, at, mt)
- threw = false
- } finally {
- if (threw) {
- try {
- fs.closeSync(fd)
- } catch (er) {}
- } else {
- fs.closeSync(fd)
- }
- }
- return ret
- }
-
- } else if (fs.futimes) {
- fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
- fs.lutimesSync = function () {}
- }
+// https://whatpr.org/fetch/1392.html#initialize-a-response
+function initializeResponse (response, init, body) {
+ // 1. If init["status"] is not in the range 200 to 599, inclusive, then
+ // throw a RangeError.
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
}
- function chmodFix (orig) {
- if (!orig) return orig
- return function (target, mode, cb) {
- return orig.call(fs, target, mode, function (er) {
- if (chownErOk(er)) er = null
- if (cb) cb.apply(this, arguments)
- })
+ // 2. If init["statusText"] does not match the reason-phrase token production,
+ // then throw a TypeError.
+ if ('statusText' in init && init.statusText != null) {
+ // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
+ // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
+ if (!isValidReasonPhrase(String(init.statusText))) {
+ throw new TypeError('Invalid statusText')
}
}
- function chmodFixSync (orig) {
- if (!orig) return orig
- return function (target, mode) {
- try {
- return orig.call(fs, target, mode)
- } catch (er) {
- if (!chownErOk(er)) throw er
- }
- }
+ // 3. Set response’s response’s status to init["status"].
+ if ('status' in init && init.status != null) {
+ response[kState].status = init.status
}
-
- function chownFix (orig) {
- if (!orig) return orig
- return function (target, uid, gid, cb) {
- return orig.call(fs, target, uid, gid, function (er) {
- if (chownErOk(er)) er = null
- if (cb) cb.apply(this, arguments)
- })
- }
+ // 4. Set response’s response’s status message to init["statusText"].
+ if ('statusText' in init && init.statusText != null) {
+ response[kState].statusText = init.statusText
}
- function chownFixSync (orig) {
- if (!orig) return orig
- return function (target, uid, gid) {
- try {
- return orig.call(fs, target, uid, gid)
- } catch (er) {
- if (!chownErOk(er)) throw er
- }
- }
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
+ if ('headers' in init && init.headers != null) {
+ fill(response[kHeaders], init.headers)
}
- function statFix (orig) {
- if (!orig) return orig
- // Older versions of Node erroneously returned signed integers for
- // uid + gid.
- return function (target, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = null
- }
- function callback (er, stats) {
- if (stats) {
- if (stats.uid < 0) stats.uid += 0x100000000
- if (stats.gid < 0) stats.gid += 0x100000000
- }
- if (cb) cb.apply(this, arguments)
- }
- return options ? orig.call(fs, target, options, callback)
- : orig.call(fs, target, callback)
+ // 6. If body was given, then:
+ if (body) {
+ // 1. If response's status is a null body status, then throw a TypeError.
+ if (nullBodyStatus.includes(response.status)) {
+ throw webidl.errors.exception({
+ header: 'Response constructor',
+ message: 'Invalid response status code ' + response.status
+ })
}
- }
-
- function statFixSync (orig) {
- if (!orig) return orig
- // Older versions of Node erroneously returned signed integers for
- // uid + gid.
- return function (target, options) {
- var stats = options ? orig.call(fs, target, options)
- : orig.call(fs, target)
- if (stats) {
- if (stats.uid < 0) stats.uid += 0x100000000
- if (stats.gid < 0) stats.gid += 0x100000000
- }
- return stats;
- }
- }
-
- // ENOSYS means that the fs doesn't support the op. Just ignore
- // that, because it doesn't matter.
- //
- // if there's no getuid, or if getuid() is something other
- // than 0, and the error is EINVAL or EPERM, then just ignore
- // it.
- //
- // This specific case is a silent failure in cp, install, tar,
- // and most other unix tools that manage permissions.
- //
- // When running as root, or if other types of errors are
- // encountered, then it's strict.
- function chownErOk (er) {
- if (!er)
- return true
- if (er.code === "ENOSYS")
- return true
+ // 2. Set response's body to body's body.
+ response[kState].body = body.body
- var nonroot = !process.getuid || process.getuid() !== 0
- if (nonroot) {
- if (er.code === "EINVAL" || er.code === "EPERM")
- return true
+ // 3. If body's type is non-null and response's header list does not contain
+ // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
+ if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
+ response[kState].headersList.append('content-type', body.type)
}
-
- return false
}
}
+webidl.converters.ReadableStream = webidl.interfaceConverter(
+ ReadableStream
+)
-/***/ }),
-
-/***/ 46863:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+webidl.converters.FormData = webidl.interfaceConverter(
+ FormData
+)
-module.exports = realpath
-realpath.realpath = realpath
-realpath.sync = realpathSync
-realpath.realpathSync = realpathSync
-realpath.monkeypatch = monkeypatch
-realpath.unmonkeypatch = unmonkeypatch
-
-var fs = __nccwpck_require__(57147)
-var origRealpath = fs.realpath
-var origRealpathSync = fs.realpathSync
-
-var version = process.version
-var ok = /^v[0-5]\./.test(version)
-var old = __nccwpck_require__(71734)
-
-function newError (er) {
- return er && er.syscall === 'realpath' && (
- er.code === 'ELOOP' ||
- er.code === 'ENOMEM' ||
- er.code === 'ENAMETOOLONG'
- )
-}
+webidl.converters.URLSearchParams = webidl.interfaceConverter(
+ URLSearchParams
+)
-function realpath (p, cache, cb) {
- if (ok) {
- return origRealpath(p, cache, cb)
+// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
+webidl.converters.XMLHttpRequestBodyInit = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
}
- if (typeof cache === 'function') {
- cb = cache
- cache = null
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- origRealpath(p, cache, function (er, result) {
- if (newError(er)) {
- old.realpath(p, cache, cb)
- } else {
- cb(er, result)
- }
- })
-}
-function realpathSync (p, cache) {
- if (ok) {
- return origRealpathSync(p, cache)
+ if (
+ types.isAnyArrayBuffer(V) ||
+ types.isTypedArray(V) ||
+ types.isDataView(V)
+ ) {
+ return webidl.converters.BufferSource(V)
}
- try {
- return origRealpathSync(p, cache)
- } catch (er) {
- if (newError(er)) {
- return old.realpathSync(p, cache)
- } else {
- throw er
- }
+ if (util.isFormDataLike(V)) {
+ return webidl.converters.FormData(V, { strict: false })
}
-}
-function monkeypatch () {
- fs.realpath = realpath
- fs.realpathSync = realpathSync
-}
+ if (V instanceof URLSearchParams) {
+ return webidl.converters.URLSearchParams(V)
+ }
-function unmonkeypatch () {
- fs.realpath = origRealpath
- fs.realpathSync = origRealpathSync
+ return webidl.converters.DOMString(V)
}
-
-/***/ }),
-
-/***/ 71734:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-var pathModule = __nccwpck_require__(71017);
-var isWindows = process.platform === 'win32';
-var fs = __nccwpck_require__(57147);
-
-// JavaScript implementation of realpath, ported from node pre-v6
-
-var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
-
-function rethrow() {
- // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
- // is fairly slow to generate.
- var callback;
- if (DEBUG) {
- var backtrace = new Error;
- callback = debugCallback;
- } else
- callback = missingCallback;
-
- return callback;
-
- function debugCallback(err) {
- if (err) {
- backtrace.message = err.message;
- err = backtrace;
- missingCallback(err);
- }
+// https://fetch.spec.whatwg.org/#bodyinit
+webidl.converters.BodyInit = function (V) {
+ if (V instanceof ReadableStream) {
+ return webidl.converters.ReadableStream(V)
}
- function missingCallback(err) {
- if (err) {
- if (process.throwDeprecation)
- throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
- else if (!process.noDeprecation) {
- var msg = 'fs: missing callback ' + (err.stack || err.message);
- if (process.traceDeprecation)
- console.trace(msg);
- else
- console.error(msg);
- }
- }
+ // Note: the spec doesn't include async iterables,
+ // this is an undici extension.
+ if (V?.[Symbol.asyncIterator]) {
+ return V
}
-}
-function maybeCallback(cb) {
- return typeof cb === 'function' ? cb : rethrow();
+ return webidl.converters.XMLHttpRequestBodyInit(V)
}
-var normalize = pathModule.normalize;
+webidl.converters.ResponseInit = webidl.dictionaryConverter([
+ {
+ key: 'status',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: 200
+ },
+ {
+ key: 'statusText',
+ converter: webidl.converters.ByteString,
+ defaultValue: ''
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ }
+])
-// Regexp that finds the next partion of a (partial) path
-// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
-if (isWindows) {
- var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
-} else {
- var nextPartRe = /(.*?)(?:[\/]+|$)/g;
+module.exports = {
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response,
+ cloneResponse
}
-// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
-if (isWindows) {
- var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
-} else {
- var splitRootRe = /^[\/]*/;
-}
-exports.realpathSync = function realpathSync(p, cache) {
- // make p is absolute
- p = pathModule.resolve(p);
+/***/ }),
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return cache[p];
- }
+/***/ 9710:
+/***/ ((module) => {
- var original = p,
- seenLinks = {},
- knownHard = {};
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
- start();
+module.exports = {
+ kUrl: Symbol('url'),
+ kHeaders: Symbol('headers'),
+ kSignal: Symbol('signal'),
+ kState: Symbol('state'),
+ kGuard: Symbol('guard'),
+ kRealm: Symbol('realm')
+}
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstatSync(base);
- knownHard[base] = true;
- }
- }
+/***/ }),
- // walk down the path, swapping out linked pathparts for their real
- // values
- // NB: p.length changes.
- while (pos < p.length) {
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
+/***/ 5523:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- continue;
- }
- var resolvedLink;
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // some known symbolic link. no need to stat again.
- resolvedLink = cache[base];
- } else {
- var stat = fs.lstatSync(base);
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- continue;
- }
- // read the link if it wasn't read before
- // dev/ino always return 0 on windows, so skip the check.
- var linkTarget = null;
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- linkTarget = seenLinks[id];
- }
- }
- if (linkTarget === null) {
- fs.statSync(base);
- linkTarget = fs.readlinkSync(base);
- }
- resolvedLink = pathModule.resolve(previous, linkTarget);
- // track this, if given a cache.
- if (cache) cache[base] = resolvedLink;
- if (!isWindows) seenLinks[id] = linkTarget;
- }
+const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(7326)
+const { getGlobalOrigin } = __nccwpck_require__(5628)
+const { performance } = __nccwpck_require__(2987)
+const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440)
+const assert = __nccwpck_require__(2613)
+const { isUint8Array } = __nccwpck_require__(8253)
- // resolve the link, then start over
- p = pathModule.resolve(resolvedLink, p.slice(pos));
- start();
- }
+// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
+/** @type {import('crypto')|undefined} */
+let crypto
- if (cache) cache[original] = p;
+try {
+ crypto = __nccwpck_require__(6982)
+} catch {
- return p;
-};
+}
+function responseURL (response) {
+ // https://fetch.spec.whatwg.org/#responses
+ // A response has an associated URL. It is a pointer to the last URL
+ // in response’s URL list and null if response’s URL list is empty.
+ const urlList = response.urlList
+ const length = urlList.length
+ return length === 0 ? null : urlList[length - 1].toString()
+}
-exports.realpath = function realpath(p, cache, cb) {
- if (typeof cb !== 'function') {
- cb = maybeCallback(cache);
- cache = null;
+// https://fetch.spec.whatwg.org/#concept-response-location-url
+function responseLocationURL (response, requestFragment) {
+ // 1. If response’s status is not a redirect status, then return null.
+ if (!redirectStatus.includes(response.status)) {
+ return null
}
- // make p is absolute
- p = pathModule.resolve(p);
+ // 2. Let location be the result of extracting header list values given
+ // `Location` and response’s header list.
+ let location = response.headersList.get('location')
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return process.nextTick(cb.bind(null, null, cache[p]));
+ // 3. If location is a header value, then set location to the result of
+ // parsing location with response’s URL.
+ if (location !== null && isValidHeaderValue(location)) {
+ location = new URL(location, responseURL(response))
}
- var original = p,
- seenLinks = {},
- knownHard = {};
+ // 4. If location is a URL whose fragment is null, then set location’s
+ // fragment to requestFragment.
+ if (location && !location.hash) {
+ location.hash = requestFragment
+ }
- // current character position in p
- var pos;
- // the partial path so far, including a trailing slash if any
- var current;
- // the partial path without a trailing slash (except when pointing at a root)
- var base;
- // the partial path scanned in the previous round, with slash
- var previous;
+ // 5. Return location.
+ return location
+}
- start();
+/** @returns {URL} */
+function requestCurrentURL (request) {
+ return request.urlList[request.urlList.length - 1]
+}
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = '';
+function requestBadPort (request) {
+ // 1. Let url be request’s current URL.
+ const url = requestCurrentURL(request)
- // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstat(base, function(err) {
- if (err) return cb(err);
- knownHard[base] = true;
- LOOP();
- });
- } else {
- process.nextTick(LOOP);
- }
+ // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
+ // then return blocked.
+ if (urlIsHttpHttpsScheme(url) && badPorts.includes(url.port)) {
+ return 'blocked'
}
- // walk down the path, swapping out linked pathparts for their real
- // values
- function LOOP() {
- // stop if scanned past end of path
- if (pos >= p.length) {
- if (cache) cache[original] = p;
- return cb(null, p);
- }
-
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex;
+ // 3. Return allowed.
+ return 'allowed'
+}
- // continue if not a symlink
- if (knownHard[base] || (cache && cache[base] === base)) {
- return process.nextTick(LOOP);
- }
+function isErrorLike (object) {
+ return object instanceof Error || (
+ object?.constructor?.name === 'Error' ||
+ object?.constructor?.name === 'DOMException'
+ )
+}
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // known symbolic link. no need to stat again.
- return gotResolvedLink(cache[base]);
+// Check whether |statusText| is a ByteString and
+// matches the Reason-Phrase token production.
+// RFC 2616: https://tools.ietf.org/html/rfc2616
+// RFC 7230: https://tools.ietf.org/html/rfc7230
+// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
+// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
+function isValidReasonPhrase (statusText) {
+ for (let i = 0; i < statusText.length; ++i) {
+ const c = statusText.charCodeAt(i)
+ if (
+ !(
+ (
+ c === 0x09 || // HTAB
+ (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
+ (c >= 0x80 && c <= 0xff)
+ ) // obs-text
+ )
+ ) {
+ return false
}
-
- return fs.lstat(base, gotStat);
}
+ return true
+}
- function gotStat(err, stat) {
- if (err) return cb(err);
-
- // if not a symlink, skip to the next path part
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- return process.nextTick(LOOP);
- }
+function isTokenChar (c) {
+ return !(
+ c >= 0x7f ||
+ c <= 0x20 ||
+ c === '(' ||
+ c === ')' ||
+ c === '<' ||
+ c === '>' ||
+ c === '@' ||
+ c === ',' ||
+ c === ';' ||
+ c === ':' ||
+ c === '\\' ||
+ c === '"' ||
+ c === '/' ||
+ c === '[' ||
+ c === ']' ||
+ c === '?' ||
+ c === '=' ||
+ c === '{' ||
+ c === '}'
+ )
+}
- // stat & read the link if not read before
- // call gotTarget as soon as the link target is known
- // dev/ino always return 0 on windows, so skip the check.
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- return gotTarget(null, seenLinks[id], base);
- }
+// See RFC 7230, Section 3.2.6.
+// https://github.com/chromium/chromium/blob/d7da0240cae77824d1eda25745c4022757499131/third_party/blink/renderer/platform/network/http_parsers.cc#L321
+function isValidHTTPToken (characters) {
+ if (!characters || typeof characters !== 'string') {
+ return false
+ }
+ for (let i = 0; i < characters.length; ++i) {
+ const c = characters.charCodeAt(i)
+ if (c > 0x7f || !isTokenChar(c)) {
+ return false
}
- fs.stat(base, function(err) {
- if (err) return cb(err);
+ }
+ return true
+}
- fs.readlink(base, function(err, target) {
- if (!isWindows) seenLinks[id] = target;
- gotTarget(err, target);
- });
- });
+// https://fetch.spec.whatwg.org/#header-name
+// https://github.com/chromium/chromium/blob/b3d37e6f94f87d59e44662d6078f6a12de845d17/net/http/http_util.cc#L342
+function isValidHeaderName (potentialValue) {
+ if (potentialValue.length === 0) {
+ return false
}
- function gotTarget(err, target, base) {
- if (err) return cb(err);
+ return isValidHTTPToken(potentialValue)
+}
- var resolvedLink = pathModule.resolve(previous, target);
- if (cache) cache[base] = resolvedLink;
- gotResolvedLink(resolvedLink);
+/**
+ * @see https://fetch.spec.whatwg.org/#header-value
+ * @param {string} potentialValue
+ */
+function isValidHeaderValue (potentialValue) {
+ // - Has no leading or trailing HTTP tab or space bytes.
+ // - Contains no 0x00 (NUL) or HTTP newline bytes.
+ if (
+ potentialValue.startsWith('\t') ||
+ potentialValue.startsWith(' ') ||
+ potentialValue.endsWith('\t') ||
+ potentialValue.endsWith(' ')
+ ) {
+ return false
}
- function gotResolvedLink(resolvedLink) {
- // resolve the link, then start over
- p = pathModule.resolve(resolvedLink, p.slice(pos));
- start();
+ if (
+ potentialValue.includes('\0') ||
+ potentialValue.includes('\r') ||
+ potentialValue.includes('\n')
+ ) {
+ return false
}
-};
-
-
-/***/ }),
-
-/***/ 19320:
-/***/ ((module) => {
-
-"use strict";
-
-/* eslint no-invalid-this: 1 */
-
-var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
-var slice = Array.prototype.slice;
-var toStr = Object.prototype.toString;
-var funcType = '[object Function]';
-
-module.exports = function bind(that) {
- var target = this;
- if (typeof target !== 'function' || toStr.call(target) !== funcType) {
- throw new TypeError(ERROR_MESSAGE + target);
- }
- var args = slice.call(arguments, 1);
+ return true
+}
- var bound;
- var binder = function () {
- if (this instanceof bound) {
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
- }
- };
+// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
+function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
+ // Given a request request and a response actualResponse, this algorithm
+ // updates request’s referrer policy according to the Referrer-Policy
+ // header (if any) in actualResponse.
- var boundLength = Math.max(0, target.length - args.length);
- var boundArgs = [];
- for (var i = 0; i < boundLength; i++) {
- boundArgs.push('$' + i);
- }
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
+ // from a Referrer-Policy header on actualResponse.
- bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
+ const { headersList } = actualResponse
+ // 2. Let policy be the empty string.
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
+ // 4. Return policy.
+ const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
- if (target.prototype) {
- var Empty = function Empty() {};
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
+ // Note: As the referrer-policy can contain multiple policies
+ // separated by comma, we need to loop through all of them
+ // and pick the first valid one.
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
+ let policy = ''
+ if (policyHeader.length > 0) {
+ // The right-most policy takes precedence.
+ // The left-most policy is the fallback.
+ for (let i = policyHeader.length; i !== 0; i--) {
+ const token = policyHeader[i - 1].trim()
+ if (referrerPolicyTokens.includes(token)) {
+ policy = token
+ break
+ }
}
+ }
- return bound;
-};
-
-
-/***/ }),
-
-/***/ 88334:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
+ if (policy !== '') {
+ request.referrerPolicy = policy
+ }
+}
-var implementation = __nccwpck_require__(19320);
+// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
+function crossOriginResourcePolicyCheck () {
+ // TODO
+ return 'allowed'
+}
-module.exports = Function.prototype.bind || implementation;
+// https://fetch.spec.whatwg.org/#concept-cors-check
+function corsCheck () {
+ // TODO
+ return 'success'
+}
+// https://fetch.spec.whatwg.org/#concept-tao-check
+function TAOCheck () {
+ // TODO
+ return 'success'
+}
-/***/ }),
+function appendFetchMetadata (httpRequest) {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
+ // TODO
-/***/ 74538:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
-"use strict";
+ // 1. Assert: r’s url is a potentially trustworthy URL.
+ // TODO
+ // 2. Let header be a Structured Header whose value is a token.
+ let header = null
-var undefined;
+ // 3. Set header’s value to r’s mode.
+ header = httpRequest.mode
-var $SyntaxError = SyntaxError;
-var $Function = Function;
-var $TypeError = TypeError;
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
+ httpRequest.headersList.set('sec-fetch-mode', header)
-// eslint-disable-next-line consistent-return
-var getEvalledConstructor = function (expressionSyntax) {
- try {
- return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
- } catch (e) {}
-};
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
+ // TODO
-var $gOPD = Object.getOwnPropertyDescriptor;
-if ($gOPD) {
- try {
- $gOPD({}, '');
- } catch (e) {
- $gOPD = null; // this is IE 8, which has a broken gOPD
- }
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
+ // TODO
}
-var throwTypeError = function () {
- throw new $TypeError();
-};
-var ThrowTypeError = $gOPD
- ? (function () {
- try {
- // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
- arguments.callee; // IE 8 does not throw here
- return throwTypeError;
- } catch (calleeThrows) {
- try {
- // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
- return $gOPD(arguments, 'callee').get;
- } catch (gOPDthrows) {
- return throwTypeError;
- }
- }
- }())
- : throwTypeError;
-
-var hasSymbols = __nccwpck_require__(40587)();
-
-var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
-
-var needsEval = {};
-
-var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
-
-var INTRINSICS = {
- '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
- '%Array%': Array,
- '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
- '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
- '%AsyncFromSyncIteratorPrototype%': undefined,
- '%AsyncFunction%': needsEval,
- '%AsyncGenerator%': needsEval,
- '%AsyncGeneratorFunction%': needsEval,
- '%AsyncIteratorPrototype%': needsEval,
- '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
- '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
- '%Boolean%': Boolean,
- '%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
- '%Date%': Date,
- '%decodeURI%': decodeURI,
- '%decodeURIComponent%': decodeURIComponent,
- '%encodeURI%': encodeURI,
- '%encodeURIComponent%': encodeURIComponent,
- '%Error%': Error,
- '%eval%': eval, // eslint-disable-line no-eval
- '%EvalError%': EvalError,
- '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
- '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
- '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
- '%Function%': $Function,
- '%GeneratorFunction%': needsEval,
- '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
- '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
- '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
- '%isFinite%': isFinite,
- '%isNaN%': isNaN,
- '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
- '%JSON%': typeof JSON === 'object' ? JSON : undefined,
- '%Map%': typeof Map === 'undefined' ? undefined : Map,
- '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
- '%Math%': Math,
- '%Number%': Number,
- '%Object%': Object,
- '%parseFloat%': parseFloat,
- '%parseInt%': parseInt,
- '%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
- '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
- '%RangeError%': RangeError,
- '%ReferenceError%': ReferenceError,
- '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
- '%RegExp%': RegExp,
- '%Set%': typeof Set === 'undefined' ? undefined : Set,
- '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
- '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
- '%String%': String,
- '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
- '%Symbol%': hasSymbols ? Symbol : undefined,
- '%SyntaxError%': $SyntaxError,
- '%ThrowTypeError%': ThrowTypeError,
- '%TypedArray%': TypedArray,
- '%TypeError%': $TypeError,
- '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
- '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
- '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
- '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
- '%URIError%': URIError,
- '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
- '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
- '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
-};
-
-var doEval = function doEval(name) {
- var value;
- if (name === '%AsyncFunction%') {
- value = getEvalledConstructor('async function () {}');
- } else if (name === '%GeneratorFunction%') {
- value = getEvalledConstructor('function* () {}');
- } else if (name === '%AsyncGeneratorFunction%') {
- value = getEvalledConstructor('async function* () {}');
- } else if (name === '%AsyncGenerator%') {
- var fn = doEval('%AsyncGeneratorFunction%');
- if (fn) {
- value = fn.prototype;
- }
- } else if (name === '%AsyncIteratorPrototype%') {
- var gen = doEval('%AsyncGenerator%');
- if (gen) {
- value = getProto(gen.prototype);
- }
- }
-
- INTRINSICS[name] = value;
-
- return value;
-};
-
-var LEGACY_ALIASES = {
- '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
- '%ArrayPrototype%': ['Array', 'prototype'],
- '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
- '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
- '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
- '%ArrayProto_values%': ['Array', 'prototype', 'values'],
- '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
- '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
- '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
- '%BooleanPrototype%': ['Boolean', 'prototype'],
- '%DataViewPrototype%': ['DataView', 'prototype'],
- '%DatePrototype%': ['Date', 'prototype'],
- '%ErrorPrototype%': ['Error', 'prototype'],
- '%EvalErrorPrototype%': ['EvalError', 'prototype'],
- '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
- '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
- '%FunctionPrototype%': ['Function', 'prototype'],
- '%Generator%': ['GeneratorFunction', 'prototype'],
- '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
- '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
- '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
- '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
- '%JSONParse%': ['JSON', 'parse'],
- '%JSONStringify%': ['JSON', 'stringify'],
- '%MapPrototype%': ['Map', 'prototype'],
- '%NumberPrototype%': ['Number', 'prototype'],
- '%ObjectPrototype%': ['Object', 'prototype'],
- '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
- '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
- '%PromisePrototype%': ['Promise', 'prototype'],
- '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
- '%Promise_all%': ['Promise', 'all'],
- '%Promise_reject%': ['Promise', 'reject'],
- '%Promise_resolve%': ['Promise', 'resolve'],
- '%RangeErrorPrototype%': ['RangeError', 'prototype'],
- '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
- '%RegExpPrototype%': ['RegExp', 'prototype'],
- '%SetPrototype%': ['Set', 'prototype'],
- '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
- '%StringPrototype%': ['String', 'prototype'],
- '%SymbolPrototype%': ['Symbol', 'prototype'],
- '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
- '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
- '%TypeErrorPrototype%': ['TypeError', 'prototype'],
- '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
- '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
- '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
- '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
- '%URIErrorPrototype%': ['URIError', 'prototype'],
- '%WeakMapPrototype%': ['WeakMap', 'prototype'],
- '%WeakSetPrototype%': ['WeakSet', 'prototype']
-};
+// https://fetch.spec.whatwg.org/#append-a-request-origin-header
+function appendRequestOriginHeader (request) {
+ // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
+ let serializedOrigin = request.origin
-var bind = __nccwpck_require__(88334);
-var hasOwn = __nccwpck_require__(76339);
-var $concat = bind.call(Function.call, Array.prototype.concat);
-var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
-var $replace = bind.call(Function.call, String.prototype.replace);
-var $strSlice = bind.call(Function.call, String.prototype.slice);
-
-/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
-var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
-var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
-var stringToPath = function stringToPath(string) {
- var first = $strSlice(string, 0, 1);
- var last = $strSlice(string, -1);
- if (first === '%' && last !== '%') {
- throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
- } else if (last === '%' && first !== '%') {
- throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
- }
- var result = [];
- $replace(string, rePropName, function (match, number, quote, subString) {
- result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
- });
- return result;
-};
-/* end adaptation */
-
-var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
- var intrinsicName = name;
- var alias;
- if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
- alias = LEGACY_ALIASES[intrinsicName];
- intrinsicName = '%' + alias[0] + '%';
- }
-
- if (hasOwn(INTRINSICS, intrinsicName)) {
- var value = INTRINSICS[intrinsicName];
- if (value === needsEval) {
- value = doEval(intrinsicName);
- }
- if (typeof value === 'undefined' && !allowMissing) {
- throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
- }
-
- return {
- alias: alias,
- name: intrinsicName,
- value: value
- };
- }
-
- throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
-};
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
+ if (serializedOrigin) {
+ request.headersList.append('origin', serializedOrigin)
+ }
-module.exports = function GetIntrinsic(name, allowMissing) {
- if (typeof name !== 'string' || name.length === 0) {
- throw new $TypeError('intrinsic name must be a non-empty string');
- }
- if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
- throw new $TypeError('"allowMissing" argument must be a boolean');
- }
-
- var parts = stringToPath(name);
- var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
-
- var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
- var intrinsicRealName = intrinsic.name;
- var value = intrinsic.value;
- var skipFurtherCaching = false;
-
- var alias = intrinsic.alias;
- if (alias) {
- intrinsicBaseName = alias[0];
- $spliceApply(parts, $concat([0, 1], alias));
- }
-
- for (var i = 1, isOwn = true; i < parts.length; i += 1) {
- var part = parts[i];
- var first = $strSlice(part, 0, 1);
- var last = $strSlice(part, -1);
- if (
- (
- (first === '"' || first === "'" || first === '`')
- || (last === '"' || last === "'" || last === '`')
- )
- && first !== last
- ) {
- throw new $SyntaxError('property names with quotes must have matching quotes');
- }
- if (part === 'constructor' || !isOwn) {
- skipFurtherCaching = true;
- }
-
- intrinsicBaseName += '.' + part;
- intrinsicRealName = '%' + intrinsicBaseName + '%';
-
- if (hasOwn(INTRINSICS, intrinsicRealName)) {
- value = INTRINSICS[intrinsicRealName];
- } else if (value != null) {
- if (!(part in value)) {
- if (!allowMissing) {
- throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
- }
- return void undefined;
- }
- if ($gOPD && (i + 1) >= parts.length) {
- var desc = $gOPD(value, part);
- isOwn = !!desc;
-
- // By convention, when a data property is converted to an accessor
- // property to emulate a data property that does not suffer from
- // the override mistake, that accessor's getter is marked with
- // an `originalValue` property. Here, when we detect this, we
- // uphold the illusion by pretending to see that original data
- // property, i.e., returning the value rather than the getter
- // itself.
- if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
- value = desc.get;
- } else {
- value = value[part];
- }
- } else {
- isOwn = hasOwn(value, part);
- value = value[part];
- }
-
- if (isOwn && !skipFurtherCaching) {
- INTRINSICS[intrinsicRealName] = value;
- }
- }
- }
- return value;
-};
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
+ } else if (request.method !== 'GET' && request.method !== 'HEAD') {
+ // 1. Switch on request’s referrer policy:
+ switch (request.referrerPolicy) {
+ case 'no-referrer':
+ // Set serializedOrigin to `null`.
+ serializedOrigin = null
+ break
+ case 'no-referrer-when-downgrade':
+ case 'strict-origin':
+ case 'strict-origin-when-cross-origin':
+ // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ case 'same-origin':
+ // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
+ if (!sameOrigin(request, requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ default:
+ // Do nothing.
+ }
+ if (serializedOrigin) {
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
+ request.headersList.append('origin', serializedOrigin)
+ }
+ }
+}
-/***/ }),
+function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
+ // TODO
+ return performance.now()
+}
-/***/ 14780:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
+function createOpaqueTimingInfo (timingInfo) {
+ return {
+ startTime: timingInfo.startTime ?? 0,
+ redirectStartTime: 0,
+ redirectEndTime: 0,
+ postRedirectStartTime: timingInfo.startTime ?? 0,
+ finalServiceWorkerStartTime: 0,
+ finalNetworkResponseStartTime: 0,
+ finalNetworkRequestStartTime: 0,
+ endTime: 0,
+ encodedBodySize: 0,
+ decodedBodySize: 0,
+ finalConnectionTimingInfo: null
+ }
+}
-"use strict";
-/**
- * gitignore-to-glob
- * https://github.com/EE/gitignore-to-glob
- *
- * Author Michał Gołębiowski
- * Licensed under the MIT license.
- */
+// https://html.spec.whatwg.org/multipage/origin.html#policy-container
+function makePolicyContainer () {
+ // Note: the fetch spec doesn't make use of embedder policy or CSP list
+ return {
+ referrerPolicy: 'strict-origin-when-cross-origin'
+ }
+}
+// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
+function clonePolicyContainer (policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
+ }
+}
+// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+function determineRequestsReferrer (request) {
+ // 1. Let policy be request's referrer policy.
+ const policy = request.referrerPolicy
-const fs = __nccwpck_require__(57147);
-const path = __nccwpck_require__(71017);
+ // Note: policy cannot (shouldn't) be null or an empty string.
+ assert(policy)
-module.exports = (gitignorePath, dirsToCheck) => {
- gitignorePath = path.resolve(gitignorePath || '.gitignore');
+ // 2. Let environment be request’s client.
- return fs.readFileSync(gitignorePath, {encoding: 'utf8'})
- .split('\n')
+ let referrerSource = null
- // Filter out empty lines and comments.
- .filter(pattern => !!pattern && pattern[0] !== '#')
+ // 3. Switch on request’s referrer:
+ if (request.referrer === 'client') {
+ // Note: node isn't a browser and doesn't implement document/iframes,
+ // so we bypass this step and replace it with our own.
- // '!' in .gitignore and glob mean opposite things so we need to swap it.
- // Return pairt [ignoreFlag, pattern], we'll concatenate it later.
- .map(pattern => pattern[0] === '!' ? ['', pattern.substring(1)] : ['!', pattern])
+ const globalOrigin = getGlobalOrigin()
- // Filter out hidden files/directories (i.e. starting with a dot).
- .filter(patternPair => {
- const pattern = patternPair[1];
- return pattern.indexOf('/.') === -1 && pattern.indexOf('.') !== 0;
- })
+ if (!globalOrigin || globalOrigin.origin === 'null') {
+ return 'no-referrer'
+ }
- // There may be a lot of files outside of directories from `dirsToCheck`, don't ignore
- // them wasting time.
- .filter(patternPair => {
- const pattern = patternPair[1];
- return pattern[0] !== '/' || !dirsToCheck ||
- new RegExp(`^/(?:${ dirsToCheck.join('|') })(?:/|$)`).test(pattern);
- })
+ // note: we need to clone it as it's mutated
+ referrerSource = new URL(globalOrigin)
+ } else if (request.referrer instanceof URL) {
+ // Let referrerSource be request’s referrer.
+ referrerSource = request.referrer
+ }
- // Patterns not starting with '/' are in fact "starting" with '**/'. Since that would
- // catch a lot of files, restrict it to directories we check.
- // Patterns starting with '/' are relative to the project directory and glob would
- // treat them as relative to the OS root directory so strip the slash then.
- .map(patternPair => {
- const pattern = patternPair[1];
- if (pattern[0] !== '/') {
- return [patternPair[0],
- `${ dirsToCheck ? `{${ dirsToCheck }}/` : '' }**/${ pattern }`];
- }
- return [patternPair[0], pattern.substring(1)];
- })
+ // 4. Let request’s referrerURL be the result of stripping referrerSource for
+ // use as a referrer.
+ let referrerURL = stripURLForReferrer(referrerSource)
- // We don't know whether a pattern points to a directory or a file and we need files.
- // Therefore, include both `pattern` and `pattern/**` for every pattern in the array.
- .reduce((result, patternPair) => {
- const pattern = patternPair.join('');
- result.push(pattern);
- result.push(`${ pattern }/**`);
- return result;
- }, []);
-};
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as
+ // a referrer, with the origin-only flag set to true.
+ const referrerOrigin = stripURLForReferrer(referrerSource, true)
+ // 6. If the result of serializing referrerURL is a string whose length is
+ // greater than 4096, set referrerURL to referrerOrigin.
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin
+ }
-/***/ }),
+ const areSameOrigin = sameOrigin(request, referrerURL)
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
+ !isURLPotentiallyTrustworthy(request.url)
-/***/ 54655:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 8. Execute the switch statements corresponding to the value of policy:
+ switch (policy) {
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
+ case 'unsafe-url': return referrerURL
+ case 'same-origin':
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
+ case 'origin-when-cross-origin':
+ return areSameOrigin ? referrerURL : referrerOrigin
+ case 'strict-origin-when-cross-origin': {
+ const currentURL = requestCurrentURL(request)
-"use strict";
+ // 1. If the origin of referrerURL and the origin of request’s current
+ // URL are the same, then return referrerURL.
+ if (sameOrigin(referrerURL, currentURL)) {
+ return referrerURL
+ }
+ // 2. If referrerURL is a potentially trustworthy URL and request’s
+ // current URL is not a potentially trustworthy URL, then return no
+ // referrer.
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer'
+ }
-var isGlob = __nccwpck_require__(34466);
-var pathPosixDirname = (__nccwpck_require__(71017).posix.dirname);
-var isWin32 = (__nccwpck_require__(22037).platform)() === 'win32';
+ // 3. Return referrerOrigin.
+ return referrerOrigin
+ }
+ case 'strict-origin': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+ case 'no-referrer-when-downgrade': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
-var slash = '/';
-var backslash = /\\/g;
-var enclosure = /[\{\[].*[\}\]]$/;
-var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
-var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
+ default: // eslint-disable-line
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
+ }
+}
/**
- * @param {string} str
- * @param {Object} opts
- * @param {boolean} [opts.flipBackslashes=true]
- * @returns {string}
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
+ * @param {URL} url
+ * @param {boolean|undefined} originOnly
*/
-module.exports = function globParent(str, opts) {
- var options = Object.assign({ flipBackslashes: true }, opts);
+function stripURLForReferrer (url, originOnly) {
+ // 1. Assert: url is a URL.
+ assert(url instanceof URL)
- // flip windows path separators
- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
- str = str.replace(backslash, slash);
+ // 2. If url’s scheme is a local scheme, then return no referrer.
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
+ return 'no-referrer'
}
- // special case for strings ending in enclosure containing path separator
- if (enclosure.test(str)) {
- str += slash;
- }
+ // 3. Set url’s username to the empty string.
+ url.username = ''
- // preserves full path in case of trailing path separator
- str += 'a';
+ // 4. Set url’s password to the empty string.
+ url.password = ''
- // remove path parts that are globby
- do {
- str = pathPosixDirname(str);
- } while (isGlob(str) || globby.test(str));
+ // 5. Set url’s fragment to null.
+ url.hash = ''
- // remove escape chars and return result
- return str.replace(escaped, '$1');
-};
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 1. Set url’s path to « the empty string ».
+ url.pathname = ''
+ // 2. Set url’s query to null.
+ url.search = ''
+ }
-/***/ }),
+ // 7. Return url.
+ return url
+}
-/***/ 47625:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function isURLPotentiallyTrustworthy (url) {
+ if (!(url instanceof URL)) {
+ return false
+ }
-exports.setopts = setopts
-exports.ownProp = ownProp
-exports.makeAbs = makeAbs
-exports.finish = finish
-exports.mark = mark
-exports.isIgnored = isIgnored
-exports.childrenIgnored = childrenIgnored
+ // If child of about, return true
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
+ return true
+ }
-function ownProp (obj, field) {
- return Object.prototype.hasOwnProperty.call(obj, field)
-}
+ // If scheme is data, return true
+ if (url.protocol === 'data:') return true
-var fs = __nccwpck_require__(57147)
-var path = __nccwpck_require__(71017)
-var minimatch = __nccwpck_require__(83973)
-var isAbsolute = __nccwpck_require__(38714)
-var Minimatch = minimatch.Minimatch
+ // If file, return true
+ if (url.protocol === 'file:') return true
-function alphasort (a, b) {
- return a.localeCompare(b, 'en')
-}
+ return isOriginPotentiallyTrustworthy(url.origin)
-function setupIgnores (self, options) {
- self.ignore = options.ignore || []
+ function isOriginPotentiallyTrustworthy (origin) {
+ // If origin is explicitly null, return false
+ if (origin == null || origin === 'null') return false
- if (!Array.isArray(self.ignore))
- self.ignore = [self.ignore]
+ const originAsURL = new URL(origin)
- if (self.ignore.length) {
- self.ignore = self.ignore.map(ignoreMap)
- }
-}
+ // If secure, return true
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
+ return true
+ }
+
+ // If localhost or variants, return true
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
+ (originAsURL.hostname.endsWith('.localhost'))) {
+ return true
+ }
-// ignore patterns are always in dot:true mode.
-function ignoreMap (pattern) {
- var gmatcher = null
- if (pattern.slice(-3) === '/**') {
- var gpattern = pattern.replace(/(\/\*\*)+$/, '')
- gmatcher = new Minimatch(gpattern, { dot: true })
+ // If any other, return false
+ return false
}
+}
- return {
- matcher: new Minimatch(pattern, { dot: true }),
- gmatcher: gmatcher
- }
-}
-
-function setopts (self, pattern, options) {
- if (!options)
- options = {}
-
- // base-matching: just use globstar for that.
- if (options.matchBase && -1 === pattern.indexOf("/")) {
- if (options.noglobstar) {
- throw new Error("base matching requires globstar")
- }
- pattern = "**/" + pattern
- }
-
- self.silent = !!options.silent
- self.pattern = pattern
- self.strict = options.strict !== false
- self.realpath = !!options.realpath
- self.realpathCache = options.realpathCache || Object.create(null)
- self.follow = !!options.follow
- self.dot = !!options.dot
- self.mark = !!options.mark
- self.nodir = !!options.nodir
- if (self.nodir)
- self.mark = true
- self.sync = !!options.sync
- self.nounique = !!options.nounique
- self.nonull = !!options.nonull
- self.nosort = !!options.nosort
- self.nocase = !!options.nocase
- self.stat = !!options.stat
- self.noprocess = !!options.noprocess
- self.absolute = !!options.absolute
- self.fs = options.fs || fs
-
- self.maxLength = options.maxLength || Infinity
- self.cache = options.cache || Object.create(null)
- self.statCache = options.statCache || Object.create(null)
- self.symlinks = options.symlinks || Object.create(null)
-
- setupIgnores(self, options)
-
- self.changedCwd = false
- var cwd = process.cwd()
- if (!ownProp(options, "cwd"))
- self.cwd = cwd
- else {
- self.cwd = path.resolve(options.cwd)
- self.changedCwd = self.cwd !== cwd
- }
-
- self.root = options.root || path.resolve(self.cwd, "/")
- self.root = path.resolve(self.root)
- if (process.platform === "win32")
- self.root = self.root.replace(/\\/g, "/")
-
- // TODO: is an absolute `cwd` supposed to be resolved against `root`?
- // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
- self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
- if (process.platform === "win32")
- self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
- self.nomount = !!options.nomount
-
- // disable comments and negation in Minimatch.
- // Note that they are not supported in Glob itself anyway.
- options.nonegate = true
- options.nocomment = true
-
- self.minimatch = new Minimatch(pattern, options)
- self.options = self.minimatch.options
-}
-
-function finish (self) {
- var nou = self.nounique
- var all = nou ? [] : Object.create(null)
-
- for (var i = 0, l = self.matches.length; i < l; i ++) {
- var matches = self.matches[i]
- if (!matches || Object.keys(matches).length === 0) {
- if (self.nonull) {
- // do like the shell, and spit out the literal glob
- var literal = self.minimatch.globSet[i]
- if (nou)
- all.push(literal)
- else
- all[literal] = true
- }
- } else {
- // had matches
- var m = Object.keys(matches)
- if (nou)
- all.push.apply(all, m)
- else
- m.forEach(function (m) {
- all[m] = true
- })
- }
+/**
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
+ * @param {Uint8Array} bytes
+ * @param {string} metadataList
+ */
+function bytesMatch (bytes, metadataList) {
+ // If node is not built with OpenSSL support, we cannot check
+ // a request's integrity, so allow it by default (the spec will
+ // allow requests if an invalid hash is given, as precedence).
+ /* istanbul ignore if: only if node is built with --without-ssl */
+ if (crypto === undefined) {
+ return true
}
- if (!nou)
- all = Object.keys(all)
+ // 1. Let parsedMetadata be the result of parsing metadataList.
+ const parsedMetadata = parseMetadata(metadataList)
- if (!self.nosort)
- all = all.sort(alphasort)
+ // 2. If parsedMetadata is no metadata, return true.
+ if (parsedMetadata === 'no metadata') {
+ return true
+ }
- // at *some* point we statted all of these
- if (self.mark) {
- for (var i = 0; i < all.length; i++) {
- all[i] = self._mark(all[i])
- }
- if (self.nodir) {
- all = all.filter(function (e) {
- var notDir = !(/\/$/.test(e))
- var c = self.cache[e] || self.cache[makeAbs(self, e)]
- if (notDir && c)
- notDir = c !== 'DIR' && !Array.isArray(c)
- return notDir
- })
- }
+ // 3. If parsedMetadata is the empty set, return true.
+ if (parsedMetadata.length === 0) {
+ return true
}
- if (self.ignore.length)
- all = all.filter(function(m) {
- return !isIgnored(self, m)
- })
+ // 4. Let metadata be the result of getting the strongest
+ // metadata from parsedMetadata.
+ const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo))
+ // get the strongest algorithm
+ const strongest = list[0].algo
+ // get all entries that use the strongest algorithm; ignore weaker
+ const metadata = list.filter((item) => item.algo === strongest)
- self.found = all
-}
+ // 5. For each item in metadata:
+ for (const item of metadata) {
+ // 1. Let algorithm be the alg component of item.
+ const algorithm = item.algo
-function mark (self, p) {
- var abs = makeAbs(self, p)
- var c = self.cache[abs]
- var m = p
- if (c) {
- var isDir = c === 'DIR' || Array.isArray(c)
- var slash = p.slice(-1) === '/'
+ // 2. Let expectedValue be the val component of item.
+ let expectedValue = item.hash
- if (isDir && !slash)
- m += '/'
- else if (!isDir && slash)
- m = m.slice(0, -1)
+ // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
+ // "be liberal with padding". This is annoying, and it's not even in the spec.
- if (m !== p) {
- var mabs = makeAbs(self, m)
- self.statCache[mabs] = self.statCache[abs]
- self.cache[mabs] = self.cache[abs]
+ if (expectedValue.endsWith('==')) {
+ expectedValue = expectedValue.slice(0, -2)
}
- }
-
- return m
-}
-// lotta situps...
-function makeAbs (self, f) {
- var abs = f
- if (f.charAt(0) === '/') {
- abs = path.join(self.root, f)
- } else if (isAbsolute(f) || f === '') {
- abs = f
- } else if (self.changedCwd) {
- abs = path.resolve(self.cwd, f)
- } else {
- abs = path.resolve(f)
- }
-
- if (process.platform === 'win32')
- abs = abs.replace(/\\/g, '/')
+ // 3. Let actualValue be the result of applying algorithm to bytes.
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
- return abs
-}
+ if (actualValue.endsWith('==')) {
+ actualValue = actualValue.slice(0, -2)
+ }
+ // 4. If actualValue is a case-sensitive match for expectedValue,
+ // return true.
+ if (actualValue === expectedValue) {
+ return true
+ }
-// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
-// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
-function isIgnored (self, path) {
- if (!self.ignore.length)
- return false
+ let actualBase64URL = crypto.createHash(algorithm).update(bytes).digest('base64url')
- return self.ignore.some(function(item) {
- return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
- })
-}
+ if (actualBase64URL.endsWith('==')) {
+ actualBase64URL = actualBase64URL.slice(0, -2)
+ }
-function childrenIgnored (self, path) {
- if (!self.ignore.length)
- return false
+ if (actualBase64URL === expectedValue) {
+ return true
+ }
+ }
- return self.ignore.some(function(item) {
- return !!(item.gmatcher && item.gmatcher.match(path))
- })
+ // 6. Return false.
+ return false
}
+// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
+// https://www.w3.org/TR/CSP2/#source-list-syntax
+// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
+const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i
-/***/ }),
+/**
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
+ * @param {string} metadata
+ */
+function parseMetadata (metadata) {
+ // 1. Let result be the empty set.
+ /** @type {{ algo: string, hash: string }[]} */
+ const result = []
-/***/ 91957:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let empty be equal to true.
+ let empty = true
-// Approach:
-//
-// 1. Get the minimatch set
-// 2. For each pattern in the set, PROCESS(pattern, false)
-// 3. Store matches per-set, then uniq them
-//
-// PROCESS(pattern, inGlobStar)
-// Get the first [n] items from pattern that are all strings
-// Join these together. This is PREFIX.
-// If there is no more remaining, then stat(PREFIX) and
-// add to matches if it succeeds. END.
-//
-// If inGlobStar and PREFIX is symlink and points to dir
-// set ENTRIES = []
-// else readdir(PREFIX) as ENTRIES
-// If fail, END
-//
-// with ENTRIES
-// If pattern[n] is GLOBSTAR
-// // handle the case where the globstar match is empty
-// // by pruning it out, and testing the resulting pattern
-// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
-// // handle other cases.
-// for ENTRY in ENTRIES (not dotfiles)
-// // attach globstar + tail onto the entry
-// // Mark that this entry is a globstar match
-// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
-//
-// else // not globstar
-// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
-// Test ENTRY against pattern[n]
-// If fails, continue
-// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
-//
-// Caveat:
-// Cache all stats and readdirs results to minimize syscall. Since all
-// we ever care about is existence and directory-ness, we can just keep
-// `true` for files, and [children,...] for directories, or `false` for
-// things that don't exist.
+ const supportedHashes = crypto.getHashes()
-module.exports = glob
+ // 3. For each token returned by splitting metadata on spaces:
+ for (const token of metadata.split(' ')) {
+ // 1. Set empty to false.
+ empty = false
-var rp = __nccwpck_require__(46863)
-var minimatch = __nccwpck_require__(83973)
-var Minimatch = minimatch.Minimatch
-var inherits = __nccwpck_require__(44124)
-var EE = (__nccwpck_require__(82361).EventEmitter)
-var path = __nccwpck_require__(71017)
-var assert = __nccwpck_require__(39491)
-var isAbsolute = __nccwpck_require__(38714)
-var globSync = __nccwpck_require__(29010)
-var common = __nccwpck_require__(47625)
-var setopts = common.setopts
-var ownProp = common.ownProp
-var inflight = __nccwpck_require__(52492)
-var util = __nccwpck_require__(73837)
-var childrenIgnored = common.childrenIgnored
-var isIgnored = common.isIgnored
+ // 2. Parse token as a hash-with-options.
+ const parsedToken = parseHashWithOptions.exec(token)
-var once = __nccwpck_require__(1223)
+ // 3. If token does not parse, continue to the next token.
+ if (parsedToken === null || parsedToken.groups === undefined) {
+ // Note: Chromium blocks the request at this point, but Firefox
+ // gives a warning that an invalid integrity was given. The
+ // correct behavior is to ignore these, and subsequently not
+ // check the integrity of the resource.
+ continue
+ }
-function glob (pattern, options, cb) {
- if (typeof options === 'function') cb = options, options = {}
- if (!options) options = {}
+ // 4. Let algorithm be the hash-algo component of token.
+ const algorithm = parsedToken.groups.algo
- if (options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return globSync(pattern, options)
+ // 5. If algorithm is a hash function recognized by the user
+ // agent, add the parsed token to result.
+ if (supportedHashes.includes(algorithm.toLowerCase())) {
+ result.push(parsedToken.groups)
+ }
}
- return new Glob(pattern, options, cb)
-}
-
-glob.sync = globSync
-var GlobSync = glob.GlobSync = globSync.GlobSync
-
-// old api surface
-glob.glob = glob
-
-function extend (origin, add) {
- if (add === null || typeof add !== 'object') {
- return origin
+ // 4. Return no metadata if empty is true, otherwise return result.
+ if (empty === true) {
+ return 'no metadata'
}
- var keys = Object.keys(add)
- var i = keys.length
- while (i--) {
- origin[keys[i]] = add[keys[i]]
- }
- return origin
+ return result
}
-glob.hasMagic = function (pattern, options_) {
- var options = extend({}, options_)
- options.noprocess = true
-
- var g = new Glob(pattern, options)
- var set = g.minimatch.set
-
- if (!pattern)
- return false
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
+function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
+ // TODO
+}
- if (set.length > 1)
+/**
+ * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
+ * @param {URL} A
+ * @param {URL} B
+ */
+function sameOrigin (A, B) {
+ // 1. If A and B are the same opaque origin, then return true.
+ if (A.origin === B.origin && A.origin === 'null') {
return true
+ }
- for (var j = 0; j < set[0].length; j++) {
- if (typeof set[0][j] !== 'string')
- return true
+ // 2. If A and B are both tuple origins and their schemes,
+ // hosts, and port are identical, then return true.
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
+ return true
}
+ // 3. Return false.
return false
}
-glob.Glob = Glob
-inherits(Glob, EE)
-function Glob (pattern, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = null
- }
+function createDeferredPromise () {
+ let res
+ let rej
+ const promise = new Promise((resolve, reject) => {
+ res = resolve
+ rej = reject
+ })
- if (options && options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return new GlobSync(pattern, options)
- }
+ return { promise, resolve: res, reject: rej }
+}
- if (!(this instanceof Glob))
- return new Glob(pattern, options, cb)
+function isAborted (fetchParams) {
+ return fetchParams.controller.state === 'aborted'
+}
- setopts(this, pattern, options)
- this._didRealPath = false
+function isCancelled (fetchParams) {
+ return fetchParams.controller.state === 'aborted' ||
+ fetchParams.controller.state === 'terminated'
+}
- // process each pattern in the minimatch set
- var n = this.minimatch.set.length
+// https://fetch.spec.whatwg.org/#concept-method-normalize
+function normalizeMethod (method) {
+ return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method)
+ ? method.toUpperCase()
+ : method
+}
- // The matches are stored as {: true,...} so that
- // duplicates are automagically pruned.
- // Later, we do an Object.keys() on these.
- // Keep them as a list so we can fill in when nonull is set.
- this.matches = new Array(n)
+// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
+function serializeJavascriptValueToJSONString (value) {
+ // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
+ const result = JSON.stringify(value)
- if (typeof cb === 'function') {
- cb = once(cb)
- this.on('error', cb)
- this.on('end', function (matches) {
- cb(null, matches)
- })
+ // 2. If result is undefined, then throw a TypeError.
+ if (result === undefined) {
+ throw new TypeError('Value is not JSON serializable')
}
- var self = this
- this._processing = 0
-
- this._emitQueue = []
- this._processQueue = []
- this.paused = false
-
- if (this.noprocess)
- return this
-
- if (n === 0)
- return done()
-
- var sync = true
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false, done)
- }
- sync = false
+ // 3. Assert: result is a string.
+ assert(typeof result === 'string')
- function done () {
- --self._processing
- if (self._processing <= 0) {
- if (sync) {
- process.nextTick(function () {
- self._finish()
- })
- } else {
- self._finish()
- }
- }
- }
+ // 4. Return result.
+ return result
}
-Glob.prototype._finish = function () {
- assert(this instanceof Glob)
- if (this.aborted)
- return
-
- if (this.realpath && !this._didRealpath)
- return this._realpath()
-
- common.finish(this)
- this.emit('end', this.found)
-}
+// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
+const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
-Glob.prototype._realpath = function () {
- if (this._didRealpath)
- return
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {() => unknown[]} iterator
+ * @param {string} name name of the instance
+ * @param {'key'|'value'|'key+value'} kind
+ */
+function makeIterator (iterator, name, kind) {
+ const object = {
+ index: 0,
+ kind,
+ target: iterator
+ }
- this._didRealpath = true
+ const i = {
+ next () {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
- var n = this.matches.length
- if (n === 0)
- return this._finish()
+ // 2. Let thisValue be the this value.
- var self = this
- for (var i = 0; i < this.matches.length; i++)
- this._realpathSet(i, next)
+ // 3. Let object be ? ToObject(thisValue).
- function next () {
- if (--n === 0)
- self._finish()
- }
-}
+ // 4. If object is a platform object, then perform a security
+ // check, passing:
-Glob.prototype._realpathSet = function (index, cb) {
- var matchset = this.matches[index]
- if (!matchset)
- return cb()
+ // 5. If object is not a default iterator object for interface,
+ // then throw a TypeError.
+ if (Object.getPrototypeOf(this) !== i) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ )
+ }
- var found = Object.keys(matchset)
- var self = this
- var n = found.length
+ // 6. Let index be object’s index.
+ // 7. Let kind be object’s kind.
+ // 8. Let values be object’s target's value pairs to iterate over.
+ const { index, kind, target } = object
+ const values = target()
- if (n === 0)
- return cb()
+ // 9. Let len be the length of values.
+ const len = values.length
- var set = this.matches[index] = Object.create(null)
- found.forEach(function (p, i) {
- // If there's a problem with the stat, then it means that
- // one or more of the links in the realpath couldn't be
- // resolved. just return the abs value in that case.
- p = self._makeAbs(p)
- rp.realpath(p, self.realpathCache, function (er, real) {
- if (!er)
- set[real] = true
- else if (er.syscall === 'stat')
- set[p] = true
- else
- self.emit('error', er) // srsly wtf right here
-
- if (--n === 0) {
- self.matches[index] = set
- cb()
+ // 10. If index is greater than or equal to len, then return
+ // CreateIterResultObject(undefined, true).
+ if (index >= len) {
+ return { value: undefined, done: true }
}
- })
- })
-}
-
-Glob.prototype._mark = function (p) {
- return common.mark(this, p)
-}
-Glob.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
-}
+ // 11. Let pair be the entry in values at index index.
+ const pair = values[index]
-Glob.prototype.abort = function () {
- this.aborted = true
- this.emit('abort')
-}
+ // 12. Set object’s index to index + 1.
+ object.index = index + 1
-Glob.prototype.pause = function () {
- if (!this.paused) {
- this.paused = true
- this.emit('pause')
+ // 13. Return the iterator result for pair and kind.
+ return iteratorResult(pair, kind)
+ },
+ // The class string of an iterator prototype object for a given interface is the
+ // result of concatenating the identifier of the interface and the string " Iterator".
+ [Symbol.toStringTag]: `${name} Iterator`
}
-}
-Glob.prototype.resume = function () {
- if (this.paused) {
- this.emit('resume')
- this.paused = false
- if (this._emitQueue.length) {
- var eq = this._emitQueue.slice(0)
- this._emitQueue.length = 0
- for (var i = 0; i < eq.length; i ++) {
- var e = eq[i]
- this._emitMatch(e[0], e[1])
- }
- }
- if (this._processQueue.length) {
- var pq = this._processQueue.slice(0)
- this._processQueue.length = 0
- for (var i = 0; i < pq.length; i ++) {
- var p = pq[i]
- this._processing--
- this._process(p[0], p[1], p[2], p[3])
- }
- }
- }
+ // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
+ Object.setPrototypeOf(i, esIteratorPrototype)
+ // esIteratorPrototype needs to be the prototype of i
+ // which is the prototype of an empty object. Yes, it's confusing.
+ return Object.setPrototypeOf({}, i)
}
-Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
- assert(this instanceof Glob)
- assert(typeof cb === 'function')
+// https://webidl.spec.whatwg.org/#iterator-result
+function iteratorResult (pair, kind) {
+ let result
- if (this.aborted)
- return
-
- this._processing++
- if (this.paused) {
- this._processQueue.push([pattern, index, inGlobStar, cb])
- return
- }
-
- //console.error('PROCESS %d', this._processing, pattern)
-
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
- }
- // now n is the index of the first one that is *not* a string.
-
- // see if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index, cb)
- return
-
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
+ // 1. Let result be a value determined by the value of kind:
+ switch (kind) {
+ case 'key': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 3. result is key.
+ result = pair[0]
break
-
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
+ }
+ case 'value': {
+ // 1. Let idlValue be pair’s value.
+ // 2. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 3. result is value.
+ result = pair[1]
break
- }
-
- var remain = pattern.slice(n)
-
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
-
- var abs = this._makeAbs(read)
-
- //if ignored, skip _processing
- if (childrenIgnored(this, read))
- return cb()
-
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
-}
-
-Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
-}
-
-Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
-
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return cb()
-
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
-
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
}
- }
-
- //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
-
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return cb()
-
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
-
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
-
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
-
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this._emitMatch(index, e)
+ case 'key+value': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let idlValue be pair’s value.
+ // 3. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 4. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 5. Let array be ! ArrayCreate(2).
+ // 6. Call ! CreateDataProperty(array, "0", key).
+ // 7. Call ! CreateDataProperty(array, "1", value).
+ // 8. result is array.
+ result = pair
+ break
}
- // This was the last one, and no stats were needed
- return cb()
}
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
- this._process([e].concat(remain), index, inGlobStar, cb)
- }
- cb()
+ // 2. Return CreateIterResultObject(result, false).
+ return { value: result, done: false }
}
-Glob.prototype._emitMatch = function (index, e) {
- if (this.aborted)
- return
-
- if (isIgnored(this, e))
- return
-
- if (this.paused) {
- this._emitQueue.push([index, e])
- return
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
+ */
+async function fullyReadBody (body, processBody, processBodyError) {
+ // 1. If taskDestination is null, then set taskDestination to
+ // the result of starting a new parallel queue.
- var abs = isAbsolute(e) ? e : this._makeAbs(e)
+ // 2. Let successSteps given a byte sequence bytes be to queue a
+ // fetch task to run processBody given bytes, with taskDestination.
+ const successSteps = processBody
- if (this.mark)
- e = this._mark(e)
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
+ // with taskDestination.
+ const errorSteps = processBodyError
- if (this.absolute)
- e = abs
+ // 4. Let reader be the result of getting a reader for body’s stream.
+ // If that threw an exception, then run errorSteps with that
+ // exception and return.
+ let reader
- if (this.matches[index][e])
+ try {
+ reader = body.stream.getReader()
+ } catch (e) {
+ errorSteps(e)
return
-
- if (this.nodir) {
- var c = this.cache[abs]
- if (c === 'DIR' || Array.isArray(c))
- return
}
- this.matches[index][e] = true
-
- var st = this.statCache[abs]
- if (st)
- this.emit('stat', e, st)
-
- this.emit('match', e)
-}
-
-Glob.prototype._readdirInGlobStar = function (abs, cb) {
- if (this.aborted)
- return
-
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false, cb)
-
- var lstatkey = 'lstat\0' + abs
- var self = this
- var lstatcb = inflight(lstatkey, lstatcb_)
-
- if (lstatcb)
- self.fs.lstat(abs, lstatcb)
-
- function lstatcb_ (er, lstat) {
- if (er && er.code === 'ENOENT')
- return cb()
-
- var isSym = lstat && lstat.isSymbolicLink()
- self.symlinks[abs] = isSym
-
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory()) {
- self.cache[abs] = 'FILE'
- cb()
- } else
- self._readdir(abs, false, cb)
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
+ try {
+ const result = await readAllBytes(reader)
+ successSteps(result)
+ } catch (e) {
+ errorSteps(e)
}
}
-Glob.prototype._readdir = function (abs, inGlobStar, cb) {
- if (this.aborted)
- return
-
- cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
- if (!cb)
- return
-
- //console.error('RD %j %j', +inGlobStar, abs)
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs, cb)
-
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return cb()
+/** @type {ReadableStream} */
+let ReadableStream = globalThis.ReadableStream
- if (Array.isArray(c))
- return cb(null, c)
+function isReadableStreamLike (stream) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(3774).ReadableStream)
}
- var self = this
- self.fs.readdir(abs, readdirCb(this, abs, cb))
+ return stream instanceof ReadableStream || (
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
+ typeof stream.tee === 'function'
+ )
}
-function readdirCb (self, abs, cb) {
- return function (er, entries) {
- if (er)
- self._readdirError(abs, er, cb)
- else
- self._readdirEntries(abs, entries, cb)
- }
-}
+const MAXIMUM_ARGUMENT_LENGTH = 65535
-Glob.prototype._readdirEntries = function (abs, entries, cb) {
- if (this.aborted)
- return
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
+ * @param {number[]|Uint8Array} input
+ */
+function isomorphicDecode (input) {
+ // 1. To isomorphic decode a byte sequence input, return a string whose code point
+ // length is equal to input’s length and whose code points have the same values
+ // as the values of input’s bytes, in the same order.
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
- }
+ if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
+ return String.fromCharCode(...input)
}
- this.cache[abs] = entries
- return cb(null, entries)
+ return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
}
-Glob.prototype._readdirError = function (f, er, cb) {
- if (this.aborted)
- return
-
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f)
- this.cache[abs] = 'FILE'
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd)
- error.path = this.cwd
- error.code = er.code
- this.emit('error', error)
- this.abort()
- }
- break
-
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
-
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict) {
- this.emit('error', er)
- // If the error is handled, then we abort
- // if not, we threw out of here
- this.abort()
- }
- if (!this.silent)
- console.error('glob error', er)
- break
+/**
+ * @param {ReadableStreamController} controller
+ */
+function readableStreamClose (controller) {
+ try {
+ controller.close()
+ } catch (err) {
+ // TODO: add comment explaining why this error occurs.
+ if (!err.message.includes('Controller is already closed')) {
+ throw err
+ }
}
-
- return cb()
-}
-
-Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
}
-
-Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- //console.error('pgs2', prefix, remain[0], entries)
-
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return cb()
-
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
-
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false, cb)
-
- var isSym = this.symlinks[abs]
- var len = entries.length
-
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return cb()
-
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
-
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true, cb)
-
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true, cb)
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
+ * @param {string} input
+ */
+function isomorphicEncode (input) {
+ // 1. Assert: input contains no code points greater than U+00FF.
+ for (let i = 0; i < input.length; i++) {
+ assert(input.charCodeAt(i) <= 0xFF)
}
- cb()
-}
-
-Glob.prototype._processSimple = function (prefix, index, cb) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var self = this
- this._stat(prefix, function (er, exists) {
- self._processSimple2(prefix, index, er, exists, cb)
- })
+ // 2. Return a byte sequence whose length is equal to input’s code
+ // point length and whose bytes have the same values as the
+ // values of input’s code points, in the same order
+ return input
}
-Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
- //console.error('ps2', prefix, exists)
+/**
+ * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
+ * @see https://streams.spec.whatwg.org/#read-loop
+ * @param {ReadableStreamDefaultReader} reader
+ */
+async function readAllBytes (reader) {
+ const bytes = []
+ let byteLength = 0
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ while (true) {
+ const { done, value: chunk } = await reader.read()
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return cb()
+ if (done) {
+ // 1. Call successSteps with bytes.
+ return Buffer.concat(bytes, byteLength)
+ }
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
+ // 1. If chunk is not a Uint8Array object, call failureSteps
+ // with a TypeError and abort these steps.
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Received non-Uint8Array chunk')
}
- }
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
+ // 2. Append the bytes represented by chunk to bytes.
+ bytes.push(chunk)
+ byteLength += chunk.length
- // Mark this as a match
- this._emitMatch(index, prefix)
- cb()
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
+ }
}
-// Returns either 'DIR', 'FILE', or false
-Glob.prototype._stat = function (f, cb) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
-
- if (f.length > this.maxLength)
- return cb()
-
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
-
- if (Array.isArray(c))
- c = 'DIR'
+/**
+ * @see https://fetch.spec.whatwg.org/#is-local
+ * @param {URL} url
+ */
+function urlIsLocal (url) {
+ assert('protocol' in url) // ensure it's a url object
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return cb(null, c)
+ const protocol = url.protocol
- if (needDir && c === 'FILE')
- return cb()
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
+}
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
+/**
+ * @param {string|URL} url
+ */
+function urlHasHttpsScheme (url) {
+ if (typeof url === 'string') {
+ return url.startsWith('https:')
}
- var exists
- var stat = this.statCache[abs]
- if (stat !== undefined) {
- if (stat === false)
- return cb(null, stat)
- else {
- var type = stat.isDirectory() ? 'DIR' : 'FILE'
- if (needDir && type === 'FILE')
- return cb()
- else
- return cb(null, type, stat)
- }
- }
-
- var self = this
- var statcb = inflight('stat\0' + abs, lstatcb_)
- if (statcb)
- self.fs.lstat(abs, statcb)
-
- function lstatcb_ (er, lstat) {
- if (lstat && lstat.isSymbolicLink()) {
- // If it's a symlink, then treat it as the target, unless
- // the target does not exist, then treat it as a file.
- return self.fs.stat(abs, function (er, stat) {
- if (er)
- self._stat2(f, abs, null, lstat, cb)
- else
- self._stat2(f, abs, er, stat, cb)
- })
- } else {
- self._stat2(f, abs, er, lstat, cb)
- }
- }
+ return url.protocol === 'https:'
}
-Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false
- return cb()
- }
-
- var needDir = f.slice(-1) === '/'
- this.statCache[abs] = stat
+/**
+ * @see https://fetch.spec.whatwg.org/#http-scheme
+ * @param {URL} url
+ */
+function urlIsHttpHttpsScheme (url) {
+ assert('protocol' in url) // ensure it's a url object
- if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
- return cb(null, false, stat)
+ const protocol = url.protocol
- var c = true
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE'
- this.cache[abs] = this.cache[abs] || c
+ return protocol === 'http:' || protocol === 'https:'
+}
- if (needDir && c === 'FILE')
- return cb()
+/**
+ * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ */
+const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
- return cb(null, c, stat)
+module.exports = {
+ isAborted,
+ isCancelled,
+ createDeferredPromise,
+ ReadableStreamFrom,
+ toUSVString,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isBlobLike,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ serializeJavascriptValueToJSONString,
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ hasOwn,
+ isErrorLike,
+ fullyReadBody,
+ bytesMatch,
+ isReadableStreamLike,
+ readableStreamClose,
+ isomorphicEncode,
+ isomorphicDecode,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes
}
/***/ }),
-/***/ 29010:
+/***/ 4222:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = globSync
-globSync.GlobSync = GlobSync
-var rp = __nccwpck_require__(46863)
-var minimatch = __nccwpck_require__(83973)
-var Minimatch = minimatch.Minimatch
-var Glob = (__nccwpck_require__(91957).Glob)
-var util = __nccwpck_require__(73837)
-var path = __nccwpck_require__(71017)
-var assert = __nccwpck_require__(39491)
-var isAbsolute = __nccwpck_require__(38714)
-var common = __nccwpck_require__(47625)
-var setopts = common.setopts
-var ownProp = common.ownProp
-var childrenIgnored = common.childrenIgnored
-var isIgnored = common.isIgnored
-function globSync (pattern, options) {
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
-
- return new GlobSync(pattern, options).found
-}
+const { types } = __nccwpck_require__(9023)
+const { hasOwn, toUSVString } = __nccwpck_require__(5523)
-function GlobSync (pattern, options) {
- if (!pattern)
- throw new Error('must provide pattern')
+/** @type {import('../../types/webidl').Webidl} */
+const webidl = {}
+webidl.converters = {}
+webidl.util = {}
+webidl.errors = {}
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
+webidl.errors.exception = function (message) {
+ return new TypeError(`${message.header}: ${message.message}`)
+}
- if (!(this instanceof GlobSync))
- return new GlobSync(pattern, options)
+webidl.errors.conversionFailed = function (context) {
+ const plural = context.types.length === 1 ? '' : ' one of'
+ const message =
+ `${context.argument} could not be converted to` +
+ `${plural}: ${context.types.join(', ')}.`
- setopts(this, pattern, options)
+ return webidl.errors.exception({
+ header: context.prefix,
+ message
+ })
+}
- if (this.noprocess)
- return this
+webidl.errors.invalidArgument = function (context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ })
+}
- var n = this.minimatch.set.length
- this.matches = new Array(n)
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false)
+// https://webidl.spec.whatwg.org/#implements
+webidl.brandCheck = function (V, I, opts = undefined) {
+ if (opts?.strict !== false && !(V instanceof I)) {
+ throw new TypeError('Illegal invocation')
+ } else {
+ return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
}
- this._finish()
}
-GlobSync.prototype._finish = function () {
- assert(this instanceof GlobSync)
- if (this.realpath) {
- var self = this
- this.matches.forEach(function (matchset, index) {
- var set = self.matches[index] = Object.create(null)
- for (var p in matchset) {
- try {
- p = self._makeAbs(p)
- var real = rp.realpathSync(p, self.realpathCache)
- set[real] = true
- } catch (er) {
- if (er.syscall === 'stat')
- set[self._makeAbs(p)] = true
- else
- throw er
- }
- }
+webidl.argumentLengthCheck = function ({ length }, min, ctx) {
+ if (length < min) {
+ throw webidl.errors.exception({
+ message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
+ `but${length ? ' only' : ''} ${length} found.`,
+ ...ctx
})
}
- common.finish(this)
}
+webidl.illegalConstructor = function () {
+ throw webidl.errors.exception({
+ header: 'TypeError',
+ message: 'Illegal constructor'
+ })
+}
-GlobSync.prototype._process = function (pattern, index, inGlobStar) {
- assert(this instanceof GlobSync)
-
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
- }
- // now n is the index of the first one that is *not* a string.
-
- // See if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index)
- return
-
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
- break
+// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
+webidl.util.Type = function (V) {
+ switch (typeof V) {
+ case 'undefined': return 'Undefined'
+ case 'boolean': return 'Boolean'
+ case 'string': return 'String'
+ case 'symbol': return 'Symbol'
+ case 'number': return 'Number'
+ case 'bigint': return 'BigInt'
+ case 'function':
+ case 'object': {
+ if (V === null) {
+ return 'Null'
+ }
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
- break
+ return 'Object'
+ }
}
+}
- var remain = pattern.slice(n)
+// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
+ let upperBound
+ let lowerBound
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
+ // 1. If bitLength is 64, then:
+ if (bitLength === 64) {
+ // 1. Let upperBound be 2^53 − 1.
+ upperBound = Math.pow(2, 53) - 1
- var abs = this._makeAbs(read)
+ // 2. If signedness is "unsigned", then let lowerBound be 0.
+ if (signedness === 'unsigned') {
+ lowerBound = 0
+ } else {
+ // 3. Otherwise let lowerBound be −2^53 + 1.
+ lowerBound = Math.pow(-2, 53) + 1
+ }
+ } else if (signedness === 'unsigned') {
+ // 2. Otherwise, if signedness is "unsigned", then:
- //if ignored, skip processing
- if (childrenIgnored(this, read))
- return
+ // 1. Let lowerBound be 0.
+ lowerBound = 0
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
-}
+ // 2. Let upperBound be 2^bitLength − 1.
+ upperBound = Math.pow(2, bitLength) - 1
+ } else {
+ // 3. Otherwise:
+ // 1. Let lowerBound be -2^bitLength − 1.
+ lowerBound = Math.pow(-2, bitLength) - 1
-GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar)
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
+ upperBound = Math.pow(2, bitLength - 1) - 1
+ }
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return
+ // 4. Let x be ? ToNumber(V).
+ let x = Number(V)
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
-
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
- }
+ // 5. If x is −0, then set x to +0.
+ if (x === 0) {
+ x = 0
}
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return
+ // 6. If the conversion is to an IDL type associated
+ // with the [EnforceRange] extended attribute, then:
+ if (opts.enforceRange === true) {
+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
+ if (
+ Number.isNaN(x) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Could not convert ${V} to an integer.`
+ })
+ }
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
-
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
-
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix.slice(-1) !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
+ // 2. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this._emitMatch(index, e)
+ // 3. If x < lowerBound or x > upperBound, then
+ // throw a TypeError.
+ if (x < lowerBound || x > upperBound) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
+ })
}
- // This was the last one, and no stats were needed
- return
- }
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix)
- newPattern = [prefix, e]
- else
- newPattern = [e]
- this._process(newPattern.concat(remain), index, inGlobStar)
+ // 4. Return x.
+ return x
}
-}
+ // 7. If x is not NaN and the conversion is to an IDL
+ // type associated with the [Clamp] extended
+ // attribute, then:
+ if (!Number.isNaN(x) && opts.clamp === true) {
+ // 1. Set x to min(max(x, lowerBound), upperBound).
+ x = Math.min(Math.max(x, lowerBound), upperBound)
-GlobSync.prototype._emitMatch = function (index, e) {
- if (isIgnored(this, e))
- return
-
- var abs = this._makeAbs(e)
-
- if (this.mark)
- e = this._mark(e)
+ // 2. Round x to the nearest integer, choosing the
+ // even integer if it lies halfway between two,
+ // and choosing +0 rather than −0.
+ if (Math.floor(x) % 2 === 0) {
+ x = Math.floor(x)
+ } else {
+ x = Math.ceil(x)
+ }
- if (this.absolute) {
- e = abs
+ // 3. Return x.
+ return x
}
- if (this.matches[index][e])
- return
-
- if (this.nodir) {
- var c = this.cache[abs]
- if (c === 'DIR' || Array.isArray(c))
- return
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
+ if (
+ Number.isNaN(x) ||
+ (x === 0 && Object.is(0, x)) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ return 0
}
- this.matches[index][e] = true
-
- if (this.stat)
- this._stat(e)
-}
-
+ // 9. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
-GlobSync.prototype._readdirInGlobStar = function (abs) {
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false)
+ // 10. Set x to x modulo 2^bitLength.
+ x = x % Math.pow(2, bitLength)
- var entries
- var lstat
- var stat
- try {
- lstat = this.fs.lstatSync(abs)
- } catch (er) {
- if (er.code === 'ENOENT') {
- // lstat failed, doesn't exist
- return null
- }
+ // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
+ // then return x − 2^bitLength.
+ if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
+ return x - Math.pow(2, bitLength)
}
- var isSym = lstat && lstat.isSymbolicLink()
- this.symlinks[abs] = isSym
-
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory())
- this.cache[abs] = 'FILE'
- else
- entries = this._readdir(abs, false)
-
- return entries
+ // 12. Otherwise, return x.
+ return x
}
-GlobSync.prototype._readdir = function (abs, inGlobStar) {
- var entries
-
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs)
-
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return null
+// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
+webidl.util.IntegerPart = function (n) {
+ // 1. Let r be floor(abs(n)).
+ const r = Math.floor(Math.abs(n))
- if (Array.isArray(c))
- return c
+ // 2. If n < 0, then return -1 × r.
+ if (n < 0) {
+ return -1 * r
}
- try {
- return this._readdirEntries(abs, this.fs.readdirSync(abs))
- } catch (er) {
- this._readdirError(abs, er)
- return null
- }
+ // 3. Otherwise, return r.
+ return r
}
-GlobSync.prototype._readdirEntries = function (abs, entries) {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
+// https://webidl.spec.whatwg.org/#es-sequence
+webidl.sequenceConverter = function (converter) {
+ return (V) => {
+ // 1. If Type(V) is not Object, throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: `Value of type ${webidl.util.Type(V)} is not an Object.`
+ })
}
- }
- this.cache[abs] = entries
+ // 2. Let method be ? GetMethod(V, @@iterator).
+ /** @type {Generator} */
+ const method = V?.[Symbol.iterator]?.()
+ const seq = []
+
+ // 3. If method is undefined, throw a TypeError.
+ if (
+ method === undefined ||
+ typeof method.next !== 'function'
+ ) {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: 'Object is not an iterator.'
+ })
+ }
- // mark and cache dir-ness
- return entries
-}
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
+ while (true) {
+ const { done, value } = method.next()
-GlobSync.prototype._readdirError = function (f, er) {
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- var abs = this._makeAbs(f)
- this.cache[abs] = 'FILE'
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd)
- error.path = this.cwd
- error.code = er.code
- throw error
+ if (done) {
+ break
}
- break
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
+ seq.push(converter(value))
+ }
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict)
- throw er
- if (!this.silent)
- console.error('glob error', er)
- break
+ return seq
}
}
-GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
-
- var entries = this._readdir(abs, inGlobStar)
-
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return
-
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
-
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false)
-
- var len = entries.length
- var isSym = this.symlinks[abs]
-
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return
-
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
+// https://webidl.spec.whatwg.org/#es-to-record
+webidl.recordConverter = function (keyConverter, valueConverter) {
+ return (O) => {
+ // 1. If Type(O) is not Object, throw a TypeError.
+ if (webidl.util.Type(O) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Record',
+ message: `Value of type ${webidl.util.Type(O)} is not an Object.`
+ })
+ }
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true)
+ // 2. Let result be a new empty instance of record.
+ const result = {}
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true)
- }
-}
+ if (!types.isProxy(O)) {
+ // Object.keys only returns enumerable properties
+ const keys = Object.keys(O)
-GlobSync.prototype._processSimple = function (prefix, index) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var exists = this._stat(prefix)
+ for (const key of keys) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
+ // 5. Return result.
+ return result
}
- }
-
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
-
- // Mark this as a match
- this._emitMatch(index, prefix)
-}
-
-// Returns either 'DIR', 'FILE', or false
-GlobSync.prototype._stat = function (f) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
-
- if (f.length > this.maxLength)
- return false
-
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (Array.isArray(c))
- c = 'DIR'
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ const keys = Reflect.ownKeys(O)
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return c
+ // 4. For each key of keys.
+ for (const key of keys) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
- if (needDir && c === 'FILE')
- return false
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
+ if (desc?.enumerable) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
- var exists
- var stat = this.statCache[abs]
- if (!stat) {
- var lstat
- try {
- lstat = this.fs.lstatSync(abs)
- } catch (er) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false
- return false
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
}
}
- if (lstat && lstat.isSymbolicLink()) {
- try {
- stat = this.fs.statSync(abs)
- } catch (er) {
- stat = lstat
- }
- } else {
- stat = lstat
- }
+ // 5. Return result.
+ return result
}
-
- this.statCache[abs] = stat
-
- var c = true
- if (stat)
- c = stat.isDirectory() ? 'DIR' : 'FILE'
-
- this.cache[abs] = this.cache[abs] || c
-
- if (needDir && c === 'FILE')
- return false
-
- return c
}
-GlobSync.prototype._mark = function (p) {
- return common.mark(this, p)
-}
+webidl.interfaceConverter = function (i) {
+ return (V, opts = {}) => {
+ if (opts.strict !== false && !(V instanceof i)) {
+ throw webidl.errors.exception({
+ header: i.name,
+ message: `Expected ${V} to be an instance of ${i.name}.`
+ })
+ }
-GlobSync.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
+ return V
+ }
}
+webidl.dictionaryConverter = function (converters) {
+ return (dictionary) => {
+ const type = webidl.util.Type(dictionary)
+ const dict = {}
-/***/ }),
-
-/***/ 40587:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var origSymbol = typeof Symbol !== 'undefined' && Symbol;
-var hasSymbolSham = __nccwpck_require__(57747);
-
-module.exports = function hasNativeSymbols() {
- if (typeof origSymbol !== 'function') { return false; }
- if (typeof Symbol !== 'function') { return false; }
- if (typeof origSymbol('foo') !== 'symbol') { return false; }
- if (typeof Symbol('bar') !== 'symbol') { return false; }
-
- return hasSymbolSham();
-};
-
-
-/***/ }),
-
-/***/ 57747:
-/***/ ((module) => {
-
-"use strict";
-
-
-/* eslint complexity: [2, 18], max-statements: [2, 33] */
-module.exports = function hasSymbols() {
- if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
- if (typeof Symbol.iterator === 'symbol') { return true; }
-
- var obj = {};
- var sym = Symbol('test');
- var symObj = Object(sym);
- if (typeof sym === 'string') { return false; }
-
- if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
- if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
-
- // temp disabled per https://github.com/ljharb/object.assign/issues/17
- // if (sym instanceof Symbol) { return false; }
- // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
- // if (!(symObj instanceof Symbol)) { return false; }
-
- // if (typeof Symbol.prototype.toString !== 'function') { return false; }
- // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
-
- var symVal = 42;
- obj[sym] = symVal;
- for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
- if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
-
- if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
-
- var syms = Object.getOwnPropertySymbols(obj);
- if (syms.length !== 1 || syms[0] !== sym) { return false; }
-
- if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
-
- if (typeof Object.getOwnPropertyDescriptor === 'function') {
- var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
- if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
- }
-
- return true;
-};
-
-
-/***/ }),
-
-/***/ 99038:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var hasSymbols = __nccwpck_require__(57747);
-
-module.exports = function hasToStringTagShams() {
- return hasSymbols() && !!Symbol.toStringTag;
-};
-
-
-/***/ }),
-
-/***/ 76339:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
+ if (type === 'Null' || type === 'Undefined') {
+ return dict
+ } else if (type !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ })
+ }
-var bind = __nccwpck_require__(88334);
+ for (const options of converters) {
+ const { key, defaultValue, required, converter } = options
-module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
+ if (required === true) {
+ if (!hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Missing required key "${key}".`
+ })
+ }
+ }
+ let value = dictionary[key]
+ const hasDefault = hasOwn(options, 'defaultValue')
-/***/ }),
+ // Only use defaultValue if value is undefined and
+ // a defaultValue options was provided.
+ if (hasDefault && value !== null) {
+ value = value ?? defaultValue
+ }
-/***/ 52492:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // A key can be optional and have no default value.
+ // When this happens, do not perform a conversion,
+ // and do not assign the key a value.
+ if (required || hasDefault || value !== undefined) {
+ value = converter(value)
-var wrappy = __nccwpck_require__(62940)
-var reqs = Object.create(null)
-var once = __nccwpck_require__(1223)
+ if (
+ options.allowedValues &&
+ !options.allowedValues.includes(value)
+ ) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
+ })
+ }
-module.exports = wrappy(inflight)
+ dict[key] = value
+ }
+ }
-function inflight (key, cb) {
- if (reqs[key]) {
- reqs[key].push(cb)
- return null
- } else {
- reqs[key] = [cb]
- return makeres(key)
+ return dict
}
}
-function makeres (key) {
- return once(function RES () {
- var cbs = reqs[key]
- var len = cbs.length
- var args = slice(arguments)
-
- // XXX It's somewhat ambiguous whether a new callback added in this
- // pass should be queued for later execution if something in the
- // list of callbacks throws, or if it should just be discarded.
- // However, it's such an edge case that it hardly matters, and either
- // choice is likely as surprising as the other.
- // As it happens, we do go ahead and schedule it for later execution.
- try {
- for (var i = 0; i < len; i++) {
- cbs[i].apply(null, args)
- }
- } finally {
- if (cbs.length > len) {
- // added more in the interim.
- // de-zalgo, just in case, but don't call again.
- cbs.splice(0, len)
- process.nextTick(function () {
- RES.apply(null, args)
- })
- } else {
- delete reqs[key]
- }
+webidl.nullableConverter = function (converter) {
+ return (V) => {
+ if (V === null) {
+ return V
}
- })
-}
-function slice (args) {
- var length = args.length
- var array = []
-
- for (var i = 0; i < length; i++) array[i] = args[i]
- return array
+ return converter(V)
+ }
}
+// https://webidl.spec.whatwg.org/#es-DOMString
+webidl.converters.DOMString = function (V, opts = {}) {
+ // 1. If V is null and the conversion is to an IDL type
+ // associated with the [LegacyNullToEmptyString]
+ // extended attribute, then return the DOMString value
+ // that represents the empty string.
+ if (V === null && opts.legacyNullToEmptyString) {
+ return ''
+ }
-/***/ }),
-
-/***/ 44124:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let x be ? ToString(V).
+ if (typeof V === 'symbol') {
+ throw new TypeError('Could not convert argument of type symbol to string.')
+ }
-try {
- var util = __nccwpck_require__(73837);
- /* istanbul ignore next */
- if (typeof util.inherits !== 'function') throw '';
- module.exports = util.inherits;
-} catch (e) {
- /* istanbul ignore next */
- module.exports = __nccwpck_require__(8544);
+ // 3. Return the IDL DOMString value that represents the
+ // same sequence of code units as the one the
+ // ECMAScript String value x represents.
+ return String(V)
}
+// https://webidl.spec.whatwg.org/#es-ByteString
+webidl.converters.ByteString = function (V) {
+ // 1. Let x be ? ToString(V).
+ // Note: DOMString converter perform ? ToString(V)
+ const x = webidl.converters.DOMString(V)
-/***/ }),
-
-/***/ 8544:
-/***/ ((module) => {
+ // 2. If the value of any element of x is greater than
+ // 255, then throw a TypeError.
+ for (let index = 0; index < x.length; index++) {
+ const charCode = x.charCodeAt(index)
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- })
- }
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
+ if (charCode > 255) {
+ throw new TypeError(
+ 'Cannot convert argument to a ByteString because the character at ' +
+ `index ${index} has a value of ${charCode} which is greater than 255.`
+ )
}
}
-}
+ // 3. Return an IDL ByteString value whose length is the
+ // length of x, and where the value of each element is
+ // the value of the corresponding element of x.
+ return x
+}
-/***/ }),
+// https://webidl.spec.whatwg.org/#es-USVString
+webidl.converters.USVString = toUSVString
-/***/ 53448:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://webidl.spec.whatwg.org/#es-boolean
+webidl.converters.boolean = function (V) {
+ // 1. Let x be the result of computing ToBoolean(V).
+ const x = Boolean(V)
-"use strict";
+ // 2. Return the IDL boolean value that is the one that represents
+ // the same truth value as the ECMAScript Boolean value x.
+ return x
+}
+// https://webidl.spec.whatwg.org/#es-any
+webidl.converters.any = function (V) {
+ return V
+}
-var acorn = __nccwpck_require__(74012);
-var objectAssign = __nccwpck_require__(17426);
+// https://webidl.spec.whatwg.org/#es-long-long
+webidl.converters['long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ const x = webidl.util.ConvertToInt(V, 64, 'signed')
-module.exports = isExpression;
+ // 2. Return the IDL long long value that represents
+ // the same numeric value as x.
+ return x
+}
-var DEFAULT_OPTIONS = {
- throw: false,
- strict: false,
- lineComment: false
-};
+// https://webidl.spec.whatwg.org/#es-unsigned-long-long
+webidl.converters['unsigned long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
-function isExpression(src, options) {
- options = objectAssign({}, DEFAULT_OPTIONS, options);
+ // 2. Return the IDL unsigned long long value that
+ // represents the same numeric value as x.
+ return x
+}
- try {
- var parser = new acorn.Parser(options, src, 0);
+// https://webidl.spec.whatwg.org/#es-unsigned-long
+webidl.converters['unsigned long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
- if (options.strict) {
- parser.strict = true;
- }
+ // 2. Return the IDL unsigned long value that
+ // represents the same numeric value as x.
+ return x
+}
- if (!options.lineComment) {
- parser.skipLineComment = function (startSkip) {
- this.raise(this.pos, 'Line comments not allowed in an expression');
- };
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-short
+webidl.converters['unsigned short'] = function (V, opts) {
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
- parser.nextToken();
- parser.parseExpression();
+ // 2. Return the IDL unsigned short value that represents
+ // the same numeric value as x.
+ return x
+}
- if (parser.type !== acorn.tokTypes.eof) {
- parser.unexpected();
- }
- } catch (ex) {
- if (!options.throw) {
- return false;
- }
+// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+webidl.converters.ArrayBuffer = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have an
+ // [[ArrayBufferData]] internal slot, then throw a
+ // TypeError.
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isAnyArrayBuffer(V)
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${V}`,
+ argument: `${V}`,
+ types: ['ArrayBuffer']
+ })
+ }
- throw ex;
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V) is true, then throw a
+ // TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- return true;
-}
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V) is true, then throw a
+ // TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal.
+ // 4. Return the IDL ArrayBuffer value that is a
+ // reference to the same object as V.
+ return V
+}
-/***/ }),
+webidl.converters.TypedArray = function (V, T, opts = {}) {
+ // 1. Let T be the IDL type V is being converted to.
-/***/ 74012:
-/***/ (function(__unused_webpack_module, exports) {
+ // 2. If Type(V) is not Object, or V does not have a
+ // [[TypedArrayName]] internal slot with a value
+ // equal to T’s name, then throw a TypeError.
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isTypedArray(V) ||
+ V.constructor.name !== T.name
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${T.name}`,
+ argument: `${V}`,
+ types: [T.name]
+ })
+ }
-(function (global, factory) {
- true ? factory(exports) :
- 0;
-}(this, (function (exports) { 'use strict';
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
+ }
- // Reserved word lists for various dialects of the language
+ // 4. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable array buffers are currently a proposal
- var reservedWords = {
- 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
- 5: "class enum extends super const export import",
- 6: "enum",
- strict: "implements interface let package private protected public static yield",
- strictBind: "eval arguments"
- };
-
- // And the keywords
-
- var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
-
- var keywords = {
- 5: ecma5AndLessKeywords,
- "5module": ecma5AndLessKeywords + " export import",
- 6: ecma5AndLessKeywords + " const class extends export import super"
- };
-
- var keywordRelationalOperator = /^in(stanceof)?$/;
-
- // ## Character categories
-
- // Big ugly regular expressions that match characters in the
- // whitespace, identifier, and identifier-start categories. These
- // are only applied when a character is found to actually have a
- // code point above 128.
- // Generated by `bin/generate-identifier-regex.js`.
- var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
- var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
-
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
-
- nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
-
- // These are a run-length and offset encoded representation of the
- // >0xffff code points that are a valid part of identifiers. The
- // offset starts at 0x10000, and each pair of numbers represents an
- // offset to the next range, and then a size of the range. They were
- // generated by bin/generate-identifier-regex.js
+ // 5. Return the IDL value of type T that is a reference
+ // to the same object as V.
+ return V
+}
- // eslint-disable-next-line comma-spacing
- var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
-
- // eslint-disable-next-line comma-spacing
- var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
-
- // This has a complexity linear to the value of the code. The
- // assumption is that looking up astral identifier characters is
- // rare.
- function isInAstralSet(code, set) {
- var pos = 0x10000;
- for (var i = 0; i < set.length; i += 2) {
- pos += set[i];
- if (pos > code) { return false }
- pos += set[i + 1];
- if (pos >= code) { return true }
- }
- }
-
- // Test whether a given character code starts an identifier.
-
- function isIdentifierStart(code, astral) {
- if (code < 65) { return code === 36 }
- if (code < 91) { return true }
- if (code < 97) { return code === 95 }
- if (code < 123) { return true }
- if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
- if (astral === false) { return false }
- return isInAstralSet(code, astralIdentifierStartCodes)
- }
-
- // Test whether a given character is part of an identifier.
-
- function isIdentifierChar(code, astral) {
- if (code < 48) { return code === 36 }
- if (code < 58) { return true }
- if (code < 65) { return false }
- if (code < 91) { return true }
- if (code < 97) { return code === 95 }
- if (code < 123) { return true }
- if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
- if (astral === false) { return false }
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
- }
-
- // ## Token types
-
- // The assignment of fine-grained, information-carrying type objects
- // allows the tokenizer to store the information it has about a
- // token in a way that is very cheap for the parser to look up.
-
- // All token type variables start with an underscore, to make them
- // easy to recognize.
-
- // The `beforeExpr` property is used to disambiguate between regular
- // expressions and divisions. It is set on all token types that can
- // be followed by an expression (thus, a slash after them would be a
- // regular expression).
- //
- // The `startsExpr` property is used to check if the token ends a
- // `yield` expression. It is set on all token types that either can
- // directly start an expression (like a quotation mark) or can
- // continue an expression (like the body of a string).
- //
- // `isLoop` marks a keyword as starting a loop, which is important
- // to know when parsing a label, in order to allow or disallow
- // continue jumps to that label.
-
- var TokenType = function TokenType(label, conf) {
- if ( conf === void 0 ) conf = {};
-
- this.label = label;
- this.keyword = conf.keyword;
- this.beforeExpr = !!conf.beforeExpr;
- this.startsExpr = !!conf.startsExpr;
- this.isLoop = !!conf.isLoop;
- this.isAssign = !!conf.isAssign;
- this.prefix = !!conf.prefix;
- this.postfix = !!conf.postfix;
- this.binop = conf.binop || null;
- this.updateContext = null;
- };
-
- function binop(name, prec) {
- return new TokenType(name, {beforeExpr: true, binop: prec})
- }
- var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
-
- // Map keyword names to token types.
-
- var keywords$1 = {};
-
- // Succinct definitions of keyword token types
- function kw(name, options) {
- if ( options === void 0 ) options = {};
-
- options.keyword = name;
- return keywords$1[name] = new TokenType(name, options)
- }
-
- var types = {
- num: new TokenType("num", startsExpr),
- regexp: new TokenType("regexp", startsExpr),
- string: new TokenType("string", startsExpr),
- name: new TokenType("name", startsExpr),
- eof: new TokenType("eof"),
-
- // Punctuation token types.
- bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
- bracketR: new TokenType("]"),
- braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
- braceR: new TokenType("}"),
- parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
- parenR: new TokenType(")"),
- comma: new TokenType(",", beforeExpr),
- semi: new TokenType(";", beforeExpr),
- colon: new TokenType(":", beforeExpr),
- dot: new TokenType("."),
- question: new TokenType("?", beforeExpr),
- questionDot: new TokenType("?."),
- arrow: new TokenType("=>", beforeExpr),
- template: new TokenType("template"),
- invalidTemplate: new TokenType("invalidTemplate"),
- ellipsis: new TokenType("...", beforeExpr),
- backQuote: new TokenType("`", startsExpr),
- dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
-
- // Operators. These carry several kinds of properties to help the
- // parser use them properly (the presence of these properties is
- // what categorizes them as operators).
- //
- // `binop`, when present, specifies that this operator is a binary
- // operator, and will refer to its precedence.
- //
- // `prefix` and `postfix` mark the operator as a prefix or postfix
- // unary operator.
- //
- // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
- // binary operators with a very low precedence, that should result
- // in AssignmentExpression nodes.
-
- eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
- assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
- incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
- prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
- logicalOR: binop("||", 1),
- logicalAND: binop("&&", 2),
- bitwiseOR: binop("|", 3),
- bitwiseXOR: binop("^", 4),
- bitwiseAND: binop("&", 5),
- equality: binop("==/!=/===/!==", 6),
- relational: binop(">/<=/>=", 7),
- bitShift: binop("<>>/>>>", 8),
- plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
- modulo: binop("%", 10),
- star: binop("*", 10),
- slash: binop("/", 10),
- starstar: new TokenType("**", {beforeExpr: true}),
- coalesce: binop("??", 1),
-
- // Keyword token types.
- _break: kw("break"),
- _case: kw("case", beforeExpr),
- _catch: kw("catch"),
- _continue: kw("continue"),
- _debugger: kw("debugger"),
- _default: kw("default", beforeExpr),
- _do: kw("do", {isLoop: true, beforeExpr: true}),
- _else: kw("else", beforeExpr),
- _finally: kw("finally"),
- _for: kw("for", {isLoop: true}),
- _function: kw("function", startsExpr),
- _if: kw("if"),
- _return: kw("return", beforeExpr),
- _switch: kw("switch"),
- _throw: kw("throw", beforeExpr),
- _try: kw("try"),
- _var: kw("var"),
- _const: kw("const"),
- _while: kw("while", {isLoop: true}),
- _with: kw("with"),
- _new: kw("new", {beforeExpr: true, startsExpr: true}),
- _this: kw("this", startsExpr),
- _super: kw("super", startsExpr),
- _class: kw("class", startsExpr),
- _extends: kw("extends", beforeExpr),
- _export: kw("export"),
- _import: kw("import", startsExpr),
- _null: kw("null", startsExpr),
- _true: kw("true", startsExpr),
- _false: kw("false", startsExpr),
- _in: kw("in", {beforeExpr: true, binop: 7}),
- _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
- _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
- _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
- _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
- };
-
- // Matches a whole line break (where CRLF is considered a single
- // line break). Used to count lines.
-
- var lineBreak = /\r\n?|\n|\u2028|\u2029/;
- var lineBreakG = new RegExp(lineBreak.source, "g");
-
- function isNewLine(code, ecma2019String) {
- return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
- }
-
- var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
-
- var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
-
- var ref = Object.prototype;
- var hasOwnProperty = ref.hasOwnProperty;
- var toString = ref.toString;
-
- // Checks if an object has a property.
-
- function has(obj, propName) {
- return hasOwnProperty.call(obj, propName)
- }
-
- var isArray = Array.isArray || (function (obj) { return (
- toString.call(obj) === "[object Array]"
- ); });
-
- function wordsRegexp(words) {
- return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
- }
-
- // These are used when `options.locations` is on, for the
- // `startLoc` and `endLoc` properties.
-
- var Position = function Position(line, col) {
- this.line = line;
- this.column = col;
- };
-
- Position.prototype.offset = function offset (n) {
- return new Position(this.line, this.column + n)
- };
-
- var SourceLocation = function SourceLocation(p, start, end) {
- this.start = start;
- this.end = end;
- if (p.sourceFile !== null) { this.source = p.sourceFile; }
- };
-
- // The `getLineInfo` function is mostly useful when the
- // `locations` option is off (for performance reasons) and you
- // want to find the line/column position for a given character
- // offset. `input` should be the code string that the offset refers
- // into.
-
- function getLineInfo(input, offset) {
- for (var line = 1, cur = 0;;) {
- lineBreakG.lastIndex = cur;
- var match = lineBreakG.exec(input);
- if (match && match.index < offset) {
- ++line;
- cur = match.index + match[0].length;
- } else {
- return new Position(line, offset - cur)
- }
- }
+webidl.converters.DataView = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have a
+ // [[DataView]] internal slot, then throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
+ throw webidl.errors.exception({
+ header: 'DataView',
+ message: 'Object is not a DataView.'
+ })
}
- // A second optional argument can be given to further configure
- // the parser process. These options are recognized:
-
- var defaultOptions = {
- // `ecmaVersion` indicates the ECMAScript version to parse. Must be
- // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
- // (2019). This influences support for strict mode, the set of
- // reserved words, and support for new syntax features. The default
- // is 10.
- ecmaVersion: 10,
- // `sourceType` indicates the mode the code should be parsed in.
- // Can be either `"script"` or `"module"`. This influences global
- // strict mode and parsing of `import` and `export` declarations.
- sourceType: "script",
- // `onInsertedSemicolon` can be a callback that will be called
- // when a semicolon is automatically inserted. It will be passed
- // the position of the comma as an offset, and if `locations` is
- // enabled, it is given the location as a `{line, column}` object
- // as second argument.
- onInsertedSemicolon: null,
- // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
- // trailing commas.
- onTrailingComma: null,
- // By default, reserved words are only enforced if ecmaVersion >= 5.
- // Set `allowReserved` to a boolean value to explicitly turn this on
- // an off. When this option has the value "never", reserved words
- // and keywords can also not be used as property names.
- allowReserved: null,
- // When enabled, a return at the top level is not considered an
- // error.
- allowReturnOutsideFunction: false,
- // When enabled, import/export statements are not constrained to
- // appearing at the top of the program.
- allowImportExportEverywhere: false,
- // When enabled, await identifiers are allowed to appear at the top-level scope,
- // but they are still not allowed in non-async functions.
- allowAwaitOutsideFunction: false,
- // When enabled, hashbang directive in the beginning of file
- // is allowed and treated as a line comment.
- allowHashBang: false,
- // When `locations` is on, `loc` properties holding objects with
- // `start` and `end` properties in `{line, column}` form (with
- // line being 1-based and column 0-based) will be attached to the
- // nodes.
- locations: false,
- // A function can be passed as `onToken` option, which will
- // cause Acorn to call that function with object in the same
- // format as tokens returned from `tokenizer().getToken()`. Note
- // that you are not allowed to call the parser from the
- // callback—that will corrupt its internal state.
- onToken: null,
- // A function can be passed as `onComment` option, which will
- // cause Acorn to call that function with `(block, text, start,
- // end)` parameters whenever a comment is skipped. `block` is a
- // boolean indicating whether this is a block (`/* */`) comment,
- // `text` is the content of the comment, and `start` and `end` are
- // character offsets that denote the start and end of the comment.
- // When the `locations` option is on, two more parameters are
- // passed, the full `{line, column}` locations of the start and
- // end of the comments. Note that you are not allowed to call the
- // parser from the callback—that will corrupt its internal state.
- onComment: null,
- // Nodes have their start and end characters offsets recorded in
- // `start` and `end` properties (directly on the node, rather than
- // the `loc` object, which holds line/column data. To also add a
- // [semi-standardized][range] `range` property holding a `[start,
- // end]` array with the same numbers, set the `ranges` option to
- // `true`.
- //
- // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
- ranges: false,
- // It is possible to parse multiple files into a single AST by
- // passing the tree produced by parsing the first file as
- // `program` option in subsequent parses. This will add the
- // toplevel forms of the parsed file to the `Program` (top) node
- // of an existing parse tree.
- program: null,
- // When `locations` is on, you can pass this to record the source
- // file in every node's `loc` object.
- sourceFile: null,
- // This value, if given, is stored in every node, whether
- // `locations` is on or off.
- directSourceFile: null,
- // When enabled, parenthesized expressions are represented by
- // (non-standard) ParenthesizedExpression nodes
- preserveParens: false
- };
-
- // Interpret and default an options object
-
- function getOptions(opts) {
- var options = {};
-
- for (var opt in defaultOptions)
- { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
-
- if (options.ecmaVersion >= 2015)
- { options.ecmaVersion -= 2009; }
-
- if (options.allowReserved == null)
- { options.allowReserved = options.ecmaVersion < 5; }
-
- if (isArray(options.onToken)) {
- var tokens = options.onToken;
- options.onToken = function (token) { return tokens.push(token); };
- }
- if (isArray(options.onComment))
- { options.onComment = pushComment(options, options.onComment); }
-
- return options
- }
-
- function pushComment(options, array) {
- return function(block, text, start, end, startLoc, endLoc) {
- var comment = {
- type: block ? "Block" : "Line",
- value: text,
- start: start,
- end: end
- };
- if (options.locations)
- { comment.loc = new SourceLocation(this, startLoc, endLoc); }
- if (options.ranges)
- { comment.range = [start, end]; }
- array.push(comment);
- }
- }
-
- // Each scope gets a bitset that may contain these flags
- var
- SCOPE_TOP = 1,
- SCOPE_FUNCTION = 2,
- SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
- SCOPE_ASYNC = 4,
- SCOPE_GENERATOR = 8,
- SCOPE_ARROW = 16,
- SCOPE_SIMPLE_CATCH = 32,
- SCOPE_SUPER = 64,
- SCOPE_DIRECT_SUPER = 128;
-
- function functionFlags(async, generator) {
- return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
- }
-
- // Used in checkLVal and declareName to determine the type of a binding
- var
- BIND_NONE = 0, // Not a binding
- BIND_VAR = 1, // Var-style binding
- BIND_LEXICAL = 2, // Let- or const-style binding
- BIND_FUNCTION = 3, // Function declaration
- BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
- BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
-
- var Parser = function Parser(options, input, startPos) {
- this.options = options = getOptions(options);
- this.sourceFile = options.sourceFile;
- this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
- var reserved = "";
- if (options.allowReserved !== true) {
- for (var v = options.ecmaVersion;; v--)
- { if (reserved = reservedWords[v]) { break } }
- if (options.sourceType === "module") { reserved += " await"; }
- }
- this.reservedWords = wordsRegexp(reserved);
- var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
- this.reservedWordsStrict = wordsRegexp(reservedStrict);
- this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
- this.input = String(input);
-
- // Used to signal to callers of `readWord1` whether the word
- // contained any escape sequences. This is needed because words with
- // escape sequences must not be interpreted as keywords.
- this.containsEsc = false;
-
- // Set up token state
-
- // The current position of the tokenizer in the input.
- if (startPos) {
- this.pos = startPos;
- this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
- this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
- } else {
- this.pos = this.lineStart = 0;
- this.curLine = 1;
- }
-
- // Properties of the current token:
- // Its type
- this.type = types.eof;
- // For tokens that include more information than their type, the value
- this.value = null;
- // Its start and end offset
- this.start = this.end = this.pos;
- // And, if locations are used, the {line, column} object
- // corresponding to those offsets
- this.startLoc = this.endLoc = this.curPosition();
-
- // Position information for the previous token
- this.lastTokEndLoc = this.lastTokStartLoc = null;
- this.lastTokStart = this.lastTokEnd = this.pos;
-
- // The context stack is used to superficially track syntactic
- // context to predict whether a regular expression is allowed in a
- // given position.
- this.context = this.initialContext();
- this.exprAllowed = true;
-
- // Figure out if it's a module code.
- this.inModule = options.sourceType === "module";
- this.strict = this.inModule || this.strictDirective(this.pos);
-
- // Used to signify the start of a potential arrow function
- this.potentialArrowAt = -1;
-
- // Positions to delayed-check that yield/await does not exist in default parameters.
- this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
- // Labels in scope.
- this.labels = [];
- // Thus-far undefined exports.
- this.undefinedExports = {};
-
- // If enabled, skip leading hashbang line.
- if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
- { this.skipLineComment(2); }
-
- // Scope tracking for duplicate variable names (see scope.js)
- this.scopeStack = [];
- this.enterScope(SCOPE_TOP);
-
- // For RegExp validation
- this.regexpState = null;
- };
-
- var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } };
-
- Parser.prototype.parse = function parse () {
- var node = this.options.program || this.startNode();
- this.nextToken();
- return this.parseTopLevel(node)
- };
-
- prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
- prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
- prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
- prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
- prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
- prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
-
- // Switch to a getter for 7.0.0.
- Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
-
- Parser.extend = function extend () {
- var plugins = [], len = arguments.length;
- while ( len-- ) plugins[ len ] = arguments[ len ];
-
- var cls = this;
- for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
- return cls
- };
-
- Parser.parse = function parse (input, options) {
- return new this(options, input).parse()
- };
-
- Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
- var parser = new this(options, input, pos);
- parser.nextToken();
- return parser.parseExpression()
- };
-
- Parser.tokenizer = function tokenizer (input, options) {
- return new this(options, input)
- };
-
- Object.defineProperties( Parser.prototype, prototypeAccessors );
-
- var pp = Parser.prototype;
-
- // ## Parser utilities
-
- var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
- pp.strictDirective = function(start) {
- for (;;) {
- // Try to find string literal.
- skipWhiteSpace.lastIndex = start;
- start += skipWhiteSpace.exec(this.input)[0].length;
- var match = literal.exec(this.input.slice(start));
- if (!match) { return false }
- if ((match[1] || match[2]) === "use strict") {
- skipWhiteSpace.lastIndex = start + match[0].length;
- var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
- var next = this.input.charAt(end);
- return next === ";" || next === "}" ||
- (lineBreak.test(spaceAfter[0]) &&
- !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
- }
- start += match[0].length;
-
- // Skip semicolon, if any.
- skipWhiteSpace.lastIndex = start;
- start += skipWhiteSpace.exec(this.input)[0].length;
- if (this.input[start] === ";")
- { start++; }
- }
- };
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
+ // then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
+ }
- // Predicate that tests whether the next token is of the given
- // type, and if yes, consumes it as a side effect.
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal
- pp.eat = function(type) {
- if (this.type === type) {
- this.next();
- return true
- } else {
- return false
- }
- };
+ // 4. Return the IDL DataView value that is a reference
+ // to the same object as V.
+ return V
+}
- // Tests whether parsed token is a contextual keyword.
+// https://webidl.spec.whatwg.org/#BufferSource
+webidl.converters.BufferSource = function (V, opts = {}) {
+ if (types.isAnyArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, opts)
+ }
- pp.isContextual = function(name) {
- return this.type === types.name && this.value === name && !this.containsEsc
- };
+ if (types.isTypedArray(V)) {
+ return webidl.converters.TypedArray(V, V.constructor)
+ }
- // Consumes contextual keyword if possible.
+ if (types.isDataView(V)) {
+ return webidl.converters.DataView(V, opts)
+ }
- pp.eatContextual = function(name) {
- if (!this.isContextual(name)) { return false }
- this.next();
- return true
- };
+ throw new TypeError(`Could not convert ${V} to a BufferSource.`)
+}
- // Asserts that following token is given contextual keyword.
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.ByteString
+)
- pp.expectContextual = function(name) {
- if (!this.eatContextual(name)) { this.unexpected(); }
- };
+webidl.converters['sequence>'] = webidl.sequenceConverter(
+ webidl.converters['sequence']
+)
- // Test whether a semicolon can be inserted at the current position.
+webidl.converters['record'] = webidl.recordConverter(
+ webidl.converters.ByteString,
+ webidl.converters.ByteString
+)
- pp.canInsertSemicolon = function() {
- return this.type === types.eof ||
- this.type === types.braceR ||
- lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
- };
+module.exports = {
+ webidl
+}
- pp.insertSemicolon = function() {
- if (this.canInsertSemicolon()) {
- if (this.options.onInsertedSemicolon)
- { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
- return true
- }
- };
- // Consume a semicolon, or, failing that, see if we are allowed to
- // pretend that there is a semicolon at this position.
+/***/ }),
- pp.semicolon = function() {
- if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
- };
+/***/ 396:
+/***/ ((module) => {
- pp.afterTrailingComma = function(tokType, notNext) {
- if (this.type === tokType) {
- if (this.options.onTrailingComma)
- { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
- if (!notNext)
- { this.next(); }
- return true
- }
- };
-
- // Expect a token of a given type. If found, consume it, otherwise,
- // raise an unexpected token error.
-
- pp.expect = function(type) {
- this.eat(type) || this.unexpected();
- };
-
- // Raise an unexpected token error.
-
- pp.unexpected = function(pos) {
- this.raise(pos != null ? pos : this.start, "Unexpected token");
- };
-
- function DestructuringErrors() {
- this.shorthandAssign =
- this.trailingComma =
- this.parenthesizedAssign =
- this.parenthesizedBind =
- this.doubleProto =
- -1;
- }
-
- pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
- if (!refDestructuringErrors) { return }
- if (refDestructuringErrors.trailingComma > -1)
- { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
- var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
- if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
- };
-
- pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
- if (!refDestructuringErrors) { return false }
- var shorthandAssign = refDestructuringErrors.shorthandAssign;
- var doubleProto = refDestructuringErrors.doubleProto;
- if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
- if (shorthandAssign >= 0)
- { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
- if (doubleProto >= 0)
- { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
- };
-
- pp.checkYieldAwaitInDefaultParams = function() {
- if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
- { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
- if (this.awaitPos)
- { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
- };
-
- pp.isSimpleAssignTarget = function(expr) {
- if (expr.type === "ParenthesizedExpression")
- { return this.isSimpleAssignTarget(expr.expression) }
- return expr.type === "Identifier" || expr.type === "MemberExpression"
- };
-
- var pp$1 = Parser.prototype;
-
- // ### Statement parsing
-
- // Parse a program. Initializes the parser, reads any number of
- // statements, and wraps them in a Program node. Optionally takes a
- // `program` argument. If present, the statements will be appended
- // to its body instead of creating a new node.
-
- pp$1.parseTopLevel = function(node) {
- var exports = {};
- if (!node.body) { node.body = []; }
- while (this.type !== types.eof) {
- var stmt = this.parseStatement(null, true, exports);
- node.body.push(stmt);
- }
- if (this.inModule)
- { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
- {
- var name = list[i];
-
- this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
- } }
- this.adaptDirectivePrologue(node.body);
- this.next();
- node.sourceType = this.options.sourceType;
- return this.finishNode(node, "Program")
- };
-
- var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
-
- pp$1.isLet = function(context) {
- if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
- skipWhiteSpace.lastIndex = this.pos;
- var skip = skipWhiteSpace.exec(this.input);
- var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
- // For ambiguous cases, determine if a LexicalDeclaration (or only a
- // Statement) is allowed here. If context is not empty then only a Statement
- // is allowed. However, `let [` is an explicit negative lookahead for
- // ExpressionStatement, so special-case it first.
- if (nextCh === 91) { return true } // '['
- if (context) { return false }
-
- if (nextCh === 123) { return true } // '{'
- if (isIdentifierStart(nextCh, true)) {
- var pos = next + 1;
- while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
- var ident = this.input.slice(next, pos);
- if (!keywordRelationalOperator.test(ident)) { return true }
- }
- return false
- };
-
- // check 'async [no LineTerminator here] function'
- // - 'async /*foo*/ function' is OK.
- // - 'async /*\n*/ function' is invalid.
- pp$1.isAsyncFunction = function() {
- if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
- { return false }
-
- skipWhiteSpace.lastIndex = this.pos;
- var skip = skipWhiteSpace.exec(this.input);
- var next = this.pos + skip[0].length;
- return !lineBreak.test(this.input.slice(this.pos, next)) &&
- this.input.slice(next, next + 8) === "function" &&
- (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
- };
-
- // Parse a single statement.
- //
- // If expecting a statement and finding a slash operator, parse a
- // regular expression literal. This is to handle cases like
- // `if (foo) /blah/.exec(foo)`, where looking at the previous token
- // does not help.
-
- pp$1.parseStatement = function(context, topLevel, exports) {
- var starttype = this.type, node = this.startNode(), kind;
-
- if (this.isLet(context)) {
- starttype = types._var;
- kind = "let";
- }
-
- // Most types of statements are recognized by the keyword they
- // start with. Many are trivial to parse, some require a bit of
- // complexity.
-
- switch (starttype) {
- case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
- case types._debugger: return this.parseDebuggerStatement(node)
- case types._do: return this.parseDoStatement(node)
- case types._for: return this.parseForStatement(node)
- case types._function:
- // Function as sole body of either an if statement or a labeled statement
- // works, but not when it is part of a labeled statement that is the sole
- // body of an if statement.
- if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
- return this.parseFunctionStatement(node, false, !context)
- case types._class:
- if (context) { this.unexpected(); }
- return this.parseClass(node, true)
- case types._if: return this.parseIfStatement(node)
- case types._return: return this.parseReturnStatement(node)
- case types._switch: return this.parseSwitchStatement(node)
- case types._throw: return this.parseThrowStatement(node)
- case types._try: return this.parseTryStatement(node)
- case types._const: case types._var:
- kind = kind || this.value;
- if (context && kind !== "var") { this.unexpected(); }
- return this.parseVarStatement(node, kind)
- case types._while: return this.parseWhileStatement(node)
- case types._with: return this.parseWithStatement(node)
- case types.braceL: return this.parseBlock(true, node)
- case types.semi: return this.parseEmptyStatement(node)
- case types._export:
- case types._import:
- if (this.options.ecmaVersion > 10 && starttype === types._import) {
- skipWhiteSpace.lastIndex = this.pos;
- var skip = skipWhiteSpace.exec(this.input);
- var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
- if (nextCh === 40 || nextCh === 46) // '(' or '.'
- { return this.parseExpressionStatement(node, this.parseExpression()) }
- }
- if (!this.options.allowImportExportEverywhere) {
- if (!topLevel)
- { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
- if (!this.inModule)
- { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
- }
- return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
-
- // If the statement does not start with a statement keyword or a
- // brace, it's an ExpressionStatement or LabeledStatement. We
- // simply start parsing an expression, and afterwards, if the
- // next token is a colon and the expression was a simple
- // Identifier node, we switch to interpreting it as a label.
- default:
- if (this.isAsyncFunction()) {
- if (context) { this.unexpected(); }
- this.next();
- return this.parseFunctionStatement(node, true, !context)
- }
- var maybeName = this.value, expr = this.parseExpression();
- if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
- { return this.parseLabeledStatement(node, maybeName, expr, context) }
- else { return this.parseExpressionStatement(node, expr) }
- }
- };
+/**
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
+ * @param {string|undefined} label
+ */
+function getEncoding (label) {
+ if (!label) {
+ return 'failure'
+ }
- pp$1.parseBreakContinueStatement = function(node, keyword) {
- var isBreak = keyword === "break";
- this.next();
- if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
- else if (this.type !== types.name) { this.unexpected(); }
- else {
- node.label = this.parseIdent();
- this.semicolon();
- }
-
- // Verify that there is an actual destination to break or
- // continue to.
- var i = 0;
- for (; i < this.labels.length; ++i) {
- var lab = this.labels[i];
- if (node.label == null || lab.name === node.label.name) {
- if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
- if (node.label && isBreak) { break }
- }
- }
- if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
- return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
- };
-
- pp$1.parseDebuggerStatement = function(node) {
- this.next();
- this.semicolon();
- return this.finishNode(node, "DebuggerStatement")
- };
-
- pp$1.parseDoStatement = function(node) {
- this.next();
- this.labels.push(loopLabel);
- node.body = this.parseStatement("do");
- this.labels.pop();
- this.expect(types._while);
- node.test = this.parseParenExpression();
- if (this.options.ecmaVersion >= 6)
- { this.eat(types.semi); }
- else
- { this.semicolon(); }
- return this.finishNode(node, "DoWhileStatement")
- };
-
- // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
- // loop is non-trivial. Basically, we have to parse the init `var`
- // statement or expression, disallowing the `in` operator (see
- // the second parameter to `parseExpression`), and then check
- // whether the next token is `in` or `of`. When there is no init
- // part (semicolon immediately after the opening parenthesis), it
- // is a regular `for` loop.
-
- pp$1.parseForStatement = function(node) {
- this.next();
- var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
- this.labels.push(loopLabel);
- this.enterScope(0);
- this.expect(types.parenL);
- if (this.type === types.semi) {
- if (awaitAt > -1) { this.unexpected(awaitAt); }
- return this.parseFor(node, null)
- }
- var isLet = this.isLet();
- if (this.type === types._var || this.type === types._const || isLet) {
- var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
- this.next();
- this.parseVar(init$1, true, kind);
- this.finishNode(init$1, "VariableDeclaration");
- if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
- if (this.options.ecmaVersion >= 9) {
- if (this.type === types._in) {
- if (awaitAt > -1) { this.unexpected(awaitAt); }
- } else { node.await = awaitAt > -1; }
- }
- return this.parseForIn(node, init$1)
- }
- if (awaitAt > -1) { this.unexpected(awaitAt); }
- return this.parseFor(node, init$1)
- }
- var refDestructuringErrors = new DestructuringErrors;
- var init = this.parseExpression(true, refDestructuringErrors);
- if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
- if (this.options.ecmaVersion >= 9) {
- if (this.type === types._in) {
- if (awaitAt > -1) { this.unexpected(awaitAt); }
- } else { node.await = awaitAt > -1; }
- }
- this.toAssignable(init, false, refDestructuringErrors);
- this.checkLVal(init);
- return this.parseForIn(node, init)
- } else {
- this.checkExpressionErrors(refDestructuringErrors, true);
- }
- if (awaitAt > -1) { this.unexpected(awaitAt); }
- return this.parseFor(node, init)
- };
-
- pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
- this.next();
- return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
- };
-
- pp$1.parseIfStatement = function(node) {
- this.next();
- node.test = this.parseParenExpression();
- // allow function declarations in branches, but only in non-strict mode
- node.consequent = this.parseStatement("if");
- node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
- return this.finishNode(node, "IfStatement")
- };
-
- pp$1.parseReturnStatement = function(node) {
- if (!this.inFunction && !this.options.allowReturnOutsideFunction)
- { this.raise(this.start, "'return' outside of function"); }
- this.next();
-
- // In `return` (and `break`/`continue`), the keywords with
- // optional arguments, we eagerly look for a semicolon or the
- // possibility to insert one.
-
- if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
- else { node.argument = this.parseExpression(); this.semicolon(); }
- return this.finishNode(node, "ReturnStatement")
- };
-
- pp$1.parseSwitchStatement = function(node) {
- this.next();
- node.discriminant = this.parseParenExpression();
- node.cases = [];
- this.expect(types.braceL);
- this.labels.push(switchLabel);
- this.enterScope(0);
-
- // Statements under must be grouped (by label) in SwitchCase
- // nodes. `cur` is used to keep the node that we are currently
- // adding statements to.
-
- var cur;
- for (var sawDefault = false; this.type !== types.braceR;) {
- if (this.type === types._case || this.type === types._default) {
- var isCase = this.type === types._case;
- if (cur) { this.finishNode(cur, "SwitchCase"); }
- node.cases.push(cur = this.startNode());
- cur.consequent = [];
- this.next();
- if (isCase) {
- cur.test = this.parseExpression();
- } else {
- if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
- sawDefault = true;
- cur.test = null;
- }
- this.expect(types.colon);
- } else {
- if (!cur) { this.unexpected(); }
- cur.consequent.push(this.parseStatement(null));
- }
- }
- this.exitScope();
- if (cur) { this.finishNode(cur, "SwitchCase"); }
- this.next(); // Closing brace
- this.labels.pop();
- return this.finishNode(node, "SwitchStatement")
- };
-
- pp$1.parseThrowStatement = function(node) {
- this.next();
- if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
- { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
- node.argument = this.parseExpression();
- this.semicolon();
- return this.finishNode(node, "ThrowStatement")
- };
-
- // Reused empty array added for node fields that are always empty.
-
- var empty = [];
-
- pp$1.parseTryStatement = function(node) {
- this.next();
- node.block = this.parseBlock();
- node.handler = null;
- if (this.type === types._catch) {
- var clause = this.startNode();
- this.next();
- if (this.eat(types.parenL)) {
- clause.param = this.parseBindingAtom();
- var simple = clause.param.type === "Identifier";
- this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
- this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
- this.expect(types.parenR);
- } else {
- if (this.options.ecmaVersion < 10) { this.unexpected(); }
- clause.param = null;
- this.enterScope(0);
- }
- clause.body = this.parseBlock(false);
- this.exitScope();
- node.handler = this.finishNode(clause, "CatchClause");
- }
- node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
- if (!node.handler && !node.finalizer)
- { this.raise(node.start, "Missing catch or finally clause"); }
- return this.finishNode(node, "TryStatement")
- };
-
- pp$1.parseVarStatement = function(node, kind) {
- this.next();
- this.parseVar(node, false, kind);
- this.semicolon();
- return this.finishNode(node, "VariableDeclaration")
- };
-
- pp$1.parseWhileStatement = function(node) {
- this.next();
- node.test = this.parseParenExpression();
- this.labels.push(loopLabel);
- node.body = this.parseStatement("while");
- this.labels.pop();
- return this.finishNode(node, "WhileStatement")
- };
-
- pp$1.parseWithStatement = function(node) {
- if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
- this.next();
- node.object = this.parseParenExpression();
- node.body = this.parseStatement("with");
- return this.finishNode(node, "WithStatement")
- };
-
- pp$1.parseEmptyStatement = function(node) {
- this.next();
- return this.finishNode(node, "EmptyStatement")
- };
-
- pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
- for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
- {
- var label = list[i$1];
-
- if (label.name === maybeName)
- { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
- } }
- var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
- for (var i = this.labels.length - 1; i >= 0; i--) {
- var label$1 = this.labels[i];
- if (label$1.statementStart === node.start) {
- // Update information about previous labels on this node
- label$1.statementStart = this.start;
- label$1.kind = kind;
- } else { break }
- }
- this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
- node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
- this.labels.pop();
- node.label = expr;
- return this.finishNode(node, "LabeledStatement")
- };
-
- pp$1.parseExpressionStatement = function(node, expr) {
- node.expression = expr;
- this.semicolon();
- return this.finishNode(node, "ExpressionStatement")
- };
-
- // Parse a semicolon-enclosed block of statements, handling `"use
- // strict"` declarations when `allowStrict` is true (used for
- // function bodies).
-
- pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
- if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
- if ( node === void 0 ) node = this.startNode();
-
- node.body = [];
- this.expect(types.braceL);
- if (createNewLexicalScope) { this.enterScope(0); }
- while (this.type !== types.braceR) {
- var stmt = this.parseStatement(null);
- node.body.push(stmt);
- }
- if (exitStrict) { this.strict = false; }
- this.next();
- if (createNewLexicalScope) { this.exitScope(); }
- return this.finishNode(node, "BlockStatement")
- };
-
- // Parse a regular `for` loop. The disambiguation code in
- // `parseStatement` will already have parsed the init statement or
- // expression.
-
- pp$1.parseFor = function(node, init) {
- node.init = init;
- this.expect(types.semi);
- node.test = this.type === types.semi ? null : this.parseExpression();
- this.expect(types.semi);
- node.update = this.type === types.parenR ? null : this.parseExpression();
- this.expect(types.parenR);
- node.body = this.parseStatement("for");
- this.exitScope();
- this.labels.pop();
- return this.finishNode(node, "ForStatement")
- };
-
- // Parse a `for`/`in` and `for`/`of` loop, which are almost
- // same from parser's perspective.
-
- pp$1.parseForIn = function(node, init) {
- var isForIn = this.type === types._in;
- this.next();
-
- if (
- init.type === "VariableDeclaration" &&
- init.declarations[0].init != null &&
- (
- !isForIn ||
- this.options.ecmaVersion < 8 ||
- this.strict ||
- init.kind !== "var" ||
- init.declarations[0].id.type !== "Identifier"
- )
- ) {
- this.raise(
- init.start,
- ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
- );
- } else if (init.type === "AssignmentPattern") {
- this.raise(init.start, "Invalid left-hand side in for-loop");
- }
- node.left = init;
- node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
- this.expect(types.parenR);
- node.body = this.parseStatement("for");
- this.exitScope();
- this.labels.pop();
- return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
- };
-
- // Parse a list of variable declarations.
-
- pp$1.parseVar = function(node, isFor, kind) {
- node.declarations = [];
- node.kind = kind;
- for (;;) {
- var decl = this.startNode();
- this.parseVarId(decl, kind);
- if (this.eat(types.eq)) {
- decl.init = this.parseMaybeAssign(isFor);
- } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
- this.unexpected();
- } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
- this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
- } else {
- decl.init = null;
- }
- node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
- if (!this.eat(types.comma)) { break }
- }
- return node
- };
-
- pp$1.parseVarId = function(decl, kind) {
- decl.id = this.parseBindingAtom();
- this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
- };
-
- var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
-
- // Parse a function declaration or literal (depending on the
- // `statement & FUNC_STATEMENT`).
-
- // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
- pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
- this.initFunction(node);
- if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
- if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
- { this.unexpected(); }
- node.generator = this.eat(types.star);
- }
- if (this.options.ecmaVersion >= 8)
- { node.async = !!isAsync; }
-
- if (statement & FUNC_STATEMENT) {
- node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
- if (node.id && !(statement & FUNC_HANGING_STATEMENT))
- // If it is a regular function declaration in sloppy mode, then it is
- // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
- // mode depends on properties of the current scope (see
- // treatFunctionsAsVar).
- { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
- }
-
- var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
- this.yieldPos = 0;
- this.awaitPos = 0;
- this.awaitIdentPos = 0;
- this.enterScope(functionFlags(node.async, node.generator));
-
- if (!(statement & FUNC_STATEMENT))
- { node.id = this.type === types.name ? this.parseIdent() : null; }
-
- this.parseFunctionParams(node);
- this.parseFunctionBody(node, allowExpressionBody, false);
-
- this.yieldPos = oldYieldPos;
- this.awaitPos = oldAwaitPos;
- this.awaitIdentPos = oldAwaitIdentPos;
- return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
- };
-
- pp$1.parseFunctionParams = function(node) {
- this.expect(types.parenL);
- node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
- this.checkYieldAwaitInDefaultParams();
- };
-
- // Parse a class declaration or literal (depending on the
- // `isStatement` parameter).
-
- pp$1.parseClass = function(node, isStatement) {
- this.next();
-
- // ecma-262 14.6 Class Definitions
- // A class definition is always strict mode code.
- var oldStrict = this.strict;
- this.strict = true;
-
- this.parseClassId(node, isStatement);
- this.parseClassSuper(node);
- var classBody = this.startNode();
- var hadConstructor = false;
- classBody.body = [];
- this.expect(types.braceL);
- while (this.type !== types.braceR) {
- var element = this.parseClassElement(node.superClass !== null);
- if (element) {
- classBody.body.push(element);
- if (element.type === "MethodDefinition" && element.kind === "constructor") {
- if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
- hadConstructor = true;
- }
- }
- }
- this.strict = oldStrict;
- this.next();
- node.body = this.finishNode(classBody, "ClassBody");
- return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
- };
-
- pp$1.parseClassElement = function(constructorAllowsSuper) {
- var this$1 = this;
-
- if (this.eat(types.semi)) { return null }
-
- var method = this.startNode();
- var tryContextual = function (k, noLineBreak) {
- if ( noLineBreak === void 0 ) noLineBreak = false;
-
- var start = this$1.start, startLoc = this$1.startLoc;
- if (!this$1.eatContextual(k)) { return false }
- if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
- if (method.key) { this$1.unexpected(); }
- method.computed = false;
- method.key = this$1.startNodeAt(start, startLoc);
- method.key.name = k;
- this$1.finishNode(method.key, "Identifier");
- return false
- };
-
- method.kind = "method";
- method.static = tryContextual("static");
- var isGenerator = this.eat(types.star);
- var isAsync = false;
- if (!isGenerator) {
- if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
- isAsync = true;
- isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
- } else if (tryContextual("get")) {
- method.kind = "get";
- } else if (tryContextual("set")) {
- method.kind = "set";
- }
- }
- if (!method.key) { this.parsePropertyName(method); }
- var key = method.key;
- var allowsDirectSuper = false;
- if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
- key.type === "Literal" && key.value === "constructor")) {
- if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
- if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
- if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
- method.kind = "constructor";
- allowsDirectSuper = constructorAllowsSuper;
- } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
- this.raise(key.start, "Classes may not have a static property named prototype");
- }
- this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
- if (method.kind === "get" && method.value.params.length !== 0)
- { this.raiseRecoverable(method.value.start, "getter should have no params"); }
- if (method.kind === "set" && method.value.params.length !== 1)
- { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
- if (method.kind === "set" && method.value.params[0].type === "RestElement")
- { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
- return method
- };
-
- pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
- method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
- return this.finishNode(method, "MethodDefinition")
- };
-
- pp$1.parseClassId = function(node, isStatement) {
- if (this.type === types.name) {
- node.id = this.parseIdent();
- if (isStatement)
- { this.checkLVal(node.id, BIND_LEXICAL, false); }
- } else {
- if (isStatement === true)
- { this.unexpected(); }
- node.id = null;
- }
- };
-
- pp$1.parseClassSuper = function(node) {
- node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
- };
-
- // Parses module export declaration.
-
- pp$1.parseExport = function(node, exports) {
- this.next();
- // export * from '...'
- if (this.eat(types.star)) {
- if (this.options.ecmaVersion >= 11) {
- if (this.eatContextual("as")) {
- node.exported = this.parseIdent(true);
- this.checkExport(exports, node.exported.name, this.lastTokStart);
- } else {
- node.exported = null;
- }
- }
- this.expectContextual("from");
- if (this.type !== types.string) { this.unexpected(); }
- node.source = this.parseExprAtom();
- this.semicolon();
- return this.finishNode(node, "ExportAllDeclaration")
- }
- if (this.eat(types._default)) { // export default ...
- this.checkExport(exports, "default", this.lastTokStart);
- var isAsync;
- if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
- var fNode = this.startNode();
- this.next();
- if (isAsync) { this.next(); }
- node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
- } else if (this.type === types._class) {
- var cNode = this.startNode();
- node.declaration = this.parseClass(cNode, "nullableID");
- } else {
- node.declaration = this.parseMaybeAssign();
- this.semicolon();
- }
- return this.finishNode(node, "ExportDefaultDeclaration")
- }
- // export var|const|let|function|class ...
- if (this.shouldParseExportStatement()) {
- node.declaration = this.parseStatement(null);
- if (node.declaration.type === "VariableDeclaration")
- { this.checkVariableExport(exports, node.declaration.declarations); }
- else
- { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
- node.specifiers = [];
- node.source = null;
- } else { // export { x, y as z } [from '...']
- node.declaration = null;
- node.specifiers = this.parseExportSpecifiers(exports);
- if (this.eatContextual("from")) {
- if (this.type !== types.string) { this.unexpected(); }
- node.source = this.parseExprAtom();
- } else {
- for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
- // check for keywords used as local names
- var spec = list[i];
-
- this.checkUnreserved(spec.local);
- // check if export is defined
- this.checkLocalExport(spec.local);
- }
-
- node.source = null;
- }
- this.semicolon();
- }
- return this.finishNode(node, "ExportNamedDeclaration")
- };
-
- pp$1.checkExport = function(exports, name, pos) {
- if (!exports) { return }
- if (has(exports, name))
- { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
- exports[name] = true;
- };
-
- pp$1.checkPatternExport = function(exports, pat) {
- var type = pat.type;
- if (type === "Identifier")
- { this.checkExport(exports, pat.name, pat.start); }
- else if (type === "ObjectPattern")
- { for (var i = 0, list = pat.properties; i < list.length; i += 1)
- {
- var prop = list[i];
-
- this.checkPatternExport(exports, prop);
- } }
- else if (type === "ArrayPattern")
- { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
- var elt = list$1[i$1];
-
- if (elt) { this.checkPatternExport(exports, elt); }
- } }
- else if (type === "Property")
- { this.checkPatternExport(exports, pat.value); }
- else if (type === "AssignmentPattern")
- { this.checkPatternExport(exports, pat.left); }
- else if (type === "RestElement")
- { this.checkPatternExport(exports, pat.argument); }
- else if (type === "ParenthesizedExpression")
- { this.checkPatternExport(exports, pat.expression); }
- };
-
- pp$1.checkVariableExport = function(exports, decls) {
- if (!exports) { return }
- for (var i = 0, list = decls; i < list.length; i += 1)
- {
- var decl = list[i];
-
- this.checkPatternExport(exports, decl.id);
- }
- };
-
- pp$1.shouldParseExportStatement = function() {
- return this.type.keyword === "var" ||
- this.type.keyword === "const" ||
- this.type.keyword === "class" ||
- this.type.keyword === "function" ||
- this.isLet() ||
- this.isAsyncFunction()
- };
-
- // Parses a comma-separated list of module exports.
-
- pp$1.parseExportSpecifiers = function(exports) {
- var nodes = [], first = true;
- // export { x, y as z } [from '...']
- this.expect(types.braceL);
- while (!this.eat(types.braceR)) {
- if (!first) {
- this.expect(types.comma);
- if (this.afterTrailingComma(types.braceR)) { break }
- } else { first = false; }
-
- var node = this.startNode();
- node.local = this.parseIdent(true);
- node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
- this.checkExport(exports, node.exported.name, node.exported.start);
- nodes.push(this.finishNode(node, "ExportSpecifier"));
- }
- return nodes
- };
-
- // Parses import declaration.
-
- pp$1.parseImport = function(node) {
- this.next();
- // import '...'
- if (this.type === types.string) {
- node.specifiers = empty;
- node.source = this.parseExprAtom();
- } else {
- node.specifiers = this.parseImportSpecifiers();
- this.expectContextual("from");
- node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
- }
- this.semicolon();
- return this.finishNode(node, "ImportDeclaration")
- };
-
- // Parses a comma-separated list of module imports.
-
- pp$1.parseImportSpecifiers = function() {
- var nodes = [], first = true;
- if (this.type === types.name) {
- // import defaultObj, { x, y as z } from '...'
- var node = this.startNode();
- node.local = this.parseIdent();
- this.checkLVal(node.local, BIND_LEXICAL);
- nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
- if (!this.eat(types.comma)) { return nodes }
- }
- if (this.type === types.star) {
- var node$1 = this.startNode();
- this.next();
- this.expectContextual("as");
- node$1.local = this.parseIdent();
- this.checkLVal(node$1.local, BIND_LEXICAL);
- nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
- return nodes
- }
- this.expect(types.braceL);
- while (!this.eat(types.braceR)) {
- if (!first) {
- this.expect(types.comma);
- if (this.afterTrailingComma(types.braceR)) { break }
- } else { first = false; }
-
- var node$2 = this.startNode();
- node$2.imported = this.parseIdent(true);
- if (this.eatContextual("as")) {
- node$2.local = this.parseIdent();
- } else {
- this.checkUnreserved(node$2.imported);
- node$2.local = node$2.imported;
- }
- this.checkLVal(node$2.local, BIND_LEXICAL);
- nodes.push(this.finishNode(node$2, "ImportSpecifier"));
- }
- return nodes
- };
-
- // Set `ExpressionStatement#directive` property for directive prologues.
- pp$1.adaptDirectivePrologue = function(statements) {
- for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
- statements[i].directive = statements[i].expression.raw.slice(1, -1);
- }
- };
- pp$1.isDirectiveCandidate = function(statement) {
- return (
- statement.type === "ExpressionStatement" &&
- statement.expression.type === "Literal" &&
- typeof statement.expression.value === "string" &&
- // Reject parenthesized strings.
- (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
- )
- };
-
- var pp$2 = Parser.prototype;
-
- // Convert existing expression atom to assignable pattern
- // if possible.
-
- pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
- if (this.options.ecmaVersion >= 6 && node) {
- switch (node.type) {
- case "Identifier":
- if (this.inAsync && node.name === "await")
- { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
- break
-
- case "ObjectPattern":
- case "ArrayPattern":
- case "RestElement":
- break
-
- case "ObjectExpression":
- node.type = "ObjectPattern";
- if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
- for (var i = 0, list = node.properties; i < list.length; i += 1) {
- var prop = list[i];
-
- this.toAssignable(prop, isBinding);
- // Early error:
- // AssignmentRestProperty[Yield, Await] :
- // `...` DestructuringAssignmentTarget[Yield, Await]
- //
- // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
- if (
- prop.type === "RestElement" &&
- (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
- ) {
- this.raise(prop.argument.start, "Unexpected token");
- }
- }
- break
-
- case "Property":
- // AssignmentProperty has type === "Property"
- if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
- this.toAssignable(node.value, isBinding);
- break
-
- case "ArrayExpression":
- node.type = "ArrayPattern";
- if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
- this.toAssignableList(node.elements, isBinding);
- break
+ // 1. Remove any leading and trailing ASCII whitespace from label.
+ // 2. If label is an ASCII case-insensitive match for any of the
+ // labels listed in the table below, then return the
+ // corresponding encoding; otherwise return failure.
+ switch (label.trim().toLowerCase()) {
+ case 'unicode-1-1-utf-8':
+ case 'unicode11utf8':
+ case 'unicode20utf8':
+ case 'utf-8':
+ case 'utf8':
+ case 'x-unicode20utf8':
+ return 'UTF-8'
+ case '866':
+ case 'cp866':
+ case 'csibm866':
+ case 'ibm866':
+ return 'IBM866'
+ case 'csisolatin2':
+ case 'iso-8859-2':
+ case 'iso-ir-101':
+ case 'iso8859-2':
+ case 'iso88592':
+ case 'iso_8859-2':
+ case 'iso_8859-2:1987':
+ case 'l2':
+ case 'latin2':
+ return 'ISO-8859-2'
+ case 'csisolatin3':
+ case 'iso-8859-3':
+ case 'iso-ir-109':
+ case 'iso8859-3':
+ case 'iso88593':
+ case 'iso_8859-3':
+ case 'iso_8859-3:1988':
+ case 'l3':
+ case 'latin3':
+ return 'ISO-8859-3'
+ case 'csisolatin4':
+ case 'iso-8859-4':
+ case 'iso-ir-110':
+ case 'iso8859-4':
+ case 'iso88594':
+ case 'iso_8859-4':
+ case 'iso_8859-4:1988':
+ case 'l4':
+ case 'latin4':
+ return 'ISO-8859-4'
+ case 'csisolatincyrillic':
+ case 'cyrillic':
+ case 'iso-8859-5':
+ case 'iso-ir-144':
+ case 'iso8859-5':
+ case 'iso88595':
+ case 'iso_8859-5':
+ case 'iso_8859-5:1988':
+ return 'ISO-8859-5'
+ case 'arabic':
+ case 'asmo-708':
+ case 'csiso88596e':
+ case 'csiso88596i':
+ case 'csisolatinarabic':
+ case 'ecma-114':
+ case 'iso-8859-6':
+ case 'iso-8859-6-e':
+ case 'iso-8859-6-i':
+ case 'iso-ir-127':
+ case 'iso8859-6':
+ case 'iso88596':
+ case 'iso_8859-6':
+ case 'iso_8859-6:1987':
+ return 'ISO-8859-6'
+ case 'csisolatingreek':
+ case 'ecma-118':
+ case 'elot_928':
+ case 'greek':
+ case 'greek8':
+ case 'iso-8859-7':
+ case 'iso-ir-126':
+ case 'iso8859-7':
+ case 'iso88597':
+ case 'iso_8859-7':
+ case 'iso_8859-7:1987':
+ case 'sun_eu_greek':
+ return 'ISO-8859-7'
+ case 'csiso88598e':
+ case 'csisolatinhebrew':
+ case 'hebrew':
+ case 'iso-8859-8':
+ case 'iso-8859-8-e':
+ case 'iso-ir-138':
+ case 'iso8859-8':
+ case 'iso88598':
+ case 'iso_8859-8':
+ case 'iso_8859-8:1988':
+ case 'visual':
+ return 'ISO-8859-8'
+ case 'csiso88598i':
+ case 'iso-8859-8-i':
+ case 'logical':
+ return 'ISO-8859-8-I'
+ case 'csisolatin6':
+ case 'iso-8859-10':
+ case 'iso-ir-157':
+ case 'iso8859-10':
+ case 'iso885910':
+ case 'l6':
+ case 'latin6':
+ return 'ISO-8859-10'
+ case 'iso-8859-13':
+ case 'iso8859-13':
+ case 'iso885913':
+ return 'ISO-8859-13'
+ case 'iso-8859-14':
+ case 'iso8859-14':
+ case 'iso885914':
+ return 'ISO-8859-14'
+ case 'csisolatin9':
+ case 'iso-8859-15':
+ case 'iso8859-15':
+ case 'iso885915':
+ case 'iso_8859-15':
+ case 'l9':
+ return 'ISO-8859-15'
+ case 'iso-8859-16':
+ return 'ISO-8859-16'
+ case 'cskoi8r':
+ case 'koi':
+ case 'koi8':
+ case 'koi8-r':
+ case 'koi8_r':
+ return 'KOI8-R'
+ case 'koi8-ru':
+ case 'koi8-u':
+ return 'KOI8-U'
+ case 'csmacintosh':
+ case 'mac':
+ case 'macintosh':
+ case 'x-mac-roman':
+ return 'macintosh'
+ case 'iso-8859-11':
+ case 'iso8859-11':
+ case 'iso885911':
+ case 'tis-620':
+ case 'windows-874':
+ return 'windows-874'
+ case 'cp1250':
+ case 'windows-1250':
+ case 'x-cp1250':
+ return 'windows-1250'
+ case 'cp1251':
+ case 'windows-1251':
+ case 'x-cp1251':
+ return 'windows-1251'
+ case 'ansi_x3.4-1968':
+ case 'ascii':
+ case 'cp1252':
+ case 'cp819':
+ case 'csisolatin1':
+ case 'ibm819':
+ case 'iso-8859-1':
+ case 'iso-ir-100':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'iso_8859-1:1987':
+ case 'l1':
+ case 'latin1':
+ case 'us-ascii':
+ case 'windows-1252':
+ case 'x-cp1252':
+ return 'windows-1252'
+ case 'cp1253':
+ case 'windows-1253':
+ case 'x-cp1253':
+ return 'windows-1253'
+ case 'cp1254':
+ case 'csisolatin5':
+ case 'iso-8859-9':
+ case 'iso-ir-148':
+ case 'iso8859-9':
+ case 'iso88599':
+ case 'iso_8859-9':
+ case 'iso_8859-9:1989':
+ case 'l5':
+ case 'latin5':
+ case 'windows-1254':
+ case 'x-cp1254':
+ return 'windows-1254'
+ case 'cp1255':
+ case 'windows-1255':
+ case 'x-cp1255':
+ return 'windows-1255'
+ case 'cp1256':
+ case 'windows-1256':
+ case 'x-cp1256':
+ return 'windows-1256'
+ case 'cp1257':
+ case 'windows-1257':
+ case 'x-cp1257':
+ return 'windows-1257'
+ case 'cp1258':
+ case 'windows-1258':
+ case 'x-cp1258':
+ return 'windows-1258'
+ case 'x-mac-cyrillic':
+ case 'x-mac-ukrainian':
+ return 'x-mac-cyrillic'
+ case 'chinese':
+ case 'csgb2312':
+ case 'csiso58gb231280':
+ case 'gb2312':
+ case 'gb_2312':
+ case 'gb_2312-80':
+ case 'gbk':
+ case 'iso-ir-58':
+ case 'x-gbk':
+ return 'GBK'
+ case 'gb18030':
+ return 'gb18030'
+ case 'big5':
+ case 'big5-hkscs':
+ case 'cn-big5':
+ case 'csbig5':
+ case 'x-x-big5':
+ return 'Big5'
+ case 'cseucpkdfmtjapanese':
+ case 'euc-jp':
+ case 'x-euc-jp':
+ return 'EUC-JP'
+ case 'csiso2022jp':
+ case 'iso-2022-jp':
+ return 'ISO-2022-JP'
+ case 'csshiftjis':
+ case 'ms932':
+ case 'ms_kanji':
+ case 'shift-jis':
+ case 'shift_jis':
+ case 'sjis':
+ case 'windows-31j':
+ case 'x-sjis':
+ return 'Shift_JIS'
+ case 'cseuckr':
+ case 'csksc56011987':
+ case 'euc-kr':
+ case 'iso-ir-149':
+ case 'korean':
+ case 'ks_c_5601-1987':
+ case 'ks_c_5601-1989':
+ case 'ksc5601':
+ case 'ksc_5601':
+ case 'windows-949':
+ return 'EUC-KR'
+ case 'csiso2022kr':
+ case 'hz-gb-2312':
+ case 'iso-2022-cn':
+ case 'iso-2022-cn-ext':
+ case 'iso-2022-kr':
+ case 'replacement':
+ return 'replacement'
+ case 'unicodefffe':
+ case 'utf-16be':
+ return 'UTF-16BE'
+ case 'csunicode':
+ case 'iso-10646-ucs-2':
+ case 'ucs-2':
+ case 'unicode':
+ case 'unicodefeff':
+ case 'utf-16':
+ case 'utf-16le':
+ return 'UTF-16LE'
+ case 'x-user-defined':
+ return 'x-user-defined'
+ default: return 'failure'
+ }
+}
- case "SpreadElement":
- node.type = "RestElement";
- this.toAssignable(node.argument, isBinding);
- if (node.argument.type === "AssignmentPattern")
- { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
- break
+module.exports = {
+ getEncoding
+}
- case "AssignmentExpression":
- if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
- node.type = "AssignmentPattern";
- delete node.operator;
- this.toAssignable(node.left, isBinding);
- // falls through to AssignmentPattern
- case "AssignmentPattern":
- break
+/***/ }),
- case "ParenthesizedExpression":
- this.toAssignable(node.expression, isBinding, refDestructuringErrors);
- break
+/***/ 2160:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- case "ChainExpression":
- this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
- break
- case "MemberExpression":
- if (!isBinding) { break }
- default:
- this.raise(node.start, "Assigning to rvalue");
- }
- } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
- return node
- };
+const {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+} = __nccwpck_require__(165)
+const {
+ kState,
+ kError,
+ kResult,
+ kEvents,
+ kAborted
+} = __nccwpck_require__(6812)
+const { webidl } = __nccwpck_require__(4222)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
- // Convert list of expression atoms to binding list.
+class FileReader extends EventTarget {
+ constructor () {
+ super()
- pp$2.toAssignableList = function(exprList, isBinding) {
- var end = exprList.length;
- for (var i = 0; i < end; i++) {
- var elt = exprList[i];
- if (elt) { this.toAssignable(elt, isBinding); }
- }
- if (end) {
- var last = exprList[end - 1];
- if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
- { this.unexpected(last.argument.start); }
+ this[kState] = 'empty'
+ this[kResult] = null
+ this[kError] = null
+ this[kEvents] = {
+ loadend: null,
+ error: null,
+ abort: null,
+ load: null,
+ progress: null,
+ loadstart: null
}
- return exprList
- };
-
- // Parses spread element.
+ }
- pp$2.parseSpread = function(refDestructuringErrors) {
- var node = this.startNode();
- this.next();
- node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
- return this.finishNode(node, "SpreadElement")
- };
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
+ * @param {import('buffer').Blob} blob
+ */
+ readAsArrayBuffer (blob) {
+ webidl.brandCheck(this, FileReader)
- pp$2.parseRestBinding = function() {
- var node = this.startNode();
- this.next();
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
- // RestElement inside of a function parameter must be an identifier
- if (this.options.ecmaVersion === 6 && this.type !== types.name)
- { this.unexpected(); }
+ blob = webidl.converters.Blob(blob, { strict: false })
- node.argument = this.parseBindingAtom();
+ // The readAsArrayBuffer(blob) method, when invoked,
+ // must initiate a read operation for blob with ArrayBuffer.
+ readOperation(this, blob, 'ArrayBuffer')
+ }
- return this.finishNode(node, "RestElement")
- };
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
+ * @param {import('buffer').Blob} blob
+ */
+ readAsBinaryString (blob) {
+ webidl.brandCheck(this, FileReader)
- // Parses lvalue (assignable) atom.
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
- pp$2.parseBindingAtom = function() {
- if (this.options.ecmaVersion >= 6) {
- switch (this.type) {
- case types.bracketL:
- var node = this.startNode();
- this.next();
- node.elements = this.parseBindingList(types.bracketR, true, true);
- return this.finishNode(node, "ArrayPattern")
+ blob = webidl.converters.Blob(blob, { strict: false })
- case types.braceL:
- return this.parseObj(true)
- }
- }
- return this.parseIdent()
- };
-
- pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
- var elts = [], first = true;
- while (!this.eat(close)) {
- if (first) { first = false; }
- else { this.expect(types.comma); }
- if (allowEmpty && this.type === types.comma) {
- elts.push(null);
- } else if (allowTrailingComma && this.afterTrailingComma(close)) {
- break
- } else if (this.type === types.ellipsis) {
- var rest = this.parseRestBinding();
- this.parseBindingListItem(rest);
- elts.push(rest);
- if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
- this.expect(close);
- break
- } else {
- var elem = this.parseMaybeDefault(this.start, this.startLoc);
- this.parseBindingListItem(elem);
- elts.push(elem);
- }
- }
- return elts
- };
-
- pp$2.parseBindingListItem = function(param) {
- return param
- };
-
- // Parses assignment pattern around given atom if possible.
-
- pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
- left = left || this.parseBindingAtom();
- if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
- var node = this.startNodeAt(startPos, startLoc);
- node.left = left;
- node.right = this.parseMaybeAssign();
- return this.finishNode(node, "AssignmentPattern")
- };
-
- // Verify that a node is an lval — something that can be assigned
- // to.
- // bindingType can be either:
- // 'var' indicating that the lval creates a 'var' binding
- // 'let' indicating that the lval creates a lexical ('let' or 'const') binding
- // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
-
- pp$2.checkLVal = function(expr, bindingType, checkClashes) {
- if ( bindingType === void 0 ) bindingType = BIND_NONE;
-
- switch (expr.type) {
- case "Identifier":
- if (bindingType === BIND_LEXICAL && expr.name === "let")
- { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
- if (this.strict && this.reservedWordsStrictBind.test(expr.name))
- { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
- if (checkClashes) {
- if (has(checkClashes, expr.name))
- { this.raiseRecoverable(expr.start, "Argument name clash"); }
- checkClashes[expr.name] = true;
- }
- if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
- break
+ // The readAsBinaryString(blob) method, when invoked,
+ // must initiate a read operation for blob with BinaryString.
+ readOperation(this, blob, 'BinaryString')
+ }
- case "ChainExpression":
- this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
- break
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
+ * @param {import('buffer').Blob} blob
+ * @param {string?} encoding
+ */
+ readAsText (blob, encoding = undefined) {
+ webidl.brandCheck(this, FileReader)
- case "MemberExpression":
- if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }
- break
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
- case "ObjectPattern":
- for (var i = 0, list = expr.properties; i < list.length; i += 1)
- {
- var prop = list[i];
+ blob = webidl.converters.Blob(blob, { strict: false })
- this.checkLVal(prop, bindingType, checkClashes);
+ if (encoding !== undefined) {
+ encoding = webidl.converters.DOMString(encoding)
}
- break
- case "Property":
- // AssignmentProperty has type === "Property"
- this.checkLVal(expr.value, bindingType, checkClashes);
- break
-
- case "ArrayPattern":
- for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
- var elem = list$1[i$1];
+ // The readAsText(blob, encoding) method, when invoked,
+ // must initiate a read operation for blob with Text and encoding.
+ readOperation(this, blob, 'Text', encoding)
+ }
- if (elem) { this.checkLVal(elem, bindingType, checkClashes); }
- }
- break
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
+ * @param {import('buffer').Blob} blob
+ */
+ readAsDataURL (blob) {
+ webidl.brandCheck(this, FileReader)
- case "AssignmentPattern":
- this.checkLVal(expr.left, bindingType, checkClashes);
- break
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
- case "RestElement":
- this.checkLVal(expr.argument, bindingType, checkClashes);
- break
+ blob = webidl.converters.Blob(blob, { strict: false })
- case "ParenthesizedExpression":
- this.checkLVal(expr.expression, bindingType, checkClashes);
- break
+ // The readAsDataURL(blob) method, when invoked, must
+ // initiate a read operation for blob with DataURL.
+ readOperation(this, blob, 'DataURL')
+ }
- default:
- this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
- }
- };
-
- // A recursive descent parser operates by defining functions for all
-
- var pp$3 = Parser.prototype;
-
- // Check if property name clashes with already added.
- // Object/class getters and setters are not allowed to clash —
- // either with each other or with an init property — and in
- // strict mode, init properties are also not allowed to be repeated.
-
- pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
- if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
- { return }
- if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
- { return }
- var key = prop.key;
- var name;
- switch (key.type) {
- case "Identifier": name = key.name; break
- case "Literal": name = String(key.value); break
- default: return
- }
- var kind = prop.kind;
- if (this.options.ecmaVersion >= 6) {
- if (name === "__proto__" && kind === "init") {
- if (propHash.proto) {
- if (refDestructuringErrors) {
- if (refDestructuringErrors.doubleProto < 0)
- { refDestructuringErrors.doubleProto = key.start; }
- // Backwards-compat kludge. Can be removed in version 6.0
- } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
- }
- propHash.proto = true;
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
+ */
+ abort () {
+ // 1. If this's state is "empty" or if this's state is
+ // "done" set this's result to null and terminate
+ // this algorithm.
+ if (this[kState] === 'empty' || this[kState] === 'done') {
+ this[kResult] = null
return
}
- name = "$" + name;
- var other = propHash[name];
- if (other) {
- var redefinition;
- if (kind === "init") {
- redefinition = this.strict && other.init || other.get || other.set;
- } else {
- redefinition = other.init || other[kind];
- }
- if (redefinition)
- { this.raiseRecoverable(key.start, "Redefinition of property"); }
- } else {
- other = propHash[name] = {
- init: false,
- get: false,
- set: false
- };
- }
- other[kind] = true;
- };
-
- // ### Expression parsing
-
- // These nest, from the most general expression type at the top to
- // 'atomic', nondivisible expression types at the bottom. Most of
- // the functions will simply let the function(s) below them parse,
- // and, *if* the syntactic construct they handle is present, wrap
- // the AST node that the inner parser gave them in another node.
-
- // Parse a full expression. The optional arguments are used to
- // forbid the `in` operator (in for loops initalization expressions)
- // and provide reference for storing '=' operator inside shorthand
- // property assignment in contexts where both object expression
- // and object pattern might appear (so it's possible to raise
- // delayed syntax error at correct position).
-
- pp$3.parseExpression = function(noIn, refDestructuringErrors) {
- var startPos = this.start, startLoc = this.startLoc;
- var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
- if (this.type === types.comma) {
- var node = this.startNodeAt(startPos, startLoc);
- node.expressions = [expr];
- while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
- return this.finishNode(node, "SequenceExpression")
- }
- return expr
- };
-
- // Parse an assignment expression. This includes applications of
- // operators like `+=`.
-
- pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
- if (this.isContextual("yield")) {
- if (this.inGenerator) { return this.parseYield(noIn) }
- // The tokenizer will assume an expression is allowed after
- // `yield`, but this isn't that kind of yield
- else { this.exprAllowed = false; }
- }
-
- var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
- if (refDestructuringErrors) {
- oldParenAssign = refDestructuringErrors.parenthesizedAssign;
- oldTrailingComma = refDestructuringErrors.trailingComma;
- refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
- } else {
- refDestructuringErrors = new DestructuringErrors;
- ownDestructuringErrors = true;
- }
-
- var startPos = this.start, startLoc = this.startLoc;
- if (this.type === types.parenL || this.type === types.name)
- { this.potentialArrowAt = this.start; }
- var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
- if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
- if (this.type.isAssign) {
- var node = this.startNodeAt(startPos, startLoc);
- node.operator = this.value;
- node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
- if (!ownDestructuringErrors) {
- refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
- }
- if (refDestructuringErrors.shorthandAssign >= node.left.start)
- { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
- this.checkLVal(left);
- this.next();
- node.right = this.parseMaybeAssign(noIn);
- return this.finishNode(node, "AssignmentExpression")
- } else {
- if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
- }
- if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
- if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
- return left
- };
-
- // Parse a ternary conditional (`?:`) operator.
-
- pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
- var startPos = this.start, startLoc = this.startLoc;
- var expr = this.parseExprOps(noIn, refDestructuringErrors);
- if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
- if (this.eat(types.question)) {
- var node = this.startNodeAt(startPos, startLoc);
- node.test = expr;
- node.consequent = this.parseMaybeAssign();
- this.expect(types.colon);
- node.alternate = this.parseMaybeAssign(noIn);
- return this.finishNode(node, "ConditionalExpression")
- }
- return expr
- };
-
- // Start the precedence parser.
-
- pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
- var startPos = this.start, startLoc = this.startLoc;
- var expr = this.parseMaybeUnary(refDestructuringErrors, false);
- if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
- return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
- };
-
- // Parse binary operators with the operator precedence parsing
- // algorithm. `left` is the left-hand side of the operator.
- // `minPrec` provides context that allows the function to stop and
- // defer further parser to one of its callers when it encounters an
- // operator that has a lower precedence than the set it is parsing.
-
- pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
- var prec = this.type.binop;
- if (prec != null && (!noIn || this.type !== types._in)) {
- if (prec > minPrec) {
- var logical = this.type === types.logicalOR || this.type === types.logicalAND;
- var coalesce = this.type === types.coalesce;
- if (coalesce) {
- // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
- // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
- prec = types.logicalAND.binop;
- }
- var op = this.value;
- this.next();
- var startPos = this.start, startLoc = this.startLoc;
- var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
- var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
- if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
- this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
- }
- return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
- }
- }
- return left
- };
-
- pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
- var node = this.startNodeAt(startPos, startLoc);
- node.left = left;
- node.operator = op;
- node.right = right;
- return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
- };
-
- // Parse unary operators, both prefix and postfix.
-
- pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
- var startPos = this.start, startLoc = this.startLoc, expr;
- if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
- expr = this.parseAwait();
- sawUnary = true;
- } else if (this.type.prefix) {
- var node = this.startNode(), update = this.type === types.incDec;
- node.operator = this.value;
- node.prefix = true;
- this.next();
- node.argument = this.parseMaybeUnary(null, true);
- this.checkExpressionErrors(refDestructuringErrors, true);
- if (update) { this.checkLVal(node.argument); }
- else if (this.strict && node.operator === "delete" &&
- node.argument.type === "Identifier")
- { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
- else { sawUnary = true; }
- expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
- } else {
- expr = this.parseExprSubscripts(refDestructuringErrors);
- if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
- while (this.type.postfix && !this.canInsertSemicolon()) {
- var node$1 = this.startNodeAt(startPos, startLoc);
- node$1.operator = this.value;
- node$1.prefix = false;
- node$1.argument = expr;
- this.checkLVal(expr);
- this.next();
- expr = this.finishNode(node$1, "UpdateExpression");
- }
- }
-
- if (!sawUnary && this.eat(types.starstar))
- { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
- else
- { return expr }
- };
-
- // Parse call, dot, and `[]`-subscript expressions.
-
- pp$3.parseExprSubscripts = function(refDestructuringErrors) {
- var startPos = this.start, startLoc = this.startLoc;
- var expr = this.parseExprAtom(refDestructuringErrors);
- if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
- { return expr }
- var result = this.parseSubscripts(expr, startPos, startLoc);
- if (refDestructuringErrors && result.type === "MemberExpression") {
- if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
- if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
- }
- return result
- };
- pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
- var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
- this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
- this.potentialArrowAt === base.start;
- var optionalChained = false;
-
- while (true) {
- var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
-
- if (element.optional) { optionalChained = true; }
- if (element === base || element.type === "ArrowFunctionExpression") {
- if (optionalChained) {
- var chainNode = this.startNodeAt(startPos, startLoc);
- chainNode.expression = element;
- element = this.finishNode(chainNode, "ChainExpression");
- }
- return element
- }
-
- base = element;
+ // 2. If this's state is "loading" set this's state to
+ // "done" and set this's result to null.
+ if (this[kState] === 'loading') {
+ this[kState] = 'done'
+ this[kResult] = null
}
- };
-
- pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
- var optionalSupported = this.options.ecmaVersion >= 11;
- var optional = optionalSupported && this.eat(types.questionDot);
- if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
-
- var computed = this.eat(types.bracketL);
- if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
- var node = this.startNodeAt(startPos, startLoc);
- node.object = base;
- node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
- node.computed = !!computed;
- if (computed) { this.expect(types.bracketR); }
- if (optionalSupported) {
- node.optional = optional;
- }
- base = this.finishNode(node, "MemberExpression");
- } else if (!noCalls && this.eat(types.parenL)) {
- var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
- this.yieldPos = 0;
- this.awaitPos = 0;
- this.awaitIdentPos = 0;
- var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
- if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
- this.checkPatternErrors(refDestructuringErrors, false);
- this.checkYieldAwaitInDefaultParams();
- if (this.awaitIdentPos > 0)
- { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
- this.yieldPos = oldYieldPos;
- this.awaitPos = oldAwaitPos;
- this.awaitIdentPos = oldAwaitIdentPos;
- return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
- }
- this.checkExpressionErrors(refDestructuringErrors, true);
- this.yieldPos = oldYieldPos || this.yieldPos;
- this.awaitPos = oldAwaitPos || this.awaitPos;
- this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
- var node$1 = this.startNodeAt(startPos, startLoc);
- node$1.callee = base;
- node$1.arguments = exprList;
- if (optionalSupported) {
- node$1.optional = optional;
- }
- base = this.finishNode(node$1, "CallExpression");
- } else if (this.type === types.backQuote) {
- if (optional || optionalChained) {
- this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
- }
- var node$2 = this.startNodeAt(startPos, startLoc);
- node$2.tag = base;
- node$2.quasi = this.parseTemplate({isTagged: true});
- base = this.finishNode(node$2, "TaggedTemplateExpression");
- }
- return base
- };
-
- // Parse an atomic expression — either a single token that is an
- // expression, an expression started by a keyword like `function` or
- // `new`, or an expression wrapped in punctuation like `()`, `[]`,
- // or `{}`.
-
- pp$3.parseExprAtom = function(refDestructuringErrors) {
- // If a division operator appears in an expression position, the
- // tokenizer got confused, and we force it to read a regexp instead.
- if (this.type === types.slash) { this.readRegexp(); }
-
- var node, canBeArrow = this.potentialArrowAt === this.start;
- switch (this.type) {
- case types._super:
- if (!this.allowSuper)
- { this.raise(this.start, "'super' keyword outside a method"); }
- node = this.startNode();
- this.next();
- if (this.type === types.parenL && !this.allowDirectSuper)
- { this.raise(node.start, "super() call outside constructor of a subclass"); }
- // The `super` keyword can appear at below:
- // SuperProperty:
- // super [ Expression ]
- // super . IdentifierName
- // SuperCall:
- // super ( Arguments )
- if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
- { this.unexpected(); }
- return this.finishNode(node, "Super")
-
- case types._this:
- node = this.startNode();
- this.next();
- return this.finishNode(node, "ThisExpression")
-
- case types.name:
- var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
- var id = this.parseIdent(false);
- if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
- { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
- if (canBeArrow && !this.canInsertSemicolon()) {
- if (this.eat(types.arrow))
- { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
- if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
- id = this.parseIdent(false);
- if (this.canInsertSemicolon() || !this.eat(types.arrow))
- { this.unexpected(); }
- return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
- }
- }
- return id
-
- case types.regexp:
- var value = this.value;
- node = this.parseLiteral(value.value);
- node.regex = {pattern: value.pattern, flags: value.flags};
- return node
-
- case types.num: case types.string:
- return this.parseLiteral(this.value)
-
- case types._null: case types._true: case types._false:
- node = this.startNode();
- node.value = this.type === types._null ? null : this.type === types._true;
- node.raw = this.type.keyword;
- this.next();
- return this.finishNode(node, "Literal")
-
- case types.parenL:
- var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
- if (refDestructuringErrors) {
- if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
- { refDestructuringErrors.parenthesizedAssign = start; }
- if (refDestructuringErrors.parenthesizedBind < 0)
- { refDestructuringErrors.parenthesizedBind = start; }
- }
- return expr
-
- case types.bracketL:
- node = this.startNode();
- this.next();
- node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
- return this.finishNode(node, "ArrayExpression")
- case types.braceL:
- return this.parseObj(false, refDestructuringErrors)
-
- case types._function:
- node = this.startNode();
- this.next();
- return this.parseFunction(node, 0)
-
- case types._class:
- return this.parseClass(this.startNode(), false)
-
- case types._new:
- return this.parseNew()
+ // 3. If there are any tasks from this on the file reading
+ // task source in an affiliated task queue, then remove
+ // those tasks from that task queue.
+ this[kAborted] = true
- case types.backQuote:
- return this.parseTemplate()
+ // 4. Terminate the algorithm for the read method being processed.
+ // TODO
- case types._import:
- if (this.options.ecmaVersion >= 11) {
- return this.parseExprImport()
- } else {
- return this.unexpected()
- }
+ // 5. Fire a progress event called abort at this.
+ fireAProgressEvent('abort', this)
- default:
- this.unexpected();
+ // 6. If this's state is not "loading", fire a progress
+ // event called loadend at this.
+ if (this[kState] !== 'loading') {
+ fireAProgressEvent('loadend', this)
}
- };
-
- pp$3.parseExprImport = function() {
- var node = this.startNode();
-
- // Consume `import` as an identifier for `import.meta`.
- // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
- if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
- var meta = this.parseIdent(true);
-
- switch (this.type) {
- case types.parenL:
- return this.parseDynamicImport(node)
- case types.dot:
- node.meta = meta;
- return this.parseImportMeta(node)
- default:
- this.unexpected();
- }
- };
-
- pp$3.parseDynamicImport = function(node) {
- this.next(); // skip `(`
-
- // Parse node.source.
- node.source = this.parseMaybeAssign();
-
- // Verify ending.
- if (!this.eat(types.parenR)) {
- var errorPos = this.start;
- if (this.eat(types.comma) && this.eat(types.parenR)) {
- this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
- } else {
- this.unexpected(errorPos);
- }
- }
-
- return this.finishNode(node, "ImportExpression")
- };
-
- pp$3.parseImportMeta = function(node) {
- this.next(); // skip `.`
-
- var containsEsc = this.containsEsc;
- node.property = this.parseIdent(true);
-
- if (node.property.name !== "meta")
- { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
- if (containsEsc)
- { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
- if (this.options.sourceType !== "module")
- { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
-
- return this.finishNode(node, "MetaProperty")
- };
-
- pp$3.parseLiteral = function(value) {
- var node = this.startNode();
- node.value = value;
- node.raw = this.input.slice(this.start, this.end);
- if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
- this.next();
- return this.finishNode(node, "Literal")
- };
-
- pp$3.parseParenExpression = function() {
- this.expect(types.parenL);
- var val = this.parseExpression();
- this.expect(types.parenR);
- return val
- };
-
- pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
- var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
- if (this.options.ecmaVersion >= 6) {
- this.next();
-
- var innerStartPos = this.start, innerStartLoc = this.startLoc;
- var exprList = [], first = true, lastIsComma = false;
- var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
- this.yieldPos = 0;
- this.awaitPos = 0;
- // Do not save awaitIdentPos to allow checking awaits nested in parameters
- while (this.type !== types.parenR) {
- first ? first = false : this.expect(types.comma);
- if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
- lastIsComma = true;
- break
- } else if (this.type === types.ellipsis) {
- spreadStart = this.start;
- exprList.push(this.parseParenItem(this.parseRestBinding()));
- if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
- break
- } else {
- exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
- }
- }
- var innerEndPos = this.start, innerEndLoc = this.startLoc;
- this.expect(types.parenR);
-
- if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
- this.checkPatternErrors(refDestructuringErrors, false);
- this.checkYieldAwaitInDefaultParams();
- this.yieldPos = oldYieldPos;
- this.awaitPos = oldAwaitPos;
- return this.parseParenArrowList(startPos, startLoc, exprList)
- }
-
- if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
- if (spreadStart) { this.unexpected(spreadStart); }
- this.checkExpressionErrors(refDestructuringErrors, true);
- this.yieldPos = oldYieldPos || this.yieldPos;
- this.awaitPos = oldAwaitPos || this.awaitPos;
-
- if (exprList.length > 1) {
- val = this.startNodeAt(innerStartPos, innerStartLoc);
- val.expressions = exprList;
- this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
- } else {
- val = exprList[0];
- }
- } else {
- val = this.parseParenExpression();
- }
-
- if (this.options.preserveParens) {
- var par = this.startNodeAt(startPos, startLoc);
- par.expression = val;
- return this.finishNode(par, "ParenthesizedExpression")
- } else {
- return val
- }
- };
-
- pp$3.parseParenItem = function(item) {
- return item
- };
-
- pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
- return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
- };
-
- // New's precedence is slightly tricky. It must allow its argument to
- // be a `[]` or dot subscript expression, but not a call — at least,
- // not without wrapping it in parentheses. Thus, it uses the noCalls
- // argument to parseSubscripts to prevent it from consuming the
- // argument list.
-
- var empty$1 = [];
-
- pp$3.parseNew = function() {
- if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
- var node = this.startNode();
- var meta = this.parseIdent(true);
- if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
- node.meta = meta;
- var containsEsc = this.containsEsc;
- node.property = this.parseIdent(true);
- if (node.property.name !== "target")
- { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
- if (containsEsc)
- { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
- if (!this.inNonArrowFunction())
- { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
- return this.finishNode(node, "MetaProperty")
- }
- var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
- node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
- if (isImport && node.callee.type === "ImportExpression") {
- this.raise(startPos, "Cannot use new with import()");
- }
- if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
- else { node.arguments = empty$1; }
- return this.finishNode(node, "NewExpression")
- };
-
- // Parse template expression.
-
- pp$3.parseTemplateElement = function(ref) {
- var isTagged = ref.isTagged;
-
- var elem = this.startNode();
- if (this.type === types.invalidTemplate) {
- if (!isTagged) {
- this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
- }
- elem.value = {
- raw: this.value,
- cooked: null
- };
- } else {
- elem.value = {
- raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
- cooked: this.value
- };
- }
- this.next();
- elem.tail = this.type === types.backQuote;
- return this.finishNode(elem, "TemplateElement")
- };
-
- pp$3.parseTemplate = function(ref) {
- if ( ref === void 0 ) ref = {};
- var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
-
- var node = this.startNode();
- this.next();
- node.expressions = [];
- var curElt = this.parseTemplateElement({isTagged: isTagged});
- node.quasis = [curElt];
- while (!curElt.tail) {
- if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
- this.expect(types.dollarBraceL);
- node.expressions.push(this.parseExpression());
- this.expect(types.braceR);
- node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
- }
- this.next();
- return this.finishNode(node, "TemplateLiteral")
- };
-
- pp$3.isAsyncProp = function(prop) {
- return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
- (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
- !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
- };
-
- // Parse an object literal or binding pattern.
-
- pp$3.parseObj = function(isPattern, refDestructuringErrors) {
- var node = this.startNode(), first = true, propHash = {};
- node.properties = [];
- this.next();
- while (!this.eat(types.braceR)) {
- if (!first) {
- this.expect(types.comma);
- if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
- } else { first = false; }
-
- var prop = this.parseProperty(isPattern, refDestructuringErrors);
- if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
- node.properties.push(prop);
- }
- return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
- };
-
- pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
- var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
- if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
- if (isPattern) {
- prop.argument = this.parseIdent(false);
- if (this.type === types.comma) {
- this.raise(this.start, "Comma is not permitted after the rest element");
- }
- return this.finishNode(prop, "RestElement")
- }
- // To disallow parenthesized identifier via `this.toAssignable()`.
- if (this.type === types.parenL && refDestructuringErrors) {
- if (refDestructuringErrors.parenthesizedAssign < 0) {
- refDestructuringErrors.parenthesizedAssign = this.start;
- }
- if (refDestructuringErrors.parenthesizedBind < 0) {
- refDestructuringErrors.parenthesizedBind = this.start;
- }
- }
- // Parse argument.
- prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
- // To disallow trailing comma via `this.toAssignable()`.
- if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
- refDestructuringErrors.trailingComma = this.start;
- }
- // Finish
- return this.finishNode(prop, "SpreadElement")
- }
- if (this.options.ecmaVersion >= 6) {
- prop.method = false;
- prop.shorthand = false;
- if (isPattern || refDestructuringErrors) {
- startPos = this.start;
- startLoc = this.startLoc;
- }
- if (!isPattern)
- { isGenerator = this.eat(types.star); }
- }
- var containsEsc = this.containsEsc;
- this.parsePropertyName(prop);
- if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
- isAsync = true;
- isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
- this.parsePropertyName(prop, refDestructuringErrors);
- } else {
- isAsync = false;
- }
- this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
- return this.finishNode(prop, "Property")
- };
-
- pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
- if ((isGenerator || isAsync) && this.type === types.colon)
- { this.unexpected(); }
-
- if (this.eat(types.colon)) {
- prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
- prop.kind = "init";
- } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
- if (isPattern) { this.unexpected(); }
- prop.kind = "init";
- prop.method = true;
- prop.value = this.parseMethod(isGenerator, isAsync);
- } else if (!isPattern && !containsEsc &&
- this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
- (prop.key.name === "get" || prop.key.name === "set") &&
- (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
- if (isGenerator || isAsync) { this.unexpected(); }
- prop.kind = prop.key.name;
- this.parsePropertyName(prop);
- prop.value = this.parseMethod(false);
- var paramCount = prop.kind === "get" ? 0 : 1;
- if (prop.value.params.length !== paramCount) {
- var start = prop.value.start;
- if (prop.kind === "get")
- { this.raiseRecoverable(start, "getter should have no params"); }
- else
- { this.raiseRecoverable(start, "setter should have exactly one param"); }
- } else {
- if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
- { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
- }
- } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
- if (isGenerator || isAsync) { this.unexpected(); }
- this.checkUnreserved(prop.key);
- if (prop.key.name === "await" && !this.awaitIdentPos)
- { this.awaitIdentPos = startPos; }
- prop.kind = "init";
- if (isPattern) {
- prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
- } else if (this.type === types.eq && refDestructuringErrors) {
- if (refDestructuringErrors.shorthandAssign < 0)
- { refDestructuringErrors.shorthandAssign = this.start; }
- prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
- } else {
- prop.value = prop.key;
- }
- prop.shorthand = true;
- } else { this.unexpected(); }
- };
-
- pp$3.parsePropertyName = function(prop) {
- if (this.options.ecmaVersion >= 6) {
- if (this.eat(types.bracketL)) {
- prop.computed = true;
- prop.key = this.parseMaybeAssign();
- this.expect(types.bracketR);
- return prop.key
- } else {
- prop.computed = false;
- }
- }
- return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
- };
-
- // Initialize empty function node.
-
- pp$3.initFunction = function(node) {
- node.id = null;
- if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
- if (this.options.ecmaVersion >= 8) { node.async = false; }
- };
-
- // Parse object or class method.
-
- pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
- var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
-
- this.initFunction(node);
- if (this.options.ecmaVersion >= 6)
- { node.generator = isGenerator; }
- if (this.options.ecmaVersion >= 8)
- { node.async = !!isAsync; }
-
- this.yieldPos = 0;
- this.awaitPos = 0;
- this.awaitIdentPos = 0;
- this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
-
- this.expect(types.parenL);
- node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
- this.checkYieldAwaitInDefaultParams();
- this.parseFunctionBody(node, false, true);
-
- this.yieldPos = oldYieldPos;
- this.awaitPos = oldAwaitPos;
- this.awaitIdentPos = oldAwaitIdentPos;
- return this.finishNode(node, "FunctionExpression")
- };
-
- // Parse arrow function expression with given parameters.
-
- pp$3.parseArrowExpression = function(node, params, isAsync) {
- var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
-
- this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
- this.initFunction(node);
- if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
-
- this.yieldPos = 0;
- this.awaitPos = 0;
- this.awaitIdentPos = 0;
-
- node.params = this.toAssignableList(params, true);
- this.parseFunctionBody(node, true, false);
-
- this.yieldPos = oldYieldPos;
- this.awaitPos = oldAwaitPos;
- this.awaitIdentPos = oldAwaitIdentPos;
- return this.finishNode(node, "ArrowFunctionExpression")
- };
-
- // Parse function body and check parameters.
-
- pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
- var isExpression = isArrowFunction && this.type !== types.braceL;
- var oldStrict = this.strict, useStrict = false;
-
- if (isExpression) {
- node.body = this.parseMaybeAssign();
- node.expression = true;
- this.checkParams(node, false);
- } else {
- var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
- if (!oldStrict || nonSimple) {
- useStrict = this.strictDirective(this.end);
- // If this is a strict mode function, verify that argument names
- // are not repeated, and it does not try to bind the words `eval`
- // or `arguments`.
- if (useStrict && nonSimple)
- { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
- }
- // Start a new scope with regard to labels and the `inFunction`
- // flag (restore them to their old value afterwards).
- var oldLabels = this.labels;
- this.labels = [];
- if (useStrict) { this.strict = true; }
-
- // Add the params to varDeclaredNames to ensure that an error is thrown
- // if a let/const declaration in the function clashes with one of the params.
- this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
- // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
- if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); }
- node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
- node.expression = false;
- this.adaptDirectivePrologue(node.body.body);
- this.labels = oldLabels;
- }
- this.exitScope();
- };
-
- pp$3.isSimpleParamList = function(params) {
- for (var i = 0, list = params; i < list.length; i += 1)
- {
- var param = list[i];
-
- if (param.type !== "Identifier") { return false
- } }
- return true
- };
-
- // Checks function params for various disallowed patterns such as using "eval"
- // or "arguments" and duplicate parameters.
-
- pp$3.checkParams = function(node, allowDuplicates) {
- var nameHash = {};
- for (var i = 0, list = node.params; i < list.length; i += 1)
- {
- var param = list[i];
-
- this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
- }
- };
-
- // Parses a comma-separated list of expressions, and returns them as
- // an array. `close` is the token type that ends the list, and
- // `allowEmpty` can be turned on to allow subsequent commas with
- // nothing in between them to be parsed as `null` (which is needed
- // for array literals).
-
- pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
- var elts = [], first = true;
- while (!this.eat(close)) {
- if (!first) {
- this.expect(types.comma);
- if (allowTrailingComma && this.afterTrailingComma(close)) { break }
- } else { first = false; }
-
- var elt = (void 0);
- if (allowEmpty && this.type === types.comma)
- { elt = null; }
- else if (this.type === types.ellipsis) {
- elt = this.parseSpread(refDestructuringErrors);
- if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
- { refDestructuringErrors.trailingComma = this.start; }
- } else {
- elt = this.parseMaybeAssign(false, refDestructuringErrors);
- }
- elts.push(elt);
- }
- return elts
- };
-
- pp$3.checkUnreserved = function(ref) {
- var start = ref.start;
- var end = ref.end;
- var name = ref.name;
-
- if (this.inGenerator && name === "yield")
- { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
- if (this.inAsync && name === "await")
- { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
- if (this.keywords.test(name))
- { this.raise(start, ("Unexpected keyword '" + name + "'")); }
- if (this.options.ecmaVersion < 6 &&
- this.input.slice(start, end).indexOf("\\") !== -1) { return }
- var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
- if (re.test(name)) {
- if (!this.inAsync && name === "await")
- { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
- this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
- }
- };
-
- // Parse the next token as an identifier. If `liberal` is true (used
- // when parsing properties), it will also convert keywords into
- // identifiers.
-
- pp$3.parseIdent = function(liberal, isBinding) {
- var node = this.startNode();
- if (this.type === types.name) {
- node.name = this.value;
- } else if (this.type.keyword) {
- node.name = this.type.keyword;
-
- // To fix https://github.com/acornjs/acorn/issues/575
- // `class` and `function` keywords push new context into this.context.
- // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
- // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
- if ((node.name === "class" || node.name === "function") &&
- (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
- this.context.pop();
- }
- } else {
- this.unexpected();
- }
- this.next(!!liberal);
- this.finishNode(node, "Identifier");
- if (!liberal) {
- this.checkUnreserved(node);
- if (node.name === "await" && !this.awaitIdentPos)
- { this.awaitIdentPos = node.start; }
- }
- return node
- };
-
- // Parses yield expression inside generator.
-
- pp$3.parseYield = function(noIn) {
- if (!this.yieldPos) { this.yieldPos = this.start; }
-
- var node = this.startNode();
- this.next();
- if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
- node.delegate = false;
- node.argument = null;
- } else {
- node.delegate = this.eat(types.star);
- node.argument = this.parseMaybeAssign(noIn);
- }
- return this.finishNode(node, "YieldExpression")
- };
-
- pp$3.parseAwait = function() {
- if (!this.awaitPos) { this.awaitPos = this.start; }
-
- var node = this.startNode();
- this.next();
- node.argument = this.parseMaybeUnary(null, false);
- return this.finishNode(node, "AwaitExpression")
- };
-
- var pp$4 = Parser.prototype;
-
- // This function is used to raise exceptions on parse errors. It
- // takes an offset integer (into the current `input`) to indicate
- // the location of the error, attaches the position to the end
- // of the error message, and then raises a `SyntaxError` with that
- // message.
-
- pp$4.raise = function(pos, message) {
- var loc = getLineInfo(this.input, pos);
- message += " (" + loc.line + ":" + loc.column + ")";
- var err = new SyntaxError(message);
- err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
- throw err
- };
-
- pp$4.raiseRecoverable = pp$4.raise;
-
- pp$4.curPosition = function() {
- if (this.options.locations) {
- return new Position(this.curLine, this.pos - this.lineStart)
- }
- };
-
- var pp$5 = Parser.prototype;
-
- var Scope = function Scope(flags) {
- this.flags = flags;
- // A list of var-declared names in the current lexical scope
- this.var = [];
- // A list of lexically-declared names in the current lexical scope
- this.lexical = [];
- // A list of lexically-declared FunctionDeclaration names in the current lexical scope
- this.functions = [];
- };
-
- // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
-
- pp$5.enterScope = function(flags) {
- this.scopeStack.push(new Scope(flags));
- };
-
- pp$5.exitScope = function() {
- this.scopeStack.pop();
- };
-
- // The spec says:
- // > At the top level of a function, or script, function declarations are
- // > treated like var declarations rather than like lexical declarations.
- pp$5.treatFunctionsAsVarInScope = function(scope) {
- return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
- };
-
- pp$5.declareName = function(name, bindingType, pos) {
- var redeclared = false;
- if (bindingType === BIND_LEXICAL) {
- var scope = this.currentScope();
- redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
- scope.lexical.push(name);
- if (this.inModule && (scope.flags & SCOPE_TOP))
- { delete this.undefinedExports[name]; }
- } else if (bindingType === BIND_SIMPLE_CATCH) {
- var scope$1 = this.currentScope();
- scope$1.lexical.push(name);
- } else if (bindingType === BIND_FUNCTION) {
- var scope$2 = this.currentScope();
- if (this.treatFunctionsAsVar)
- { redeclared = scope$2.lexical.indexOf(name) > -1; }
- else
- { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
- scope$2.functions.push(name);
- } else {
- for (var i = this.scopeStack.length - 1; i >= 0; --i) {
- var scope$3 = this.scopeStack[i];
- if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
- !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
- redeclared = true;
- break
- }
- scope$3.var.push(name);
- if (this.inModule && (scope$3.flags & SCOPE_TOP))
- { delete this.undefinedExports[name]; }
- if (scope$3.flags & SCOPE_VAR) { break }
- }
- }
- if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
- };
-
- pp$5.checkLocalExport = function(id) {
- // scope.functions must be empty as Module code is always strict.
- if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
- this.scopeStack[0].var.indexOf(id.name) === -1) {
- this.undefinedExports[id.name] = id;
- }
- };
-
- pp$5.currentScope = function() {
- return this.scopeStack[this.scopeStack.length - 1]
- };
-
- pp$5.currentVarScope = function() {
- for (var i = this.scopeStack.length - 1;; i--) {
- var scope = this.scopeStack[i];
- if (scope.flags & SCOPE_VAR) { return scope }
- }
- };
-
- // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
- pp$5.currentThisScope = function() {
- for (var i = this.scopeStack.length - 1;; i--) {
- var scope = this.scopeStack[i];
- if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
- }
- };
-
- var Node = function Node(parser, pos, loc) {
- this.type = "";
- this.start = pos;
- this.end = 0;
- if (parser.options.locations)
- { this.loc = new SourceLocation(parser, loc); }
- if (parser.options.directSourceFile)
- { this.sourceFile = parser.options.directSourceFile; }
- if (parser.options.ranges)
- { this.range = [pos, 0]; }
- };
-
- // Start an AST node, attaching a start offset.
-
- var pp$6 = Parser.prototype;
-
- pp$6.startNode = function() {
- return new Node(this, this.start, this.startLoc)
- };
-
- pp$6.startNodeAt = function(pos, loc) {
- return new Node(this, pos, loc)
- };
-
- // Finish an AST node, adding `type` and `end` properties.
-
- function finishNodeAt(node, type, pos, loc) {
- node.type = type;
- node.end = pos;
- if (this.options.locations)
- { node.loc.end = loc; }
- if (this.options.ranges)
- { node.range[1] = pos; }
- return node
- }
-
- pp$6.finishNode = function(node, type) {
- return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
- };
-
- // Finish node at given position
-
- pp$6.finishNodeAt = function(node, type, pos, loc) {
- return finishNodeAt.call(this, node, type, pos, loc)
- };
-
- // The algorithm used to determine whether a regexp can appear at a
-
- var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
- this.token = token;
- this.isExpr = !!isExpr;
- this.preserveSpace = !!preserveSpace;
- this.override = override;
- this.generator = !!generator;
- };
-
- var types$1 = {
- b_stat: new TokContext("{", false),
- b_expr: new TokContext("{", true),
- b_tmpl: new TokContext("${", false),
- p_stat: new TokContext("(", false),
- p_expr: new TokContext("(", true),
- q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
- f_stat: new TokContext("function", false),
- f_expr: new TokContext("function", true),
- f_expr_gen: new TokContext("function", true, false, null, true),
- f_gen: new TokContext("function", false, false, null, true)
- };
-
- var pp$7 = Parser.prototype;
-
- pp$7.initialContext = function() {
- return [types$1.b_stat]
- };
-
- pp$7.braceIsBlock = function(prevType) {
- var parent = this.curContext();
- if (parent === types$1.f_expr || parent === types$1.f_stat)
- { return true }
- if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
- { return !parent.isExpr }
-
- // The check for `tt.name && exprAllowed` detects whether we are
- // after a `yield` or `of` construct. See the `updateContext` for
- // `tt.name`.
- if (prevType === types._return || prevType === types.name && this.exprAllowed)
- { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
- if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
- { return true }
- if (prevType === types.braceL)
- { return parent === types$1.b_stat }
- if (prevType === types._var || prevType === types._const || prevType === types.name)
- { return false }
- return !this.exprAllowed
- };
-
- pp$7.inGeneratorContext = function() {
- for (var i = this.context.length - 1; i >= 1; i--) {
- var context = this.context[i];
- if (context.token === "function")
- { return context.generator }
- }
- return false
- };
-
- pp$7.updateContext = function(prevType) {
- var update, type = this.type;
- if (type.keyword && prevType === types.dot)
- { this.exprAllowed = false; }
- else if (update = type.updateContext)
- { update.call(this, prevType); }
- else
- { this.exprAllowed = type.beforeExpr; }
- };
-
- // Token-specific context update code
-
- types.parenR.updateContext = types.braceR.updateContext = function() {
- if (this.context.length === 1) {
- this.exprAllowed = true;
- return
- }
- var out = this.context.pop();
- if (out === types$1.b_stat && this.curContext().token === "function") {
- out = this.context.pop();
- }
- this.exprAllowed = !out.isExpr;
- };
-
- types.braceL.updateContext = function(prevType) {
- this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
- this.exprAllowed = true;
- };
-
- types.dollarBraceL.updateContext = function() {
- this.context.push(types$1.b_tmpl);
- this.exprAllowed = true;
- };
-
- types.parenL.updateContext = function(prevType) {
- var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
- this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
- this.exprAllowed = true;
- };
-
- types.incDec.updateContext = function() {
- // tokExprAllowed stays unchanged
- };
-
- types._function.updateContext = types._class.updateContext = function(prevType) {
- if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&
- !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
- !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
- { this.context.push(types$1.f_expr); }
- else
- { this.context.push(types$1.f_stat); }
- this.exprAllowed = false;
- };
-
- types.backQuote.updateContext = function() {
- if (this.curContext() === types$1.q_tmpl)
- { this.context.pop(); }
- else
- { this.context.push(types$1.q_tmpl); }
- this.exprAllowed = false;
- };
-
- types.star.updateContext = function(prevType) {
- if (prevType === types._function) {
- var index = this.context.length - 1;
- if (this.context[index] === types$1.f_expr)
- { this.context[index] = types$1.f_expr_gen; }
- else
- { this.context[index] = types$1.f_gen; }
- }
- this.exprAllowed = true;
- };
-
- types.name.updateContext = function(prevType) {
- var allowed = false;
- if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
- if (this.value === "of" && !this.exprAllowed ||
- this.value === "yield" && this.inGeneratorContext())
- { allowed = true; }
- }
- this.exprAllowed = allowed;
- };
-
- // This file contains Unicode properties extracted from the ECMAScript
- // specification. The lists are extracted like so:
- // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
-
- // #table-binary-unicode-properties
- var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
- var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
- var ecma11BinaryProperties = ecma10BinaryProperties;
- var unicodeBinaryProperties = {
- 9: ecma9BinaryProperties,
- 10: ecma10BinaryProperties,
- 11: ecma11BinaryProperties
- };
-
- // #table-unicode-general-category-values
- var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
-
- // #table-unicode-script-values
- var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
- var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
- var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
- var unicodeScriptValues = {
- 9: ecma9ScriptValues,
- 10: ecma10ScriptValues,
- 11: ecma11ScriptValues
- };
-
- var data = {};
- function buildUnicodeData(ecmaVersion) {
- var d = data[ecmaVersion] = {
- binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
- nonBinary: {
- General_Category: wordsRegexp(unicodeGeneralCategoryValues),
- Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
- }
- };
- d.nonBinary.Script_Extensions = d.nonBinary.Script;
-
- d.nonBinary.gc = d.nonBinary.General_Category;
- d.nonBinary.sc = d.nonBinary.Script;
- d.nonBinary.scx = d.nonBinary.Script_Extensions;
- }
- buildUnicodeData(9);
- buildUnicodeData(10);
- buildUnicodeData(11);
-
- var pp$8 = Parser.prototype;
-
- var RegExpValidationState = function RegExpValidationState(parser) {
- this.parser = parser;
- this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
- this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];
- this.source = "";
- this.flags = "";
- this.start = 0;
- this.switchU = false;
- this.switchN = false;
- this.pos = 0;
- this.lastIntValue = 0;
- this.lastStringValue = "";
- this.lastAssertionIsQuantifiable = false;
- this.numCapturingParens = 0;
- this.maxBackReference = 0;
- this.groupNames = [];
- this.backReferenceNames = [];
- };
-
- RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
- var unicode = flags.indexOf("u") !== -1;
- this.start = start | 0;
- this.source = pattern + "";
- this.flags = flags;
- this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
- this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
- };
-
- RegExpValidationState.prototype.raise = function raise (message) {
- this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
- };
-
- // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
- // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
- RegExpValidationState.prototype.at = function at (i, forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- var s = this.source;
- var l = s.length;
- if (i >= l) {
- return -1
- }
- var c = s.charCodeAt(i);
- if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
- return c
- }
- var next = s.charCodeAt(i + 1);
- return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
- };
-
- RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- var s = this.source;
- var l = s.length;
- if (i >= l) {
- return l
- }
- var c = s.charCodeAt(i), next;
- if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
- (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
- return i + 1
- }
- return i + 2
- };
-
- RegExpValidationState.prototype.current = function current (forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- return this.at(this.pos, forceU)
- };
-
- RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- return this.at(this.nextIndex(this.pos, forceU), forceU)
- };
-
- RegExpValidationState.prototype.advance = function advance (forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- this.pos = this.nextIndex(this.pos, forceU);
- };
-
- RegExpValidationState.prototype.eat = function eat (ch, forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- if (this.current(forceU) === ch) {
- this.advance(forceU);
- return true
- }
- return false
- };
-
- function codePointToString(ch) {
- if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
- ch -= 0x10000;
- return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
- }
-
- /**
- * Validate the flags part of a given RegExpLiteral.
- *
- * @param {RegExpValidationState} state The state to validate RegExp.
- * @returns {void}
- */
- pp$8.validateRegExpFlags = function(state) {
- var validFlags = state.validFlags;
- var flags = state.flags;
-
- for (var i = 0; i < flags.length; i++) {
- var flag = flags.charAt(i);
- if (validFlags.indexOf(flag) === -1) {
- this.raise(state.start, "Invalid regular expression flag");
- }
- if (flags.indexOf(flag, i + 1) > -1) {
- this.raise(state.start, "Duplicate regular expression flag");
- }
- }
- };
+ }
/**
- * Validate the pattern part of a given RegExpLiteral.
- *
- * @param {RegExpValidationState} state The state to validate RegExp.
- * @returns {void}
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
*/
- pp$8.validateRegExpPattern = function(state) {
- this.regexp_pattern(state);
-
- // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
- // parsing contains a |GroupName|, reparse with the goal symbol
- // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
- // exception if _P_ did not conform to the grammar, if any elements of _P_
- // were not matched by the parse, or if any Early Error conditions exist.
- if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
- state.switchN = true;
- this.regexp_pattern(state);
- }
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
- pp$8.regexp_pattern = function(state) {
- state.pos = 0;
- state.lastIntValue = 0;
- state.lastStringValue = "";
- state.lastAssertionIsQuantifiable = false;
- state.numCapturingParens = 0;
- state.maxBackReference = 0;
- state.groupNames.length = 0;
- state.backReferenceNames.length = 0;
-
- this.regexp_disjunction(state);
-
- if (state.pos !== state.source.length) {
- // Make the same messages as V8.
- if (state.eat(0x29 /* ) */)) {
- state.raise("Unmatched ')'");
- }
- if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
- state.raise("Lone quantifier brackets");
- }
- }
- if (state.maxBackReference > state.numCapturingParens) {
- state.raise("Invalid escape");
- }
- for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
- var name = list[i];
-
- if (state.groupNames.indexOf(name) === -1) {
- state.raise("Invalid named capture referenced");
- }
- }
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
- pp$8.regexp_disjunction = function(state) {
- this.regexp_alternative(state);
- while (state.eat(0x7C /* | */)) {
- this.regexp_alternative(state);
- }
-
- // Make the same message as V8.
- if (this.regexp_eatQuantifier(state, true)) {
- state.raise("Nothing to repeat");
- }
- if (state.eat(0x7B /* { */)) {
- state.raise("Lone quantifier brackets");
- }
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
- pp$8.regexp_alternative = function(state) {
- while (state.pos < state.source.length && this.regexp_eatTerm(state))
- { }
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
- pp$8.regexp_eatTerm = function(state) {
- if (this.regexp_eatAssertion(state)) {
- // Handle `QuantifiableAssertion Quantifier` alternative.
- // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
- // is a QuantifiableAssertion.
- if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
- // Make the same message as V8.
- if (state.switchU) {
- state.raise("Invalid quantifier");
- }
- }
- return true
- }
-
- if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
- this.regexp_eatQuantifier(state);
- return true
- }
-
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
- pp$8.regexp_eatAssertion = function(state) {
- var start = state.pos;
- state.lastAssertionIsQuantifiable = false;
-
- // ^, $
- if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
- return true
- }
-
- // \b \B
- if (state.eat(0x5C /* \ */)) {
- if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
- return true
- }
- state.pos = start;
- }
-
- // Lookahead / Lookbehind
- if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
- var lookbehind = false;
- if (this.options.ecmaVersion >= 9) {
- lookbehind = state.eat(0x3C /* < */);
- }
- if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
- this.regexp_disjunction(state);
- if (!state.eat(0x29 /* ) */)) {
- state.raise("Unterminated group");
- }
- state.lastAssertionIsQuantifiable = !lookbehind;
- return true
- }
- }
-
- state.pos = start;
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
- pp$8.regexp_eatQuantifier = function(state, noError) {
- if ( noError === void 0 ) noError = false;
-
- if (this.regexp_eatQuantifierPrefix(state, noError)) {
- state.eat(0x3F /* ? */);
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
- pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
- return (
- state.eat(0x2A /* * */) ||
- state.eat(0x2B /* + */) ||
- state.eat(0x3F /* ? */) ||
- this.regexp_eatBracedQuantifier(state, noError)
- )
- };
- pp$8.regexp_eatBracedQuantifier = function(state, noError) {
- var start = state.pos;
- if (state.eat(0x7B /* { */)) {
- var min = 0, max = -1;
- if (this.regexp_eatDecimalDigits(state)) {
- min = state.lastIntValue;
- if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
- max = state.lastIntValue;
- }
- if (state.eat(0x7D /* } */)) {
- // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
- if (max !== -1 && max < min && !noError) {
- state.raise("numbers out of order in {} quantifier");
- }
- return true
- }
- }
- if (state.switchU && !noError) {
- state.raise("Incomplete quantifier");
- }
- state.pos = start;
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
- pp$8.regexp_eatAtom = function(state) {
- return (
- this.regexp_eatPatternCharacters(state) ||
- state.eat(0x2E /* . */) ||
- this.regexp_eatReverseSolidusAtomEscape(state) ||
- this.regexp_eatCharacterClass(state) ||
- this.regexp_eatUncapturingGroup(state) ||
- this.regexp_eatCapturingGroup(state)
- )
- };
- pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
- var start = state.pos;
- if (state.eat(0x5C /* \ */)) {
- if (this.regexp_eatAtomEscape(state)) {
- return true
- }
- state.pos = start;
- }
- return false
- };
- pp$8.regexp_eatUncapturingGroup = function(state) {
- var start = state.pos;
- if (state.eat(0x28 /* ( */)) {
- if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
- this.regexp_disjunction(state);
- if (state.eat(0x29 /* ) */)) {
- return true
- }
- state.raise("Unterminated group");
- }
- state.pos = start;
- }
- return false
- };
- pp$8.regexp_eatCapturingGroup = function(state) {
- if (state.eat(0x28 /* ( */)) {
- if (this.options.ecmaVersion >= 9) {
- this.regexp_groupSpecifier(state);
- } else if (state.current() === 0x3F /* ? */) {
- state.raise("Invalid group");
- }
- this.regexp_disjunction(state);
- if (state.eat(0x29 /* ) */)) {
- state.numCapturingParens += 1;
- return true
- }
- state.raise("Unterminated group");
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
- pp$8.regexp_eatExtendedAtom = function(state) {
- return (
- state.eat(0x2E /* . */) ||
- this.regexp_eatReverseSolidusAtomEscape(state) ||
- this.regexp_eatCharacterClass(state) ||
- this.regexp_eatUncapturingGroup(state) ||
- this.regexp_eatCapturingGroup(state) ||
- this.regexp_eatInvalidBracedQuantifier(state) ||
- this.regexp_eatExtendedPatternCharacter(state)
- )
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
- pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
- if (this.regexp_eatBracedQuantifier(state, true)) {
- state.raise("Nothing to repeat");
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
- pp$8.regexp_eatSyntaxCharacter = function(state) {
- var ch = state.current();
- if (isSyntaxCharacter(ch)) {
- state.lastIntValue = ch;
- state.advance();
- return true
- }
- return false
- };
- function isSyntaxCharacter(ch) {
- return (
- ch === 0x24 /* $ */ ||
- ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
- ch === 0x2E /* . */ ||
- ch === 0x3F /* ? */ ||
- ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
- ch >= 0x7B /* { */ && ch <= 0x7D /* } */
- )
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
- // But eat eager.
- pp$8.regexp_eatPatternCharacters = function(state) {
- var start = state.pos;
- var ch = 0;
- while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
- state.advance();
- }
- return state.pos !== start
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
- pp$8.regexp_eatExtendedPatternCharacter = function(state) {
- var ch = state.current();
- if (
- ch !== -1 &&
- ch !== 0x24 /* $ */ &&
- !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
- ch !== 0x2E /* . */ &&
- ch !== 0x3F /* ? */ &&
- ch !== 0x5B /* [ */ &&
- ch !== 0x5E /* ^ */ &&
- ch !== 0x7C /* | */
- ) {
- state.advance();
- return true
- }
- return false
- };
-
- // GroupSpecifier ::
- // [empty]
- // `?` GroupName
- pp$8.regexp_groupSpecifier = function(state) {
- if (state.eat(0x3F /* ? */)) {
- if (this.regexp_eatGroupName(state)) {
- if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
- state.raise("Duplicate capture group name");
- }
- state.groupNames.push(state.lastStringValue);
- return
- }
- state.raise("Invalid group");
- }
- };
-
- // GroupName ::
- // `<` RegExpIdentifierName `>`
- // Note: this updates `state.lastStringValue` property with the eaten name.
- pp$8.regexp_eatGroupName = function(state) {
- state.lastStringValue = "";
- if (state.eat(0x3C /* < */)) {
- if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
- return true
- }
- state.raise("Invalid capture group name");
- }
- return false
- };
-
- // RegExpIdentifierName ::
- // RegExpIdentifierStart
- // RegExpIdentifierName RegExpIdentifierPart
- // Note: this updates `state.lastStringValue` property with the eaten name.
- pp$8.regexp_eatRegExpIdentifierName = function(state) {
- state.lastStringValue = "";
- if (this.regexp_eatRegExpIdentifierStart(state)) {
- state.lastStringValue += codePointToString(state.lastIntValue);
- while (this.regexp_eatRegExpIdentifierPart(state)) {
- state.lastStringValue += codePointToString(state.lastIntValue);
- }
- return true
- }
- return false
- };
-
- // RegExpIdentifierStart ::
- // UnicodeIDStart
- // `$`
- // `_`
- // `\` RegExpUnicodeEscapeSequence[+U]
- pp$8.regexp_eatRegExpIdentifierStart = function(state) {
- var start = state.pos;
- var forceU = this.options.ecmaVersion >= 11;
- var ch = state.current(forceU);
- state.advance(forceU);
-
- if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
- ch = state.lastIntValue;
- }
- if (isRegExpIdentifierStart(ch)) {
- state.lastIntValue = ch;
- return true
- }
-
- state.pos = start;
- return false
- };
- function isRegExpIdentifierStart(ch) {
- return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
- }
-
- // RegExpIdentifierPart ::
- // UnicodeIDContinue
- // `$`
- // `_`
- // `\` RegExpUnicodeEscapeSequence[+U]
- //
- //
- pp$8.regexp_eatRegExpIdentifierPart = function(state) {
- var start = state.pos;
- var forceU = this.options.ecmaVersion >= 11;
- var ch = state.current(forceU);
- state.advance(forceU);
-
- if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
- ch = state.lastIntValue;
- }
- if (isRegExpIdentifierPart(ch)) {
- state.lastIntValue = ch;
- return true
- }
-
- state.pos = start;
- return false
- };
- function isRegExpIdentifierPart(ch) {
- return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
- pp$8.regexp_eatAtomEscape = function(state) {
- if (
- this.regexp_eatBackReference(state) ||
- this.regexp_eatCharacterClassEscape(state) ||
- this.regexp_eatCharacterEscape(state) ||
- (state.switchN && this.regexp_eatKGroupName(state))
- ) {
- return true
- }
- if (state.switchU) {
- // Make the same message as V8.
- if (state.current() === 0x63 /* c */) {
- state.raise("Invalid unicode escape");
- }
- state.raise("Invalid escape");
- }
- return false
- };
- pp$8.regexp_eatBackReference = function(state) {
- var start = state.pos;
- if (this.regexp_eatDecimalEscape(state)) {
- var n = state.lastIntValue;
- if (state.switchU) {
- // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
- if (n > state.maxBackReference) {
- state.maxBackReference = n;
- }
- return true
- }
- if (n <= state.numCapturingParens) {
- return true
- }
- state.pos = start;
- }
- return false
- };
- pp$8.regexp_eatKGroupName = function(state) {
- if (state.eat(0x6B /* k */)) {
- if (this.regexp_eatGroupName(state)) {
- state.backReferenceNames.push(state.lastStringValue);
- return true
- }
- state.raise("Invalid named reference");
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
- pp$8.regexp_eatCharacterEscape = function(state) {
- return (
- this.regexp_eatControlEscape(state) ||
- this.regexp_eatCControlLetter(state) ||
- this.regexp_eatZero(state) ||
- this.regexp_eatHexEscapeSequence(state) ||
- this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
- (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
- this.regexp_eatIdentityEscape(state)
- )
- };
- pp$8.regexp_eatCControlLetter = function(state) {
- var start = state.pos;
- if (state.eat(0x63 /* c */)) {
- if (this.regexp_eatControlLetter(state)) {
- return true
- }
- state.pos = start;
- }
- return false
- };
- pp$8.regexp_eatZero = function(state) {
- if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
- state.lastIntValue = 0;
- state.advance();
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
- pp$8.regexp_eatControlEscape = function(state) {
- var ch = state.current();
- if (ch === 0x74 /* t */) {
- state.lastIntValue = 0x09; /* \t */
- state.advance();
- return true
- }
- if (ch === 0x6E /* n */) {
- state.lastIntValue = 0x0A; /* \n */
- state.advance();
- return true
- }
- if (ch === 0x76 /* v */) {
- state.lastIntValue = 0x0B; /* \v */
- state.advance();
- return true
- }
- if (ch === 0x66 /* f */) {
- state.lastIntValue = 0x0C; /* \f */
- state.advance();
- return true
- }
- if (ch === 0x72 /* r */) {
- state.lastIntValue = 0x0D; /* \r */
- state.advance();
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
- pp$8.regexp_eatControlLetter = function(state) {
- var ch = state.current();
- if (isControlLetter(ch)) {
- state.lastIntValue = ch % 0x20;
- state.advance();
- return true
- }
- return false
- };
- function isControlLetter(ch) {
- return (
- (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
- (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
- )
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
- pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
- if ( forceU === void 0 ) forceU = false;
-
- var start = state.pos;
- var switchU = forceU || state.switchU;
-
- if (state.eat(0x75 /* u */)) {
- if (this.regexp_eatFixedHexDigits(state, 4)) {
- var lead = state.lastIntValue;
- if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
- var leadSurrogateEnd = state.pos;
- if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
- var trail = state.lastIntValue;
- if (trail >= 0xDC00 && trail <= 0xDFFF) {
- state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
- return true
- }
- }
- state.pos = leadSurrogateEnd;
- state.lastIntValue = lead;
- }
- return true
- }
- if (
- switchU &&
- state.eat(0x7B /* { */) &&
- this.regexp_eatHexDigits(state) &&
- state.eat(0x7D /* } */) &&
- isValidUnicode(state.lastIntValue)
- ) {
- return true
- }
- if (switchU) {
- state.raise("Invalid unicode escape");
- }
- state.pos = start;
- }
-
- return false
- };
- function isValidUnicode(ch) {
- return ch >= 0 && ch <= 0x10FFFF
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
- pp$8.regexp_eatIdentityEscape = function(state) {
- if (state.switchU) {
- if (this.regexp_eatSyntaxCharacter(state)) {
- return true
- }
- if (state.eat(0x2F /* / */)) {
- state.lastIntValue = 0x2F; /* / */
- return true
- }
- return false
- }
-
- var ch = state.current();
- if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
- state.lastIntValue = ch;
- state.advance();
- return true
- }
-
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
- pp$8.regexp_eatDecimalEscape = function(state) {
- state.lastIntValue = 0;
- var ch = state.current();
- if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
- do {
- state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
- state.advance();
- } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
- pp$8.regexp_eatCharacterClassEscape = function(state) {
- var ch = state.current();
-
- if (isCharacterClassEscape(ch)) {
- state.lastIntValue = -1;
- state.advance();
- return true
- }
-
- if (
- state.switchU &&
- this.options.ecmaVersion >= 9 &&
- (ch === 0x50 /* P */ || ch === 0x70 /* p */)
- ) {
- state.lastIntValue = -1;
- state.advance();
- if (
- state.eat(0x7B /* { */) &&
- this.regexp_eatUnicodePropertyValueExpression(state) &&
- state.eat(0x7D /* } */)
- ) {
- return true
- }
- state.raise("Invalid property name");
- }
-
- return false
- };
- function isCharacterClassEscape(ch) {
- return (
- ch === 0x64 /* d */ ||
- ch === 0x44 /* D */ ||
- ch === 0x73 /* s */ ||
- ch === 0x53 /* S */ ||
- ch === 0x77 /* w */ ||
- ch === 0x57 /* W */
- )
- }
-
- // UnicodePropertyValueExpression ::
- // UnicodePropertyName `=` UnicodePropertyValue
- // LoneUnicodePropertyNameOrValue
- pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
- var start = state.pos;
-
- // UnicodePropertyName `=` UnicodePropertyValue
- if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
- var name = state.lastStringValue;
- if (this.regexp_eatUnicodePropertyValue(state)) {
- var value = state.lastStringValue;
- this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
- return true
- }
- }
- state.pos = start;
-
- // LoneUnicodePropertyNameOrValue
- if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
- var nameOrValue = state.lastStringValue;
- this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
- return true
- }
- return false
- };
- pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
- if (!has(state.unicodeProperties.nonBinary, name))
- { state.raise("Invalid property name"); }
- if (!state.unicodeProperties.nonBinary[name].test(value))
- { state.raise("Invalid property value"); }
- };
- pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
- if (!state.unicodeProperties.binary.test(nameOrValue))
- { state.raise("Invalid property name"); }
- };
-
- // UnicodePropertyName ::
- // UnicodePropertyNameCharacters
- pp$8.regexp_eatUnicodePropertyName = function(state) {
- var ch = 0;
- state.lastStringValue = "";
- while (isUnicodePropertyNameCharacter(ch = state.current())) {
- state.lastStringValue += codePointToString(ch);
- state.advance();
- }
- return state.lastStringValue !== ""
- };
- function isUnicodePropertyNameCharacter(ch) {
- return isControlLetter(ch) || ch === 0x5F /* _ */
- }
-
- // UnicodePropertyValue ::
- // UnicodePropertyValueCharacters
- pp$8.regexp_eatUnicodePropertyValue = function(state) {
- var ch = 0;
- state.lastStringValue = "";
- while (isUnicodePropertyValueCharacter(ch = state.current())) {
- state.lastStringValue += codePointToString(ch);
- state.advance();
- }
- return state.lastStringValue !== ""
- };
- function isUnicodePropertyValueCharacter(ch) {
- return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
- }
-
- // LoneUnicodePropertyNameOrValue ::
- // UnicodePropertyValueCharacters
- pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
- return this.regexp_eatUnicodePropertyValue(state)
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
- pp$8.regexp_eatCharacterClass = function(state) {
- if (state.eat(0x5B /* [ */)) {
- state.eat(0x5E /* ^ */);
- this.regexp_classRanges(state);
- if (state.eat(0x5D /* ] */)) {
- return true
- }
- // Unreachable since it threw "unterminated regular expression" error before.
- state.raise("Unterminated character class");
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
- // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
- // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
- pp$8.regexp_classRanges = function(state) {
- while (this.regexp_eatClassAtom(state)) {
- var left = state.lastIntValue;
- if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
- var right = state.lastIntValue;
- if (state.switchU && (left === -1 || right === -1)) {
- state.raise("Invalid character class");
- }
- if (left !== -1 && right !== -1 && left > right) {
- state.raise("Range out of order in character class");
- }
- }
- }
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
- // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
- pp$8.regexp_eatClassAtom = function(state) {
- var start = state.pos;
-
- if (state.eat(0x5C /* \ */)) {
- if (this.regexp_eatClassEscape(state)) {
- return true
- }
- if (state.switchU) {
- // Make the same message as V8.
- var ch$1 = state.current();
- if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
- state.raise("Invalid class escape");
- }
- state.raise("Invalid escape");
- }
- state.pos = start;
- }
-
- var ch = state.current();
- if (ch !== 0x5D /* ] */) {
- state.lastIntValue = ch;
- state.advance();
- return true
- }
-
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
- pp$8.regexp_eatClassEscape = function(state) {
- var start = state.pos;
-
- if (state.eat(0x62 /* b */)) {
- state.lastIntValue = 0x08; /* */
- return true
- }
-
- if (state.switchU && state.eat(0x2D /* - */)) {
- state.lastIntValue = 0x2D; /* - */
- return true
- }
-
- if (!state.switchU && state.eat(0x63 /* c */)) {
- if (this.regexp_eatClassControlLetter(state)) {
- return true
- }
- state.pos = start;
- }
-
- return (
- this.regexp_eatCharacterClassEscape(state) ||
- this.regexp_eatCharacterEscape(state)
- )
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
- pp$8.regexp_eatClassControlLetter = function(state) {
- var ch = state.current();
- if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
- state.lastIntValue = ch % 0x20;
- state.advance();
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
- pp$8.regexp_eatHexEscapeSequence = function(state) {
- var start = state.pos;
- if (state.eat(0x78 /* x */)) {
- if (this.regexp_eatFixedHexDigits(state, 2)) {
- return true
- }
- if (state.switchU) {
- state.raise("Invalid escape");
- }
- state.pos = start;
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
- pp$8.regexp_eatDecimalDigits = function(state) {
- var start = state.pos;
- var ch = 0;
- state.lastIntValue = 0;
- while (isDecimalDigit(ch = state.current())) {
- state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
- state.advance();
- }
- return state.pos !== start
- };
- function isDecimalDigit(ch) {
- return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
- pp$8.regexp_eatHexDigits = function(state) {
- var start = state.pos;
- var ch = 0;
- state.lastIntValue = 0;
- while (isHexDigit(ch = state.current())) {
- state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
- state.advance();
- }
- return state.pos !== start
- };
- function isHexDigit(ch) {
- return (
- (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
- (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
- (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
- )
- }
- function hexToInt(ch) {
- if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
- return 10 + (ch - 0x41 /* A */)
- }
- if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
- return 10 + (ch - 0x61 /* a */)
- }
- return ch - 0x30 /* 0 */
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
- // Allows only 0-377(octal) i.e. 0-255(decimal).
- pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
- if (this.regexp_eatOctalDigit(state)) {
- var n1 = state.lastIntValue;
- if (this.regexp_eatOctalDigit(state)) {
- var n2 = state.lastIntValue;
- if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
- state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
- } else {
- state.lastIntValue = n1 * 8 + n2;
- }
- } else {
- state.lastIntValue = n1;
- }
- return true
- }
- return false
- };
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
- pp$8.regexp_eatOctalDigit = function(state) {
- var ch = state.current();
- if (isOctalDigit(ch)) {
- state.lastIntValue = ch - 0x30; /* 0 */
- state.advance();
- return true
- }
- state.lastIntValue = 0;
- return false
- };
- function isOctalDigit(ch) {
- return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
- }
-
- // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
- // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
- // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
- pp$8.regexp_eatFixedHexDigits = function(state, length) {
- var start = state.pos;
- state.lastIntValue = 0;
- for (var i = 0; i < length; ++i) {
- var ch = state.current();
- if (!isHexDigit(ch)) {
- state.pos = start;
- return false
- }
- state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
- state.advance();
- }
- return true
- };
-
- // Object type used to represent tokens. Note that normally, tokens
- // simply exist as properties on the parser object. This is only
- // used for the onToken callback and the external tokenizer.
-
- var Token = function Token(p) {
- this.type = p.type;
- this.value = p.value;
- this.start = p.start;
- this.end = p.end;
- if (p.options.locations)
- { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
- if (p.options.ranges)
- { this.range = [p.start, p.end]; }
- };
-
- // ## Tokenizer
-
- var pp$9 = Parser.prototype;
-
- // Move to the next token
-
- pp$9.next = function(ignoreEscapeSequenceInKeyword) {
- if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
- { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
- if (this.options.onToken)
- { this.options.onToken(new Token(this)); }
-
- this.lastTokEnd = this.end;
- this.lastTokStart = this.start;
- this.lastTokEndLoc = this.endLoc;
- this.lastTokStartLoc = this.startLoc;
- this.nextToken();
- };
-
- pp$9.getToken = function() {
- this.next();
- return new Token(this)
- };
-
- // If we're in an ES6 environment, make parsers iterable
- if (typeof Symbol !== "undefined")
- { pp$9[Symbol.iterator] = function() {
- var this$1 = this;
-
- return {
- next: function () {
- var token = this$1.getToken();
- return {
- done: token.type === types.eof,
- value: token
- }
- }
- }
- }; }
-
- // Toggle strict mode. Re-reads the next number or string to please
- // pedantic tests (`"use strict"; 010;` should fail).
-
- pp$9.curContext = function() {
- return this.context[this.context.length - 1]
- };
-
- // Read a single token, updating the parser object's token-related
- // properties.
-
- pp$9.nextToken = function() {
- var curContext = this.curContext();
- if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
-
- this.start = this.pos;
- if (this.options.locations) { this.startLoc = this.curPosition(); }
- if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
-
- if (curContext.override) { return curContext.override(this) }
- else { this.readToken(this.fullCharCodeAtPos()); }
- };
-
- pp$9.readToken = function(code) {
- // Identifier or keyword. '\uXXXX' sequences are allowed in
- // identifiers, so '\' also dispatches to that.
- if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
- { return this.readWord() }
-
- return this.getTokenFromCode(code)
- };
-
- pp$9.fullCharCodeAtPos = function() {
- var code = this.input.charCodeAt(this.pos);
- if (code <= 0xd7ff || code >= 0xe000) { return code }
- var next = this.input.charCodeAt(this.pos + 1);
- return (code << 10) + next - 0x35fdc00
- };
-
- pp$9.skipBlockComment = function() {
- var startLoc = this.options.onComment && this.curPosition();
- var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
- if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
- this.pos = end + 2;
- if (this.options.locations) {
- lineBreakG.lastIndex = start;
- var match;
- while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
- ++this.curLine;
- this.lineStart = match.index + match[0].length;
- }
- }
- if (this.options.onComment)
- { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
- startLoc, this.curPosition()); }
- };
-
- pp$9.skipLineComment = function(startSkip) {
- var start = this.pos;
- var startLoc = this.options.onComment && this.curPosition();
- var ch = this.input.charCodeAt(this.pos += startSkip);
- while (this.pos < this.input.length && !isNewLine(ch)) {
- ch = this.input.charCodeAt(++this.pos);
- }
- if (this.options.onComment)
- { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
- startLoc, this.curPosition()); }
- };
-
- // Called at the start of the parse and after every token. Skips
- // whitespace and comments, and.
-
- pp$9.skipSpace = function() {
- loop: while (this.pos < this.input.length) {
- var ch = this.input.charCodeAt(this.pos);
- switch (ch) {
- case 32: case 160: // ' '
- ++this.pos;
- break
- case 13:
- if (this.input.charCodeAt(this.pos + 1) === 10) {
- ++this.pos;
- }
- case 10: case 8232: case 8233:
- ++this.pos;
- if (this.options.locations) {
- ++this.curLine;
- this.lineStart = this.pos;
- }
- break
- case 47: // '/'
- switch (this.input.charCodeAt(this.pos + 1)) {
- case 42: // '*'
- this.skipBlockComment();
- break
- case 47:
- this.skipLineComment(2);
- break
- default:
- break loop
- }
- break
- default:
- if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
- ++this.pos;
- } else {
- break loop
- }
- }
- }
- };
-
- // Called at the end of every token. Sets `end`, `val`, and
- // maintains `context` and `exprAllowed`, and skips the space after
- // the token, so that the next one's `start` will point at the
- // right position.
-
- pp$9.finishToken = function(type, val) {
- this.end = this.pos;
- if (this.options.locations) { this.endLoc = this.curPosition(); }
- var prevType = this.type;
- this.type = type;
- this.value = val;
-
- this.updateContext(prevType);
- };
-
- // ### Token reading
-
- // This is the function that is called to fetch the next token. It
- // is somewhat obscure, because it works in character codes rather
- // than characters, and because operator parsing has been inlined
- // into it.
- //
- // All in the name of speed.
- //
- pp$9.readToken_dot = function() {
- var next = this.input.charCodeAt(this.pos + 1);
- if (next >= 48 && next <= 57) { return this.readNumber(true) }
- var next2 = this.input.charCodeAt(this.pos + 2);
- if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
- this.pos += 3;
- return this.finishToken(types.ellipsis)
- } else {
- ++this.pos;
- return this.finishToken(types.dot)
- }
- };
-
- pp$9.readToken_slash = function() { // '/'
- var next = this.input.charCodeAt(this.pos + 1);
- if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
- if (next === 61) { return this.finishOp(types.assign, 2) }
- return this.finishOp(types.slash, 1)
- };
-
- pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
- var next = this.input.charCodeAt(this.pos + 1);
- var size = 1;
- var tokentype = code === 42 ? types.star : types.modulo;
-
- // exponentiation operator ** and **=
- if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
- ++size;
- tokentype = types.starstar;
- next = this.input.charCodeAt(this.pos + 2);
- }
-
- if (next === 61) { return this.finishOp(types.assign, size + 1) }
- return this.finishOp(tokentype, size)
- };
-
- pp$9.readToken_pipe_amp = function(code) { // '|&'
- var next = this.input.charCodeAt(this.pos + 1);
- if (next === code) {
- if (this.options.ecmaVersion >= 12) {
- var next2 = this.input.charCodeAt(this.pos + 2);
- if (next2 === 61) { return this.finishOp(types.assign, 3) }
- }
- return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
- }
- if (next === 61) { return this.finishOp(types.assign, 2) }
- return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
- };
-
- pp$9.readToken_caret = function() { // '^'
- var next = this.input.charCodeAt(this.pos + 1);
- if (next === 61) { return this.finishOp(types.assign, 2) }
- return this.finishOp(types.bitwiseXOR, 1)
- };
-
- pp$9.readToken_plus_min = function(code) { // '+-'
- var next = this.input.charCodeAt(this.pos + 1);
- if (next === code) {
- if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
- (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
- // A `-->` line comment
- this.skipLineComment(3);
- this.skipSpace();
- return this.nextToken()
- }
- return this.finishOp(types.incDec, 2)
- }
- if (next === 61) { return this.finishOp(types.assign, 2) }
- return this.finishOp(types.plusMin, 1)
- };
-
- pp$9.readToken_lt_gt = function(code) { // '<>'
- var next = this.input.charCodeAt(this.pos + 1);
- var size = 1;
- if (next === code) {
- size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
- if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
- return this.finishOp(types.bitShift, size)
- }
- if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
- this.input.charCodeAt(this.pos + 3) === 45) {
- // ` regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this)
-
- this.debug(this.pattern, set)
-
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- })
-
- this.debug(this.pattern, set)
-
- this.set = set
-}
-
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
- var pattern = this.pattern
- var negate = false
- var options = this.options
- var negateOffset = 0
-
- if (options.nonegate) return
-
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate
- negateOffset++
- }
-
- if (negateOffset) this.pattern = pattern.substr(negateOffset)
- this.negate = negate
-}
-
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
-}
-
-Minimatch.prototype.braceExpand = braceExpand
-
-function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options
- } else {
- options = {}
- }
- }
-
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern
-
- assertValidPattern(pattern)
-
- // Thanks to Yeting Li for
- // improving this regexp to avoid a ReDOS vulnerability.
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
- // shortcut. no need to expand.
- return [pattern]
- }
-
- return expand(pattern)
-}
-
-var MAX_PATTERN_LENGTH = 1024 * 64
-var assertValidPattern = function (pattern) {
- if (typeof pattern !== 'string') {
- throw new TypeError('invalid pattern')
- }
-
- if (pattern.length > MAX_PATTERN_LENGTH) {
- throw new TypeError('pattern is too long')
- }
-}
-
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
- assertValidPattern(pattern)
-
- var options = this.options
-
- // shortcuts
- if (pattern === '**') {
- if (!options.noglobstar)
- return GLOBSTAR
- else
- pattern = '*'
- }
- if (pattern === '') return ''
-
- var re = ''
- var hasMagic = !!options.nocase
- var escaping = false
- // ? => one single character
- var patternListStack = []
- var negativeLists = []
- var stateChar
- var inClass = false
- var reClassStart = -1
- var classStart = -1
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
- var self = this
-
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
- }
- self.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
- }
- }
-
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
-
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c
- escaping = false
- continue
- }
-
- switch (c) {
- /* istanbul ignore next */
- case '/': {
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
- }
-
- case '\\':
- clearStateChar()
- escaping = true
- continue
-
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
-
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
- }
-
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
-
- case '(':
- if (inClass) {
- re += '('
- continue
- }
-
- if (!stateChar) {
- re += '\\('
- continue
- }
-
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
-
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
-
- clearStateChar()
- hasMagic = true
- var pl = patternListStack.pop()
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- re += pl.close
- if (pl.type === '!') {
- negativeLists.push(pl)
- }
- pl.reEnd = re.length
- continue
-
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|'
- escaping = false
- continue
- }
-
- clearStateChar()
- re += '|'
- continue
-
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
-
- if (inClass) {
- re += '\\' + c
- continue
- }
-
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
-
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- escaping = false
- continue
- }
-
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
- }
-
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
-
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
-
- if (escaping) {
- // no need
- escaping = false
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\'
- }
-
- re += c
-
- } // switch
- } // for
-
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
-
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length)
- this.debug('setting tail', re, pl)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
-
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
-
- this.debug('tail=%j\n %s', tail, tail, pl, re)
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
-
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
- }
-
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
-
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false
- switch (re.charAt(0)) {
- case '[': case '.': case '(': addPatternStart = true
- }
-
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n]
-
- var nlBefore = re.slice(0, nl.reStart)
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
- var nlAfter = re.slice(nl.reEnd)
-
- nlLast += nlAfter
-
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1
- var cleanAfter = nlAfter
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
- }
- nlAfter = cleanAfter
-
- var dollar = ''
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$'
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
- re = newRe
- }
-
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
- }
-
- if (addPatternStart) {
- re = patternStart + re
- }
-
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
-
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
-
- var flags = options.nocase ? 'i' : ''
- try {
- var regExp = new RegExp('^' + re + '$', flags)
- } catch (er) /* istanbul ignore next - should be impossible */ {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
- }
-
- regExp._glob = pattern
- regExp._src = re
-
- return regExp
-}
-
-minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe()
-}
-
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
-
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set
-
- if (!set.length) {
- this.regexp = false
- return this.regexp
- }
- var options = this.options
-
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- var flags = options.nocase ? 'i' : ''
-
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|')
-
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
-
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
-
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) /* istanbul ignore next - should be impossible */ {
- this.regexp = false
- }
- return this.regexp
-}
-
-minimatch.match = function (list, pattern, options) {
- options = options || {}
- var mm = new Minimatch(pattern, options)
- list = list.filter(function (f) {
- return mm.match(f)
- })
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
- }
- return list
-}
-
-Minimatch.prototype.match = function match (f, partial) {
- if (typeof partial === 'undefined') partial = this.partial
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
-
- if (f === '/' && partial) return true
-
- var options = this.options
-
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
- }
-
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
-
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
-
- var set = this.set
- this.debug(this.pattern, 'set', set)
-
- // Find the basename of the path by looking for the last non-empty segment
- var filename
- var i
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
- }
-
- for (i = 0; i < set.length; i++) {
- var pattern = set[i]
- var file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
- }
- var hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
- }
- }
-
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
-}
-
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options
-
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
-
- this.debug('matchOne', file.length, pattern.length)
-
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
-
- this.debug(pattern, p, f)
-
- // should be impossible.
- // some invalid regexp stuff in the set.
- /* istanbul ignore if */
- if (p === false) return false
-
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
-
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
- }
-
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
-
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
-
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
- }
-
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
- }
- }
-
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- /* istanbul ignore if */
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
- }
- return false
- }
-
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- hit = f === p
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
- }
-
- if (!hit) return false
- }
-
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
-
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else /* istanbul ignore else */ if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- return (fi === fl - 1) && (file[fi] === '')
- }
-
- // should be unreachable.
- /* istanbul ignore next */
- throw new Error('wtf?')
-}
-
-// replace stuff like \* with *
-function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
-}
-
-function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
-}
-
-
-/***/ }),
-
-/***/ 80467:
-/***/ ((module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
-
-var Stream = _interopDefault(__nccwpck_require__(12781));
-var http = _interopDefault(__nccwpck_require__(13685));
-var Url = _interopDefault(__nccwpck_require__(57310));
-var whatwgUrl = _interopDefault(__nccwpck_require__(28665));
-var https = _interopDefault(__nccwpck_require__(95687));
-var zlib = _interopDefault(__nccwpck_require__(59796));
-
-// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
-
-// fix for "Readable" isn't a named export issue
-const Readable = Stream.Readable;
-
-const BUFFER = Symbol('buffer');
-const TYPE = Symbol('type');
-
-class Blob {
- constructor() {
- this[TYPE] = '';
-
- const blobParts = arguments[0];
- const options = arguments[1];
-
- const buffers = [];
- let size = 0;
-
- if (blobParts) {
- const a = blobParts;
- const length = Number(a.length);
- for (let i = 0; i < length; i++) {
- const element = a[i];
- let buffer;
- if (element instanceof Buffer) {
- buffer = element;
- } else if (ArrayBuffer.isView(element)) {
- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
- } else if (element instanceof ArrayBuffer) {
- buffer = Buffer.from(element);
- } else if (element instanceof Blob) {
- buffer = element[BUFFER];
- } else {
- buffer = Buffer.from(typeof element === 'string' ? element : String(element));
- }
- size += buffer.length;
- buffers.push(buffer);
- }
- }
-
- this[BUFFER] = Buffer.concat(buffers);
-
- let type = options && options.type !== undefined && String(options.type).toLowerCase();
- if (type && !/[^\u0020-\u007E]/.test(type)) {
- this[TYPE] = type;
- }
- }
- get size() {
- return this[BUFFER].length;
- }
- get type() {
- return this[TYPE];
- }
- text() {
- return Promise.resolve(this[BUFFER].toString());
- }
- arrayBuffer() {
- const buf = this[BUFFER];
- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- return Promise.resolve(ab);
- }
- stream() {
- const readable = new Readable();
- readable._read = function () {};
- readable.push(this[BUFFER]);
- readable.push(null);
- return readable;
- }
- toString() {
- return '[object Blob]';
- }
- slice() {
- const size = this.size;
-
- const start = arguments[0];
- const end = arguments[1];
- let relativeStart, relativeEnd;
- if (start === undefined) {
- relativeStart = 0;
- } else if (start < 0) {
- relativeStart = Math.max(size + start, 0);
- } else {
- relativeStart = Math.min(start, size);
- }
- if (end === undefined) {
- relativeEnd = size;
- } else if (end < 0) {
- relativeEnd = Math.max(size + end, 0);
- } else {
- relativeEnd = Math.min(end, size);
- }
- const span = Math.max(relativeEnd - relativeStart, 0);
-
- const buffer = this[BUFFER];
- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
- const blob = new Blob([], { type: arguments[2] });
- blob[BUFFER] = slicedBuffer;
- return blob;
- }
-}
-
-Object.defineProperties(Blob.prototype, {
- size: { enumerable: true },
- type: { enumerable: true },
- slice: { enumerable: true }
-});
-
-Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
- value: 'Blob',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-/**
- * fetch-error.js
- *
- * FetchError interface for operational errors
- */
-
-/**
- * Create FetchError instance
- *
- * @param String message Error message for human
- * @param String type Error type for machine
- * @param String systemError For Node.js system error
- * @return FetchError
- */
-function FetchError(message, type, systemError) {
- Error.call(this, message);
-
- this.message = message;
- this.type = type;
-
- // when err.type is `system`, err.code contains system error code
- if (systemError) {
- this.code = this.errno = systemError.code;
- }
-
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
-}
-
-FetchError.prototype = Object.create(Error.prototype);
-FetchError.prototype.constructor = FetchError;
-FetchError.prototype.name = 'FetchError';
-
-let convert;
-try {
- convert = (__nccwpck_require__(22877).convert);
-} catch (e) {}
-
-const INTERNALS = Symbol('Body internals');
-
-// fix an issue where "PassThrough" isn't a named export for node <10
-const PassThrough = Stream.PassThrough;
-
-/**
- * Body mixin
- *
- * Ref: https://fetch.spec.whatwg.org/#body
- *
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
- */
-function Body(body) {
- var _this = this;
-
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
- _ref$size = _ref.size;
-
- let size = _ref$size === undefined ? 0 : _ref$size;
- var _ref$timeout = _ref.timeout;
- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
-
- if (body == null) {
- // body is undefined or null
- body = null;
- } else if (isURLSearchParams(body)) {
- // body is a URLSearchParams
- body = Buffer.from(body.toString());
- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
- // body is ArrayBuffer
- body = Buffer.from(body);
- } else if (ArrayBuffer.isView(body)) {
- // body is ArrayBufferView
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
- } else if (body instanceof Stream) ; else {
- // none of the above
- // coerce to string then buffer
- body = Buffer.from(String(body));
- }
- this[INTERNALS] = {
- body,
- disturbed: false,
- error: null
- };
- this.size = size;
- this.timeout = timeout;
-
- if (body instanceof Stream) {
- body.on('error', function (err) {
- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
- _this[INTERNALS].error = error;
- });
- }
-}
-
-Body.prototype = {
- get body() {
- return this[INTERNALS].body;
- },
-
- get bodyUsed() {
- return this[INTERNALS].disturbed;
- },
-
- /**
- * Decode response as ArrayBuffer
- *
- * @return Promise
- */
- arrayBuffer() {
- return consumeBody.call(this).then(function (buf) {
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- });
- },
-
- /**
- * Return raw response as Blob
- *
- * @return Promise
- */
- blob() {
- let ct = this.headers && this.headers.get('content-type') || '';
- return consumeBody.call(this).then(function (buf) {
- return Object.assign(
- // Prevent copying
- new Blob([], {
- type: ct.toLowerCase()
- }), {
- [BUFFER]: buf
- });
- });
- },
-
- /**
- * Decode response as json
- *
- * @return Promise
- */
- json() {
- var _this2 = this;
-
- return consumeBody.call(this).then(function (buffer) {
- try {
- return JSON.parse(buffer.toString());
- } catch (err) {
- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
- }
- });
- },
-
- /**
- * Decode response as text
- *
- * @return Promise
- */
- text() {
- return consumeBody.call(this).then(function (buffer) {
- return buffer.toString();
- });
- },
-
- /**
- * Decode response as buffer (non-spec api)
- *
- * @return Promise
- */
- buffer() {
- return consumeBody.call(this);
- },
-
- /**
- * Decode response as text, while automatically detecting the encoding and
- * trying to decode to UTF-8 (non-spec api)
- *
- * @return Promise
- */
- textConverted() {
- var _this3 = this;
-
- return consumeBody.call(this).then(function (buffer) {
- return convertBody(buffer, _this3.headers);
- });
- }
-};
-
-// In browsers, all properties are enumerable.
-Object.defineProperties(Body.prototype, {
- body: { enumerable: true },
- bodyUsed: { enumerable: true },
- arrayBuffer: { enumerable: true },
- blob: { enumerable: true },
- json: { enumerable: true },
- text: { enumerable: true }
-});
-
-Body.mixIn = function (proto) {
- for (const name of Object.getOwnPropertyNames(Body.prototype)) {
- // istanbul ignore else: future proof
- if (!(name in proto)) {
- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
- Object.defineProperty(proto, name, desc);
- }
- }
-};
-
-/**
- * Consume and convert an entire Body to a Buffer.
- *
- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
- *
- * @return Promise
- */
-function consumeBody() {
- var _this4 = this;
-
- if (this[INTERNALS].disturbed) {
- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
- }
-
- this[INTERNALS].disturbed = true;
-
- if (this[INTERNALS].error) {
- return Body.Promise.reject(this[INTERNALS].error);
- }
-
- let body = this.body;
-
- // body is null
- if (body === null) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
-
- // body is blob
- if (isBlob(body)) {
- body = body.stream();
- }
-
- // body is buffer
- if (Buffer.isBuffer(body)) {
- return Body.Promise.resolve(body);
- }
-
- // istanbul ignore if: should never happen
- if (!(body instanceof Stream)) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
-
- // body is stream
- // get ready to actually consume the body
- let accum = [];
- let accumBytes = 0;
- let abort = false;
-
- return new Body.Promise(function (resolve, reject) {
- let resTimeout;
-
- // allow timeout on slow response body
- if (_this4.timeout) {
- resTimeout = setTimeout(function () {
- abort = true;
- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
- }, _this4.timeout);
- }
-
- // handle stream errors
- body.on('error', function (err) {
- if (err.name === 'AbortError') {
- // if the request was aborted, reject with this Error
- abort = true;
- reject(err);
- } else {
- // other errors, such as incorrect content-encoding
- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
-
- body.on('data', function (chunk) {
- if (abort || chunk === null) {
- return;
- }
-
- if (_this4.size && accumBytes + chunk.length > _this4.size) {
- abort = true;
- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
- return;
- }
-
- accumBytes += chunk.length;
- accum.push(chunk);
- });
-
- body.on('end', function () {
- if (abort) {
- return;
- }
-
- clearTimeout(resTimeout);
-
- try {
- resolve(Buffer.concat(accum, accumBytes));
- } catch (err) {
- // handle streams that have accumulated too much data (issue #414)
- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
- });
-}
-
-/**
- * Detect buffer encoding and convert to target encoding
- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
- *
- * @param Buffer buffer Incoming buffer
- * @param String encoding Target encoding
- * @return String
- */
-function convertBody(buffer, headers) {
- if (typeof convert !== 'function') {
- throw new Error('The package `encoding` must be installed to use the textConverted() function');
- }
-
- const ct = headers.get('content-type');
- let charset = 'utf-8';
- let res, str;
-
- // header
- if (ct) {
- res = /charset=([^;]*)/i.exec(ct);
- }
-
- // no charset in content type, peek at response body for at most 1024 bytes
- str = buffer.slice(0, 1024).toString();
-
- // html5
- if (!res && str) {
- res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
-
- this[MAP] = Object.create(null);
-
- if (init instanceof Headers) {
- const rawHeaders = init.raw();
- const headerNames = Object.keys(rawHeaders);
-
- for (const headerName of headerNames) {
- for (const value of rawHeaders[headerName]) {
- this.append(headerName, value);
- }
- }
-
- return;
- }
-
- // We don't worry about converting prop to ByteString here as append()
- // will handle it.
- if (init == null) ; else if (typeof init === 'object') {
- const method = init[Symbol.iterator];
- if (method != null) {
- if (typeof method !== 'function') {
- throw new TypeError('Header pairs must be iterable');
- }
-
- // sequence>
- // Note: per spec we have to first exhaust the lists then process them
- const pairs = [];
- for (const pair of init) {
- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
- throw new TypeError('Each header pair must be iterable');
- }
- pairs.push(Array.from(pair));
- }
-
- for (const pair of pairs) {
- if (pair.length !== 2) {
- throw new TypeError('Each header pair must be a name/value tuple');
- }
- this.append(pair[0], pair[1]);
- }
- } else {
- // record
- for (const key of Object.keys(init)) {
- const value = init[key];
- this.append(key, value);
- }
- }
- } else {
- throw new TypeError('Provided initializer must be an object');
- }
- }
-
- /**
- * Return combined header value given name
- *
- * @param String name Header name
- * @return Mixed
- */
- get(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key === undefined) {
- return null;
- }
-
- return this[MAP][key].join(', ');
- }
-
- /**
- * Iterate over all headers
- *
- * @param Function callback Executed for each item with parameters (value, name, thisArg)
- * @param Boolean thisArg `this` context for callback function
- * @return Void
- */
- forEach(callback) {
- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
-
- let pairs = getHeaders(this);
- let i = 0;
- while (i < pairs.length) {
- var _pairs$i = pairs[i];
- const name = _pairs$i[0],
- value = _pairs$i[1];
-
- callback.call(thisArg, value, name, this);
- pairs = getHeaders(this);
- i++;
- }
- }
-
- /**
- * Overwrite header values given name
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- set(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- this[MAP][key !== undefined ? key : name] = [value];
- }
-
- /**
- * Append a value onto existing header
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- append(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- this[MAP][key].push(value);
- } else {
- this[MAP][name] = [value];
- }
- }
-
- /**
- * Check for header name existence
- *
- * @param String name Header name
- * @return Boolean
- */
- has(name) {
- name = `${name}`;
- validateName(name);
- return find(this[MAP], name) !== undefined;
- }
-
- /**
- * Delete all header values given name
- *
- * @param String name Header name
- * @return Void
- */
- delete(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- delete this[MAP][key];
- }
- }
-
- /**
- * Return raw headers (non-spec api)
- *
- * @return Object
- */
- raw() {
- return this[MAP];
- }
-
- /**
- * Get an iterator on keys.
- *
- * @return Iterator
- */
- keys() {
- return createHeadersIterator(this, 'key');
- }
-
- /**
- * Get an iterator on values.
- *
- * @return Iterator
- */
- values() {
- return createHeadersIterator(this, 'value');
- }
-
- /**
- * Get an iterator on entries.
- *
- * This is the default iterator of the Headers object.
- *
- * @return Iterator
- */
- [Symbol.iterator]() {
- return createHeadersIterator(this, 'key+value');
- }
-}
-Headers.prototype.entries = Headers.prototype[Symbol.iterator];
-
-Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
- value: 'Headers',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-Object.defineProperties(Headers.prototype, {
- get: { enumerable: true },
- forEach: { enumerable: true },
- set: { enumerable: true },
- append: { enumerable: true },
- has: { enumerable: true },
- delete: { enumerable: true },
- keys: { enumerable: true },
- values: { enumerable: true },
- entries: { enumerable: true }
-});
-
-function getHeaders(headers) {
- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
-
- const keys = Object.keys(headers[MAP]).sort();
- return keys.map(kind === 'key' ? function (k) {
- return k.toLowerCase();
- } : kind === 'value' ? function (k) {
- return headers[MAP][k].join(', ');
- } : function (k) {
- return [k.toLowerCase(), headers[MAP][k].join(', ')];
- });
-}
-
-const INTERNAL = Symbol('internal');
-
-function createHeadersIterator(target, kind) {
- const iterator = Object.create(HeadersIteratorPrototype);
- iterator[INTERNAL] = {
- target,
- kind,
- index: 0
- };
- return iterator;
-}
-
-const HeadersIteratorPrototype = Object.setPrototypeOf({
- next() {
- // istanbul ignore if
- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
- throw new TypeError('Value of `this` is not a HeadersIterator');
- }
-
- var _INTERNAL = this[INTERNAL];
- const target = _INTERNAL.target,
- kind = _INTERNAL.kind,
- index = _INTERNAL.index;
-
- const values = getHeaders(target, kind);
- const len = values.length;
- if (index >= len) {
- return {
- value: undefined,
- done: true
- };
- }
-
- this[INTERNAL].index = index + 1;
-
- return {
- value: values[index],
- done: false
- };
- }
-}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
-
-Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
- value: 'HeadersIterator',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-/**
- * Export the Headers object in a form that Node.js can consume.
- *
- * @param Headers headers
- * @return Object
- */
-function exportNodeCompatibleHeaders(headers) {
- const obj = Object.assign({ __proto__: null }, headers[MAP]);
-
- // http.request() only supports string as Host header. This hack makes
- // specifying custom Host header possible.
- const hostHeaderKey = find(headers[MAP], 'Host');
- if (hostHeaderKey !== undefined) {
- obj[hostHeaderKey] = obj[hostHeaderKey][0];
- }
-
- return obj;
-}
-
-/**
- * Create a Headers object from an object of headers, ignoring those that do
- * not conform to HTTP grammar productions.
- *
- * @param Object obj Object of headers
- * @return Headers
- */
-function createHeadersLenient(obj) {
- const headers = new Headers();
- for (const name of Object.keys(obj)) {
- if (invalidTokenRegex.test(name)) {
- continue;
- }
- if (Array.isArray(obj[name])) {
- for (const val of obj[name]) {
- if (invalidHeaderCharRegex.test(val)) {
- continue;
- }
- if (headers[MAP][name] === undefined) {
- headers[MAP][name] = [val];
- } else {
- headers[MAP][name].push(val);
- }
- }
- } else if (!invalidHeaderCharRegex.test(obj[name])) {
- headers[MAP][name] = [obj[name]];
- }
- }
- return headers;
-}
-
-const INTERNALS$1 = Symbol('Response internals');
-
-// fix an issue where "STATUS_CODES" aren't a named export for node <10
-const STATUS_CODES = http.STATUS_CODES;
-
-/**
- * Response class
- *
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
- */
-class Response {
- constructor() {
- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- Body.call(this, body, opts);
-
- const status = opts.status || 200;
- const headers = new Headers(opts.headers);
-
- if (body != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(body);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
-
- this[INTERNALS$1] = {
- url: opts.url,
- status,
- statusText: opts.statusText || STATUS_CODES[status],
- headers,
- counter: opts.counter
- };
- }
-
- get url() {
- return this[INTERNALS$1].url || '';
- }
-
- get status() {
- return this[INTERNALS$1].status;
- }
-
- /**
- * Convenience property representing if the request ended normally
- */
- get ok() {
- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
- }
-
- get redirected() {
- return this[INTERNALS$1].counter > 0;
- }
-
- get statusText() {
- return this[INTERNALS$1].statusText;
- }
-
- get headers() {
- return this[INTERNALS$1].headers;
- }
-
- /**
- * Clone this response
- *
- * @return Response
- */
- clone() {
- return new Response(clone(this), {
- url: this.url,
- status: this.status,
- statusText: this.statusText,
- headers: this.headers,
- ok: this.ok,
- redirected: this.redirected
- });
- }
-}
-
-Body.mixIn(Response.prototype);
-
-Object.defineProperties(Response.prototype, {
- url: { enumerable: true },
- status: { enumerable: true },
- ok: { enumerable: true },
- redirected: { enumerable: true },
- statusText: { enumerable: true },
- headers: { enumerable: true },
- clone: { enumerable: true }
-});
-
-Object.defineProperty(Response.prototype, Symbol.toStringTag, {
- value: 'Response',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-const INTERNALS$2 = Symbol('Request internals');
-const URL = Url.URL || whatwgUrl.URL;
-
-// fix an issue where "format", "parse" aren't a named export for node <10
-const parse_url = Url.parse;
-const format_url = Url.format;
-
-/**
- * Wrapper around `new URL` to handle arbitrary URLs
- *
- * @param {string} urlStr
- * @return {void}
- */
-function parseURL(urlStr) {
- /*
- Check whether the URL is absolute or not
- Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
- Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
- */
- if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
- urlStr = new URL(urlStr).toString();
- }
-
- // Fallback to old implementation for arbitrary URLs
- return parse_url(urlStr);
-}
-
-const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
-
-/**
- * Check if a value is an instance of Request.
- *
- * @param Mixed input
- * @return Boolean
- */
-function isRequest(input) {
- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
-}
-
-function isAbortSignal(signal) {
- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
- return !!(proto && proto.constructor.name === 'AbortSignal');
-}
-
-/**
- * Request class
- *
- * @param Mixed input Url or Request instance
- * @param Object init Custom options
- * @return Void
- */
-class Request {
- constructor(input) {
- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- let parsedURL;
-
- // normalize input
- if (!isRequest(input)) {
- if (input && input.href) {
- // in order to support Node.js' Url objects; though WHATWG's URL objects
- // will fall into this branch also (since their `toString()` will return
- // `href` property anyway)
- parsedURL = parseURL(input.href);
- } else {
- // coerce input to a string before attempting to parse
- parsedURL = parseURL(`${input}`);
- }
- input = {};
- } else {
- parsedURL = parseURL(input.url);
- }
-
- let method = init.method || input.method || 'GET';
- method = method.toUpperCase();
-
- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
- throw new TypeError('Request with GET/HEAD method cannot have body');
- }
-
- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
-
- Body.call(this, inputBody, {
- timeout: init.timeout || input.timeout || 0,
- size: init.size || input.size || 0
- });
-
- const headers = new Headers(init.headers || input.headers || {});
-
- if (inputBody != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(inputBody);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
-
- let signal = isRequest(input) ? input.signal : null;
- if ('signal' in init) signal = init.signal;
-
- if (signal != null && !isAbortSignal(signal)) {
- throw new TypeError('Expected signal to be an instanceof AbortSignal');
- }
-
- this[INTERNALS$2] = {
- method,
- redirect: init.redirect || input.redirect || 'follow',
- headers,
- parsedURL,
- signal
- };
-
- // node-fetch-only options
- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
- this.counter = init.counter || input.counter || 0;
- this.agent = init.agent || input.agent;
- }
-
- get method() {
- return this[INTERNALS$2].method;
- }
-
- get url() {
- return format_url(this[INTERNALS$2].parsedURL);
- }
-
- get headers() {
- return this[INTERNALS$2].headers;
- }
-
- get redirect() {
- return this[INTERNALS$2].redirect;
- }
-
- get signal() {
- return this[INTERNALS$2].signal;
- }
-
- /**
- * Clone this request
- *
- * @return Request
- */
- clone() {
- return new Request(this);
- }
-}
-
-Body.mixIn(Request.prototype);
-
-Object.defineProperty(Request.prototype, Symbol.toStringTag, {
- value: 'Request',
- writable: false,
- enumerable: false,
- configurable: true
-});
-
-Object.defineProperties(Request.prototype, {
- method: { enumerable: true },
- url: { enumerable: true },
- headers: { enumerable: true },
- redirect: { enumerable: true },
- clone: { enumerable: true },
- signal: { enumerable: true }
-});
-
-/**
- * Convert a Request to Node.js http request options.
- *
- * @param Request A Request instance
- * @return Object The options object to be passed to http.request
- */
-function getNodeRequestOptions(request) {
- const parsedURL = request[INTERNALS$2].parsedURL;
- const headers = new Headers(request[INTERNALS$2].headers);
-
- // fetch step 1.3
- if (!headers.has('Accept')) {
- headers.set('Accept', '*/*');
- }
-
- // Basic fetch
- if (!parsedURL.protocol || !parsedURL.hostname) {
- throw new TypeError('Only absolute URLs are supported');
- }
-
- if (!/^https?:$/.test(parsedURL.protocol)) {
- throw new TypeError('Only HTTP(S) protocols are supported');
- }
-
- if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
- }
-
- // HTTP-network-or-cache fetch steps 2.4-2.7
- let contentLengthValue = null;
- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
- contentLengthValue = '0';
- }
- if (request.body != null) {
- const totalBytes = getTotalBytes(request);
- if (typeof totalBytes === 'number') {
- contentLengthValue = String(totalBytes);
- }
- }
- if (contentLengthValue) {
- headers.set('Content-Length', contentLengthValue);
- }
-
- // HTTP-network-or-cache fetch step 2.11
- if (!headers.has('User-Agent')) {
- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
- }
-
- // HTTP-network-or-cache fetch step 2.15
- if (request.compress && !headers.has('Accept-Encoding')) {
- headers.set('Accept-Encoding', 'gzip,deflate');
- }
-
- let agent = request.agent;
- if (typeof agent === 'function') {
- agent = agent(parsedURL);
- }
-
- // HTTP-network fetch step 4.2
- // chunked encoding is handled by Node.js
-
- return Object.assign({}, parsedURL, {
- method: request.method,
- headers: exportNodeCompatibleHeaders(headers),
- agent
- });
-}
-
-/**
- * abort-error.js
- *
- * AbortError interface for cancelled requests
- */
-
-/**
- * Create AbortError instance
- *
- * @param String message Error message for human
- * @return AbortError
- */
-function AbortError(message) {
- Error.call(this, message);
-
- this.type = 'aborted';
- this.message = message;
-
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
-}
-
-AbortError.prototype = Object.create(Error.prototype);
-AbortError.prototype.constructor = AbortError;
-AbortError.prototype.name = 'AbortError';
-
-const URL$1 = Url.URL || whatwgUrl.URL;
-
-// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
-const PassThrough$1 = Stream.PassThrough;
-
-const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
- const orig = new URL$1(original).hostname;
- const dest = new URL$1(destination).hostname;
-
- return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
-};
-
-/**
- * isSameProtocol reports whether the two provided URLs use the same protocol.
- *
- * Both domains must already be in canonical form.
- * @param {string|URL} original
- * @param {string|URL} destination
- */
-const isSameProtocol = function isSameProtocol(destination, original) {
- const orig = new URL$1(original).protocol;
- const dest = new URL$1(destination).protocol;
-
- return orig === dest;
-};
-
-/**
- * Fetch function
- *
- * @param Mixed url Absolute url or Request instance
- * @param Object opts Fetch options
- * @return Promise
- */
-function fetch(url, opts) {
-
- // allow custom promise
- if (!fetch.Promise) {
- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
- }
-
- Body.Promise = fetch.Promise;
-
- // wrap http.request into fetch
- return new fetch.Promise(function (resolve, reject) {
- // build request object
- const request = new Request(url, opts);
- const options = getNodeRequestOptions(request);
-
- const send = (options.protocol === 'https:' ? https : http).request;
- const signal = request.signal;
-
- let response = null;
-
- const abort = function abort() {
- let error = new AbortError('The user aborted a request.');
- reject(error);
- if (request.body && request.body instanceof Stream.Readable) {
- destroyStream(request.body, error);
- }
- if (!response || !response.body) return;
- response.body.emit('error', error);
- };
-
- if (signal && signal.aborted) {
- abort();
- return;
- }
-
- const abortAndFinalize = function abortAndFinalize() {
- abort();
- finalize();
- };
-
- // send request
- const req = send(options);
- let reqTimeout;
-
- if (signal) {
- signal.addEventListener('abort', abortAndFinalize);
- }
-
- function finalize() {
- req.abort();
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- clearTimeout(reqTimeout);
- }
-
- if (request.timeout) {
- req.once('socket', function (socket) {
- reqTimeout = setTimeout(function () {
- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
- finalize();
- }, request.timeout);
- });
- }
-
- req.on('error', function (err) {
- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
-
- if (response && response.body) {
- destroyStream(response.body, err);
- }
-
- finalize();
- });
-
- fixResponseChunkedTransferBadEnding(req, function (err) {
- if (signal && signal.aborted) {
- return;
- }
-
- if (response && response.body) {
- destroyStream(response.body, err);
- }
- });
-
- /* c8 ignore next 18 */
- if (parseInt(process.version.substring(1)) < 14) {
- // Before Node.js 14, pipeline() does not fully support async iterators and does not always
- // properly handle when the socket close/end events are out of order.
- req.on('socket', function (s) {
- s.addListener('close', function (hadError) {
- // if a data listener is still present we didn't end cleanly
- const hasDataListener = s.listenerCount('data') > 0;
-
- // if end happened before close but the socket didn't emit an error, do it now
- if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
- const err = new Error('Premature close');
- err.code = 'ERR_STREAM_PREMATURE_CLOSE';
- response.body.emit('error', err);
- }
- });
- });
- }
-
- req.on('response', function (res) {
- clearTimeout(reqTimeout);
-
- const headers = createHeadersLenient(res.headers);
-
- // HTTP fetch step 5
- if (fetch.isRedirect(res.statusCode)) {
- // HTTP fetch step 5.2
- const location = headers.get('Location');
-
- // HTTP fetch step 5.3
- let locationURL = null;
- try {
- locationURL = location === null ? null : new URL$1(location, request.url).toString();
- } catch (err) {
- // error here can only be invalid URL in Location: header
- // do not throw when options.redirect == manual
- // let the user extract the errorneous redirect URL
- if (request.redirect !== 'manual') {
- reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
- finalize();
- return;
- }
- }
-
- // HTTP fetch step 5.5
- switch (request.redirect) {
- case 'error':
- reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
- finalize();
- return;
- case 'manual':
- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
- if (locationURL !== null) {
- // handle corrupted header
- try {
- headers.set('Location', locationURL);
- } catch (err) {
- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
- reject(err);
- }
- }
- break;
- case 'follow':
- // HTTP-redirect fetch step 2
- if (locationURL === null) {
- break;
- }
-
- // HTTP-redirect fetch step 5
- if (request.counter >= request.follow) {
- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
- finalize();
- return;
- }
-
- // HTTP-redirect fetch step 6 (counter increment)
- // Create a new Request object.
- const requestOpts = {
- headers: new Headers(request.headers),
- follow: request.follow,
- counter: request.counter + 1,
- agent: request.agent,
- compress: request.compress,
- method: request.method,
- body: request.body,
- signal: request.signal,
- timeout: request.timeout,
- size: request.size
- };
-
- if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
- for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
- requestOpts.headers.delete(name);
- }
- }
-
- // HTTP-redirect fetch step 9
- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
- finalize();
- return;
- }
-
- // HTTP-redirect fetch step 11
- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
- requestOpts.method = 'GET';
- requestOpts.body = undefined;
- requestOpts.headers.delete('content-length');
- }
-
- // HTTP-redirect fetch step 15
- resolve(fetch(new Request(locationURL, requestOpts)));
- finalize();
- return;
- }
- }
-
- // prepare response
- res.once('end', function () {
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- });
- let body = res.pipe(new PassThrough$1());
-
- const response_options = {
- url: request.url,
- status: res.statusCode,
- statusText: res.statusMessage,
- headers: headers,
- size: request.size,
- timeout: request.timeout,
- counter: request.counter
- };
-
- // HTTP-network fetch step 12.1.1.3
- const codings = headers.get('Content-Encoding');
-
- // HTTP-network fetch step 12.1.1.4: handle content codings
-
- // in following scenarios we ignore compression support
- // 1. compression support is disabled
- // 2. HEAD request
- // 3. no Content-Encoding header
- // 4. no content response (204)
- // 5. content not modified response (304)
- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // For Node v6+
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- const zlibOptions = {
- flush: zlib.Z_SYNC_FLUSH,
- finishFlush: zlib.Z_SYNC_FLUSH
- };
-
- // for gzip
- if (codings == 'gzip' || codings == 'x-gzip') {
- body = body.pipe(zlib.createGunzip(zlibOptions));
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // for deflate
- if (codings == 'deflate' || codings == 'x-deflate') {
- // handle the infamous raw deflate response from old servers
- // a hack for old IIS and Apache servers
- const raw = res.pipe(new PassThrough$1());
- raw.once('data', function (chunk) {
- // see http://stackoverflow.com/questions/37519828
- if ((chunk[0] & 0x0F) === 0x08) {
- body = body.pipe(zlib.createInflate());
- } else {
- body = body.pipe(zlib.createInflateRaw());
- }
- response = new Response(body, response_options);
- resolve(response);
- });
- raw.on('end', function () {
- // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
- if (!response) {
- response = new Response(body, response_options);
- resolve(response);
- }
- });
- return;
- }
-
- // for br
- if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
- body = body.pipe(zlib.createBrotliDecompress());
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
-
- // otherwise, use response as-is
- response = new Response(body, response_options);
- resolve(response);
- });
-
- writeToStream(req, request);
- });
-}
-function fixResponseChunkedTransferBadEnding(request, errorCallback) {
- let socket;
-
- request.on('socket', function (s) {
- socket = s;
- });
-
- request.on('response', function (response) {
- const headers = response.headers;
-
- if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
- response.once('close', function (hadError) {
- // tests for socket presence, as in some situations the
- // the 'socket' event is not triggered for the request
- // (happens in deno), avoids `TypeError`
- // if a data listener is still present we didn't end cleanly
- const hasDataListener = socket && socket.listenerCount('data') > 0;
-
- if (hasDataListener && !hadError) {
- const err = new Error('Premature close');
- err.code = 'ERR_STREAM_PREMATURE_CLOSE';
- errorCallback(err);
- }
- });
- }
- });
-}
-
-function destroyStream(stream, err) {
- if (stream.destroy) {
- stream.destroy(err);
- } else {
- // node < 8
- stream.emit('error', err);
- stream.end();
- }
-}
-
-/**
- * Redirect code matching
- *
- * @param Number code Status code
- * @return Boolean
- */
-fetch.isRedirect = function (code) {
- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
-};
-
-// expose Promise
-fetch.Promise = global.Promise;
-
-module.exports = exports = fetch;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = exports;
-exports.Headers = Headers;
-exports.Request = Request;
-exports.Response = Response;
-exports.FetchError = FetchError;
-exports.AbortError = AbortError;
-
-
-/***/ }),
-
-/***/ 20502:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-const path = __nccwpck_require__(71017);
-const pathKey = __nccwpck_require__(20539);
-
-const npmRunPath = options => {
- options = {
- cwd: process.cwd(),
- path: process.env[pathKey()],
- execPath: process.execPath,
- ...options
- };
-
- let previous;
- let cwdPath = path.resolve(options.cwd);
- const result = [];
-
- while (previous !== cwdPath) {
- result.push(path.join(cwdPath, 'node_modules/.bin'));
- previous = cwdPath;
- cwdPath = path.resolve(cwdPath, '..');
- }
-
- // Ensure the running `node` binary is used
- const execPathDir = path.resolve(options.cwd, options.execPath, '..');
- result.push(execPathDir);
-
- return result.concat(options.path).join(path.delimiter);
-};
-
-module.exports = npmRunPath;
-// TODO: Remove this for the next major release
-module.exports["default"] = npmRunPath;
-
-module.exports.env = options => {
- options = {
- env: process.env,
- ...options
- };
-
- const env = {...options.env};
- const path = pathKey({env});
-
- options.path = env[path];
- env[path] = module.exports(options);
-
- return env;
-};
-
-
-/***/ }),
-
-/***/ 17426:
-/***/ ((module) => {
-
-"use strict";
-/*
-object-assign
-(c) Sindre Sorhus
-@license MIT
-*/
-
-
-/* eslint-disable no-unused-vars */
-var getOwnPropertySymbols = Object.getOwnPropertySymbols;
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-var propIsEnumerable = Object.prototype.propertyIsEnumerable;
-
-function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
-
- return Object(val);
-}
-
-function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
-
- // Detect buggy property enumeration order in older V8 versions.
-
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- }
-
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- }
-
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !==
- 'abcdefghijklmnopqrst') {
- return false;
- }
-
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
-}
-
-module.exports = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
-
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
-
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
-
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
-
- return to;
-};
-
-
-/***/ }),
-
-/***/ 1223:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var wrappy = __nccwpck_require__(62940)
-module.exports = wrappy(once)
-module.exports.strict = wrappy(onceStrict)
-
-once.proto = once(function () {
- Object.defineProperty(Function.prototype, 'once', {
- value: function () {
- return once(this)
- },
- configurable: true
- })
-
- Object.defineProperty(Function.prototype, 'onceStrict', {
- value: function () {
- return onceStrict(this)
- },
- configurable: true
- })
-})
-
-function once (fn) {
- var f = function () {
- if (f.called) return f.value
- f.called = true
- return f.value = fn.apply(this, arguments)
- }
- f.called = false
- return f
-}
-
-function onceStrict (fn) {
- var f = function () {
- if (f.called)
- throw new Error(f.onceError)
- f.called = true
- return f.value = fn.apply(this, arguments)
- }
- var name = fn.name || 'Function wrapped with `once`'
- f.onceError = name + " shouldn't be called more than once"
- f.called = false
- return f
-}
-
-
-/***/ }),
-
-/***/ 89082:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-const mimicFn = __nccwpck_require__(76047);
-
-const calledFunctions = new WeakMap();
-
-const onetime = (function_, options = {}) => {
- if (typeof function_ !== 'function') {
- throw new TypeError('Expected a function');
- }
-
- let returnValue;
- let callCount = 0;
- const functionName = function_.displayName || function_.name || '';
-
- const onetime = function (...arguments_) {
- calledFunctions.set(onetime, ++callCount);
-
- if (callCount === 1) {
- returnValue = function_.apply(this, arguments_);
- function_ = null;
- } else if (options.throw === true) {
- throw new Error(`Function \`${functionName}\` can only be called once`);
- }
-
- return returnValue;
- };
-
- mimicFn(onetime, function_);
- calledFunctions.set(onetime, callCount);
-
- return onetime;
-};
-
-module.exports = onetime;
-// TODO: Remove this for the next major release
-module.exports["default"] = onetime;
-
-module.exports.callCount = function_ => {
- if (!calledFunctions.has(function_)) {
- throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
- }
-
- return calledFunctions.get(function_);
-};
-
-
-/***/ }),
-
-/***/ 38714:
-/***/ ((module) => {
-
-"use strict";
-
-
-function posix(path) {
- return path.charAt(0) === '/';
-}
-
-function win32(path) {
- // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
- var result = splitDeviceRe.exec(path);
- var device = result[1] || '';
- var isUnc = Boolean(device && device.charAt(1) !== ':');
-
- // UNC paths are always absolute
- return Boolean(result[2] || isUnc);
-}
-
-module.exports = process.platform === 'win32' ? win32 : posix;
-module.exports.posix = posix;
-module.exports.win32 = win32;
-
-
-/***/ }),
-
-/***/ 20539:
-/***/ ((module) => {
-
-"use strict";
-
-
-const pathKey = (options = {}) => {
- const environment = options.env || process.env;
- const platform = options.platform || process.platform;
-
- if (platform !== 'win32') {
- return 'PATH';
- }
-
- return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
-};
-
-module.exports = pathKey;
-// TODO: Remove this for the next major release
-module.exports["default"] = pathKey;
-
-
-/***/ }),
-
-/***/ 5980:
-/***/ ((module) => {
-
-"use strict";
-
-
-var isWindows = process.platform === 'win32';
-
-// Regex to split a windows path into into [dir, root, basename, name, ext]
-var splitWindowsRe =
- /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
-
-var win32 = {};
-
-function win32SplitPath(filename) {
- return splitWindowsRe.exec(filename).slice(1);
-}
-
-win32.parse = function(pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError(
- "Parameter 'pathString' must be a string, not " + typeof pathString
- );
- }
- var allParts = win32SplitPath(pathString);
- if (!allParts || allParts.length !== 5) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
- return {
- root: allParts[1],
- dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
- base: allParts[2],
- ext: allParts[4],
- name: allParts[3]
- };
-};
-
-
-
-// Split a filename into [dir, root, basename, name, ext], unix version
-// 'root' is just a slash, or nothing.
-var splitPathRe =
- /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
-var posix = {};
-
-
-function posixSplitPath(filename) {
- return splitPathRe.exec(filename).slice(1);
-}
-
-
-posix.parse = function(pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError(
- "Parameter 'pathString' must be a string, not " + typeof pathString
- );
- }
- var allParts = posixSplitPath(pathString);
- if (!allParts || allParts.length !== 5) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
-
- return {
- root: allParts[1],
- dir: allParts[0].slice(0, -1),
- base: allParts[2],
- ext: allParts[4],
- name: allParts[3],
- };
-};
-
-
-if (isWindows)
- module.exports = win32.parse;
-else /* posix */
- module.exports = posix.parse;
-
-module.exports.posix = posix.parse;
-module.exports.win32 = win32.parse;
-
-
-/***/ }),
-
-/***/ 78569:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-module.exports = __nccwpck_require__(33322);
-
-
-/***/ }),
-
-/***/ 16099:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const path = __nccwpck_require__(71017);
-const WIN_SLASH = '\\\\/';
-const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
-
-/**
- * Posix glob regex
- */
-
-const DOT_LITERAL = '\\.';
-const PLUS_LITERAL = '\\+';
-const QMARK_LITERAL = '\\?';
-const SLASH_LITERAL = '\\/';
-const ONE_CHAR = '(?=.)';
-const QMARK = '[^/]';
-const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
-const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
-const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
-const NO_DOT = `(?!${DOT_LITERAL})`;
-const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
-const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
-const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
-const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
-const STAR = `${QMARK}*?`;
-
-const POSIX_CHARS = {
- DOT_LITERAL,
- PLUS_LITERAL,
- QMARK_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- QMARK,
- END_ANCHOR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
-};
-
-/**
- * Windows glob regex
- */
-
-const WINDOWS_CHARS = {
- ...POSIX_CHARS,
-
- SLASH_LITERAL: `[${WIN_SLASH}]`,
- QMARK: WIN_NO_SLASH,
- STAR: `${WIN_NO_SLASH}*?`,
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
- NO_DOT: `(?!${DOT_LITERAL})`,
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
-};
-
-/**
- * POSIX Bracket Regex
- */
-
-const POSIX_REGEX_SOURCE = {
- alnum: 'a-zA-Z0-9',
- alpha: 'a-zA-Z',
- ascii: '\\x00-\\x7F',
- blank: ' \\t',
- cntrl: '\\x00-\\x1F\\x7F',
- digit: '0-9',
- graph: '\\x21-\\x7E',
- lower: 'a-z',
- print: '\\x20-\\x7E ',
- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
- space: ' \\t\\r\\n\\v\\f',
- upper: 'A-Z',
- word: 'A-Za-z0-9_',
- xdigit: 'A-Fa-f0-9'
-};
-
-module.exports = {
- MAX_LENGTH: 1024 * 64,
- POSIX_REGEX_SOURCE,
-
- // regular expressions
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
-
- // Replace globs with equivalent patterns to reduce parsing time.
- REPLACEMENTS: {
- '***': '*',
- '**/**': '**',
- '**/**/**': '**'
- },
-
- // Digits
- CHAR_0: 48, /* 0 */
- CHAR_9: 57, /* 9 */
-
- // Alphabet chars.
- CHAR_UPPERCASE_A: 65, /* A */
- CHAR_LOWERCASE_A: 97, /* a */
- CHAR_UPPERCASE_Z: 90, /* Z */
- CHAR_LOWERCASE_Z: 122, /* z */
-
- CHAR_LEFT_PARENTHESES: 40, /* ( */
- CHAR_RIGHT_PARENTHESES: 41, /* ) */
-
- CHAR_ASTERISK: 42, /* * */
-
- // Non-alphabetic chars.
- CHAR_AMPERSAND: 38, /* & */
- CHAR_AT: 64, /* @ */
- CHAR_BACKWARD_SLASH: 92, /* \ */
- CHAR_CARRIAGE_RETURN: 13, /* \r */
- CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
- CHAR_COLON: 58, /* : */
- CHAR_COMMA: 44, /* , */
- CHAR_DOT: 46, /* . */
- CHAR_DOUBLE_QUOTE: 34, /* " */
- CHAR_EQUAL: 61, /* = */
- CHAR_EXCLAMATION_MARK: 33, /* ! */
- CHAR_FORM_FEED: 12, /* \f */
- CHAR_FORWARD_SLASH: 47, /* / */
- CHAR_GRAVE_ACCENT: 96, /* ` */
- CHAR_HASH: 35, /* # */
- CHAR_HYPHEN_MINUS: 45, /* - */
- CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
- CHAR_LEFT_CURLY_BRACE: 123, /* { */
- CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
- CHAR_LINE_FEED: 10, /* \n */
- CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
- CHAR_PERCENT: 37, /* % */
- CHAR_PLUS: 43, /* + */
- CHAR_QUESTION_MARK: 63, /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
- CHAR_RIGHT_CURLY_BRACE: 125, /* } */
- CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
- CHAR_SEMICOLON: 59, /* ; */
- CHAR_SINGLE_QUOTE: 39, /* ' */
- CHAR_SPACE: 32, /* */
- CHAR_TAB: 9, /* \t */
- CHAR_UNDERSCORE: 95, /* _ */
- CHAR_VERTICAL_LINE: 124, /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
-
- SEP: path.sep,
-
- /**
- * Create EXTGLOB_CHARS
- */
-
- extglobChars(chars) {
- return {
- '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
- '?': { type: 'qmark', open: '(?:', close: ')?' },
- '+': { type: 'plus', open: '(?:', close: ')+' },
- '*': { type: 'star', open: '(?:', close: ')*' },
- '@': { type: 'at', open: '(?:', close: ')' }
- };
- },
-
- /**
- * Create GLOB_CHARS
- */
-
- globChars(win32) {
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
- }
-};
-
-
-/***/ }),
-
-/***/ 92139:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const constants = __nccwpck_require__(16099);
-const utils = __nccwpck_require__(30479);
-
-/**
- * Constants
- */
-
-const {
- MAX_LENGTH,
- POSIX_REGEX_SOURCE,
- REGEX_NON_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_BACKREF,
- REPLACEMENTS
-} = constants;
-
-/**
- * Helpers
- */
-
-const expandRange = (args, options) => {
- if (typeof options.expandRange === 'function') {
- return options.expandRange(...args, options);
- }
-
- args.sort();
- const value = `[${args.join('-')}]`;
-
- try {
- /* eslint-disable-next-line no-new */
- new RegExp(value);
- } catch (ex) {
- return args.map(v => utils.escapeRegex(v)).join('..');
- }
-
- return value;
-};
-
-/**
- * Create the message for a syntax error
- */
-
-const syntaxError = (type, char) => {
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
-};
-
-/**
- * Parse the given input string.
- * @param {String} input
- * @param {Object} options
- * @return {Object}
- */
-
-const parse = (input, options) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
-
- input = REPLACEMENTS[input] || input;
-
- const opts = { ...options };
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
-
- let len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
-
- const bos = { type: 'bos', value: '', output: opts.prepend || '' };
- const tokens = [bos];
-
- const capture = opts.capture ? '' : '?:';
- const win32 = utils.isWindows(options);
-
- // create constants based on platform, for windows or posix
- const PLATFORM_CHARS = constants.globChars(win32);
- const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
-
- const {
- DOT_LITERAL,
- PLUS_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- } = PLATFORM_CHARS;
-
- const globstar = opts => {
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
-
- const nodot = opts.dot ? '' : NO_DOT;
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
- let star = opts.bash === true ? globstar(opts) : STAR;
-
- if (opts.capture) {
- star = `(${star})`;
- }
-
- // minimatch options support
- if (typeof opts.noext === 'boolean') {
- opts.noextglob = opts.noext;
- }
-
- const state = {
- input,
- index: -1,
- start: 0,
- dot: opts.dot === true,
- consumed: '',
- output: '',
- prefix: '',
- backtrack: false,
- negated: false,
- brackets: 0,
- braces: 0,
- parens: 0,
- quotes: 0,
- globstar: false,
- tokens
- };
-
- input = utils.removePrefix(input, state);
- len = input.length;
-
- const extglobs = [];
- const braces = [];
- const stack = [];
- let prev = bos;
- let value;
-
- /**
- * Tokenizing helpers
- */
-
- const eos = () => state.index === len - 1;
- const peek = state.peek = (n = 1) => input[state.index + n];
- const advance = state.advance = () => input[++state.index] || '';
- const remaining = () => input.slice(state.index + 1);
- const consume = (value = '', num = 0) => {
- state.consumed += value;
- state.index += num;
- };
-
- const append = token => {
- state.output += token.output != null ? token.output : token.value;
- consume(token.value);
- };
-
- const negate = () => {
- let count = 1;
-
- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
- advance();
- state.start++;
- count++;
- }
-
- if (count % 2 === 0) {
- return false;
- }
-
- state.negated = true;
- state.start++;
- return true;
- };
-
- const increment = type => {
- state[type]++;
- stack.push(type);
- };
-
- const decrement = type => {
- state[type]--;
- stack.pop();
- };
-
- /**
- * Push tokens onto the tokens array. This helper speeds up
- * tokenizing by 1) helping us avoid backtracking as much as possible,
- * and 2) helping us avoid creating extra tokens when consecutive
- * characters are plain text. This improves performance and simplifies
- * lookbehinds.
- */
-
- const push = tok => {
- if (prev.type === 'globstar') {
- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
- const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
-
- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = 'star';
- prev.value = '*';
- prev.output = star;
- state.output += prev.output;
- }
- }
-
- if (extglobs.length && tok.type !== 'paren') {
- extglobs[extglobs.length - 1].inner += tok.value;
- }
-
- if (tok.value || tok.output) append(tok);
- if (prev && prev.type === 'text' && tok.type === 'text') {
- prev.value += tok.value;
- prev.output = (prev.output || '') + tok.value;
- return;
- }
-
- tok.prev = prev;
- tokens.push(tok);
- prev = tok;
- };
-
- const extglobOpen = (type, value) => {
- const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
-
- token.prev = prev;
- token.parens = state.parens;
- token.output = state.output;
- const output = (opts.capture ? '(' : '') + token.open;
-
- increment('parens');
- push({ type, value, output: state.output ? '' : ONE_CHAR });
- push({ type: 'paren', extglob: true, value: advance(), output });
- extglobs.push(token);
- };
-
- const extglobClose = token => {
- let output = token.close + (opts.capture ? ')' : '');
- let rest;
-
- if (token.type === 'negate') {
- let extglobStar = star;
-
- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
- extglobStar = globstar(opts);
- }
-
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
- output = token.close = `)$))${extglobStar}`;
- }
-
- if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
- // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
- // In this case, we need to parse the string and use it in the output of the original pattern.
- // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
- //
- // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
- const expression = parse(rest, { ...options, fastpaths: false }).output;
-
- output = token.close = `)${expression})${extglobStar})`;
- }
-
- if (token.prev.type === 'bos') {
- state.negatedExtglob = true;
- }
- }
-
- push({ type: 'paren', extglob: true, value, output });
- decrement('parens');
- };
-
- /**
- * Fast paths
- */
-
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
- let backslashes = false;
-
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
- if (first === '\\') {
- backslashes = true;
- return m;
- }
-
- if (first === '?') {
- if (esc) {
- return esc + first + (rest ? QMARK.repeat(rest.length) : '');
- }
- if (index === 0) {
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
- }
- return QMARK.repeat(chars.length);
- }
-
- if (first === '.') {
- return DOT_LITERAL.repeat(chars.length);
- }
-
- if (first === '*') {
- if (esc) {
- return esc + first + (rest ? star : '');
- }
- return star;
- }
- return esc ? m : `\\${m}`;
- });
-
- if (backslashes === true) {
- if (opts.unescape === true) {
- output = output.replace(/\\/g, '');
- } else {
- output = output.replace(/\\+/g, m => {
- return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
- });
- }
- }
-
- if (output === input && opts.contains === true) {
- state.output = input;
- return state;
- }
-
- state.output = utils.wrapOutput(output, state, options);
- return state;
- }
-
- /**
- * Tokenize input until we reach end-of-string
- */
-
- while (!eos()) {
- value = advance();
-
- if (value === '\u0000') {
- continue;
- }
-
- /**
- * Escaped characters
- */
-
- if (value === '\\') {
- const next = peek();
-
- if (next === '/' && opts.bash !== true) {
- continue;
- }
-
- if (next === '.' || next === ';') {
- continue;
- }
-
- if (!next) {
- value += '\\';
- push({ type: 'text', value });
- continue;
- }
-
- // collapse slashes to reduce potential for exploits
- const match = /^\\+/.exec(remaining());
- let slashes = 0;
-
- if (match && match[0].length > 2) {
- slashes = match[0].length;
- state.index += slashes;
- if (slashes % 2 !== 0) {
- value += '\\';
- }
- }
-
- if (opts.unescape === true) {
- value = advance();
- } else {
- value += advance();
- }
-
- if (state.brackets === 0) {
- push({ type: 'text', value });
- continue;
- }
- }
-
- /**
- * If we're inside a regex character class, continue
- * until we reach the closing bracket.
- */
-
- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
- if (opts.posix !== false && value === ':') {
- const inner = prev.value.slice(1);
- if (inner.includes('[')) {
- prev.posix = true;
-
- if (inner.includes(':')) {
- const idx = prev.value.lastIndexOf('[');
- const pre = prev.value.slice(0, idx);
- const rest = prev.value.slice(idx + 2);
- const posix = POSIX_REGEX_SOURCE[rest];
- if (posix) {
- prev.value = pre + posix;
- state.backtrack = true;
- advance();
-
- if (!bos.output && tokens.indexOf(prev) === 1) {
- bos.output = ONE_CHAR;
- }
- continue;
- }
- }
- }
- }
-
- if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
- value = `\\${value}`;
- }
-
- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
- value = `\\${value}`;
- }
-
- if (opts.posix === true && value === '!' && prev.value === '[') {
- value = '^';
- }
-
- prev.value += value;
- append({ value });
- continue;
- }
-
- /**
- * If we're inside a quoted string, continue
- * until we reach the closing double quote.
- */
-
- if (state.quotes === 1 && value !== '"') {
- value = utils.escapeRegex(value);
- prev.value += value;
- append({ value });
- continue;
- }
-
- /**
- * Double quotes
- */
-
- if (value === '"') {
- state.quotes = state.quotes === 1 ? 0 : 1;
- if (opts.keepQuotes === true) {
- push({ type: 'text', value });
- }
- continue;
- }
-
- /**
- * Parentheses
- */
-
- if (value === '(') {
- increment('parens');
- push({ type: 'paren', value });
- continue;
- }
-
- if (value === ')') {
- if (state.parens === 0 && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '('));
- }
-
- const extglob = extglobs[extglobs.length - 1];
- if (extglob && state.parens === extglob.parens + 1) {
- extglobClose(extglobs.pop());
- continue;
- }
-
- push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
- decrement('parens');
- continue;
- }
-
- /**
- * Square brackets
- */
-
- if (value === '[') {
- if (opts.nobracket === true || !remaining().includes(']')) {
- if (opts.nobracket !== true && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('closing', ']'));
- }
-
- value = `\\${value}`;
- } else {
- increment('brackets');
- }
-
- push({ type: 'bracket', value });
- continue;
- }
-
- if (value === ']') {
- if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
- push({ type: 'text', value, output: `\\${value}` });
- continue;
- }
-
- if (state.brackets === 0) {
- if (opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError('opening', '['));
- }
-
- push({ type: 'text', value, output: `\\${value}` });
- continue;
- }
-
- decrement('brackets');
-
- const prevValue = prev.value.slice(1);
- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
- value = `/${value}`;
- }
-
- prev.value += value;
- append({ value });
-
- // when literal brackets are explicitly disabled
- // assume we should match with a regex character class
- if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
- continue;
- }
-
- const escaped = utils.escapeRegex(prev.value);
- state.output = state.output.slice(0, -prev.value.length);
-
- // when literal brackets are explicitly enabled
- // assume we should escape the brackets to match literal characters
- if (opts.literalBrackets === true) {
- state.output += escaped;
- prev.value = escaped;
- continue;
- }
-
- // when the user specifies nothing, try to match both
- prev.value = `(${capture}${escaped}|${prev.value})`;
- state.output += prev.value;
- continue;
- }
-
- /**
- * Braces
- */
-
- if (value === '{' && opts.nobrace !== true) {
- increment('braces');
-
- const open = {
- type: 'brace',
- value,
- output: '(',
- outputIndex: state.output.length,
- tokensIndex: state.tokens.length
- };
-
- braces.push(open);
- push(open);
- continue;
- }
-
- if (value === '}') {
- const brace = braces[braces.length - 1];
-
- if (opts.nobrace === true || !brace) {
- push({ type: 'text', value, output: value });
- continue;
- }
-
- let output = ')';
-
- if (brace.dots === true) {
- const arr = tokens.slice();
- const range = [];
-
- for (let i = arr.length - 1; i >= 0; i--) {
- tokens.pop();
- if (arr[i].type === 'brace') {
- break;
- }
- if (arr[i].type !== 'dots') {
- range.unshift(arr[i].value);
- }
- }
-
- output = expandRange(range, opts);
- state.backtrack = true;
- }
-
- if (brace.comma !== true && brace.dots !== true) {
- const out = state.output.slice(0, brace.outputIndex);
- const toks = state.tokens.slice(brace.tokensIndex);
- brace.value = brace.output = '\\{';
- value = output = '\\}';
- state.output = out;
- for (const t of toks) {
- state.output += (t.output || t.value);
- }
- }
-
- push({ type: 'brace', value, output });
- decrement('braces');
- braces.pop();
- continue;
- }
-
- /**
- * Pipes
- */
-
- if (value === '|') {
- if (extglobs.length > 0) {
- extglobs[extglobs.length - 1].conditions++;
- }
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Commas
- */
-
- if (value === ',') {
- let output = value;
-
- const brace = braces[braces.length - 1];
- if (brace && stack[stack.length - 1] === 'braces') {
- brace.comma = true;
- output = '|';
- }
-
- push({ type: 'comma', value, output });
- continue;
- }
-
- /**
- * Slashes
- */
-
- if (value === '/') {
- // if the beginning of the glob is "./", advance the start
- // to the current index, and don't add the "./" characters
- // to the state. This greatly simplifies lookbehinds when
- // checking for BOS characters like "!" and "." (not "./")
- if (prev.type === 'dot' && state.index === state.start + 1) {
- state.start = state.index + 1;
- state.consumed = '';
- state.output = '';
- tokens.pop();
- prev = bos; // reset "prev" to the first token
- continue;
- }
-
- push({ type: 'slash', value, output: SLASH_LITERAL });
- continue;
- }
-
- /**
- * Dots
- */
-
- if (value === '.') {
- if (state.braces > 0 && prev.type === 'dot') {
- if (prev.value === '.') prev.output = DOT_LITERAL;
- const brace = braces[braces.length - 1];
- prev.type = 'dots';
- prev.output += value;
- prev.value += value;
- brace.dots = true;
- continue;
- }
-
- if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
- push({ type: 'text', value, output: DOT_LITERAL });
- continue;
- }
-
- push({ type: 'dot', value, output: DOT_LITERAL });
- continue;
- }
-
- /**
- * Question marks
- */
-
- if (value === '?') {
- const isGroup = prev && prev.value === '(';
- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('qmark', value);
- continue;
- }
-
- if (prev && prev.type === 'paren') {
- const next = peek();
- let output = value;
-
- if (next === '<' && !utils.supportsLookbehinds()) {
- throw new Error('Node.js v10 or higher is required for regex lookbehinds');
- }
-
- if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
- output = `\\${value}`;
- }
-
- push({ type: 'text', value, output });
- continue;
- }
-
- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
- push({ type: 'qmark', value, output: QMARK_NO_DOT });
- continue;
- }
-
- push({ type: 'qmark', value, output: QMARK });
- continue;
- }
-
- /**
- * Exclamation
- */
-
- if (value === '!') {
- if (opts.noextglob !== true && peek() === '(') {
- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
- extglobOpen('negate', value);
- continue;
- }
- }
-
- if (opts.nonegate !== true && state.index === 0) {
- negate();
- continue;
- }
- }
-
- /**
- * Plus
- */
-
- if (value === '+') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('plus', value);
- continue;
- }
-
- if ((prev && prev.value === '(') || opts.regex === false) {
- push({ type: 'plus', value, output: PLUS_LITERAL });
- continue;
- }
-
- if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
- push({ type: 'plus', value });
- continue;
- }
-
- push({ type: 'plus', value: PLUS_LITERAL });
- continue;
- }
-
- /**
- * Plain text
- */
-
- if (value === '@') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- push({ type: 'at', extglob: true, value, output: '' });
- continue;
- }
-
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Plain text
- */
-
- if (value !== '*') {
- if (value === '$' || value === '^') {
- value = `\\${value}`;
- }
-
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
- if (match) {
- value += match[0];
- state.index += match[0].length;
- }
-
- push({ type: 'text', value });
- continue;
- }
-
- /**
- * Stars
- */
-
- if (prev && (prev.type === 'globstar' || prev.star === true)) {
- prev.type = 'star';
- prev.star = true;
- prev.value += value;
- prev.output = star;
- state.backtrack = true;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- let rest = remaining();
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
- extglobOpen('star', value);
- continue;
- }
-
- if (prev.type === 'star') {
- if (opts.noglobstar === true) {
- consume(value);
- continue;
- }
-
- const prior = prev.prev;
- const before = prior.prev;
- const isStart = prior.type === 'slash' || prior.type === 'bos';
- const afterStar = before && (before.type === 'star' || before.type === 'globstar');
-
- if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
- push({ type: 'star', value, output: '' });
- continue;
- }
-
- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
- push({ type: 'star', value, output: '' });
- continue;
- }
-
- // strip consecutive `/**/`
- while (rest.slice(0, 3) === '/**') {
- const after = input[state.index + 4];
- if (after && after !== '/') {
- break;
- }
- rest = rest.slice(3);
- consume('/**', 3);
- }
-
- if (prior.type === 'bos' && eos()) {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = globstar(opts);
- state.output = prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
-
- prev.type = 'globstar';
- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
- prev.value += value;
- state.globstar = true;
- state.output += prior.output + prev.output;
- consume(value);
- continue;
- }
-
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
- const end = rest[1] !== void 0 ? '|$' : '';
-
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
-
- prev.type = 'globstar';
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
- prev.value += value;
-
- state.output += prior.output + prev.output;
- state.globstar = true;
-
- consume(value + advance());
-
- push({ type: 'slash', value: '/', output: '' });
- continue;
- }
-
- if (prior.type === 'bos' && rest[0] === '/') {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
- state.output = prev.output;
- state.globstar = true;
- consume(value + advance());
- push({ type: 'slash', value: '/', output: '' });
- continue;
- }
-
- // remove single star from output
- state.output = state.output.slice(0, -prev.output.length);
-
- // reset previous token to globstar
- prev.type = 'globstar';
- prev.output = globstar(opts);
- prev.value += value;
-
- // reset output with globstar
- state.output += prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
-
- const token = { type: 'star', value, output: star };
-
- if (opts.bash === true) {
- token.output = '.*?';
- if (prev.type === 'bos' || prev.type === 'slash') {
- token.output = nodot + token.output;
- }
- push(token);
- continue;
- }
-
- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
- token.output = value;
- push(token);
- continue;
- }
-
- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
- if (prev.type === 'dot') {
- state.output += NO_DOT_SLASH;
- prev.output += NO_DOT_SLASH;
-
- } else if (opts.dot === true) {
- state.output += NO_DOTS_SLASH;
- prev.output += NO_DOTS_SLASH;
-
- } else {
- state.output += nodot;
- prev.output += nodot;
- }
-
- if (peek() !== '*') {
- state.output += ONE_CHAR;
- prev.output += ONE_CHAR;
- }
- }
-
- push(token);
- }
-
- while (state.brackets > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
- state.output = utils.escapeLast(state.output, '[');
- decrement('brackets');
- }
-
- while (state.parens > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
- state.output = utils.escapeLast(state.output, '(');
- decrement('parens');
- }
-
- while (state.braces > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
- state.output = utils.escapeLast(state.output, '{');
- decrement('braces');
- }
-
- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
- push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
- }
-
- // rebuild the output if we had to backtrack at any point
- if (state.backtrack === true) {
- state.output = '';
-
- for (const token of state.tokens) {
- state.output += token.output != null ? token.output : token.value;
-
- if (token.suffix) {
- state.output += token.suffix;
- }
- }
- }
-
- return state;
-};
-
-/**
- * Fast paths for creating regular expressions for common glob patterns.
- * This can significantly speed up processing and has very little downside
- * impact when none of the fast paths match.
- */
-
-parse.fastpaths = (input, options) => {
- const opts = { ...options };
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- const len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
-
- input = REPLACEMENTS[input] || input;
- const win32 = utils.isWindows(options);
-
- // create constants based on platform, for windows or posix
- const {
- DOT_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOTS_SLASH,
- STAR,
- START_ANCHOR
- } = constants.globChars(win32);
-
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
- const capture = opts.capture ? '' : '?:';
- const state = { negated: false, prefix: '' };
- let star = opts.bash === true ? '.*?' : STAR;
-
- if (opts.capture) {
- star = `(${star})`;
- }
-
- const globstar = opts => {
- if (opts.noglobstar === true) return star;
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
-
- const create = str => {
- switch (str) {
- case '*':
- return `${nodot}${ONE_CHAR}${star}`;
-
- case '.*':
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '*.*':
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '*/*':
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
-
- case '**':
- return nodot + globstar(opts);
-
- case '**/*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
-
- case '**/*.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- case '**/.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
-
- default: {
- const match = /^(.*?)\.(\w+)$/.exec(str);
- if (!match) return;
-
- const source = create(match[1]);
- if (!source) return;
-
- return source + DOT_LITERAL + match[2];
- }
- }
- };
-
- const output = utils.removePrefix(input, state);
- let source = create(output);
-
- if (source && opts.strictSlashes !== true) {
- source += `${SLASH_LITERAL}?`;
- }
-
- return source;
-};
-
-module.exports = parse;
-
-
-/***/ }),
-
-/***/ 33322:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const path = __nccwpck_require__(71017);
-const scan = __nccwpck_require__(32429);
-const parse = __nccwpck_require__(92139);
-const utils = __nccwpck_require__(30479);
-const constants = __nccwpck_require__(16099);
-const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
-
-/**
- * Creates a matcher function from one or more glob patterns. The
- * returned function takes a string to match as its first argument,
- * and returns true if the string is a match. The returned matcher
- * function also takes a boolean as the second argument that, when true,
- * returns an object with additional information.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch(glob[, options]);
- *
- * const isMatch = picomatch('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @name picomatch
- * @param {String|Array} `globs` One or more glob patterns.
- * @param {Object=} `options`
- * @return {Function=} Returns a matcher function.
- * @api public
- */
-
-const picomatch = (glob, options, returnState = false) => {
- if (Array.isArray(glob)) {
- const fns = glob.map(input => picomatch(input, options, returnState));
- const arrayMatcher = str => {
- for (const isMatch of fns) {
- const state = isMatch(str);
- if (state) return state;
- }
- return false;
- };
- return arrayMatcher;
- }
-
- const isState = isObject(glob) && glob.tokens && glob.input;
-
- if (glob === '' || (typeof glob !== 'string' && !isState)) {
- throw new TypeError('Expected pattern to be a non-empty string');
- }
-
- const opts = options || {};
- const posix = utils.isWindows(options);
- const regex = isState
- ? picomatch.compileRe(glob, options)
- : picomatch.makeRe(glob, options, false, true);
-
- const state = regex.state;
- delete regex.state;
-
- let isIgnored = () => false;
- if (opts.ignore) {
- const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
- }
-
- const matcher = (input, returnObject = false) => {
- const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
- const result = { glob, state, regex, posix, input, output, match, isMatch };
-
- if (typeof opts.onResult === 'function') {
- opts.onResult(result);
- }
-
- if (isMatch === false) {
- result.isMatch = false;
- return returnObject ? result : false;
- }
-
- if (isIgnored(input)) {
- if (typeof opts.onIgnore === 'function') {
- opts.onIgnore(result);
- }
- result.isMatch = false;
- return returnObject ? result : false;
- }
-
- if (typeof opts.onMatch === 'function') {
- opts.onMatch(result);
- }
- return returnObject ? result : true;
- };
-
- if (returnState) {
- matcher.state = state;
- }
-
- return matcher;
-};
-
-/**
- * Test `input` with the given `regex`. This is used by the main
- * `picomatch()` function to test the input string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.test(input, regex[, options]);
- *
- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp} `regex`
- * @return {Object} Returns an object with matching info.
- * @api public
- */
-
-picomatch.test = (input, regex, options, { glob, posix } = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected input to be a string');
- }
-
- if (input === '') {
- return { isMatch: false, output: '' };
- }
-
- const opts = options || {};
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
- let match = input === glob;
- let output = (match && format) ? format(input) : input;
-
- if (match === false) {
- output = format ? format(input) : input;
- match = output === glob;
- }
-
- if (match === false || opts.capture === true) {
- if (opts.matchBase === true || opts.basename === true) {
- match = picomatch.matchBase(input, regex, options, posix);
- } else {
- match = regex.exec(output);
- }
- }
-
- return { isMatch: Boolean(match), match, output };
-};
-
-/**
- * Match the basename of a filepath.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.matchBase(input, glob[, options]);
- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
- * @return {Boolean}
- * @api public
- */
-
-picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
- return regex.test(path.basename(input));
-};
-
-/**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.isMatch(string, patterns[, options]);
- *
- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String|Array} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
-
-picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
-
-/**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const result = picomatch.parse(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
- * @api public
- */
-
-picomatch.parse = (pattern, options) => {
- if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
- return parse(pattern, { ...options, fastpaths: false });
-};
-
-/**
- * Scan a glob pattern to separate the pattern into segments.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.scan(input[, options]);
- *
- * const result = picomatch.scan('!./foo/*.js');
- * console.log(result);
- * { prefix: '!./',
- * input: '!./foo/*.js',
- * start: 3,
- * base: 'foo',
- * glob: '*.js',
- * isBrace: false,
- * isBracket: false,
- * isGlob: true,
- * isExtglob: false,
- * isGlobstar: false,
- * negated: true }
- * ```
- * @param {String} `input` Glob pattern to scan.
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
- */
-
-picomatch.scan = (input, options) => scan(input, options);
-
-/**
- * Compile a regular expression from the `state` object returned by the
- * [parse()](#parse) method.
- *
- * @param {Object} `state`
- * @param {Object} `options`
- * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
- * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
- * @return {RegExp}
- * @api public
- */
-
-picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
- if (returnOutput === true) {
- return state.output;
- }
-
- const opts = options || {};
- const prepend = opts.contains ? '' : '^';
- const append = opts.contains ? '' : '$';
-
- let source = `${prepend}(?:${state.output})${append}`;
- if (state && state.negated === true) {
- source = `^(?!${source}).*$`;
- }
-
- const regex = picomatch.toRegex(source, options);
- if (returnState === true) {
- regex.state = state;
- }
-
- return regex;
-};
-
-/**
- * Create a regular expression from a parsed glob pattern.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const state = picomatch.parse('*.js');
- * // picomatch.compileRe(state[, options]);
- *
- * console.log(picomatch.compileRe(state));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `state` The object returned from the `.parse` method.
- * @param {Object} `options`
- * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
- * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
-
-picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
- if (!input || typeof input !== 'string') {
- throw new TypeError('Expected a non-empty string');
- }
-
- let parsed = { negated: false, fastpaths: true };
-
- if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
- parsed.output = parse.fastpaths(input, options);
- }
-
- if (!parsed.output) {
- parsed = parse(input, options);
- }
-
- return picomatch.compileRe(parsed, options, returnOutput, returnState);
-};
-
-/**
- * Create a regular expression from the given regex source string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.toRegex(source[, options]);
- *
- * const { output } = picomatch.parse('*.js');
- * console.log(picomatch.toRegex(output));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `source` Regular expression source string.
- * @param {Object} `options`
- * @return {RegExp}
- * @api public
- */
-
-picomatch.toRegex = (source, options) => {
- try {
- const opts = options || {};
- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
- } catch (err) {
- if (options && options.debug === true) throw err;
- return /$^/;
- }
-};
-
-/**
- * Picomatch constants.
- * @return {Object}
- */
-
-picomatch.constants = constants;
-
-/**
- * Expose "picomatch"
- */
-
-module.exports = picomatch;
-
-
-/***/ }),
-
-/***/ 32429:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const utils = __nccwpck_require__(30479);
-const {
- CHAR_ASTERISK, /* * */
- CHAR_AT, /* @ */
- CHAR_BACKWARD_SLASH, /* \ */
- CHAR_COMMA, /* , */
- CHAR_DOT, /* . */
- CHAR_EXCLAMATION_MARK, /* ! */
- CHAR_FORWARD_SLASH, /* / */
- CHAR_LEFT_CURLY_BRACE, /* { */
- CHAR_LEFT_PARENTHESES, /* ( */
- CHAR_LEFT_SQUARE_BRACKET, /* [ */
- CHAR_PLUS, /* + */
- CHAR_QUESTION_MARK, /* ? */
- CHAR_RIGHT_CURLY_BRACE, /* } */
- CHAR_RIGHT_PARENTHESES, /* ) */
- CHAR_RIGHT_SQUARE_BRACKET /* ] */
-} = __nccwpck_require__(16099);
-
-const isPathSeparator = code => {
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
-};
-
-const depth = token => {
- if (token.isPrefix !== true) {
- token.depth = token.isGlobstar ? Infinity : 1;
- }
-};
-
-/**
- * Quickly scans a glob pattern and returns an object with a handful of
- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
- * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
- * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
- *
- * ```js
- * const pm = require('picomatch');
- * console.log(pm.scan('foo/bar/*.js'));
- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {Object} Returns an object with tokens and regex source string.
- * @api public
- */
-
-const scan = (input, options) => {
- const opts = options || {};
-
- const length = input.length - 1;
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
- const slashes = [];
- const tokens = [];
- const parts = [];
-
- let str = input;
- let index = -1;
- let start = 0;
- let lastIndex = 0;
- let isBrace = false;
- let isBracket = false;
- let isGlob = false;
- let isExtglob = false;
- let isGlobstar = false;
- let braceEscaped = false;
- let backslashes = false;
- let negated = false;
- let negatedExtglob = false;
- let finished = false;
- let braces = 0;
- let prev;
- let code;
- let token = { value: '', depth: 0, isGlob: false };
-
- const eos = () => index >= length;
- const peek = () => str.charCodeAt(index + 1);
- const advance = () => {
- prev = code;
- return str.charCodeAt(++index);
- };
-
- while (index < length) {
- code = advance();
- let next;
-
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
-
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braceEscaped = true;
- }
- continue;
- }
-
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
-
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
-
- if (code === CHAR_LEFT_CURLY_BRACE) {
- braces++;
- continue;
- }
-
- if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (braceEscaped !== true && code === CHAR_COMMA) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (code === CHAR_RIGHT_CURLY_BRACE) {
- braces--;
-
- if (braces === 0) {
- braceEscaped = false;
- isBrace = token.isBrace = true;
- finished = true;
- break;
- }
- }
- }
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (code === CHAR_FORWARD_SLASH) {
- slashes.push(index);
- tokens.push(token);
- token = { value: '', depth: 0, isGlob: false };
-
- if (finished === true) continue;
- if (prev === CHAR_DOT && index === (start + 1)) {
- start += 2;
- continue;
- }
-
- lastIndex = index + 1;
- continue;
- }
-
- if (opts.noext !== true) {
- const isExtglobChar = code === CHAR_PLUS
- || code === CHAR_AT
- || code === CHAR_ASTERISK
- || code === CHAR_QUESTION_MARK
- || code === CHAR_EXCLAMATION_MARK;
-
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
- isExtglob = token.isExtglob = true;
- finished = true;
- if (code === CHAR_EXCLAMATION_MARK && index === start) {
- negatedExtglob = true;
- }
-
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
-
- if (code === CHAR_RIGHT_PARENTHESES) {
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- }
-
- if (code === CHAR_ASTERISK) {
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
-
- if (code === CHAR_QUESTION_MARK) {
- isGlob = token.isGlob = true;
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
-
- if (code === CHAR_LEFT_SQUARE_BRACKET) {
- while (eos() !== true && (next = advance())) {
- if (next === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
-
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- isBracket = token.isBracket = true;
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
-
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
- negated = token.negated = true;
- start++;
- continue;
- }
-
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
- isGlob = token.isGlob = true;
-
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_LEFT_PARENTHESES) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
-
- if (code === CHAR_RIGHT_PARENTHESES) {
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
-
- if (isGlob === true) {
- finished = true;
-
- if (scanToEnd === true) {
- continue;
- }
-
- break;
- }
- }
-
- if (opts.noext === true) {
- isExtglob = false;
- isGlob = false;
- }
-
- let base = str;
- let prefix = '';
- let glob = '';
-
- if (start > 0) {
- prefix = str.slice(0, start);
- str = str.slice(start);
- lastIndex -= start;
- }
-
- if (base && isGlob === true && lastIndex > 0) {
- base = str.slice(0, lastIndex);
- glob = str.slice(lastIndex);
- } else if (isGlob === true) {
- base = '';
- glob = str;
- } else {
- base = str;
- }
-
- if (base && base !== '' && base !== '/' && base !== str) {
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
- base = base.slice(0, -1);
- }
- }
-
- if (opts.unescape === true) {
- if (glob) glob = utils.removeBackslashes(glob);
-
- if (base && backslashes === true) {
- base = utils.removeBackslashes(base);
- }
- }
-
- const state = {
- prefix,
- input,
- start,
- base,
- glob,
- isBrace,
- isBracket,
- isGlob,
- isExtglob,
- isGlobstar,
- negated,
- negatedExtglob
- };
-
- if (opts.tokens === true) {
- state.maxDepth = 0;
- if (!isPathSeparator(code)) {
- tokens.push(token);
- }
- state.tokens = tokens;
- }
-
- if (opts.parts === true || opts.tokens === true) {
- let prevIndex;
-
- for (let idx = 0; idx < slashes.length; idx++) {
- const n = prevIndex ? prevIndex + 1 : start;
- const i = slashes[idx];
- const value = input.slice(n, i);
- if (opts.tokens) {
- if (idx === 0 && start !== 0) {
- tokens[idx].isPrefix = true;
- tokens[idx].value = prefix;
- } else {
- tokens[idx].value = value;
- }
- depth(tokens[idx]);
- state.maxDepth += tokens[idx].depth;
- }
- if (idx !== 0 || value !== '') {
- parts.push(value);
- }
- prevIndex = i;
- }
-
- if (prevIndex && prevIndex + 1 < input.length) {
- const value = input.slice(prevIndex + 1);
- parts.push(value);
-
- if (opts.tokens) {
- tokens[tokens.length - 1].value = value;
- depth(tokens[tokens.length - 1]);
- state.maxDepth += tokens[tokens.length - 1].depth;
- }
- }
-
- state.slashes = slashes;
- state.parts = parts;
- }
-
- return state;
-};
-
-module.exports = scan;
-
-
-/***/ }),
-
-/***/ 30479:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-const path = __nccwpck_require__(71017);
-const win32 = process.platform === 'win32';
-const {
- REGEX_BACKSLASH,
- REGEX_REMOVE_BACKSLASH,
- REGEX_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_GLOBAL
-} = __nccwpck_require__(16099);
-
-exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
-exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
-exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
-exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
-exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
-
-exports.removeBackslashes = str => {
- return str.replace(REGEX_REMOVE_BACKSLASH, match => {
- return match === '\\' ? '' : match;
- });
-};
-
-exports.supportsLookbehinds = () => {
- const segs = process.version.slice(1).split('.').map(Number);
- if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
- return true;
- }
- return false;
-};
-
-exports.isWindows = options => {
- if (options && typeof options.windows === 'boolean') {
- return options.windows;
- }
- return win32 === true || path.sep === '\\';
-};
-
-exports.escapeLast = (input, char, lastIdx) => {
- const idx = input.lastIndexOf(char, lastIdx);
- if (idx === -1) return input;
- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
-};
-
-exports.removePrefix = (input, state = {}) => {
- let output = input;
- if (output.startsWith('./')) {
- output = output.slice(2);
- state.prefix = './';
- }
- return output;
-};
-
-exports.wrapOutput = (input, state = {}, options = {}) => {
- const prepend = options.contains ? '' : '^';
- const append = options.contains ? '' : '$';
-
- let output = `${prepend}(?:${input})${append}`;
- if (state.negated === true) {
- output = `(?:^(?!${output}).*$)`;
- }
- return output;
-};
-
-
-/***/ }),
-
-/***/ 47096:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-module.exports = __nccwpck_require__(15836)
-
-
-/***/ }),
-
-/***/ 48874:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var asap = __nccwpck_require__(83691);
-
-function noop() {}
-
-// States:
-//
-// 0 - pending
-// 1 - fulfilled with _value
-// 2 - rejected with _value
-// 3 - adopted the state of another promise, _value
-//
-// once the state is no longer pending (0) it is immutable
-
-// All `_` prefixed properties will be reduced to `_{random number}`
-// at build time to obfuscate them and discourage their use.
-// We don't use symbols or Object.defineProperty to fully hide them
-// because the performance isn't good enough.
-
-
-// to avoid using try/catch inside critical functions, we
-// extract them to here.
-var LAST_ERROR = null;
-var IS_ERROR = {};
-function getThen(obj) {
- try {
- return obj.then;
- } catch (ex) {
- LAST_ERROR = ex;
- return IS_ERROR;
- }
-}
-
-function tryCallOne(fn, a) {
- try {
- return fn(a);
- } catch (ex) {
- LAST_ERROR = ex;
- return IS_ERROR;
- }
-}
-function tryCallTwo(fn, a, b) {
- try {
- fn(a, b);
- } catch (ex) {
- LAST_ERROR = ex;
- return IS_ERROR;
- }
-}
-
-module.exports = Promise;
-
-function Promise(fn) {
- if (typeof this !== 'object') {
- throw new TypeError('Promises must be constructed via new');
- }
- if (typeof fn !== 'function') {
- throw new TypeError('Promise constructor\'s argument is not a function');
- }
- this._40 = 0;
- this._65 = 0;
- this._55 = null;
- this._72 = null;
- if (fn === noop) return;
- doResolve(fn, this);
-}
-Promise._37 = null;
-Promise._87 = null;
-Promise._61 = noop;
-
-Promise.prototype.then = function(onFulfilled, onRejected) {
- if (this.constructor !== Promise) {
- return safeThen(this, onFulfilled, onRejected);
- }
- var res = new Promise(noop);
- handle(this, new Handler(onFulfilled, onRejected, res));
- return res;
-};
-
-function safeThen(self, onFulfilled, onRejected) {
- return new self.constructor(function (resolve, reject) {
- var res = new Promise(noop);
- res.then(resolve, reject);
- handle(self, new Handler(onFulfilled, onRejected, res));
- });
-}
-function handle(self, deferred) {
- while (self._65 === 3) {
- self = self._55;
- }
- if (Promise._37) {
- Promise._37(self);
- }
- if (self._65 === 0) {
- if (self._40 === 0) {
- self._40 = 1;
- self._72 = deferred;
- return;
- }
- if (self._40 === 1) {
- self._40 = 2;
- self._72 = [self._72, deferred];
- return;
- }
- self._72.push(deferred);
- return;
- }
- handleResolved(self, deferred);
-}
-
-function handleResolved(self, deferred) {
- asap(function() {
- var cb = self._65 === 1 ? deferred.onFulfilled : deferred.onRejected;
- if (cb === null) {
- if (self._65 === 1) {
- resolve(deferred.promise, self._55);
- } else {
- reject(deferred.promise, self._55);
- }
- return;
- }
- var ret = tryCallOne(cb, self._55);
- if (ret === IS_ERROR) {
- reject(deferred.promise, LAST_ERROR);
- } else {
- resolve(deferred.promise, ret);
- }
- });
-}
-function resolve(self, newValue) {
- // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
- if (newValue === self) {
- return reject(
- self,
- new TypeError('A promise cannot be resolved with itself.')
- );
- }
- if (
- newValue &&
- (typeof newValue === 'object' || typeof newValue === 'function')
- ) {
- var then = getThen(newValue);
- if (then === IS_ERROR) {
- return reject(self, LAST_ERROR);
- }
- if (
- then === self.then &&
- newValue instanceof Promise
- ) {
- self._65 = 3;
- self._55 = newValue;
- finale(self);
- return;
- } else if (typeof then === 'function') {
- doResolve(then.bind(newValue), self);
- return;
- }
- }
- self._65 = 1;
- self._55 = newValue;
- finale(self);
-}
-
-function reject(self, newValue) {
- self._65 = 2;
- self._55 = newValue;
- if (Promise._87) {
- Promise._87(self, newValue);
- }
- finale(self);
-}
-function finale(self) {
- if (self._40 === 1) {
- handle(self, self._72);
- self._72 = null;
- }
- if (self._40 === 2) {
- for (var i = 0; i < self._72.length; i++) {
- handle(self, self._72[i]);
- }
- self._72 = null;
- }
-}
-
-function Handler(onFulfilled, onRejected, promise){
- this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
- this.onRejected = typeof onRejected === 'function' ? onRejected : null;
- this.promise = promise;
-}
-
-/**
- * Take a potentially misbehaving resolver function and make sure
- * onFulfilled and onRejected are only called once.
- *
- * Makes no guarantees about asynchrony.
- */
-function doResolve(fn, promise) {
- var done = false;
- var res = tryCallTwo(fn, function (value) {
- if (done) return;
- done = true;
- resolve(promise, value);
- }, function (reason) {
- if (done) return;
- done = true;
- reject(promise, reason);
- });
- if (!done && res === IS_ERROR) {
- done = true;
- reject(promise, LAST_ERROR);
- }
-}
-
-
-/***/ }),
-
-/***/ 85222:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var Promise = __nccwpck_require__(48874);
-
-module.exports = Promise;
-Promise.prototype.done = function (onFulfilled, onRejected) {
- var self = arguments.length ? this.then.apply(this, arguments) : this;
- self.then(null, function (err) {
- setTimeout(function () {
- throw err;
- }, 0);
- });
-};
-
-
-/***/ }),
-
-/***/ 47492:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-//This file contains the ES6 extensions to the core Promises/A+ API
-
-var Promise = __nccwpck_require__(48874);
-
-module.exports = Promise;
-
-/* Static Functions */
-
-var TRUE = valuePromise(true);
-var FALSE = valuePromise(false);
-var NULL = valuePromise(null);
-var UNDEFINED = valuePromise(undefined);
-var ZERO = valuePromise(0);
-var EMPTYSTRING = valuePromise('');
-
-function valuePromise(value) {
- var p = new Promise(Promise._61);
- p._65 = 1;
- p._55 = value;
- return p;
-}
-Promise.resolve = function (value) {
- if (value instanceof Promise) return value;
-
- if (value === null) return NULL;
- if (value === undefined) return UNDEFINED;
- if (value === true) return TRUE;
- if (value === false) return FALSE;
- if (value === 0) return ZERO;
- if (value === '') return EMPTYSTRING;
-
- if (typeof value === 'object' || typeof value === 'function') {
- try {
- var then = value.then;
- if (typeof then === 'function') {
- return new Promise(then.bind(value));
- }
- } catch (ex) {
- return new Promise(function (resolve, reject) {
- reject(ex);
- });
- }
- }
- return valuePromise(value);
-};
-
-Promise.all = function (arr) {
- var args = Array.prototype.slice.call(arr);
-
- return new Promise(function (resolve, reject) {
- if (args.length === 0) return resolve([]);
- var remaining = args.length;
- function res(i, val) {
- if (val && (typeof val === 'object' || typeof val === 'function')) {
- if (val instanceof Promise && val.then === Promise.prototype.then) {
- while (val._65 === 3) {
- val = val._55;
- }
- if (val._65 === 1) return res(i, val._55);
- if (val._65 === 2) reject(val._55);
- val.then(function (val) {
- res(i, val);
- }, reject);
- return;
- } else {
- var then = val.then;
- if (typeof then === 'function') {
- var p = new Promise(then.bind(val));
- p.then(function (val) {
- res(i, val);
- }, reject);
- return;
- }
- }
- }
- args[i] = val;
- if (--remaining === 0) {
- resolve(args);
- }
- }
- for (var i = 0; i < args.length; i++) {
- res(i, args[i]);
- }
- });
-};
-
-Promise.reject = function (value) {
- return new Promise(function (resolve, reject) {
- reject(value);
- });
-};
-
-Promise.race = function (values) {
- return new Promise(function (resolve, reject) {
- values.forEach(function(value){
- Promise.resolve(value).then(resolve, reject);
- });
- });
-};
-
-/* Prototype Methods */
-
-Promise.prototype['catch'] = function (onRejected) {
- return this.then(null, onRejected);
-};
-
-
-/***/ }),
-
-/***/ 93963:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var Promise = __nccwpck_require__(48874);
-
-module.exports = Promise;
-Promise.prototype['finally'] = function (f) {
- return this.then(function (value) {
- return Promise.resolve(f()).then(function () {
- return value;
- });
- }, function (err) {
- return Promise.resolve(f()).then(function () {
- throw err;
- });
- });
-};
-
-
-/***/ }),
-
-/***/ 15836:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-module.exports = __nccwpck_require__(48874);
-__nccwpck_require__(85222);
-__nccwpck_require__(93963);
-__nccwpck_require__(47492);
-__nccwpck_require__(92090);
-__nccwpck_require__(72995);
-
-
-/***/ }),
-
-/***/ 92090:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-// This file contains then/promise specific extensions that are only useful
-// for node.js interop
-
-var Promise = __nccwpck_require__(48874);
-var asap = __nccwpck_require__(87943);
-
-module.exports = Promise;
-
-/* Static Functions */
-
-Promise.denodeify = function (fn, argumentCount) {
- if (
- typeof argumentCount === 'number' && argumentCount !== Infinity
- ) {
- return denodeifyWithCount(fn, argumentCount);
- } else {
- return denodeifyWithoutCount(fn);
- }
-};
-
-var callbackFn = (
- 'function (err, res) {' +
- 'if (err) { rj(err); } else { rs(res); }' +
- '}'
-);
-function denodeifyWithCount(fn, argumentCount) {
- var args = [];
- for (var i = 0; i < argumentCount; i++) {
- args.push('a' + i);
- }
- var body = [
- 'return function (' + args.join(',') + ') {',
- 'var self = this;',
- 'return new Promise(function (rs, rj) {',
- 'var res = fn.call(',
- ['self'].concat(args).concat([callbackFn]).join(','),
- ');',
- 'if (res &&',
- '(typeof res === "object" || typeof res === "function") &&',
- 'typeof res.then === "function"',
- ') {rs(res);}',
- '});',
- '};'
- ].join('');
- return Function(['Promise', 'fn'], body)(Promise, fn);
-}
-function denodeifyWithoutCount(fn) {
- var fnLength = Math.max(fn.length - 1, 3);
- var args = [];
- for (var i = 0; i < fnLength; i++) {
- args.push('a' + i);
- }
- var body = [
- 'return function (' + args.join(',') + ') {',
- 'var self = this;',
- 'var args;',
- 'var argLength = arguments.length;',
- 'if (arguments.length > ' + fnLength + ') {',
- 'args = new Array(arguments.length + 1);',
- 'for (var i = 0; i < arguments.length; i++) {',
- 'args[i] = arguments[i];',
- '}',
- '}',
- 'return new Promise(function (rs, rj) {',
- 'var cb = ' + callbackFn + ';',
- 'var res;',
- 'switch (argLength) {',
- args.concat(['extra']).map(function (_, index) {
- return (
- 'case ' + (index) + ':' +
- 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' +
- 'break;'
- );
- }).join(''),
- 'default:',
- 'args[argLength] = cb;',
- 'res = fn.apply(self, args);',
- '}',
-
- 'if (res &&',
- '(typeof res === "object" || typeof res === "function") &&',
- 'typeof res.then === "function"',
- ') {rs(res);}',
- '});',
- '};'
- ].join('');
-
- return Function(
- ['Promise', 'fn'],
- body
- )(Promise, fn);
-}
-
-Promise.nodeify = function (fn) {
- return function () {
- var args = Array.prototype.slice.call(arguments);
- var callback =
- typeof args[args.length - 1] === 'function' ? args.pop() : null;
- var ctx = this;
- try {
- return fn.apply(this, arguments).nodeify(callback, ctx);
- } catch (ex) {
- if (callback === null || typeof callback == 'undefined') {
- return new Promise(function (resolve, reject) {
- reject(ex);
- });
- } else {
- asap(function () {
- callback.call(ctx, ex);
- })
- }
- }
- }
-};
-
-Promise.prototype.nodeify = function (callback, ctx) {
- if (typeof callback != 'function') return this;
-
- this.then(function (value) {
- asap(function () {
- callback.call(ctx, null, value);
- });
- }, function (err) {
- asap(function () {
- callback.call(ctx, err);
- });
- });
-};
-
-
-/***/ }),
-
-/***/ 72995:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var Promise = __nccwpck_require__(48874);
-
-module.exports = Promise;
-Promise.enableSynchronous = function () {
- Promise.prototype.isPending = function() {
- return this.getState() == 0;
- };
-
- Promise.prototype.isFulfilled = function() {
- return this.getState() == 1;
- };
-
- Promise.prototype.isRejected = function() {
- return this.getState() == 2;
- };
-
- Promise.prototype.getValue = function () {
- if (this._65 === 3) {
- return this._55.getValue();
- }
-
- if (!this.isFulfilled()) {
- throw new Error('Cannot get a value of an unfulfilled promise.');
- }
-
- return this._55;
- };
-
- Promise.prototype.getReason = function () {
- if (this._65 === 3) {
- return this._55.getReason();
- }
-
- if (!this.isRejected()) {
- throw new Error('Cannot get a rejection reason of a non-rejected promise.');
- }
-
- return this._55;
- };
-
- Promise.prototype.getState = function () {
- if (this._65 === 3) {
- return this._55.getState();
- }
- if (this._65 === -1 || this._65 === -2) {
- return 0;
- }
-
- return this._65;
- };
-};
-
-Promise.disableSynchronous = function() {
- Promise.prototype.isPending = undefined;
- Promise.prototype.isFulfilled = undefined;
- Promise.prototype.isRejected = undefined;
- Promise.prototype.getValue = undefined;
- Promise.prototype.getReason = undefined;
- Promise.prototype.getState = undefined;
-};
-
-
-/***/ }),
-
-/***/ 11322:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var assert = __nccwpck_require__(39491);
-var constantinople = __nccwpck_require__(40953);
-var runtime = __nccwpck_require__(27596);
-var stringify = __nccwpck_require__(94878);
-
-function isConstant(src) {
- return constantinople(src, {pug: runtime, pug_interp: undefined});
-}
-function toConstant(src) {
- return constantinople.toConstant(src, {pug: runtime, pug_interp: undefined});
-}
-
-module.exports = compileAttrs;
-/**
- * options:
- * - terse
- * - runtime
- * - format ('html' || 'object')
- */
-function compileAttrs(attrs, options) {
- assert(Array.isArray(attrs), 'Attrs should be an array');
- assert(
- attrs.every(function(attr) {
- return (
- attr &&
- typeof attr === 'object' &&
- typeof attr.name === 'string' &&
- (typeof attr.val === 'string' || typeof attr.val === 'boolean') &&
- typeof attr.mustEscape === 'boolean'
- );
- }),
- 'All attributes should be supplied as an object of the form {name, val, mustEscape}'
- );
- assert(options && typeof options === 'object', 'Options should be an object');
- assert(
- typeof options.terse === 'boolean',
- 'Options.terse should be a boolean'
- );
- assert(
- typeof options.runtime === 'function',
- 'Options.runtime should be a function that takes a runtime function name and returns the source code that will evaluate to that function at runtime'
- );
- assert(
- options.format === 'html' || options.format === 'object',
- 'Options.format should be "html" or "object"'
- );
-
- var buf = [];
- var classes = [];
- var classEscaping = [];
-
- function addAttribute(key, val, mustEscape, buf) {
- if (isConstant(val)) {
- if (options.format === 'html') {
- var str = stringify(
- runtime.attr(key, toConstant(val), mustEscape, options.terse)
- );
- var last = buf[buf.length - 1];
- if (last && last[last.length - 1] === str[0]) {
- buf[buf.length - 1] = last.substr(0, last.length - 1) + str.substr(1);
- } else {
- buf.push(str);
- }
- } else {
- val = toConstant(val);
- if (mustEscape) {
- val = runtime.escape(val);
- }
- buf.push(stringify(key) + ': ' + stringify(val));
- }
- } else {
- if (options.format === 'html') {
- buf.push(
- options.runtime('attr') +
- '("' +
- key +
- '", ' +
- val +
- ', ' +
- stringify(mustEscape) +
- ', ' +
- stringify(options.terse) +
- ')'
- );
- } else {
- if (mustEscape) {
- val = options.runtime('escape') + '(' + val + ')';
- }
- buf.push(stringify(key) + ': ' + val);
- }
- }
- }
-
- attrs.forEach(function(attr) {
- var key = attr.name;
- var val = attr.val;
- var mustEscape = attr.mustEscape;
-
- if (key === 'class') {
- classes.push(val);
- classEscaping.push(mustEscape);
- } else {
- if (key === 'style') {
- if (isConstant(val)) {
- val = stringify(runtime.style(toConstant(val)));
- } else {
- val = options.runtime('style') + '(' + val + ')';
- }
- }
- addAttribute(key, val, mustEscape, buf);
- }
- });
- var classesBuf = [];
- if (classes.length) {
- if (classes.every(isConstant)) {
- addAttribute(
- 'class',
- stringify(runtime.classes(classes.map(toConstant), classEscaping)),
- false,
- classesBuf
- );
- } else {
- classes = classes.map(function(cls, i) {
- if (isConstant(cls)) {
- cls = stringify(
- classEscaping[i] ? runtime.escape(toConstant(cls)) : toConstant(cls)
- );
- classEscaping[i] = false;
- }
- return cls;
- });
- addAttribute(
- 'class',
- options.runtime('classes') +
- '([' +
- classes.join(',') +
- '], ' +
- stringify(classEscaping) +
- ')',
- false,
- classesBuf
- );
- }
- }
- buf = classesBuf.concat(buf);
- if (options.format === 'html') return buf.length ? buf.join('+') : '""';
- else return '{' + buf.join(',') + '}';
-}
-
-
-/***/ }),
-
-/***/ 90331:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var doctypes = __nccwpck_require__(3194);
-var makeError = __nccwpck_require__(11449);
-var buildRuntime = __nccwpck_require__(37364);
-var runtime = __nccwpck_require__(27596);
-var compileAttrs = __nccwpck_require__(11322);
-var selfClosing = __nccwpck_require__(97529);
-var constantinople = __nccwpck_require__(40953);
-var stringify = __nccwpck_require__(94878);
-var addWith = __nccwpck_require__(78904);
-
-// This is used to prevent pretty printing inside certain tags
-var WHITE_SPACE_SENSITIVE_TAGS = {
- pre: true,
- textarea: true,
-};
-
-var INTERNAL_VARIABLES = [
- 'pug',
- 'pug_mixins',
- 'pug_interp',
- 'pug_debug_filename',
- 'pug_debug_line',
- 'pug_debug_sources',
- 'pug_html',
-];
-
-module.exports = generateCode;
-module.exports.CodeGenerator = Compiler;
-function generateCode(ast, options) {
- return new Compiler(ast, options).compile();
-}
-
-function isConstant(src) {
- return constantinople(src, {pug: runtime, pug_interp: undefined});
-}
-function toConstant(src) {
- return constantinople.toConstant(src, {pug: runtime, pug_interp: undefined});
-}
-
-/**
- * Initialize `Compiler` with the given `node`.
- *
- * @param {Node} node
- * @param {Object} options
- * @api public
- */
-
-function Compiler(node, options) {
- this.options = options = options || {};
- this.node = node;
- this.bufferedConcatenationCount = 0;
- this.hasCompiledDoctype = false;
- this.hasCompiledTag = false;
- this.pp = options.pretty || false;
- if (this.pp && typeof this.pp !== 'string') {
- this.pp = ' ';
- }
- if (this.pp && !/^\s+$/.test(this.pp)) {
- throw new Error(
- 'The pretty parameter should either be a boolean or whitespace only string'
- );
- }
- this.debug = false !== options.compileDebug;
- this.indents = 0;
- this.parentIndents = 0;
- this.terse = false;
- this.mixins = {};
- this.dynamicMixins = false;
- this.eachCount = 0;
- if (options.doctype) this.setDoctype(options.doctype);
- this.runtimeFunctionsUsed = [];
- this.inlineRuntimeFunctions = options.inlineRuntimeFunctions || false;
- if (this.debug && this.inlineRuntimeFunctions) {
- this.runtimeFunctionsUsed.push('rethrow');
- }
-}
-
-/**
- * Compiler prototype.
- */
-
-Compiler.prototype = {
- runtime: function(name) {
- if (this.inlineRuntimeFunctions) {
- this.runtimeFunctionsUsed.push(name);
- return 'pug_' + name;
- } else {
- return 'pug.' + name;
- }
- },
-
- error: function(message, code, node) {
- var err = makeError(code, message, {
- line: node.line,
- column: node.column,
- filename: node.filename,
- });
- throw err;
- },
-
- /**
- * Compile parse tree to JavaScript.
- *
- * @api public
- */
-
- compile: function() {
- this.buf = [];
- if (this.pp) this.buf.push('var pug_indent = [];');
- this.lastBufferedIdx = -1;
- this.visit(this.node);
- if (!this.dynamicMixins) {
- // if there are no dynamic mixins we can remove any un-used mixins
- var mixinNames = Object.keys(this.mixins);
- for (var i = 0; i < mixinNames.length; i++) {
- var mixin = this.mixins[mixinNames[i]];
- if (!mixin.used) {
- for (var x = 0; x < mixin.instances.length; x++) {
- for (
- var y = mixin.instances[x].start;
- y < mixin.instances[x].end;
- y++
- ) {
- this.buf[y] = '';
- }
- }
- }
- }
- }
- var js = this.buf.join('\n');
- var globals = this.options.globals
- ? this.options.globals.concat(INTERNAL_VARIABLES)
- : INTERNAL_VARIABLES;
- if (this.options.self) {
- js = 'var self = locals || {};' + js;
- } else {
- js = addWith(
- 'locals || {}',
- js,
- globals.concat(
- this.runtimeFunctionsUsed.map(function(name) {
- return 'pug_' + name;
- })
- )
- );
- }
- if (this.debug) {
- if (this.options.includeSources) {
- js =
- 'var pug_debug_sources = ' +
- stringify(this.options.includeSources) +
- ';\n' +
- js;
- }
- js =
- 'var pug_debug_filename, pug_debug_line;' +
- 'try {' +
- js +
- '} catch (err) {' +
- (this.inlineRuntimeFunctions ? 'pug_rethrow' : 'pug.rethrow') +
- '(err, pug_debug_filename, pug_debug_line' +
- (this.options.includeSources
- ? ', pug_debug_sources[pug_debug_filename]'
- : '') +
- ');' +
- '}';
- }
- return (
- buildRuntime(this.runtimeFunctionsUsed) +
- 'function ' +
- (this.options.templateName || 'template') +
- '(locals) {var pug_html = "", pug_mixins = {}, pug_interp;' +
- js +
- ';return pug_html;}'
- );
- },
-
- /**
- * Sets the default doctype `name`. Sets terse mode to `true` when
- * html 5 is used, causing self-closing tags to end with ">" vs "/>",
- * and boolean attributes are not mirrored.
- *
- * @param {string} name
- * @api public
- */
-
- setDoctype: function(name) {
- this.doctype = doctypes[name.toLowerCase()] || '';
- this.terse = this.doctype.toLowerCase() == '';
- this.xml = 0 == this.doctype.indexOf(' 1 &&
- !escapePrettyMode &&
- block.nodes[0].type === 'Text' &&
- block.nodes[1].type === 'Text'
- ) {
- this.prettyIndent(1, true);
- }
- for (var i = 0; i < block.nodes.length; ++i) {
- // Pretty print text
- if (
- pp &&
- i > 0 &&
- !escapePrettyMode &&
- block.nodes[i].type === 'Text' &&
- block.nodes[i - 1].type === 'Text' &&
- /\n$/.test(block.nodes[i - 1].val)
- ) {
- this.prettyIndent(1, false);
- }
- this.visit(block.nodes[i], block);
- }
- },
-
- /**
- * Visit a mixin's `block` keyword.
- *
- * @param {MixinBlock} block
- * @api public
- */
-
- visitMixinBlock: function(block) {
- if (this.pp)
- this.buf.push(
- 'pug_indent.push(' +
- stringify(Array(this.indents + 1).join(this.pp)) +
- ');'
- );
- this.buf.push('block && block();');
- if (this.pp) this.buf.push('pug_indent.pop();');
- },
-
- /**
- * Visit `doctype`. Sets terse mode to `true` when html 5
- * is used, causing self-closing tags to end with ">" vs "/>",
- * and boolean attributes are not mirrored.
- *
- * @param {Doctype} doctype
- * @api public
- */
-
- visitDoctype: function(doctype) {
- if (doctype && (doctype.val || !this.doctype)) {
- this.setDoctype(doctype.val || 'html');
- }
-
- if (this.doctype) this.buffer(this.doctype);
- this.hasCompiledDoctype = true;
- },
-
- /**
- * Visit `mixin`, generating a function that
- * may be called within the template.
- *
- * @param {Mixin} mixin
- * @api public
- */
-
- visitMixin: function(mixin) {
- var name = 'pug_mixins[';
- var args = mixin.args || '';
- var block = mixin.block;
- var attrs = mixin.attrs;
- var attrsBlocks = this.attributeBlocks(mixin.attributeBlocks);
- var pp = this.pp;
- var dynamic = mixin.name[0] === '#';
- var key = mixin.name;
- if (dynamic) this.dynamicMixins = true;
- name +=
- (dynamic
- ? mixin.name.substr(2, mixin.name.length - 3)
- : '"' + mixin.name + '"') + ']';
-
- this.mixins[key] = this.mixins[key] || {used: false, instances: []};
- if (mixin.call) {
- this.mixins[key].used = true;
- if (pp)
- this.buf.push(
- 'pug_indent.push(' +
- stringify(Array(this.indents + 1).join(pp)) +
- ');'
- );
- if (block || attrs.length || attrsBlocks.length) {
- this.buf.push(name + '.call({');
-
- if (block) {
- this.buf.push('block: function(){');
-
- // Render block with no indents, dynamically added when rendered
- this.parentIndents++;
- var _indents = this.indents;
- this.indents = 0;
- this.visit(mixin.block, mixin);
- this.indents = _indents;
- this.parentIndents--;
-
- if (attrs.length || attrsBlocks.length) {
- this.buf.push('},');
- } else {
- this.buf.push('}');
- }
- }
-
- if (attrsBlocks.length) {
- if (attrs.length) {
- var val = this.attrs(attrs);
- attrsBlocks.unshift(val);
- }
- if (attrsBlocks.length > 1) {
- this.buf.push(
- 'attributes: ' +
- this.runtime('merge') +
- '([' +
- attrsBlocks.join(',') +
- '])'
- );
- } else {
- this.buf.push('attributes: ' + attrsBlocks[0]);
- }
- } else if (attrs.length) {
- var val = this.attrs(attrs);
- this.buf.push('attributes: ' + val);
- }
-
- if (args) {
- this.buf.push('}, ' + args + ');');
- } else {
- this.buf.push('});');
- }
- } else {
- this.buf.push(name + '(' + args + ');');
- }
- if (pp) this.buf.push('pug_indent.pop();');
- } else {
- var mixin_start = this.buf.length;
- args = args ? args.split(',') : [];
- var rest;
- if (args.length && /^\.\.\./.test(args[args.length - 1].trim())) {
- rest = args
- .pop()
- .trim()
- .replace(/^\.\.\./, '');
- }
- // we need use pug_interp here for v8: https://code.google.com/p/v8/issues/detail?id=4165
- // once fixed, use this: this.buf.push(name + ' = function(' + args.join(',') + '){');
- this.buf.push(name + ' = pug_interp = function(' + args.join(',') + '){');
- this.buf.push(
- 'var block = (this && this.block), attributes = (this && this.attributes) || {};'
- );
- if (rest) {
- this.buf.push('var ' + rest + ' = [];');
- this.buf.push(
- 'for (pug_interp = ' +
- args.length +
- '; pug_interp < arguments.length; pug_interp++) {'
- );
- this.buf.push(' ' + rest + '.push(arguments[pug_interp]);');
- this.buf.push('}');
- }
- this.parentIndents++;
- this.visit(block, mixin);
- this.parentIndents--;
- this.buf.push('};');
- var mixin_end = this.buf.length;
- this.mixins[key].instances.push({start: mixin_start, end: mixin_end});
- }
- },
-
- /**
- * Visit `tag` buffering tag markup, generating
- * attributes, visiting the `tag`'s code and block.
- *
- * @param {Tag} tag
- * @param {boolean} interpolated
- * @api public
- */
-
- visitTag: function(tag, interpolated) {
- this.indents++;
- var name = tag.name,
- pp = this.pp,
- self = this;
-
- function bufferName() {
- if (interpolated) self.bufferExpression(tag.expr);
- else self.buffer(name);
- }
-
- if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true)
- this.escapePrettyMode = true;
-
- if (!this.hasCompiledTag) {
- if (!this.hasCompiledDoctype && 'html' == name) {
- this.visitDoctype();
- }
- this.hasCompiledTag = true;
- }
-
- // pretty print
- if (pp && !tag.isInline) this.prettyIndent(0, true);
- if (tag.selfClosing || (!this.xml && selfClosing[tag.name])) {
- this.buffer('<');
- bufferName();
- this.visitAttributes(
- tag.attrs,
- this.attributeBlocks(tag.attributeBlocks)
- );
- if (this.terse && !tag.selfClosing) {
- this.buffer('>');
- } else {
- this.buffer('/>');
- }
- // if it is non-empty throw an error
- if (
- tag.code ||
- (tag.block &&
- !(tag.block.type === 'Block' && tag.block.nodes.length === 0) &&
- tag.block.nodes.some(function(tag) {
- return tag.type !== 'Text' || !/^\s*$/.test(tag.val);
- }))
- ) {
- this.error(
- name +
- ' is a self closing element: <' +
- name +
- '/> but contains nested content.',
- 'SELF_CLOSING_CONTENT',
- tag
- );
- }
- } else {
- // Optimize attributes buffering
- this.buffer('<');
- bufferName();
- this.visitAttributes(
- tag.attrs,
- this.attributeBlocks(tag.attributeBlocks)
- );
- this.buffer('>');
- if (tag.code) this.visitCode(tag.code);
- this.visit(tag.block, tag);
-
- // pretty print
- if (
- pp &&
- !tag.isInline &&
- WHITE_SPACE_SENSITIVE_TAGS[tag.name] !== true &&
- !tagCanInline(tag)
- )
- this.prettyIndent(0, true);
-
- this.buffer('');
- bufferName();
- this.buffer('>');
- }
-
- if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true)
- this.escapePrettyMode = false;
-
- this.indents--;
- },
-
- /**
- * Visit InterpolatedTag.
- *
- * @param {InterpolatedTag} tag
- * @api public
- */
-
- visitInterpolatedTag: function(tag) {
- return this.visitTag(tag, true);
- },
-
- /**
- * Visit `text` node.
- *
- * @param {Text} text
- * @api public
- */
-
- visitText: function(text) {
- this.buffer(text.val);
- },
-
- /**
- * Visit a `comment`, only buffering when the buffer flag is set.
- *
- * @param {Comment} comment
- * @api public
- */
-
- visitComment: function(comment) {
- if (!comment.buffer) return;
- if (this.pp) this.prettyIndent(1, true);
- this.buffer('');
- },
-
- /**
- * Visit a `YieldBlock`.
- *
- * This is necessary since we allow compiling a file with `yield`.
- *
- * @param {YieldBlock} block
- * @api public
- */
-
- visitYieldBlock: function(block) {},
-
- /**
- * Visit a `BlockComment`.
- *
- * @param {Comment} comment
- * @api public
- */
-
- visitBlockComment: function(comment) {
- if (!comment.buffer) return;
- if (this.pp) this.prettyIndent(1, true);
- this.buffer('');
- },
-
- /**
- * Visit `code`, respecting buffer / escape flags.
- * If the code is followed by a block, wrap it in
- * a self-calling function.
- *
- * @param {Code} code
- * @api public
- */
-
- visitCode: function(code) {
- // Wrap code blocks with {}.
- // we only wrap unbuffered code blocks ATM
- // since they are usually flow control
-
- // Buffer code
- if (code.buffer) {
- var val = code.val.trim();
- val = 'null == (pug_interp = ' + val + ') ? "" : pug_interp';
- if (code.mustEscape !== false)
- val = this.runtime('escape') + '(' + val + ')';
- this.bufferExpression(val);
- } else {
- this.buf.push(code.val);
- }
-
- // Block support
- if (code.block) {
- if (!code.buffer) this.buf.push('{');
- this.visit(code.block, code);
- if (!code.buffer) this.buf.push('}');
- }
- },
-
- /**
- * Visit `Conditional`.
- *
- * @param {Conditional} cond
- * @api public
- */
-
- visitConditional: function(cond) {
- var test = cond.test;
- this.buf.push('if (' + test + ') {');
- this.visit(cond.consequent, cond);
- this.buf.push('}');
- if (cond.alternate) {
- if (cond.alternate.type === 'Conditional') {
- this.buf.push('else');
- this.visitConditional(cond.alternate);
- } else {
- this.buf.push('else {');
- this.visit(cond.alternate, cond);
- this.buf.push('}');
- }
- }
- },
-
- /**
- * Visit `While`.
- *
- * @param {While} loop
- * @api public
- */
-
- visitWhile: function(loop) {
- var test = loop.test;
- this.buf.push('while (' + test + ') {');
- this.visit(loop.block, loop);
- this.buf.push('}');
- },
-
- /**
- * Visit `each` block.
- *
- * @param {Each} each
- * @api public
- */
-
- visitEach: function(each) {
- var indexVarName = each.key || 'pug_index' + this.eachCount;
- this.eachCount++;
-
- this.buf.push(
- '' +
- '// iterate ' +
- each.obj +
- '\n' +
- ';(function(){\n' +
- ' var $$obj = ' +
- each.obj +
- ';\n' +
- " if ('number' == typeof $$obj.length) {"
- );
-
- if (each.alternate) {
- this.buf.push(' if ($$obj.length) {');
- }
-
- this.buf.push(
- '' +
- ' for (var ' +
- indexVarName +
- ' = 0, $$l = $$obj.length; ' +
- indexVarName +
- ' < $$l; ' +
- indexVarName +
- '++) {\n' +
- ' var ' +
- each.val +
- ' = $$obj[' +
- indexVarName +
- '];'
- );
-
- this.visit(each.block, each);
-
- this.buf.push(' }');
-
- if (each.alternate) {
- this.buf.push(' } else {');
- this.visit(each.alternate, each);
- this.buf.push(' }');
- }
-
- this.buf.push(
- '' +
- ' } else {\n' +
- ' var $$l = 0;\n' +
- ' for (var ' +
- indexVarName +
- ' in $$obj) {\n' +
- ' $$l++;\n' +
- ' var ' +
- each.val +
- ' = $$obj[' +
- indexVarName +
- '];'
- );
-
- this.visit(each.block, each);
-
- this.buf.push(' }');
- if (each.alternate) {
- this.buf.push(' if ($$l === 0) {');
- this.visit(each.alternate, each);
- this.buf.push(' }');
- }
- this.buf.push(' }\n}).call(this);\n');
- },
-
- visitEachOf: function(each) {
- this.buf.push(
- '' +
- '// iterate ' +
- each.obj +
- '\n' +
- 'for (const ' +
- each.val +
- ' of ' +
- each.obj +
- ') {\n'
- );
-
- this.visit(each.block, each);
-
- this.buf.push('}\n');
- },
-
- /**
- * Visit `attrs`.
- *
- * @param {Array} attrs
- * @api public
- */
-
- visitAttributes: function(attrs, attributeBlocks) {
- if (attributeBlocks.length) {
- if (attrs.length) {
- var val = this.attrs(attrs);
- attributeBlocks.unshift(val);
- }
- if (attributeBlocks.length > 1) {
- this.bufferExpression(
- this.runtime('attrs') +
- '(' +
- this.runtime('merge') +
- '([' +
- attributeBlocks.join(',') +
- ']), ' +
- stringify(this.terse) +
- ')'
- );
- } else {
- this.bufferExpression(
- this.runtime('attrs') +
- '(' +
- attributeBlocks[0] +
- ', ' +
- stringify(this.terse) +
- ')'
- );
- }
- } else if (attrs.length) {
- this.attrs(attrs, true);
- }
- },
-
- /**
- * Compile attributes.
- */
-
- attrs: function(attrs, buffer) {
- var res = compileAttrs(attrs, {
- terse: this.terse,
- format: buffer ? 'html' : 'object',
- runtime: this.runtime.bind(this),
- });
- if (buffer) {
- this.bufferExpression(res);
- }
- return res;
- },
-
- /**
- * Compile attribute blocks.
- */
-
- attributeBlocks: function(attributeBlocks) {
- return (
- attributeBlocks &&
- attributeBlocks.slice().map(function(attrBlock) {
- return attrBlock.val;
- })
- );
- },
-};
-
-function tagCanInline(tag) {
- function isInline(node) {
- // Recurse if the node is a block
- if (node.type === 'Block') return node.nodes.every(isInline);
- // When there is a YieldBlock here, it is an indication that the file is
- // expected to be included but is not. If this is the case, the block
- // must be empty.
- if (node.type === 'YieldBlock') return true;
- return (node.type === 'Text' && !/\n/.test(node.val)) || node.isInline;
- }
-
- return tag.block.nodes.every(isInline);
-}
-
-
-/***/ }),
-
-/***/ 11449:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = makeError;
-function makeError(code, message, options) {
- var line = options.line;
- var column = options.column;
- var filename = options.filename;
- var src = options.src;
- var fullMessage;
- var location = line + (column ? ':' + column : '');
- if (src && line >= 1 && line <= src.split('\n').length) {
- var lines = src.split('\n');
- var start = Math.max(line - 3, 0);
- var end = Math.min(lines.length, line + 3);
- // Error context
- var context = lines
- .slice(start, end)
- .map(function(text, i) {
- var curr = i + start + 1;
- var preamble = (curr == line ? ' > ' : ' ') + curr + '| ';
- var out = preamble + text;
- if (curr === line && column > 0) {
- out += '\n';
- out += Array(preamble.length + column).join('-') + '^';
- }
- return out;
- })
- .join('\n');
- fullMessage =
- (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message;
- } else {
- fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message;
- }
- var err = new Error(fullMessage);
- err.code = 'PUG:' + code;
- err.msg = message;
- err.line = line;
- err.column = column;
- err.filename = filename;
- err.src = src;
- err.toJSON = function() {
- return {
- code: this.code,
- msg: this.msg,
- line: this.line,
- column: this.column,
- filename: this.filename,
- };
- };
- return err;
-}
-
-
-/***/ }),
-
-/***/ 69309:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-exports.runFilter = __nccwpck_require__(9498);
-exports.handleFilters = __nccwpck_require__(77823);
-
-
-/***/ }),
-
-/***/ 77823:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var dirname = (__nccwpck_require__(71017).dirname);
-var constantinople = __nccwpck_require__(40953);
-var walk = __nccwpck_require__(60283);
-var error = __nccwpck_require__(11449);
-var runFilter = __nccwpck_require__(9498);
-
-module.exports = handleFilters;
-function handleFilters(ast, filters, options, filterAliases) {
- options = options || {};
- walk(
- ast,
- function(node) {
- var dir = node.filename ? dirname(node.filename) : null;
- if (node.type === 'Filter') {
- handleNestedFilters(node, filters, options, filterAliases);
- var text = getBodyAsText(node);
- var attrs = getAttributes(node, options);
- attrs.filename = node.filename;
- node.type = 'Text';
- node.val = filterWithFallback(node, text, attrs);
- } else if (node.type === 'RawInclude' && node.filters.length) {
- var firstFilter = node.filters.pop();
- var attrs = getAttributes(firstFilter, options);
- var filename = (attrs.filename = node.file.fullPath);
- node.type = 'Text';
- node.val = filterFileWithFallback(
- firstFilter,
- filename,
- node.file,
- attrs
- );
- node.filters
- .slice()
- .reverse()
- .forEach(function(filter) {
- var attrs = getAttributes(filter, options);
- attrs.filename = filename;
- node.val = filterWithFallback(filter, node.val, attrs);
- });
- node.filters = undefined;
- node.file = undefined;
- }
-
- function filterWithFallback(filter, text, attrs, funcName) {
- try {
- var filterName = getFilterName(filter);
- if (filters && filters[filterName]) {
- return filters[filterName](text, attrs);
- } else {
- return runFilter(filterName, text, attrs, dir, funcName);
- }
- } catch (ex) {
- if (ex.code === 'UNKNOWN_FILTER') {
- throw error(ex.code, ex.message, filter);
- }
- throw ex;
- }
- }
-
- function filterFileWithFallback(filter, filename, file, attrs) {
- var filterName = getFilterName(filter);
- if (filters && filters[filterName]) {
- if (filters[filterName].renderBuffer) {
- return filters[filterName].renderBuffer(file.raw, attrs);
- } else {
- return filters[filterName](file.str, attrs);
- }
- } else {
- return filterWithFallback(filter, filename, attrs, 'renderFile');
- }
- }
- },
- {includeDependencies: true}
- );
- function getFilterName(filter) {
- var filterName = filter.name;
- if (filterAliases && filterAliases[filterName]) {
- filterName = filterAliases[filterName];
- if (filterAliases[filterName]) {
- throw error(
- 'FILTER_ALISE_CHAIN',
- 'The filter "' +
- filter.name +
- '" is an alias for "' +
- filterName +
- '", which is an alias for "' +
- filterAliases[filterName] +
- '". Pug does not support chains of filter aliases.',
- filter
- );
- }
- }
- return filterName;
- }
- return ast;
-}
-
-function handleNestedFilters(node, filters, options, filterAliases) {
- if (node.block.nodes[0] && node.block.nodes[0].type === 'Filter') {
- node.block.nodes[0] = handleFilters(
- node.block,
- filters,
- options,
- filterAliases
- ).nodes[0];
- }
-}
-
-function getBodyAsText(node) {
- return node.block.nodes
- .map(function(node) {
- return node.val;
- })
- .join('');
-}
-
-function getAttributes(node, options) {
- var attrs = {};
- node.attrs.forEach(function(attr) {
- try {
- attrs[attr.name] =
- attr.val === true ? true : constantinople.toConstant(attr.val);
- } catch (ex) {
- if (/not constant/.test(ex.message)) {
- throw error(
- 'FILTER_OPTION_NOT_CONSTANT',
- ex.message +
- ' All filters are rendered compile-time so filter options must be constants.',
- node
- );
- }
- throw ex;
- }
- });
- var opts = options[node.name] || {};
- Object.keys(opts).forEach(function(opt) {
- if (!attrs.hasOwnProperty(opt)) {
- attrs[opt] = opts[opt];
- }
- });
- return attrs;
-}
-
-
-/***/ }),
-
-/***/ 9498:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var jstransformer = __nccwpck_require__(77369);
-var resolve = __nccwpck_require__(81679);
-
-module.exports = filter;
-
-function getMinifyTransformerName(outputFormat) {
- switch (outputFormat) {
- case 'js':
- return 'uglify-js';
- case 'css':
- return 'clean-css';
- }
-}
-
-function filter(name, str, options, currentDirectory, funcName) {
- funcName = funcName || 'render';
- var trPath;
- try {
- try {
- trPath = resolve.sync('jstransformer-' + name, {
- basedir: currentDirectory || process.cwd(),
- });
- } catch (ex) {
- trPath = require.resolve('jstransformer-' + name);
- }
- } catch (ex) {
- var err = new Error('unknown filter ":' + name + '"');
- err.code = 'UNKNOWN_FILTER';
- throw err;
- }
- var tr = jstransformer(require(trPath));
- // TODO: we may want to add a way for people to separately specify "locals"
- var result = tr[funcName](str, options, options).body;
- if (options && options.minify) {
- var minifyTranformer = getMinifyTransformerName(tr.outputFormat);
- if (minifyTranformer) {
- try {
- result = filter(minifyTranformer, result, null, currentDirectory);
- } catch (ex) {
- // better to fail to minify than output nothing
- }
- }
- }
- return result;
-}
-
-
-/***/ }),
-
-/***/ 53230:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var has = __nccwpck_require__(76339);
-
-function specifierIncluded(current, specifier) {
- var nodeParts = current.split('.');
- var parts = specifier.split(' ');
- var op = parts.length > 1 ? parts[0] : '=';
- var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
-
- for (var i = 0; i < 3; ++i) {
- var cur = parseInt(nodeParts[i] || 0, 10);
- var ver = parseInt(versionParts[i] || 0, 10);
- if (cur === ver) {
- continue; // eslint-disable-line no-restricted-syntax, no-continue
- }
- if (op === '<') {
- return cur < ver;
- }
- if (op === '>=') {
- return cur >= ver;
- }
- return false;
- }
- return op === '>=';
-}
-
-function matchesRange(current, range) {
- var specifiers = range.split(/ ?&& ?/);
- if (specifiers.length === 0) {
- return false;
- }
- for (var i = 0; i < specifiers.length; ++i) {
- if (!specifierIncluded(current, specifiers[i])) {
- return false;
- }
- }
- return true;
-}
-
-function versionIncluded(nodeVersion, specifierValue) {
- if (typeof specifierValue === 'boolean') {
- return specifierValue;
- }
-
- var current = typeof nodeVersion === 'undefined'
- ? process.versions && process.versions.node
- : nodeVersion;
-
- if (typeof current !== 'string') {
- throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');
- }
-
- if (specifierValue && typeof specifierValue === 'object') {
- for (var i = 0; i < specifierValue.length; ++i) {
- if (matchesRange(current, specifierValue[i])) {
- return true;
- }
- }
- return false;
- }
- return matchesRange(current, specifierValue);
-}
-
-var data = __nccwpck_require__(79849);
-
-module.exports = function isCore(x, nodeVersion) {
- return has(data, x) && versionIncluded(nodeVersion, data[x]);
-};
-
-
-/***/ }),
-
-/***/ 81679:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var async = __nccwpck_require__(37600);
-async.core = __nccwpck_require__(4632);
-async.isCore = __nccwpck_require__(16520);
-async.sync = __nccwpck_require__(92966);
-
-module.exports = async;
-
-
-/***/ }),
-
-/***/ 37600:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var fs = __nccwpck_require__(57147);
-var getHomedir = __nccwpck_require__(58108);
-var path = __nccwpck_require__(71017);
-var caller = __nccwpck_require__(50907);
-var nodeModulesPaths = __nccwpck_require__(4287);
-var normalizeOptions = __nccwpck_require__(48315);
-var isCore = __nccwpck_require__(53230);
-
-var realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
-
-var homedir = getHomedir();
-var defaultPaths = function () {
- return [
- path.join(homedir, '.node_modules'),
- path.join(homedir, '.node_libraries')
- ];
-};
-
-var defaultIsFile = function isFile(file, cb) {
- fs.stat(file, function (err, stat) {
- if (!err) {
- return cb(null, stat.isFile() || stat.isFIFO());
- }
- if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
- return cb(err);
- });
-};
-
-var defaultIsDir = function isDirectory(dir, cb) {
- fs.stat(dir, function (err, stat) {
- if (!err) {
- return cb(null, stat.isDirectory());
- }
- if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
- return cb(err);
- });
-};
-
-var defaultRealpath = function realpath(x, cb) {
- realpathFS(x, function (realpathErr, realPath) {
- if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);
- else cb(null, realpathErr ? x : realPath);
- });
-};
-
-var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {
- if (opts && opts.preserveSymlinks === false) {
- realpath(x, cb);
- } else {
- cb(null, x);
- }
-};
-
-var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) {
- readFile(pkgfile, function (readFileErr, body) {
- if (readFileErr) cb(readFileErr);
- else {
- try {
- var pkg = JSON.parse(body);
- cb(null, pkg);
- } catch (jsonErr) {
- cb(null);
- }
- }
- });
-};
-
-var getPackageCandidates = function getPackageCandidates(x, start, opts) {
- var dirs = nodeModulesPaths(start, opts, x);
- for (var i = 0; i < dirs.length; i++) {
- dirs[i] = path.join(dirs[i], x);
- }
- return dirs;
-};
-
-module.exports = function resolve(x, options, callback) {
- var cb = callback;
- var opts = options;
- if (typeof options === 'function') {
- cb = opts;
- opts = {};
- }
- if (typeof x !== 'string') {
- var err = new TypeError('Path must be a string.');
- return process.nextTick(function () {
- cb(err);
- });
- }
-
- opts = normalizeOptions(x, opts);
-
- var isFile = opts.isFile || defaultIsFile;
- var isDirectory = opts.isDirectory || defaultIsDir;
- var readFile = opts.readFile || fs.readFile;
- var realpath = opts.realpath || defaultRealpath;
- var readPackage = opts.readPackage || defaultReadPackage;
- if (opts.readFile && opts.readPackage) {
- var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.');
- return process.nextTick(function () {
- cb(conflictErr);
- });
- }
- var packageIterator = opts.packageIterator;
-
- var extensions = opts.extensions || ['.js'];
- var includeCoreModules = opts.includeCoreModules !== false;
- var basedir = opts.basedir || path.dirname(caller());
- var parent = opts.filename || basedir;
-
- opts.paths = opts.paths || defaultPaths();
-
- // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
- var absoluteStart = path.resolve(basedir);
-
- maybeRealpath(
- realpath,
- absoluteStart,
- opts,
- function (err, realStart) {
- if (err) cb(err);
- else init(realStart);
- }
- );
-
- var res;
- function init(basedir) {
- if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
- res = path.resolve(basedir, x);
- if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
- if ((/\/$/).test(x) && res === basedir) {
- loadAsDirectory(res, opts.package, onfile);
- } else loadAsFile(res, opts.package, onfile);
- } else if (includeCoreModules && isCore(x)) {
- return cb(null, x);
- } else loadNodeModules(x, basedir, function (err, n, pkg) {
- if (err) cb(err);
- else if (n) {
- return maybeRealpath(realpath, n, opts, function (err, realN) {
- if (err) {
- cb(err);
- } else {
- cb(null, realN, pkg);
- }
- });
- } else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- }
-
- function onfile(err, m, pkg) {
- if (err) cb(err);
- else if (m) cb(null, m, pkg);
- else loadAsDirectory(res, function (err, d, pkg) {
- if (err) cb(err);
- else if (d) {
- maybeRealpath(realpath, d, opts, function (err, realD) {
- if (err) {
- cb(err);
- } else {
- cb(null, realD, pkg);
- }
- });
- } else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- }
-
- function loadAsFile(x, thePackage, callback) {
- var loadAsFilePackage = thePackage;
- var cb = callback;
- if (typeof loadAsFilePackage === 'function') {
- cb = loadAsFilePackage;
- loadAsFilePackage = undefined;
- }
-
- var exts = [''].concat(extensions);
- load(exts, x, loadAsFilePackage);
-
- function load(exts, x, loadPackage) {
- if (exts.length === 0) return cb(null, undefined, loadPackage);
- var file = x + exts[0];
-
- var pkg = loadPackage;
- if (pkg) onpkg(null, pkg);
- else loadpkg(path.dirname(file), onpkg);
-
- function onpkg(err, pkg_, dir) {
- pkg = pkg_;
- if (err) return cb(err);
- if (dir && pkg && opts.pathFilter) {
- var rfile = path.relative(dir, file);
- var rel = rfile.slice(0, rfile.length - exts[0].length);
- var r = opts.pathFilter(pkg, x, rel);
- if (r) return load(
- [''].concat(extensions.slice()),
- path.resolve(dir, r),
- pkg
- );
- }
- isFile(file, onex);
- }
- function onex(err, ex) {
- if (err) return cb(err);
- if (ex) return cb(null, file, pkg);
- load(exts.slice(1), x, pkg);
- }
- }
- }
-
- function loadpkg(dir, cb) {
- if (dir === '' || dir === '/') return cb(null);
- if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
- return cb(null);
- }
- if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null);
-
- maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
- if (unwrapErr) return loadpkg(path.dirname(dir), cb);
- var pkgfile = path.join(pkgdir, 'package.json');
- isFile(pkgfile, function (err, ex) {
- // on err, ex is false
- if (!ex) return loadpkg(path.dirname(dir), cb);
-
- readPackage(readFile, pkgfile, function (err, pkgParam) {
- if (err) cb(err);
-
- var pkg = pkgParam;
-
- if (pkg && opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
- cb(null, pkg, dir);
- });
- });
- });
- }
-
- function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
- var cb = callback;
- var fpkg = loadAsDirectoryPackage;
- if (typeof fpkg === 'function') {
- cb = fpkg;
- fpkg = opts.package;
- }
-
- maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
- if (unwrapErr) return cb(unwrapErr);
- var pkgfile = path.join(pkgdir, 'package.json');
- isFile(pkgfile, function (err, ex) {
- if (err) return cb(err);
- if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);
-
- readPackage(readFile, pkgfile, function (err, pkgParam) {
- if (err) return cb(err);
-
- var pkg = pkgParam;
-
- if (pkg && opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
-
- if (pkg && pkg.main) {
- if (typeof pkg.main !== 'string') {
- var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
- mainError.code = 'INVALID_PACKAGE_MAIN';
- return cb(mainError);
- }
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);
-
- var dir = path.resolve(x, pkg.main);
- loadAsDirectory(dir, pkg, function (err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- loadAsFile(path.join(x, 'index'), pkg, cb);
- });
- });
- return;
- }
-
- loadAsFile(path.join(x, '/index'), pkg, cb);
- });
- });
- });
- }
-
- function processDirs(cb, dirs) {
- if (dirs.length === 0) return cb(null, undefined);
- var dir = dirs[0];
-
- isDirectory(path.dirname(dir), isdir);
-
- function isdir(err, isdir) {
- if (err) return cb(err);
- if (!isdir) return processDirs(cb, dirs.slice(1));
- loadAsFile(dir, opts.package, onfile);
- }
-
- function onfile(err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- loadAsDirectory(dir, opts.package, ondir);
- }
-
- function ondir(err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- processDirs(cb, dirs.slice(1));
- }
- }
- function loadNodeModules(x, start, cb) {
- var thunk = function () { return getPackageCandidates(x, start, opts); };
- processDirs(
- cb,
- packageIterator ? packageIterator(x, start, thunk, opts) : thunk()
- );
- }
-};
-
-
-/***/ }),
-
-/***/ 50907:
-/***/ ((module) => {
-
-module.exports = function () {
- // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
- var origPrepareStackTrace = Error.prepareStackTrace;
- Error.prepareStackTrace = function (_, stack) { return stack; };
- var stack = (new Error()).stack;
- Error.prepareStackTrace = origPrepareStackTrace;
- return stack[2].getFileName();
-};
-
-
-/***/ }),
-
-/***/ 4632:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var isCoreModule = __nccwpck_require__(53230);
-var data = __nccwpck_require__(19495);
-
-var core = {};
-for (var mod in data) { // eslint-disable-line no-restricted-syntax
- if (Object.prototype.hasOwnProperty.call(data, mod)) {
- core[mod] = isCoreModule(mod);
- }
-}
-module.exports = core;
-
-
-/***/ }),
-
-/***/ 58108:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var os = __nccwpck_require__(22037);
-
-// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js
-
-module.exports = os.homedir || function homedir() {
- var home = process.env.HOME;
- var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
-
- if (process.platform === 'win32') {
- return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
- }
-
- if (process.platform === 'darwin') {
- return home || (user ? '/Users/' + user : null);
- }
-
- if (process.platform === 'linux') {
- return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens
- }
-
- return home || null;
-};
-
-
-/***/ }),
-
-/***/ 16520:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var isCoreModule = __nccwpck_require__(53230);
-
-module.exports = function isCore(x) {
- return isCoreModule(x);
-};
-
-
-/***/ }),
-
-/***/ 4287:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var path = __nccwpck_require__(71017);
-var parse = path.parse || __nccwpck_require__(5980); // eslint-disable-line global-require
-
-var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
- var prefix = '/';
- if ((/^([A-Za-z]:)/).test(absoluteStart)) {
- prefix = '';
- } else if ((/^\\\\/).test(absoluteStart)) {
- prefix = '\\\\';
- }
-
- var paths = [absoluteStart];
- var parsed = parse(absoluteStart);
- while (parsed.dir !== paths[paths.length - 1]) {
- paths.push(parsed.dir);
- parsed = parse(parsed.dir);
- }
-
- return paths.reduce(function (dirs, aPath) {
- return dirs.concat(modules.map(function (moduleDir) {
- return path.resolve(prefix, aPath, moduleDir);
- }));
- }, []);
-};
-
-module.exports = function nodeModulesPaths(start, opts, request) {
- var modules = opts && opts.moduleDirectory
- ? [].concat(opts.moduleDirectory)
- : ['node_modules'];
-
- if (opts && typeof opts.paths === 'function') {
- return opts.paths(
- request,
- start,
- function () { return getNodeModulesDirs(start, modules); },
- opts
- );
- }
-
- var dirs = getNodeModulesDirs(start, modules);
- return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
-};
-
-
-/***/ }),
-
-/***/ 48315:
-/***/ ((module) => {
-
-module.exports = function (x, opts) {
- /**
- * This file is purposefully a passthrough. It's expected that third-party
- * environments will override it at runtime in order to inject special logic
- * into `resolve` (by manipulating the options). One such example is the PnP
- * code path in Yarn.
- */
-
- return opts || {};
-};
-
-
-/***/ }),
-
-/***/ 92966:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var isCore = __nccwpck_require__(53230);
-var fs = __nccwpck_require__(57147);
-var path = __nccwpck_require__(71017);
-var getHomedir = __nccwpck_require__(58108);
-var caller = __nccwpck_require__(50907);
-var nodeModulesPaths = __nccwpck_require__(4287);
-var normalizeOptions = __nccwpck_require__(48315);
-
-var realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
-
-var homedir = getHomedir();
-var defaultPaths = function () {
- return [
- path.join(homedir, '.node_modules'),
- path.join(homedir, '.node_libraries')
- ];
-};
-
-var defaultIsFile = function isFile(file) {
- try {
- var stat = fs.statSync(file, { throwIfNoEntry: false });
- } catch (e) {
- if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
- throw e;
- }
- return !!stat && (stat.isFile() || stat.isFIFO());
-};
-
-var defaultIsDir = function isDirectory(dir) {
- try {
- var stat = fs.statSync(dir, { throwIfNoEntry: false });
- } catch (e) {
- if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
- throw e;
- }
- return !!stat && stat.isDirectory();
-};
-
-var defaultRealpathSync = function realpathSync(x) {
- try {
- return realpathFS(x);
- } catch (realpathErr) {
- if (realpathErr.code !== 'ENOENT') {
- throw realpathErr;
- }
- }
- return x;
-};
-
-var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {
- if (opts && opts.preserveSymlinks === false) {
- return realpathSync(x);
- }
- return x;
-};
-
-var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) {
- var body = readFileSync(pkgfile);
- try {
- var pkg = JSON.parse(body);
- return pkg;
- } catch (jsonErr) {}
-};
-
-var getPackageCandidates = function getPackageCandidates(x, start, opts) {
- var dirs = nodeModulesPaths(start, opts, x);
- for (var i = 0; i < dirs.length; i++) {
- dirs[i] = path.join(dirs[i], x);
- }
- return dirs;
-};
-
-module.exports = function resolveSync(x, options) {
- if (typeof x !== 'string') {
- throw new TypeError('Path must be a string.');
- }
- var opts = normalizeOptions(x, options);
-
- var isFile = opts.isFile || defaultIsFile;
- var readFileSync = opts.readFileSync || fs.readFileSync;
- var isDirectory = opts.isDirectory || defaultIsDir;
- var realpathSync = opts.realpathSync || defaultRealpathSync;
- var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
- if (opts.readFileSync && opts.readPackageSync) {
- throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.');
- }
- var packageIterator = opts.packageIterator;
-
- var extensions = opts.extensions || ['.js'];
- var includeCoreModules = opts.includeCoreModules !== false;
- var basedir = opts.basedir || path.dirname(caller());
- var parent = opts.filename || basedir;
-
- opts.paths = opts.paths || defaultPaths();
-
- // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
- var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts);
-
- if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
- var res = path.resolve(absoluteStart, x);
- if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
- var m = loadAsFileSync(res) || loadAsDirectorySync(res);
- if (m) return maybeRealpathSync(realpathSync, m, opts);
- } else if (includeCoreModules && isCore(x)) {
- return x;
- } else {
- var n = loadNodeModulesSync(x, absoluteStart);
- if (n) return maybeRealpathSync(realpathSync, n, opts);
- }
-
- var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- err.code = 'MODULE_NOT_FOUND';
- throw err;
-
- function loadAsFileSync(x) {
- var pkg = loadpkg(path.dirname(x));
-
- if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
- var rfile = path.relative(pkg.dir, x);
- var r = opts.pathFilter(pkg.pkg, x, rfile);
- if (r) {
- x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
- }
- }
-
- if (isFile(x)) {
- return x;
- }
-
- for (var i = 0; i < extensions.length; i++) {
- var file = x + extensions[i];
- if (isFile(file)) {
- return file;
- }
- }
- }
-
- function loadpkg(dir) {
- if (dir === '' || dir === '/') return;
- if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
- return;
- }
- if ((/[/\\]node_modules[/\\]*$/).test(dir)) return;
-
- var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');
-
- if (!isFile(pkgfile)) {
- return loadpkg(path.dirname(dir));
- }
-
- var pkg = readPackageSync(readFileSync, pkgfile);
-
- if (pkg && opts.packageFilter) {
- // v2 will pass pkgfile
- pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment
- }
-
- return { pkg: pkg, dir: dir };
- }
-
- function loadAsDirectorySync(x) {
- var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json');
- if (isFile(pkgfile)) {
- try {
- var pkg = readPackageSync(readFileSync, pkgfile);
- } catch (e) {}
-
- if (pkg && opts.packageFilter) {
- // v2 will pass pkgfile
- pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment
- }
-
- if (pkg && pkg.main) {
- if (typeof pkg.main !== 'string') {
- var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
- mainError.code = 'INVALID_PACKAGE_MAIN';
- throw mainError;
- }
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- try {
- var m = loadAsFileSync(path.resolve(x, pkg.main));
- if (m) return m;
- var n = loadAsDirectorySync(path.resolve(x, pkg.main));
- if (n) return n;
- } catch (e) {}
- }
- }
-
- return loadAsFileSync(path.join(x, '/index'));
- }
-
- function loadNodeModulesSync(x, start) {
- var thunk = function () { return getPackageCandidates(x, start, opts); };
- var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
-
- for (var i = 0; i < dirs.length; i++) {
- var dir = dirs[i];
- if (isDirectory(path.dirname(dir))) {
- var m = loadAsFileSync(dir);
- if (m) return m;
- var n = loadAsDirectorySync(dir);
- if (n) return n;
- }
- }
- }
-};
-
-
-/***/ }),
-
-/***/ 32428:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var assert = __nccwpck_require__(39491);
-var isExpression = __nccwpck_require__(53448);
-var characterParser = __nccwpck_require__(8937);
-var error = __nccwpck_require__(11449);
-
-module.exports = lex;
-module.exports.Lexer = Lexer;
-function lex(str, options) {
- var lexer = new Lexer(str, options);
- return JSON.parse(JSON.stringify(lexer.getTokens()));
-}
-
-/**
- * Initialize `Lexer` with the given `str`.
- *
- * @param {String} str
- * @param {String} filename
- * @api private
- */
-
-function Lexer(str, options) {
- options = options || {};
- if (typeof str !== 'string') {
- throw new Error(
- 'Expected source code to be a string but got "' + typeof str + '"'
- );
- }
- if (typeof options !== 'object') {
- throw new Error(
- 'Expected "options" to be an object but got "' + typeof options + '"'
- );
- }
- //Strip any UTF-8 BOM off of the start of `str`, if it exists.
- str = str.replace(/^\uFEFF/, '');
- this.input = str.replace(/\r\n|\r/g, '\n');
- this.originalInput = this.input;
- this.filename = options.filename;
- this.interpolated = options.interpolated || false;
- this.lineno = options.startingLine || 1;
- this.colno = options.startingColumn || 1;
- this.plugins = options.plugins || [];
- this.indentStack = [0];
- this.indentRe = null;
- // If #{}, !{} or #[] syntax is allowed when adding text
- this.interpolationAllowed = true;
- this.whitespaceRe = /[ \n\t]/;
-
- this.tokens = [];
- this.ended = false;
-}
-
-/**
- * Lexer prototype.
- */
-
-Lexer.prototype = {
- constructor: Lexer,
-
- error: function(code, message) {
- var err = error(code, message, {
- line: this.lineno,
- column: this.colno,
- filename: this.filename,
- src: this.originalInput,
- });
- throw err;
- },
-
- assert: function(value, message) {
- if (!value) this.error('ASSERT_FAILED', message);
- },
-
- isExpression: function(exp) {
- return isExpression(exp, {
- throw: true,
- });
- },
-
- assertExpression: function(exp, noThrow) {
- //this verifies that a JavaScript expression is valid
- try {
- this.callLexerFunction('isExpression', exp);
- return true;
- } catch (ex) {
- if (noThrow) return false;
-
- // not coming from acorn
- if (!ex.loc) throw ex;
-
- this.incrementLine(ex.loc.line - 1);
- this.incrementColumn(ex.loc.column);
- var msg =
- 'Syntax Error: ' + ex.message.replace(/ \([0-9]+:[0-9]+\)$/, '');
- this.error('SYNTAX_ERROR', msg);
- }
- },
-
- assertNestingCorrect: function(exp) {
- //this verifies that code is properly nested, but allows
- //invalid JavaScript such as the contents of `attributes`
- var res = characterParser(exp);
- if (res.isNesting()) {
- this.error(
- 'INCORRECT_NESTING',
- 'Nesting must match on expression `' + exp + '`'
- );
- }
- },
-
- /**
- * Construct a token with the given `type` and `val`.
- *
- * @param {String} type
- * @param {String} val
- * @return {Object}
- * @api private
- */
-
- tok: function(type, val) {
- var res = {
- type: type,
- loc: {
- start: {
- line: this.lineno,
- column: this.colno,
- },
- filename: this.filename,
- },
- };
-
- if (val !== undefined) res.val = val;
-
- return res;
- },
-
- /**
- * Set the token's `loc.end` value.
- *
- * @param {Object} tok
- * @returns {Object}
- * @api private
- */
-
- tokEnd: function(tok) {
- tok.loc.end = {
- line: this.lineno,
- column: this.colno,
- };
- return tok;
- },
-
- /**
- * Increment `this.lineno` and reset `this.colno`.
- *
- * @param {Number} increment
- * @api private
- */
-
- incrementLine: function(increment) {
- this.lineno += increment;
- if (increment) this.colno = 1;
- },
-
- /**
- * Increment `this.colno`.
- *
- * @param {Number} increment
- * @api private
- */
-
- incrementColumn: function(increment) {
- this.colno += increment;
- },
-
- /**
- * Consume the given `len` of input.
- *
- * @param {Number} len
- * @api private
- */
-
- consume: function(len) {
- this.input = this.input.substr(len);
- },
-
- /**
- * Scan for `type` with the given `regexp`.
- *
- * @param {String} type
- * @param {RegExp} regexp
- * @return {Object}
- * @api private
- */
-
- scan: function(regexp, type) {
- var captures;
- if ((captures = regexp.exec(this.input))) {
- var len = captures[0].length;
- var val = captures[1];
- var diff = len - (val ? val.length : 0);
- var tok = this.tok(type, val);
- this.consume(len);
- this.incrementColumn(diff);
- return tok;
- }
- },
- scanEndOfLine: function(regexp, type) {
- var captures;
- if ((captures = regexp.exec(this.input))) {
- var whitespaceLength = 0;
- var whitespace;
- var tok;
- if ((whitespace = /^([ ]+)([^ ]*)/.exec(captures[0]))) {
- whitespaceLength = whitespace[1].length;
- this.incrementColumn(whitespaceLength);
- }
- var newInput = this.input.substr(captures[0].length);
- if (newInput[0] === ':') {
- this.input = newInput;
- tok = this.tok(type, captures[1]);
- this.incrementColumn(captures[0].length - whitespaceLength);
- return tok;
- }
- if (/^[ \t]*(\n|$)/.test(newInput)) {
- this.input = newInput.substr(/^[ \t]*/.exec(newInput)[0].length);
- tok = this.tok(type, captures[1]);
- this.incrementColumn(captures[0].length - whitespaceLength);
- return tok;
- }
- }
- },
-
- /**
- * Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters.
- *
- * Make sure that when calling this function, colno is at the character
- * immediately before the beginning.
- *
- * @return {Number}
- * @api private
- */
-
- bracketExpression: function(skip) {
- skip = skip || 0;
- var start = this.input[skip];
- assert(
- start === '(' || start === '{' || start === '[',
- 'The start character should be "(", "{" or "["'
- );
- var end = characterParser.BRACKETS[start];
- var range;
- try {
- range = characterParser.parseUntil(this.input, end, {start: skip + 1});
- } catch (ex) {
- if (ex.index !== undefined) {
- var idx = ex.index;
- // starting from this.input[skip]
- var tmp = this.input.substr(skip).indexOf('\n');
- // starting from this.input[0]
- var nextNewline = tmp + skip;
- var ptr = 0;
- while (idx > nextNewline && tmp !== -1) {
- this.incrementLine(1);
- idx -= nextNewline + 1;
- ptr += nextNewline + 1;
- tmp = nextNewline = this.input.substr(ptr).indexOf('\n');
- }
-
- this.incrementColumn(idx);
- }
- if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
- this.error(
- 'NO_END_BRACKET',
- 'The end of the string reached with no closing bracket ' +
- end +
- ' found.'
- );
- } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
- this.error('BRACKET_MISMATCH', ex.message);
- }
- throw ex;
- }
- return range;
- },
-
- scanIndentation: function() {
- var captures, re;
-
- // established regexp
- if (this.indentRe) {
- captures = this.indentRe.exec(this.input);
- // determine regexp
- } else {
- // tabs
- re = /^\n(\t*) */;
- captures = re.exec(this.input);
-
- // spaces
- if (captures && !captures[1].length) {
- re = /^\n( *)/;
- captures = re.exec(this.input);
- }
-
- // established
- if (captures && captures[1].length) this.indentRe = re;
- }
-
- return captures;
- },
-
- /**
- * end-of-source.
- */
-
- eos: function() {
- if (this.input.length) return;
- if (this.interpolated) {
- this.error(
- 'NO_END_BRACKET',
- 'End of line was reached with no closing bracket for interpolation.'
- );
- }
- for (var i = 0; this.indentStack[i]; i++) {
- this.tokens.push(this.tokEnd(this.tok('outdent')));
- }
- this.tokens.push(this.tokEnd(this.tok('eos')));
- this.ended = true;
- return true;
- },
-
- /**
- * Blank line.
- */
-
- blank: function() {
- var captures;
- if ((captures = /^\n[ \t]*\n/.exec(this.input))) {
- this.consume(captures[0].length - 1);
- this.incrementLine(1);
- return true;
- }
- },
-
- /**
- * Comment.
- */
-
- comment: function() {
- var captures;
- if ((captures = /^\/\/(-)?([^\n]*)/.exec(this.input))) {
- this.consume(captures[0].length);
- var tok = this.tok('comment', captures[2]);
- tok.buffer = '-' != captures[1];
- this.interpolationAllowed = tok.buffer;
- this.tokens.push(tok);
- this.incrementColumn(captures[0].length);
- this.tokEnd(tok);
- this.callLexerFunction('pipelessText');
- return true;
- }
- },
-
- /**
- * Interpolated tag.
- */
-
- interpolation: function() {
- if (/^#\{/.test(this.input)) {
- var match = this.bracketExpression(1);
- this.consume(match.end + 1);
- var tok = this.tok('interpolation', match.src);
- this.tokens.push(tok);
- this.incrementColumn(2); // '#{'
- this.assertExpression(match.src);
-
- var splitted = match.src.split('\n');
- var lines = splitted.length - 1;
- this.incrementLine(lines);
- this.incrementColumn(splitted[lines].length + 1); // + 1 → '}'
- this.tokEnd(tok);
- return true;
- }
- },
-
- /**
- * Tag.
- */
-
- tag: function() {
- var captures;
-
- if ((captures = /^(\w(?:[-:\w]*\w)?)/.exec(this.input))) {
- var tok,
- name = captures[1],
- len = captures[0].length;
- this.consume(len);
- tok = this.tok('tag', name);
- this.tokens.push(tok);
- this.incrementColumn(len);
- this.tokEnd(tok);
- return true;
- }
- },
-
- /**
- * Filter.
- */
-
- filter: function(opts) {
- var tok = this.scan(/^:([\w\-]+)/, 'filter');
- var inInclude = opts && opts.inInclude;
- if (tok) {
- this.tokens.push(tok);
- this.incrementColumn(tok.val.length);
- this.tokEnd(tok);
- this.callLexerFunction('attrs');
- if (!inInclude) {
- this.interpolationAllowed = false;
- this.callLexerFunction('pipelessText');
- }
- return true;
- }
- },
-
- /**
- * Doctype.
- */
-
- doctype: function() {
- var node = this.scanEndOfLine(/^doctype *([^\n]*)/, 'doctype');
- if (node) {
- this.tokens.push(this.tokEnd(node));
- return true;
- }
- },
-
- /**
- * Id.
- */
-
- id: function() {
- var tok = this.scan(/^#([\w-]+)/, 'id');
- if (tok) {
- this.tokens.push(tok);
- this.incrementColumn(tok.val.length);
- this.tokEnd(tok);
- return true;
- }
- if (/^#/.test(this.input)) {
- this.error(
- 'INVALID_ID',
- '"' +
- /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] +
- '" is not a valid ID.'
- );
- }
- },
-
- /**
- * Class.
- */
-
- className: function() {
- var tok = this.scan(/^\.([_a-z0-9\-]*[_a-z][_a-z0-9\-]*)/i, 'class');
- if (tok) {
- this.tokens.push(tok);
- this.incrementColumn(tok.val.length);
- this.tokEnd(tok);
- return true;
- }
- if (/^\.[_a-z0-9\-]+/i.test(this.input)) {
- this.error(
- 'INVALID_CLASS_NAME',
- 'Class names must contain at least one letter or underscore.'
- );
- }
- if (/^\./.test(this.input)) {
- this.error(
- 'INVALID_CLASS_NAME',
- '"' +
- /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] +
- '" is not a valid class name. Class names can only contain "_", "-", a-z and 0-9, and must contain at least one of "_", or a-z'
- );
- }
- },
-
- /**
- * Text.
- */
- endInterpolation: function() {
- if (this.interpolated && this.input[0] === ']') {
- this.input = this.input.substr(1);
- this.ended = true;
- return true;
- }
- },
- addText: function(type, value, prefix, escaped) {
- var tok;
- if (value + prefix === '') return;
- prefix = prefix || '';
- escaped = escaped || 0;
- var indexOfEnd = this.interpolated ? value.indexOf(']') : -1;
- var indexOfStart = this.interpolationAllowed ? value.indexOf('#[') : -1;
- var indexOfEscaped = this.interpolationAllowed ? value.indexOf('\\#[') : -1;
- var matchOfStringInterp = /(\\)?([#!]){((?:.|\n)*)$/.exec(value);
- var indexOfStringInterp =
- this.interpolationAllowed && matchOfStringInterp
- ? matchOfStringInterp.index
- : Infinity;
-
- if (indexOfEnd === -1) indexOfEnd = Infinity;
- if (indexOfStart === -1) indexOfStart = Infinity;
- if (indexOfEscaped === -1) indexOfEscaped = Infinity;
-
- if (
- indexOfEscaped !== Infinity &&
- indexOfEscaped < indexOfEnd &&
- indexOfEscaped < indexOfStart &&
- indexOfEscaped < indexOfStringInterp
- ) {
- prefix = prefix + value.substring(0, indexOfEscaped) + '#[';
- return this.addText(
- type,
- value.substring(indexOfEscaped + 3),
- prefix,
- escaped + 1
- );
- }
- if (
- indexOfStart !== Infinity &&
- indexOfStart < indexOfEnd &&
- indexOfStart < indexOfEscaped &&
- indexOfStart < indexOfStringInterp
- ) {
- tok = this.tok(type, prefix + value.substring(0, indexOfStart));
- this.incrementColumn(prefix.length + indexOfStart + escaped);
- this.tokens.push(this.tokEnd(tok));
- tok = this.tok('start-pug-interpolation');
- this.incrementColumn(2);
- this.tokens.push(this.tokEnd(tok));
- var child = new this.constructor(value.substr(indexOfStart + 2), {
- filename: this.filename,
- interpolated: true,
- startingLine: this.lineno,
- startingColumn: this.colno,
- plugins: this.plugins,
- });
- var interpolated;
- try {
- interpolated = child.getTokens();
- } catch (ex) {
- if (ex.code && /^PUG:/.test(ex.code)) {
- this.colno = ex.column;
- this.error(ex.code.substr(4), ex.msg);
- }
- throw ex;
- }
- this.colno = child.colno;
- this.tokens = this.tokens.concat(interpolated);
- tok = this.tok('end-pug-interpolation');
- this.incrementColumn(1);
- this.tokens.push(this.tokEnd(tok));
- this.addText(type, child.input);
- return;
- }
- if (
- indexOfEnd !== Infinity &&
- indexOfEnd < indexOfStart &&
- indexOfEnd < indexOfEscaped &&
- indexOfEnd < indexOfStringInterp
- ) {
- if (prefix + value.substring(0, indexOfEnd)) {
- this.addText(type, value.substring(0, indexOfEnd), prefix);
- }
- this.ended = true;
- this.input = value.substr(value.indexOf(']') + 1) + this.input;
- return;
- }
- if (indexOfStringInterp !== Infinity) {
- if (matchOfStringInterp[1]) {
- prefix =
- prefix +
- value.substring(0, indexOfStringInterp) +
- matchOfStringInterp[2] +
- '{';
- return this.addText(
- type,
- value.substring(indexOfStringInterp + 3),
- prefix,
- escaped + 1
- );
- }
- var before = value.substr(0, indexOfStringInterp);
- if (prefix || before) {
- before = prefix + before;
- tok = this.tok(type, before);
- this.incrementColumn(before.length + escaped);
- this.tokens.push(this.tokEnd(tok));
- }
-
- var rest = matchOfStringInterp[3];
- var range;
- tok = this.tok('interpolated-code');
- this.incrementColumn(2);
- try {
- range = characterParser.parseUntil(rest, '}');
- } catch (ex) {
- if (ex.index !== undefined) {
- this.incrementColumn(ex.index);
- }
- if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
- this.error(
- 'NO_END_BRACKET',
- 'End of line was reached with no closing bracket for interpolation.'
- );
- } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
- this.error('BRACKET_MISMATCH', ex.message);
- } else {
- throw ex;
- }
- }
- tok.mustEscape = matchOfStringInterp[2] === '#';
- tok.buffer = true;
- tok.val = range.src;
- this.assertExpression(range.src);
-
- if (range.end + 1 < rest.length) {
- rest = rest.substr(range.end + 1);
- this.incrementColumn(range.end + 1);
- this.tokens.push(this.tokEnd(tok));
- this.addText(type, rest);
- } else {
- this.incrementColumn(rest.length);
- this.tokens.push(this.tokEnd(tok));
- }
- return;
- }
-
- value = prefix + value;
- tok = this.tok(type, value);
- this.incrementColumn(value.length + escaped);
- this.tokens.push(this.tokEnd(tok));
- },
-
- text: function() {
- var tok =
- this.scan(/^(?:\| ?| )([^\n]+)/, 'text') ||
- this.scan(/^( )/, 'text') ||
- this.scan(/^\|( ?)/, 'text');
- if (tok) {
- this.addText('text', tok.val);
- return true;
- }
- },
-
- textHtml: function() {
- var tok = this.scan(/^(<[^\n]*)/, 'text-html');
- if (tok) {
- this.addText('text-html', tok.val);
- return true;
- }
- },
-
- /**
- * Dot.
- */
-
- dot: function() {
- var tok;
- if ((tok = this.scanEndOfLine(/^\./, 'dot'))) {
- this.tokens.push(this.tokEnd(tok));
- this.callLexerFunction('pipelessText');
- return true;
- }
- },
-
- /**
- * Extends.
- */
-
- extends: function() {
- var tok = this.scan(/^extends?(?= |$|\n)/, 'extends');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- if (!this.callLexerFunction('path')) {
- this.error('NO_EXTENDS_PATH', 'missing path for extends');
- }
- return true;
- }
- if (this.scan(/^extends?\b/)) {
- this.error('MALFORMED_EXTENDS', 'malformed extends');
- }
- },
-
- /**
- * Block prepend.
- */
-
- prepend: function() {
- var captures;
- if ((captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input))) {
- var name = captures[1].trim();
- var comment = '';
- if (name.indexOf('//') !== -1) {
- comment =
- '//' +
- name
- .split('//')
- .slice(1)
- .join('//');
- name = name.split('//')[0].trim();
- }
- if (!name) return;
- var tok = this.tok('block', name);
- var len = captures[0].length - comment.length;
- while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
- this.incrementColumn(len);
- tok.mode = 'prepend';
- this.tokens.push(this.tokEnd(tok));
- this.consume(captures[0].length - comment.length);
- this.incrementColumn(captures[0].length - comment.length - len);
- return true;
- }
- },
-
- /**
- * Block append.
- */
-
- append: function() {
- var captures;
- if ((captures = /^(?:block +)?append +([^\n]+)/.exec(this.input))) {
- var name = captures[1].trim();
- var comment = '';
- if (name.indexOf('//') !== -1) {
- comment =
- '//' +
- name
- .split('//')
- .slice(1)
- .join('//');
- name = name.split('//')[0].trim();
- }
- if (!name) return;
- var tok = this.tok('block', name);
- var len = captures[0].length - comment.length;
- while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
- this.incrementColumn(len);
- tok.mode = 'append';
- this.tokens.push(this.tokEnd(tok));
- this.consume(captures[0].length - comment.length);
- this.incrementColumn(captures[0].length - comment.length - len);
- return true;
- }
- },
-
- /**
- * Block.
- */
-
- block: function() {
- var captures;
- if ((captures = /^block +([^\n]+)/.exec(this.input))) {
- var name = captures[1].trim();
- var comment = '';
- if (name.indexOf('//') !== -1) {
- comment =
- '//' +
- name
- .split('//')
- .slice(1)
- .join('//');
- name = name.split('//')[0].trim();
- }
- if (!name) return;
- var tok = this.tok('block', name);
- var len = captures[0].length - comment.length;
- while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--;
- this.incrementColumn(len);
- tok.mode = 'replace';
- this.tokens.push(this.tokEnd(tok));
- this.consume(captures[0].length - comment.length);
- this.incrementColumn(captures[0].length - comment.length - len);
- return true;
- }
- },
-
- /**
- * Mixin Block.
- */
-
- mixinBlock: function() {
- var tok;
- if ((tok = this.scanEndOfLine(/^block/, 'mixin-block'))) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Yield.
- */
-
- yield: function() {
- var tok = this.scanEndOfLine(/^yield/, 'yield');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Include.
- */
-
- include: function() {
- var tok = this.scan(/^include(?=:| |$|\n)/, 'include');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- while (this.callLexerFunction('filter', {inInclude: true}));
- if (!this.callLexerFunction('path')) {
- if (/^[^ \n]+/.test(this.input)) {
- // if there is more text
- this.fail();
- } else {
- // if not
- this.error('NO_INCLUDE_PATH', 'missing path for include');
- }
- }
- return true;
- }
- if (this.scan(/^include\b/)) {
- this.error('MALFORMED_INCLUDE', 'malformed include');
- }
- },
-
- /**
- * Path
- */
-
- path: function() {
- var tok = this.scanEndOfLine(/^ ([^\n]+)/, 'path');
- if (tok && (tok.val = tok.val.trim())) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Case.
- */
-
- case: function() {
- var tok = this.scanEndOfLine(/^case +([^\n]+)/, 'case');
- if (tok) {
- this.incrementColumn(-tok.val.length);
- this.assertExpression(tok.val);
- this.incrementColumn(tok.val.length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- if (this.scan(/^case\b/)) {
- this.error('NO_CASE_EXPRESSION', 'missing expression for case');
- }
- },
-
- /**
- * When.
- */
-
- when: function() {
- var tok = this.scanEndOfLine(/^when +([^:\n]+)/, 'when');
- if (tok) {
- var parser = characterParser(tok.val);
- while (parser.isNesting() || parser.isString()) {
- var rest = /:([^:\n]+)/.exec(this.input);
- if (!rest) break;
-
- tok.val += rest[0];
- this.consume(rest[0].length);
- this.incrementColumn(rest[0].length);
- parser = characterParser(tok.val);
- }
-
- this.incrementColumn(-tok.val.length);
- this.assertExpression(tok.val);
- this.incrementColumn(tok.val.length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- if (this.scan(/^when\b/)) {
- this.error('NO_WHEN_EXPRESSION', 'missing expression for when');
- }
- },
-
- /**
- * Default.
- */
-
- default: function() {
- var tok = this.scanEndOfLine(/^default/, 'default');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- if (this.scan(/^default\b/)) {
- this.error(
- 'DEFAULT_WITH_EXPRESSION',
- 'default should not have an expression'
- );
- }
- },
-
- /**
- * Call mixin.
- */
-
- call: function() {
- var tok, captures, increment;
- if ((captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input))) {
- // try to consume simple or interpolated call
- if (captures[3]) {
- // simple call
- increment = captures[0].length;
- this.consume(increment);
- tok = this.tok('call', captures[3]);
- } else {
- // interpolated call
- var match = this.bracketExpression(2 + captures[1].length);
- increment = match.end + 1;
- this.consume(increment);
- this.assertExpression(match.src);
- tok = this.tok('call', '#{' + match.src + '}');
- }
-
- this.incrementColumn(increment);
-
- tok.args = null;
- // Check for args (not attributes)
- if ((captures = /^ *\(/.exec(this.input))) {
- var range = this.bracketExpression(captures[0].length - 1);
- if (!/^\s*[-\w]+ *=/.test(range.src)) {
- // not attributes
- this.incrementColumn(1);
- this.consume(range.end + 1);
- tok.args = range.src;
- this.assertExpression('[' + tok.args + ']');
- for (var i = 0; i <= tok.args.length; i++) {
- if (tok.args[i] === '\n') {
- this.incrementLine(1);
- } else {
- this.incrementColumn(1);
- }
- }
- }
- }
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Mixin.
- */
-
- mixin: function() {
- var captures;
- if ((captures = /^mixin +([-\w]+)(?: *\((.*)\))? */.exec(this.input))) {
- this.consume(captures[0].length);
- var tok = this.tok('mixin', captures[1]);
- tok.args = captures[2] || null;
- this.incrementColumn(captures[0].length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Conditional.
- */
-
- conditional: function() {
- var captures;
- if ((captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input))) {
- this.consume(captures[0].length);
- var type = captures[1].replace(/ /g, '-');
- var js = captures[2] && captures[2].trim();
- // type can be "if", "else-if" and "else"
- var tok = this.tok(type, js);
- this.incrementColumn(captures[0].length - js.length);
-
- switch (type) {
- case 'if':
- case 'else-if':
- this.assertExpression(js);
- break;
- case 'unless':
- this.assertExpression(js);
- tok.val = '!(' + js + ')';
- tok.type = 'if';
- break;
- case 'else':
- if (js) {
- this.error(
- 'ELSE_CONDITION',
- '`else` cannot have a condition, perhaps you meant `else if`'
- );
- }
- break;
- }
- this.incrementColumn(js.length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * While.
- */
-
- while: function() {
- var captures, tok;
- if ((captures = /^while +([^\n]+)/.exec(this.input))) {
- this.consume(captures[0].length);
- this.assertExpression(captures[1]);
- tok = this.tok('while', captures[1]);
- this.incrementColumn(captures[0].length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- if (this.scan(/^while\b/)) {
- this.error('NO_WHILE_EXPRESSION', 'missing expression for while');
- }
- },
-
- /**
- * Each.
- */
-
- each: function() {
- var captures;
- if (
- (captures = /^(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec(
- this.input
- ))
- ) {
- this.consume(captures[0].length);
- var tok = this.tok('each', captures[1]);
- tok.key = captures[2] || null;
- this.incrementColumn(captures[0].length - captures[3].length);
- this.assertExpression(captures[3]);
- tok.code = captures[3];
- this.incrementColumn(captures[3].length);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- const name = /^each\b/.exec(this.input) ? 'each' : 'for';
- if (this.scan(/^(?:each|for)\b/)) {
- this.error(
- 'MALFORMED_EACH',
- 'This `' +
- name +
- '` has a syntax error. `' +
- name +
- '` statements should be of the form: `' +
- name +
- ' VARIABLE_NAME of JS_EXPRESSION`'
- );
- }
- if (
- (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +in +([^\n]+)/.exec(
- this.input
- ))
- ) {
- this.error(
- 'MALFORMED_EACH',
- 'Pug each and for should no longer be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.'
- );
- }
- },
-
- /**
- * EachOf.
- */
-
- eachOf: function() {
- var captures;
- if ((captures = /^(?:each|for) (.*?) of *([^\n]+)/.exec(this.input))) {
- this.consume(captures[0].length);
- var tok = this.tok('eachOf', captures[1]);
- tok.value = captures[1];
- this.incrementColumn(captures[0].length - captures[2].length);
- this.assertExpression(captures[2]);
- tok.code = captures[2];
- this.incrementColumn(captures[2].length);
- this.tokens.push(this.tokEnd(tok));
-
- if (
- !(
- /^[a-zA-Z_$][\w$]*$/.test(tok.value.trim()) ||
- /^\[ *[a-zA-Z_$][\w$]* *\, *[a-zA-Z_$][\w$]* *\]$/.test(
- tok.value.trim()
- )
- )
- ) {
- this.error(
- 'MALFORMED_EACH_OF_LVAL',
- 'The value variable for each must either be a valid identifier (e.g. `item`) or a pair of identifiers in square brackets (e.g. `[key, value]`).'
- );
- }
-
- return true;
- }
- if (
- (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +of +([^\n]+)/.exec(
- this.input
- ))
- ) {
- this.error(
- 'MALFORMED_EACH',
- 'Pug each and for should not be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.'
- );
- }
- },
-
- /**
- * Code.
- */
-
- code: function() {
- var captures;
- if ((captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input))) {
- var flags = captures[1];
- var code = captures[2];
- var shortened = 0;
- if (this.interpolated) {
- var parsed;
- try {
- parsed = characterParser.parseUntil(code, ']');
- } catch (err) {
- if (err.index !== undefined) {
- this.incrementColumn(captures[0].length - code.length + err.index);
- }
- if (err.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') {
- this.error(
- 'NO_END_BRACKET',
- 'End of line was reached with no closing bracket for interpolation.'
- );
- } else if (err.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') {
- this.error('BRACKET_MISMATCH', err.message);
- } else {
- throw err;
- }
- }
- shortened = code.length - parsed.end;
- code = parsed.src;
- }
- var consumed = captures[0].length - shortened;
- this.consume(consumed);
- var tok = this.tok('code', code);
- tok.mustEscape = flags.charAt(0) === '=';
- tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '=';
-
- // p #[!= abc] hey
- // ^ original colno
- // -------------- captures[0]
- // -------- captures[2]
- // ------ captures[0] - captures[2]
- // ^ after colno
-
- // = abc
- // ^ original colno
- // ------- captures[0]
- // --- captures[2]
- // ---- captures[0] - captures[2]
- // ^ after colno
- this.incrementColumn(captures[0].length - captures[2].length);
- if (tok.buffer) this.assertExpression(code);
- this.tokens.push(tok);
-
- // p #[!= abc] hey
- // ^ original colno
- // ----- shortened
- // --- code
- // ^ after colno
-
- // = abc
- // ^ original colno
- // shortened
- // --- code
- // ^ after colno
- this.incrementColumn(code.length);
- this.tokEnd(tok);
- return true;
- }
- },
-
- /**
- * Block code.
- */
- blockCode: function() {
- var tok;
- if ((tok = this.scanEndOfLine(/^-/, 'blockcode'))) {
- this.tokens.push(this.tokEnd(tok));
- this.interpolationAllowed = false;
- this.callLexerFunction('pipelessText');
- return true;
- }
- },
-
- /**
- * Attribute Name.
- */
- attribute: function(str) {
- var quote = '';
- var quoteRe = /['"]/;
- var key = '';
- var i;
-
- // consume all whitespace before the key
- for (i = 0; i < str.length; i++) {
- if (!this.whitespaceRe.test(str[i])) break;
- if (str[i] === '\n') {
- this.incrementLine(1);
- } else {
- this.incrementColumn(1);
- }
- }
-
- if (i === str.length) {
- return '';
- }
-
- var tok = this.tok('attribute');
-
- // quote?
- if (quoteRe.test(str[i])) {
- quote = str[i];
- this.incrementColumn(1);
- i++;
- }
-
- // start looping through the key
- for (; i < str.length; i++) {
- if (quote) {
- if (str[i] === quote) {
- this.incrementColumn(1);
- i++;
- break;
- }
- } else {
- if (
- this.whitespaceRe.test(str[i]) ||
- str[i] === '!' ||
- str[i] === '=' ||
- str[i] === ','
- ) {
- break;
- }
- }
-
- key += str[i];
-
- if (str[i] === '\n') {
- this.incrementLine(1);
- } else {
- this.incrementColumn(1);
- }
- }
-
- tok.name = key;
-
- var valueResponse = this.attributeValue(str.substr(i));
-
- if (valueResponse.val) {
- tok.val = valueResponse.val;
- tok.mustEscape = valueResponse.mustEscape;
- } else {
- // was a boolean attribute (ex: `input(disabled)`)
- tok.val = true;
- tok.mustEscape = true;
- }
-
- str = valueResponse.remainingSource;
-
- this.tokens.push(this.tokEnd(tok));
-
- for (i = 0; i < str.length; i++) {
- if (!this.whitespaceRe.test(str[i])) {
- break;
- }
- if (str[i] === '\n') {
- this.incrementLine(1);
- } else {
- this.incrementColumn(1);
- }
- }
-
- if (str[i] === ',') {
- this.incrementColumn(1);
- i++;
- }
-
- return str.substr(i);
- },
-
- /**
- * Attribute Value.
- */
- attributeValue: function(str) {
- var quoteRe = /['"]/;
- var val = '';
- var done, i, x;
- var escapeAttr = true;
- var state = characterParser.defaultState();
- var col = this.colno;
- var line = this.lineno;
-
- // consume all whitespace before the equals sign
- for (i = 0; i < str.length; i++) {
- if (!this.whitespaceRe.test(str[i])) break;
- if (str[i] === '\n') {
- line++;
- col = 1;
- } else {
- col++;
- }
- }
-
- if (i === str.length) {
- return {remainingSource: str};
- }
-
- if (str[i] === '!') {
- escapeAttr = false;
- col++;
- i++;
- if (str[i] !== '=')
- this.error(
- 'INVALID_KEY_CHARACTER',
- 'Unexpected character ' + str[i] + ' expected `=`'
- );
- }
-
- if (str[i] !== '=') {
- // check for anti-pattern `div("foo"bar)`
- if (i === 0 && str && !this.whitespaceRe.test(str[0]) && str[0] !== ',') {
- this.error(
- 'INVALID_KEY_CHARACTER',
- 'Unexpected character ' + str[0] + ' expected `=`'
- );
- } else {
- return {remainingSource: str};
- }
- }
-
- this.lineno = line;
- this.colno = col + 1;
- i++;
-
- // consume all whitespace before the value
- for (; i < str.length; i++) {
- if (!this.whitespaceRe.test(str[i])) break;
- if (str[i] === '\n') {
- this.incrementLine(1);
- } else {
- this.incrementColumn(1);
- }
- }
-
- line = this.lineno;
- col = this.colno;
-
- // start looping through the value
- for (; i < str.length; i++) {
- // if the character is in a string or in parentheses/brackets/braces
- if (!(state.isNesting() || state.isString())) {
- if (this.whitespaceRe.test(str[i])) {
- done = false;
-
- // find the first non-whitespace character
- for (x = i; x < str.length; x++) {
- if (!this.whitespaceRe.test(str[x])) {
- // if it is a JavaScript punctuator, then assume that it is
- // a part of the value
- const isNotPunctuator = !characterParser.isPunctuator(str[x]);
- const isQuote = quoteRe.test(str[x]);
- const isColon = str[x] === ':';
- const isSpreadOperator =
- str[x] + str[x + 1] + str[x + 2] === '...';
- if (
- (isNotPunctuator || isQuote || isColon || isSpreadOperator) &&
- this.assertExpression(val, true)
- ) {
- done = true;
- }
- break;
- }
- }
-
- // if everything else is whitespace, return now so last attribute
- // does not include trailing whitespace
- if (done || x === str.length) {
- break;
- }
- }
-
- // if there's no whitespace and the character is not ',', the
- // attribute did not end.
- if (str[i] === ',' && this.assertExpression(val, true)) {
- break;
- }
- }
-
- state = characterParser.parseChar(str[i], state);
- val += str[i];
-
- if (str[i] === '\n') {
- line++;
- col = 1;
- } else {
- col++;
- }
- }
-
- this.assertExpression(val);
-
- this.lineno = line;
- this.colno = col;
-
- return {val: val, mustEscape: escapeAttr, remainingSource: str.substr(i)};
- },
-
- /**
- * Attributes.
- */
-
- attrs: function() {
- var tok;
-
- if ('(' == this.input.charAt(0)) {
- tok = this.tok('start-attributes');
- var index = this.bracketExpression().end;
- var str = this.input.substr(1, index - 1);
-
- this.incrementColumn(1);
- this.tokens.push(this.tokEnd(tok));
- this.assertNestingCorrect(str);
- this.consume(index + 1);
-
- while (str) {
- str = this.attribute(str);
- }
-
- tok = this.tok('end-attributes');
- this.incrementColumn(1);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * &attributes block
- */
- attributesBlock: function() {
- if (/^&attributes\b/.test(this.input)) {
- var consumed = 11;
- this.consume(consumed);
- var tok = this.tok('&attributes');
- this.incrementColumn(consumed);
- var args = this.bracketExpression();
- consumed = args.end + 1;
- this.consume(consumed);
- tok.val = args.src;
- this.incrementColumn(consumed);
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * Indent | Outdent | Newline.
- */
-
- indent: function() {
- var captures = this.scanIndentation();
- var tok;
-
- if (captures) {
- var indents = captures[1].length;
-
- this.incrementLine(1);
- this.consume(indents + 1);
-
- if (' ' == this.input[0] || '\t' == this.input[0]) {
- this.error(
- 'INVALID_INDENTATION',
- 'Invalid indentation, you can use tabs or spaces but not both'
- );
- }
-
- // blank line
- if ('\n' == this.input[0]) {
- this.interpolationAllowed = true;
- return this.tokEnd(this.tok('newline'));
- }
-
- // outdent
- if (indents < this.indentStack[0]) {
- var outdent_count = 0;
- while (this.indentStack[0] > indents) {
- if (this.indentStack[1] < indents) {
- this.error(
- 'INCONSISTENT_INDENTATION',
- 'Inconsistent indentation. Expecting either ' +
- this.indentStack[1] +
- ' or ' +
- this.indentStack[0] +
- ' spaces/tabs.'
- );
- }
- outdent_count++;
- this.indentStack.shift();
- }
- while (outdent_count--) {
- this.colno = 1;
- tok = this.tok('outdent');
- this.colno = this.indentStack[0] + 1;
- this.tokens.push(this.tokEnd(tok));
- }
- // indent
- } else if (indents && indents != this.indentStack[0]) {
- tok = this.tok('indent', indents);
- this.colno = 1 + indents;
- this.tokens.push(this.tokEnd(tok));
- this.indentStack.unshift(indents);
- // newline
- } else {
- tok = this.tok('newline');
- this.colno = 1 + Math.min(this.indentStack[0] || 0, indents);
- this.tokens.push(this.tokEnd(tok));
- }
-
- this.interpolationAllowed = true;
- return true;
- }
- },
-
- pipelessText: function pipelessText(indents) {
- while (this.callLexerFunction('blank'));
-
- var captures = this.scanIndentation();
-
- indents = indents || (captures && captures[1].length);
- if (indents > this.indentStack[0]) {
- this.tokens.push(this.tokEnd(this.tok('start-pipeless-text')));
- var tokens = [];
- var token_indent = [];
- var isMatch;
- // Index in this.input. Can't use this.consume because we might need to
- // retry lexing the block.
- var stringPtr = 0;
- do {
- // text has `\n` as a prefix
- var i = this.input.substr(stringPtr + 1).indexOf('\n');
- if (-1 == i) i = this.input.length - stringPtr - 1;
- var str = this.input.substr(stringPtr + 1, i);
- var lineCaptures = this.indentRe.exec('\n' + str);
- var lineIndents = lineCaptures && lineCaptures[1].length;
- isMatch = lineIndents >= indents;
- token_indent.push(isMatch);
- isMatch = isMatch || !str.trim();
- if (isMatch) {
- // consume test along with `\n` prefix if match
- stringPtr += str.length + 1;
- tokens.push(str.substr(indents));
- } else if (lineIndents > this.indentStack[0]) {
- // line is indented less than the first line but is still indented
- // need to retry lexing the text block
- this.tokens.pop();
- return pipelessText.call(this, lineCaptures[1].length);
- }
- } while (this.input.length - stringPtr && isMatch);
- this.consume(stringPtr);
- while (this.input.length === 0 && tokens[tokens.length - 1] === '')
- tokens.pop();
- tokens.forEach(
- function(token, i) {
- var tok;
- this.incrementLine(1);
- if (i !== 0) tok = this.tok('newline');
- if (token_indent[i]) this.incrementColumn(indents);
- if (tok) this.tokens.push(this.tokEnd(tok));
- this.addText('text', token);
- }.bind(this)
- );
- this.tokens.push(this.tokEnd(this.tok('end-pipeless-text')));
- return true;
- }
- },
-
- /**
- * Slash.
- */
-
- slash: function() {
- var tok = this.scan(/^\//, 'slash');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- /**
- * ':'
- */
-
- colon: function() {
- var tok = this.scan(/^: +/, ':');
- if (tok) {
- this.tokens.push(this.tokEnd(tok));
- return true;
- }
- },
-
- fail: function() {
- this.error(
- 'UNEXPECTED_TEXT',
- 'unexpected text "' + this.input.substr(0, 5) + '"'
- );
- },
-
- callLexerFunction: function(func) {
- var rest = [];
- for (var i = 1; i < arguments.length; i++) {
- rest.push(arguments[i]);
- }
- var pluginArgs = [this].concat(rest);
- for (var i = 0; i < this.plugins.length; i++) {
- var plugin = this.plugins[i];
- if (plugin[func] && plugin[func].apply(plugin, pluginArgs)) {
- return true;
- }
- }
- return this[func].apply(this, rest);
- },
-
- /**
- * Move to the next token
- *
- * @api private
- */
-
- advance: function() {
- return (
- this.callLexerFunction('blank') ||
- this.callLexerFunction('eos') ||
- this.callLexerFunction('endInterpolation') ||
- this.callLexerFunction('yield') ||
- this.callLexerFunction('doctype') ||
- this.callLexerFunction('interpolation') ||
- this.callLexerFunction('case') ||
- this.callLexerFunction('when') ||
- this.callLexerFunction('default') ||
- this.callLexerFunction('extends') ||
- this.callLexerFunction('append') ||
- this.callLexerFunction('prepend') ||
- this.callLexerFunction('block') ||
- this.callLexerFunction('mixinBlock') ||
- this.callLexerFunction('include') ||
- this.callLexerFunction('mixin') ||
- this.callLexerFunction('call') ||
- this.callLexerFunction('conditional') ||
- this.callLexerFunction('eachOf') ||
- this.callLexerFunction('each') ||
- this.callLexerFunction('while') ||
- this.callLexerFunction('tag') ||
- this.callLexerFunction('filter') ||
- this.callLexerFunction('blockCode') ||
- this.callLexerFunction('code') ||
- this.callLexerFunction('id') ||
- this.callLexerFunction('dot') ||
- this.callLexerFunction('className') ||
- this.callLexerFunction('attrs') ||
- this.callLexerFunction('attributesBlock') ||
- this.callLexerFunction('indent') ||
- this.callLexerFunction('text') ||
- this.callLexerFunction('textHtml') ||
- this.callLexerFunction('comment') ||
- this.callLexerFunction('slash') ||
- this.callLexerFunction('colon') ||
- this.fail()
- );
- },
-
- /**
- * Return an array of tokens for the current file
- *
- * @returns {Array.}
- * @api public
- */
- getTokens: function() {
- while (!this.ended) {
- this.callLexerFunction('advance');
- }
- return this.tokens;
- },
-};
-
-
-/***/ }),
-
-/***/ 63234:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var assert = __nccwpck_require__(39491);
-var walk = __nccwpck_require__(60283);
-
-function error() {
- throw (__nccwpck_require__(11449).apply)(null, arguments);
-}
-
-module.exports = link;
-function link(ast) {
- assert(
- ast.type === 'Block',
- 'The top level element should always be a block'
- );
- var extendsNode = null;
- if (ast.nodes.length) {
- var hasExtends = ast.nodes[0].type === 'Extends';
- checkExtendPosition(ast, hasExtends);
- if (hasExtends) {
- extendsNode = ast.nodes.shift();
- }
- }
- ast = applyIncludes(ast);
- ast.declaredBlocks = findDeclaredBlocks(ast);
- if (extendsNode) {
- var mixins = [];
- var expectedBlocks = [];
- ast.nodes.forEach(function addNode(node) {
- if (node.type === 'NamedBlock') {
- expectedBlocks.push(node);
- } else if (node.type === 'Block') {
- node.nodes.forEach(addNode);
- } else if (node.type === 'Mixin' && node.call === false) {
- mixins.push(node);
- } else {
- error(
- 'UNEXPECTED_NODES_IN_EXTENDING_ROOT',
- 'Only named blocks and mixins can appear at the top level of an extending template',
- node
- );
- }
- });
- var parent = link(extendsNode.file.ast);
- extend(parent.declaredBlocks, ast);
- var foundBlockNames = [];
- walk(parent, function(node) {
- if (node.type === 'NamedBlock') {
- foundBlockNames.push(node.name);
- }
- });
- expectedBlocks.forEach(function(expectedBlock) {
- if (foundBlockNames.indexOf(expectedBlock.name) === -1) {
- error(
- 'UNEXPECTED_BLOCK',
- 'Unexpected block ' + expectedBlock.name,
- expectedBlock
- );
- }
- });
- Object.keys(ast.declaredBlocks).forEach(function(name) {
- parent.declaredBlocks[name] = ast.declaredBlocks[name];
- });
- parent.nodes = mixins.concat(parent.nodes);
- parent.hasExtends = true;
- return parent;
- }
- return ast;
-}
-
-function findDeclaredBlocks(ast) /*: {[name: string]: Array}*/ {
- var definitions = {};
- walk(ast, function before(node) {
- if (node.type === 'NamedBlock' && node.mode === 'replace') {
- definitions[node.name] = definitions[node.name] || [];
- definitions[node.name].push(node);
- }
- });
- return definitions;
-}
-
-function flattenParentBlocks(parentBlocks, accumulator) {
- accumulator = accumulator || [];
- parentBlocks.forEach(function(parentBlock) {
- if (parentBlock.parents) {
- flattenParentBlocks(parentBlock.parents, accumulator);
- }
- accumulator.push(parentBlock);
- });
- return accumulator;
-}
-
-function extend(parentBlocks, ast) {
- var stack = {};
- walk(
- ast,
- function before(node) {
- if (node.type === 'NamedBlock') {
- if (stack[node.name] === node.name) {
- return (node.ignore = true);
- }
- stack[node.name] = node.name;
- var parentBlockList = parentBlocks[node.name]
- ? flattenParentBlocks(parentBlocks[node.name])
- : [];
- if (parentBlockList.length) {
- node.parents = parentBlockList;
- parentBlockList.forEach(function(parentBlock) {
- switch (node.mode) {
- case 'append':
- parentBlock.nodes = parentBlock.nodes.concat(node.nodes);
- break;
- case 'prepend':
- parentBlock.nodes = node.nodes.concat(parentBlock.nodes);
- break;
- case 'replace':
- parentBlock.nodes = node.nodes;
- break;
- }
- });
- }
- }
- },
- function after(node) {
- if (node.type === 'NamedBlock' && !node.ignore) {
- delete stack[node.name];
- }
- }
- );
-}
-
-function applyIncludes(ast, child) {
- return walk(
- ast,
- function before(node, replace) {
- if (node.type === 'RawInclude') {
- replace({type: 'Text', val: node.file.str.replace(/\r/g, '')});
- }
- },
- function after(node, replace) {
- if (node.type === 'Include') {
- var childAST = link(node.file.ast);
- if (childAST.hasExtends) {
- childAST = removeBlocks(childAST);
- }
- replace(applyYield(childAST, node.block));
- }
- }
- );
-}
-function removeBlocks(ast) {
- return walk(ast, function(node, replace) {
- if (node.type === 'NamedBlock') {
- replace({
- type: 'Block',
- nodes: node.nodes,
- });
- }
- });
-}
-
-function applyYield(ast, block) {
- if (!block || !block.nodes.length) return ast;
- var replaced = false;
- ast = walk(ast, null, function(node, replace) {
- if (node.type === 'YieldBlock') {
- replaced = true;
- node.type = 'Block';
- node.nodes = [block];
- }
- });
- function defaultYieldLocation(node) {
- var res = node;
- for (var i = 0; i < node.nodes.length; i++) {
- if (node.nodes[i].textOnly) continue;
- if (node.nodes[i].type === 'Block') {
- res = defaultYieldLocation(node.nodes[i]);
- } else if (node.nodes[i].block && node.nodes[i].block.nodes.length) {
- res = defaultYieldLocation(node.nodes[i].block);
- }
- }
- return res;
- }
- if (!replaced) {
- // todo: probably should deprecate this with a warning
- defaultYieldLocation(ast).nodes.push(block);
- }
- return ast;
-}
-
-function checkExtendPosition(ast, hasExtends) {
- var legitExtendsReached = false;
- walk(ast, function(node) {
- if (node.type === 'Extends') {
- if (hasExtends && !legitExtendsReached) {
- legitExtendsReached = true;
- } else {
- error(
- 'EXTENDS_NOT_FIRST',
- 'Declaration of template inheritance ("extends") should be the first thing in the file. There can only be one extends statement per file.',
- node
- );
- }
- }
- });
-}
-
-
-/***/ }),
-
-/***/ 44254:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var fs = __nccwpck_require__(57147);
-var path = __nccwpck_require__(71017);
-var walk = __nccwpck_require__(60283);
-var assign = __nccwpck_require__(17426);
-
-module.exports = load;
-function load(ast, options) {
- options = getOptions(options);
- // clone the ast
- ast = JSON.parse(JSON.stringify(ast));
- return walk(ast, function(node) {
- if (node.str === undefined) {
- if (
- node.type === 'Include' ||
- node.type === 'RawInclude' ||
- node.type === 'Extends'
- ) {
- var file = node.file;
- if (file.type !== 'FileReference') {
- throw new Error('Expected file.type to be "FileReference"');
- }
- var path, str, raw;
- try {
- path = options.resolve(file.path, file.filename, options);
- file.fullPath = path;
- raw = options.read(path, options);
- str = raw.toString('utf8');
- } catch (ex) {
- ex.message += '\n at ' + node.filename + ' line ' + node.line;
- throw ex;
- }
- file.str = str;
- file.raw = raw;
- if (node.type === 'Extends' || node.type === 'Include') {
- file.ast = load.string(
- str,
- assign({}, options, {
- filename: path,
- })
- );
- }
- }
- }
- });
-}
-
-load.string = function loadString(src, options) {
- options = assign(getOptions(options), {
- src: src,
- });
- var tokens = options.lex(src, options);
- var ast = options.parse(tokens, options);
- return load(ast, options);
-};
-load.file = function loadFile(filename, options) {
- options = assign(getOptions(options), {
- filename: filename,
- });
- var str = options.read(filename).toString('utf8');
- return load.string(str, options);
-};
-
-load.resolve = function resolve(filename, source, options) {
- filename = filename.trim();
- if (filename[0] !== '/' && !source)
- throw new Error(
- 'the "filename" option is required to use includes and extends with "relative" paths'
- );
-
- if (filename[0] === '/' && !options.basedir)
- throw new Error(
- 'the "basedir" option is required to use includes and extends with "absolute" paths'
- );
-
- filename = path.join(
- filename[0] === '/' ? options.basedir : path.dirname(source.trim()),
- filename
- );
-
- return filename;
-};
-load.read = function read(filename, options) {
- return fs.readFileSync(filename);
-};
-
-load.validateOptions = function validateOptions(options) {
- /* istanbul ignore if */
- if (typeof options !== 'object') {
- throw new TypeError('options must be an object');
- }
- /* istanbul ignore if */
- if (typeof options.lex !== 'function') {
- throw new TypeError('options.lex must be a function');
- }
- /* istanbul ignore if */
- if (typeof options.parse !== 'function') {
- throw new TypeError('options.parse must be a function');
- }
- /* istanbul ignore if */
- if (options.resolve && typeof options.resolve !== 'function') {
- throw new TypeError('options.resolve must be a function');
- }
- /* istanbul ignore if */
- if (options.read && typeof options.read !== 'function') {
- throw new TypeError('options.read must be a function');
- }
-};
-
-function getOptions(options) {
- load.validateOptions(options);
- return assign(
- {
- resolve: load.resolve,
- read: load.read,
- },
- options
- );
-}
-
-
-/***/ }),
-
-/***/ 40558:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var assert = __nccwpck_require__(39491);
-var TokenStream = __nccwpck_require__(68758);
-var error = __nccwpck_require__(11449);
-var inlineTags = __nccwpck_require__(33470);
-
-module.exports = parse;
-module.exports.Parser = Parser;
-function parse(tokens, options) {
- var parser = new Parser(tokens, options);
- var ast = parser.parse();
- return JSON.parse(JSON.stringify(ast));
-}
-
-/**
- * Initialize `Parser` with the given input `str` and `filename`.
- *
- * @param {String} str
- * @param {String} filename
- * @param {Object} options
- * @api public
- */
-
-function Parser(tokens, options) {
- options = options || {};
- if (!Array.isArray(tokens)) {
- throw new Error(
- 'Expected tokens to be an Array but got "' + typeof tokens + '"'
- );
- }
- if (typeof options !== 'object') {
- throw new Error(
- 'Expected "options" to be an object but got "' + typeof options + '"'
- );
- }
- this.tokens = new TokenStream(tokens);
- this.filename = options.filename;
- this.src = options.src;
- this.inMixin = 0;
- this.plugins = options.plugins || [];
-}
-
-/**
- * Parser prototype.
- */
-
-Parser.prototype = {
- /**
- * Save original constructor
- */
-
- constructor: Parser,
-
- error: function(code, message, token) {
- var err = error(code, message, {
- line: token.loc.start.line,
- column: token.loc.start.column,
- filename: this.filename,
- src: this.src,
- });
- throw err;
- },
-
- /**
- * Return the next token object.
- *
- * @return {Object}
- * @api private
- */
-
- advance: function() {
- return this.tokens.advance();
- },
-
- /**
- * Single token lookahead.
- *
- * @return {Object}
- * @api private
- */
-
- peek: function() {
- return this.tokens.peek();
- },
-
- /**
- * `n` token lookahead.
- *
- * @param {Number} n
- * @return {Object}
- * @api private
- */
-
- lookahead: function(n) {
- return this.tokens.lookahead(n);
- },
-
- /**
- * Parse input returning a string of js for evaluation.
- *
- * @return {String}
- * @api public
- */
-
- parse: function() {
- var block = this.emptyBlock(0);
-
- while ('eos' != this.peek().type) {
- if ('newline' == this.peek().type) {
- this.advance();
- } else if ('text-html' == this.peek().type) {
- block.nodes = block.nodes.concat(this.parseTextHtml());
- } else {
- var expr = this.parseExpr();
- if (expr) {
- if (expr.type === 'Block') {
- block.nodes = block.nodes.concat(expr.nodes);
- } else {
- block.nodes.push(expr);
- }
- }
- }
- }
-
- return block;
- },
-
- /**
- * Expect the given type, or throw an exception.
- *
- * @param {String} type
- * @api private
- */
-
- expect: function(type) {
- if (this.peek().type === type) {
- return this.advance();
- } else {
- this.error(
- 'INVALID_TOKEN',
- 'expected "' + type + '", but got "' + this.peek().type + '"',
- this.peek()
- );
- }
- },
-
- /**
- * Accept the given `type`.
- *
- * @param {String} type
- * @api private
- */
-
- accept: function(type) {
- if (this.peek().type === type) {
- return this.advance();
- }
- },
-
- initBlock: function(line, nodes) {
- /* istanbul ignore if */
- if ((line | 0) !== line) throw new Error('`line` is not an integer');
- /* istanbul ignore if */
- if (!Array.isArray(nodes)) throw new Error('`nodes` is not an array');
- return {
- type: 'Block',
- nodes: nodes,
- line: line,
- filename: this.filename,
- };
- },
-
- emptyBlock: function(line) {
- return this.initBlock(line, []);
- },
-
- runPlugin: function(context, tok) {
- var rest = [this];
- for (var i = 2; i < arguments.length; i++) {
- rest.push(arguments[i]);
- }
- var pluginContext;
- for (var i = 0; i < this.plugins.length; i++) {
- var plugin = this.plugins[i];
- if (plugin[context] && plugin[context][tok.type]) {
- if (pluginContext)
- throw new Error(
- 'Multiple plugin handlers found for context ' +
- JSON.stringify(context) +
- ', token type ' +
- JSON.stringify(tok.type)
- );
- pluginContext = plugin[context];
- }
- }
- if (pluginContext)
- return pluginContext[tok.type].apply(pluginContext, rest);
- },
-
- /**
- * tag
- * | doctype
- * | mixin
- * | include
- * | filter
- * | comment
- * | text
- * | text-html
- * | dot
- * | each
- * | code
- * | yield
- * | id
- * | class
- * | interpolation
- */
-
- parseExpr: function() {
- switch (this.peek().type) {
- case 'tag':
- return this.parseTag();
- case 'mixin':
- return this.parseMixin();
- case 'block':
- return this.parseBlock();
- case 'mixin-block':
- return this.parseMixinBlock();
- case 'case':
- return this.parseCase();
- case 'extends':
- return this.parseExtends();
- case 'include':
- return this.parseInclude();
- case 'doctype':
- return this.parseDoctype();
- case 'filter':
- return this.parseFilter();
- case 'comment':
- return this.parseComment();
- case 'text':
- case 'interpolated-code':
- case 'start-pug-interpolation':
- return this.parseText({block: true});
- case 'text-html':
- return this.initBlock(this.peek().loc.start.line, this.parseTextHtml());
- case 'dot':
- return this.parseDot();
- case 'each':
- return this.parseEach();
- case 'eachOf':
- return this.parseEachOf();
- case 'code':
- return this.parseCode();
- case 'blockcode':
- return this.parseBlockCode();
- case 'if':
- return this.parseConditional();
- case 'while':
- return this.parseWhile();
- case 'call':
- return this.parseCall();
- case 'interpolation':
- return this.parseInterpolation();
- case 'yield':
- return this.parseYield();
- case 'id':
- case 'class':
- if (!this.peek().loc.start) debugger;
- this.tokens.defer({
- type: 'tag',
- val: 'div',
- loc: this.peek().loc,
- filename: this.filename,
- });
- return this.parseExpr();
- default:
- var pluginResult = this.runPlugin('expressionTokens', this.peek());
- if (pluginResult) return pluginResult;
- this.error(
- 'INVALID_TOKEN',
- 'unexpected token "' + this.peek().type + '"',
- this.peek()
- );
- }
- },
-
- parseDot: function() {
- this.advance();
- return this.parseTextBlock();
- },
-
- /**
- * Text
- */
-
- parseText: function(options) {
- var tags = [];
- var lineno = this.peek().loc.start.line;
- var nextTok = this.peek();
- loop: while (true) {
- switch (nextTok.type) {
- case 'text':
- var tok = this.advance();
- tags.push({
- type: 'Text',
- val: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- case 'interpolated-code':
- var tok = this.advance();
- tags.push({
- type: 'Code',
- val: tok.val,
- buffer: tok.buffer,
- mustEscape: tok.mustEscape !== false,
- isInline: true,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- case 'newline':
- if (!options || !options.block) break loop;
- var tok = this.advance();
- var nextType = this.peek().type;
- if (nextType === 'text' || nextType === 'interpolated-code') {
- tags.push({
- type: 'Text',
- val: '\n',
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- }
- break;
- case 'start-pug-interpolation':
- this.advance();
- tags.push(this.parseExpr());
- this.expect('end-pug-interpolation');
- break;
- default:
- var pluginResult = this.runPlugin('textTokens', nextTok, tags);
- if (pluginResult) break;
- break loop;
- }
- nextTok = this.peek();
- }
- if (tags.length === 1) return tags[0];
- else return this.initBlock(lineno, tags);
- },
-
- parseTextHtml: function() {
- var nodes = [];
- var currentNode = null;
- loop: while (true) {
- switch (this.peek().type) {
- case 'text-html':
- var text = this.advance();
- if (!currentNode) {
- currentNode = {
- type: 'Text',
- val: text.val,
- filename: this.filename,
- line: text.loc.start.line,
- column: text.loc.start.column,
- isHtml: true,
- };
- nodes.push(currentNode);
- } else {
- currentNode.val += '\n' + text.val;
- }
- break;
- case 'indent':
- var block = this.block();
- block.nodes.forEach(function(node) {
- if (node.isHtml) {
- if (!currentNode) {
- currentNode = node;
- nodes.push(currentNode);
- } else {
- currentNode.val += '\n' + node.val;
- }
- } else {
- currentNode = null;
- nodes.push(node);
- }
- });
- break;
- case 'code':
- currentNode = null;
- nodes.push(this.parseCode(true));
- break;
- case 'newline':
- this.advance();
- break;
- default:
- break loop;
- }
- }
- return nodes;
- },
-
- /**
- * ':' expr
- * | block
- */
-
- parseBlockExpansion: function() {
- var tok = this.accept(':');
- if (tok) {
- var expr = this.parseExpr();
- return expr.type === 'Block'
- ? expr
- : this.initBlock(tok.loc.start.line, [expr]);
- } else {
- return this.block();
- }
- },
-
- /**
- * case
- */
-
- parseCase: function() {
- var tok = this.expect('case');
- var node = {
- type: 'Case',
- expr: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- var block = this.emptyBlock(tok.loc.start.line + 1);
- this.expect('indent');
- while ('outdent' != this.peek().type) {
- switch (this.peek().type) {
- case 'comment':
- case 'newline':
- this.advance();
- break;
- case 'when':
- block.nodes.push(this.parseWhen());
- break;
- case 'default':
- block.nodes.push(this.parseDefault());
- break;
- default:
- var pluginResult = this.runPlugin('caseTokens', this.peek(), block);
- if (pluginResult) break;
- this.error(
- 'INVALID_TOKEN',
- 'Unexpected token "' +
- this.peek().type +
- '", expected "when", "default" or "newline"',
- this.peek()
- );
- }
- }
- this.expect('outdent');
-
- node.block = block;
-
- return node;
- },
-
- /**
- * when
- */
-
- parseWhen: function() {
- var tok = this.expect('when');
- if (this.peek().type !== 'newline') {
- return {
- type: 'When',
- expr: tok.val,
- block: this.parseBlockExpansion(),
- debug: false,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- } else {
- return {
- type: 'When',
- expr: tok.val,
- debug: false,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- }
- },
-
- /**
- * default
- */
-
- parseDefault: function() {
- var tok = this.expect('default');
- return {
- type: 'When',
- expr: 'default',
- block: this.parseBlockExpansion(),
- debug: false,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- /**
- * code
- */
-
- parseCode: function(noBlock) {
- var tok = this.expect('code');
- assert(
- typeof tok.mustEscape === 'boolean',
- 'Please update to the newest version of pug-lexer.'
- );
- var node = {
- type: 'Code',
- val: tok.val,
- buffer: tok.buffer,
- mustEscape: tok.mustEscape !== false,
- isInline: !!noBlock,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- // todo: why is this here? It seems like a hacky workaround
- if (node.val.match(/^ *else/)) node.debug = false;
-
- if (noBlock) return node;
-
- var block;
-
- // handle block
- block = 'indent' == this.peek().type;
- if (block) {
- if (tok.buffer) {
- this.error(
- 'BLOCK_IN_BUFFERED_CODE',
- 'Buffered code cannot have a block attached to it',
- this.peek()
- );
- }
- node.block = this.block();
- }
-
- return node;
- },
- parseConditional: function() {
- var tok = this.expect('if');
- var node = {
- type: 'Conditional',
- test: tok.val,
- consequent: this.emptyBlock(tok.loc.start.line),
- alternate: null,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- // handle block
- if ('indent' == this.peek().type) {
- node.consequent = this.block();
- }
-
- var currentNode = node;
- while (true) {
- if (this.peek().type === 'newline') {
- this.expect('newline');
- } else if (this.peek().type === 'else-if') {
- tok = this.expect('else-if');
- currentNode = currentNode.alternate = {
- type: 'Conditional',
- test: tok.val,
- consequent: this.emptyBlock(tok.loc.start.line),
- alternate: null,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- if ('indent' == this.peek().type) {
- currentNode.consequent = this.block();
- }
- } else if (this.peek().type === 'else') {
- this.expect('else');
- if (this.peek().type === 'indent') {
- currentNode.alternate = this.block();
- }
- break;
- } else {
- break;
- }
- }
-
- return node;
- },
- parseWhile: function() {
- var tok = this.expect('while');
- var node = {
- type: 'While',
- test: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- // handle block
- if ('indent' == this.peek().type) {
- node.block = this.block();
- } else {
- node.block = this.emptyBlock(tok.loc.start.line);
- }
-
- return node;
- },
-
- /**
- * block code
- */
-
- parseBlockCode: function() {
- var tok = this.expect('blockcode');
- var line = tok.loc.start.line;
- var column = tok.loc.start.column;
- var body = this.peek();
- var text = '';
- if (body.type === 'start-pipeless-text') {
- this.advance();
- while (this.peek().type !== 'end-pipeless-text') {
- tok = this.advance();
- switch (tok.type) {
- case 'text':
- text += tok.val;
- break;
- case 'newline':
- text += '\n';
- break;
- default:
- var pluginResult = this.runPlugin('blockCodeTokens', tok, tok);
- if (pluginResult) {
- text += pluginResult;
- break;
- }
- this.error(
- 'INVALID_TOKEN',
- 'Unexpected token type: ' + tok.type,
- tok
- );
- }
- }
- this.advance();
- }
- return {
- type: 'Code',
- val: text,
- buffer: false,
- mustEscape: false,
- isInline: false,
- line: line,
- column: column,
- filename: this.filename,
- };
- },
- /**
- * comment
- */
-
- parseComment: function() {
- var tok = this.expect('comment');
- var block;
- if ((block = this.parseTextBlock())) {
- return {
- type: 'BlockComment',
- val: tok.val,
- block: block,
- buffer: tok.buffer,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- } else {
- return {
- type: 'Comment',
- val: tok.val,
- buffer: tok.buffer,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- }
- },
-
- /**
- * doctype
- */
-
- parseDoctype: function() {
- var tok = this.expect('doctype');
- return {
- type: 'Doctype',
- val: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- parseIncludeFilter: function() {
- var tok = this.expect('filter');
- var attrs = [];
-
- if (this.peek().type === 'start-attributes') {
- attrs = this.attrs();
- }
-
- return {
- type: 'IncludeFilter',
- name: tok.val,
- attrs: attrs,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- /**
- * filter attrs? text-block
- */
-
- parseFilter: function() {
- var tok = this.expect('filter');
- var block,
- attrs = [];
-
- if (this.peek().type === 'start-attributes') {
- attrs = this.attrs();
- }
-
- if (this.peek().type === 'text') {
- var textToken = this.advance();
- block = this.initBlock(textToken.loc.start.line, [
- {
- type: 'Text',
- val: textToken.val,
- line: textToken.loc.start.line,
- column: textToken.loc.start.column,
- filename: this.filename,
- },
- ]);
- } else if (this.peek().type === 'filter') {
- block = this.initBlock(tok.loc.start.line, [this.parseFilter()]);
- } else {
- block = this.parseTextBlock() || this.emptyBlock(tok.loc.start.line);
- }
-
- return {
- type: 'Filter',
- name: tok.val,
- block: block,
- attrs: attrs,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- /**
- * each block
- */
-
- parseEach: function() {
- var tok = this.expect('each');
- var node = {
- type: 'Each',
- obj: tok.code,
- val: tok.val,
- key: tok.key,
- block: this.block(),
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- if (this.peek().type == 'else') {
- this.advance();
- node.alternate = this.block();
- }
- return node;
- },
-
- parseEachOf: function() {
- var tok = this.expect('eachOf');
- var node = {
- type: 'EachOf',
- obj: tok.code,
- val: tok.val,
- block: this.block(),
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- return node;
- },
- /**
- * 'extends' name
- */
-
- parseExtends: function() {
- var tok = this.expect('extends');
- var path = this.expect('path');
- return {
- type: 'Extends',
- file: {
- type: 'FileReference',
- path: path.val.trim(),
- line: path.loc.start.line,
- column: path.loc.start.column,
- filename: this.filename,
- },
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- /**
- * 'block' name block
- */
-
- parseBlock: function() {
- var tok = this.expect('block');
-
- var node =
- 'indent' == this.peek().type
- ? this.block()
- : this.emptyBlock(tok.loc.start.line);
- node.type = 'NamedBlock';
- node.name = tok.val.trim();
- node.mode = tok.mode;
- node.line = tok.loc.start.line;
- node.column = tok.loc.start.column;
-
- return node;
- },
-
- parseMixinBlock: function() {
- var tok = this.expect('mixin-block');
- if (!this.inMixin) {
- this.error(
- 'BLOCK_OUTISDE_MIXIN',
- 'Anonymous blocks are not allowed unless they are part of a mixin.',
- tok
- );
- }
- return {
- type: 'MixinBlock',
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- parseYield: function() {
- var tok = this.expect('yield');
- return {
- type: 'YieldBlock',
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- },
-
- /**
- * include block?
- */
-
- parseInclude: function() {
- var tok = this.expect('include');
- var node = {
- type: 'Include',
- file: {
- type: 'FileReference',
- filename: this.filename,
- },
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- var filters = [];
- while (this.peek().type === 'filter') {
- filters.push(this.parseIncludeFilter());
- }
- var path = this.expect('path');
-
- node.file.path = path.val.trim();
- node.file.line = path.loc.start.line;
- node.file.column = path.loc.start.column;
-
- if (
- (/\.jade$/.test(node.file.path) || /\.pug$/.test(node.file.path)) &&
- !filters.length
- ) {
- node.block =
- 'indent' == this.peek().type
- ? this.block()
- : this.emptyBlock(tok.loc.start.line);
- if (/\.jade$/.test(node.file.path)) {
- console.warn(
- this.filename +
- ', line ' +
- tok.loc.start.line +
- ':\nThe .jade extension is deprecated, use .pug for "' +
- node.file.path +
- '".'
- );
- }
- } else {
- node.type = 'RawInclude';
- node.filters = filters;
- if (this.peek().type === 'indent') {
- this.error(
- 'RAW_INCLUDE_BLOCK',
- 'Raw inclusion cannot contain a block',
- this.peek()
- );
- }
- }
- return node;
- },
-
- /**
- * call ident block
- */
-
- parseCall: function() {
- var tok = this.expect('call');
- var name = tok.val;
- var args = tok.args;
- var mixin = {
- type: 'Mixin',
- name: name,
- args: args,
- block: this.emptyBlock(tok.loc.start.line),
- call: true,
- attrs: [],
- attributeBlocks: [],
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- this.tag(mixin);
- if (mixin.code) {
- mixin.block.nodes.push(mixin.code);
- delete mixin.code;
- }
- if (mixin.block.nodes.length === 0) mixin.block = null;
- return mixin;
- },
-
- /**
- * mixin block
- */
-
- parseMixin: function() {
- var tok = this.expect('mixin');
- var name = tok.val;
- var args = tok.args;
-
- if ('indent' == this.peek().type) {
- this.inMixin++;
- var mixin = {
- type: 'Mixin',
- name: name,
- args: args,
- block: this.block(),
- call: false,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
- this.inMixin--;
- return mixin;
- } else {
- this.error(
- 'MIXIN_WITHOUT_BODY',
- 'Mixin ' + name + ' declared without body',
- tok
- );
- }
- },
-
- /**
- * indent (text | newline)* outdent
- */
-
- parseTextBlock: function() {
- var tok = this.accept('start-pipeless-text');
- if (!tok) return;
- var block = this.emptyBlock(tok.loc.start.line);
- while (this.peek().type !== 'end-pipeless-text') {
- var tok = this.advance();
- switch (tok.type) {
- case 'text':
- block.nodes.push({
- type: 'Text',
- val: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- case 'newline':
- block.nodes.push({
- type: 'Text',
- val: '\n',
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- case 'start-pug-interpolation':
- block.nodes.push(this.parseExpr());
- this.expect('end-pug-interpolation');
- break;
- case 'interpolated-code':
- block.nodes.push({
- type: 'Code',
- val: tok.val,
- buffer: tok.buffer,
- mustEscape: tok.mustEscape !== false,
- isInline: true,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- default:
- var pluginResult = this.runPlugin('textBlockTokens', tok, block, tok);
- if (pluginResult) break;
- this.error(
- 'INVALID_TOKEN',
- 'Unexpected token type: ' + tok.type,
- tok
- );
- }
- }
- this.advance();
- return block;
- },
-
- /**
- * indent expr* outdent
- */
-
- block: function() {
- var tok = this.expect('indent');
- var block = this.emptyBlock(tok.loc.start.line);
- while ('outdent' != this.peek().type) {
- if ('newline' == this.peek().type) {
- this.advance();
- } else if ('text-html' == this.peek().type) {
- block.nodes = block.nodes.concat(this.parseTextHtml());
- } else {
- var expr = this.parseExpr();
- if (expr.type === 'Block') {
- block.nodes = block.nodes.concat(expr.nodes);
- } else {
- block.nodes.push(expr);
- }
- }
- }
- this.expect('outdent');
- return block;
- },
-
- /**
- * interpolation (attrs | class | id)* (text | code | ':')? newline* block?
- */
-
- parseInterpolation: function() {
- var tok = this.advance();
- var tag = {
- type: 'InterpolatedTag',
- expr: tok.val,
- selfClosing: false,
- block: this.emptyBlock(tok.loc.start.line),
- attrs: [],
- attributeBlocks: [],
- isInline: false,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- return this.tag(tag, {selfClosingAllowed: true});
- },
-
- /**
- * tag (attrs | class | id)* (text | code | ':')? newline* block?
- */
-
- parseTag: function() {
- var tok = this.advance();
- var tag = {
- type: 'Tag',
- name: tok.val,
- selfClosing: false,
- block: this.emptyBlock(tok.loc.start.line),
- attrs: [],
- attributeBlocks: [],
- isInline: inlineTags.indexOf(tok.val) !== -1,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- };
-
- return this.tag(tag, {selfClosingAllowed: true});
- },
-
- /**
- * Parse tag.
- */
-
- tag: function(tag, options) {
- var seenAttrs = false;
- var attributeNames = [];
- var selfClosingAllowed = options && options.selfClosingAllowed;
- // (attrs | class | id)*
- out: while (true) {
- switch (this.peek().type) {
- case 'id':
- case 'class':
- var tok = this.advance();
- if (tok.type === 'id') {
- if (attributeNames.indexOf('id') !== -1) {
- this.error(
- 'DUPLICATE_ID',
- 'Duplicate attribute "id" is not allowed.',
- tok
- );
- }
- attributeNames.push('id');
- }
- tag.attrs.push({
- name: tok.type,
- val: "'" + tok.val + "'",
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- mustEscape: false,
- });
- continue;
- case 'start-attributes':
- if (seenAttrs) {
- console.warn(
- this.filename +
- ', line ' +
- this.peek().loc.start.line +
- ':\nYou should not have pug tags with multiple attributes.'
- );
- }
- seenAttrs = true;
- tag.attrs = tag.attrs.concat(this.attrs(attributeNames));
- continue;
- case '&attributes':
- var tok = this.advance();
- tag.attributeBlocks.push({
- type: 'AttributeBlock',
- val: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- });
- break;
- default:
- var pluginResult = this.runPlugin(
- 'tagAttributeTokens',
- this.peek(),
- tag,
- attributeNames
- );
- if (pluginResult) break;
- break out;
- }
- }
-
- // check immediate '.'
- if ('dot' == this.peek().type) {
- tag.textOnly = true;
- this.advance();
- }
-
- // (text | code | ':')?
- switch (this.peek().type) {
- case 'text':
- case 'interpolated-code':
- var text = this.parseText();
- if (text.type === 'Block') {
- tag.block.nodes.push.apply(tag.block.nodes, text.nodes);
- } else {
- tag.block.nodes.push(text);
- }
- break;
- case 'code':
- tag.block.nodes.push(this.parseCode(true));
- break;
- case ':':
- this.advance();
- var expr = this.parseExpr();
- tag.block =
- expr.type === 'Block' ? expr : this.initBlock(tag.line, [expr]);
- break;
- case 'newline':
- case 'indent':
- case 'outdent':
- case 'eos':
- case 'start-pipeless-text':
- case 'end-pug-interpolation':
- break;
- case 'slash':
- if (selfClosingAllowed) {
- this.advance();
- tag.selfClosing = true;
- break;
- }
- default:
- var pluginResult = this.runPlugin(
- 'tagTokens',
- this.peek(),
- tag,
- options
- );
- if (pluginResult) break;
- this.error(
- 'INVALID_TOKEN',
- 'Unexpected token `' +
- this.peek().type +
- '` expected `text`, `interpolated-code`, `code`, `:`' +
- (selfClosingAllowed ? ', `slash`' : '') +
- ', `newline` or `eos`',
- this.peek()
- );
- }
-
- // newline*
- while ('newline' == this.peek().type) this.advance();
-
- // block?
- if (tag.textOnly) {
- tag.block = this.parseTextBlock() || this.emptyBlock(tag.line);
- } else if ('indent' == this.peek().type) {
- var block = this.block();
- for (var i = 0, len = block.nodes.length; i < len; ++i) {
- tag.block.nodes.push(block.nodes[i]);
- }
- }
-
- return tag;
- },
-
- attrs: function(attributeNames) {
- this.expect('start-attributes');
-
- var attrs = [];
- var tok = this.advance();
- while (tok.type === 'attribute') {
- if (tok.name !== 'class' && attributeNames) {
- if (attributeNames.indexOf(tok.name) !== -1) {
- this.error(
- 'DUPLICATE_ATTRIBUTE',
- 'Duplicate attribute "' + tok.name + '" is not allowed.',
- tok
- );
- }
- attributeNames.push(tok.name);
- }
- attrs.push({
- name: tok.name,
- val: tok.val,
- line: tok.loc.start.line,
- column: tok.loc.start.column,
- filename: this.filename,
- mustEscape: tok.mustEscape !== false,
- });
- tok = this.advance();
- }
- this.tokens.defer(tok);
- this.expect('end-attributes');
- return attrs;
- },
-};
-
-
-/***/ }),
-
-/***/ 33470:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = [
- 'a',
- 'abbr',
- 'acronym',
- 'b',
- 'br',
- 'code',
- 'em',
- 'font',
- 'i',
- 'img',
- 'ins',
- 'kbd',
- 'map',
- 'samp',
- 'small',
- 'span',
- 'strong',
- 'sub',
- 'sup',
-];
-
-
-/***/ }),
-
-/***/ 37364:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var fs = __nccwpck_require__(57147);
-var dependencies = __nccwpck_require__(41222);
-var internals = __nccwpck_require__(373);
-var sources = __nccwpck_require__(21003);
-
-module.exports = build;
-
-function build(functions) {
- var fns = [];
- functions = functions.filter(function(fn) {
- return !internals[fn];
- });
- for (var i = 0; i < functions.length; i++) {
- if (fns.indexOf(functions[i]) === -1) {
- fns.push(functions[i]);
- functions.push.apply(functions, dependencies[functions[i]]);
- }
- }
- return fns
- .sort()
- .map(function(name) {
- return sources[name];
- })
- .join('\n');
-}
-
-
-/***/ }),
-
-/***/ 27596:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var pug_has_own_property = Object.prototype.hasOwnProperty;
-
-/**
- * Merge two attribute objects giving precedence
- * to values in object `b`. Classes are special-cased
- * allowing for arrays and merging/joining appropriately
- * resulting in a string.
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Object} a
- * @api private
- */
-
-exports.merge = pug_merge;
-function pug_merge(a, b) {
- if (arguments.length === 1) {
- var attrs = a[0];
- for (var i = 1; i < a.length; i++) {
- attrs = pug_merge(attrs, a[i]);
- }
- return attrs;
- }
-
- for (var key in b) {
- if (key === 'class') {
- var valA = a[key] || [];
- a[key] = (Array.isArray(valA) ? valA : [valA]).concat(b[key] || []);
- } else if (key === 'style') {
- var valA = pug_style(a[key]);
- valA = valA && valA[valA.length - 1] !== ';' ? valA + ';' : valA;
- var valB = pug_style(b[key]);
- valB = valB && valB[valB.length - 1] !== ';' ? valB + ';' : valB;
- a[key] = valA + valB;
- } else {
- a[key] = b[key];
- }
- }
-
- return a;
-}
-
-/**
- * Process array, object, or string as a string of classes delimited by a space.
- *
- * If `val` is an array, all members of it and its subarrays are counted as
- * classes. If `escaping` is an array, then whether or not the item in `val` is
- * escaped depends on the corresponding item in `escaping`. If `escaping` is
- * not an array, no escaping is done.
- *
- * If `val` is an object, all the keys whose value is truthy are counted as
- * classes. No escaping is done.
- *
- * If `val` is a string, it is counted as a class. No escaping is done.
- *
- * @param {(Array.|Object.|string)} val
- * @param {?Array.} escaping
- * @return {String}
- */
-exports.classes = pug_classes;
-function pug_classes_array(val, escaping) {
- var classString = '',
- className,
- padding = '',
- escapeEnabled = Array.isArray(escaping);
- for (var i = 0; i < val.length; i++) {
- className = pug_classes(val[i]);
- if (!className) continue;
- escapeEnabled && escaping[i] && (className = pug_escape(className));
- classString = classString + padding + className;
- padding = ' ';
- }
- return classString;
-}
-function pug_classes_object(val) {
- var classString = '',
- padding = '';
- for (var key in val) {
- if (key && val[key] && pug_has_own_property.call(val, key)) {
- classString = classString + padding + key;
- padding = ' ';
- }
- }
- return classString;
-}
-function pug_classes(val, escaping) {
- if (Array.isArray(val)) {
- return pug_classes_array(val, escaping);
- } else if (val && typeof val === 'object') {
- return pug_classes_object(val);
- } else {
- return val || '';
- }
-}
-
-/**
- * Convert object or string to a string of CSS styles delimited by a semicolon.
- *
- * @param {(Object.|string)} val
- * @return {String}
- */
-
-exports.style = pug_style;
-function pug_style(val) {
- if (!val) return '';
- if (typeof val === 'object') {
- var out = '';
- for (var style in val) {
- /* istanbul ignore else */
- if (pug_has_own_property.call(val, style)) {
- out = out + style + ':' + val[style] + ';';
- }
- }
- return out;
- } else {
- return val + '';
- }
-}
-
-/**
- * Render the given attribute.
- *
- * @param {String} key
- * @param {String} val
- * @param {Boolean} escaped
- * @param {Boolean} terse
- * @return {String}
- */
-exports.attr = pug_attr;
-function pug_attr(key, val, escaped, terse) {
- if (
- val === false ||
- val == null ||
- (!val && (key === 'class' || key === 'style'))
- ) {
- return '';
- }
- if (val === true) {
- return ' ' + (terse ? key : key + '="' + key + '"');
- }
- var type = typeof val;
- if (
- (type === 'object' || type === 'function') &&
- typeof val.toJSON === 'function'
- ) {
- val = val.toJSON();
- }
- if (typeof val !== 'string') {
- val = JSON.stringify(val);
- if (!escaped && val.indexOf('"') !== -1) {
- return ' ' + key + "='" + val.replace(/'/g, ''') + "'";
- }
- }
- if (escaped) val = pug_escape(val);
- return ' ' + key + '="' + val + '"';
-}
-
-/**
- * Render the given attributes object.
- *
- * @param {Object} obj
- * @param {Object} terse whether to use HTML5 terse boolean attributes
- * @return {String}
- */
-exports.attrs = pug_attrs;
-function pug_attrs(obj, terse) {
- var attrs = '';
-
- for (var key in obj) {
- if (pug_has_own_property.call(obj, key)) {
- var val = obj[key];
-
- if ('class' === key) {
- val = pug_classes(val);
- attrs = pug_attr(key, val, false, terse) + attrs;
- continue;
- }
- if ('style' === key) {
- val = pug_style(val);
- }
- attrs += pug_attr(key, val, false, terse);
- }
- }
-
- return attrs;
-}
-
-/**
- * Escape the given string of `html`.
- *
- * @param {String} html
- * @return {String}
- * @api private
- */
-
-var pug_match_html = /["&<>]/;
-exports.escape = pug_escape;
-function pug_escape(_html) {
- var html = '' + _html;
- var regexResult = pug_match_html.exec(html);
- if (!regexResult) return _html;
-
- var result = '';
- var i, lastIndex, escape;
- for (i = regexResult.index, lastIndex = 0; i < html.length; i++) {
- switch (html.charCodeAt(i)) {
- case 34:
- escape = '"';
- break;
- case 38:
- escape = '&';
- break;
- case 60:
- escape = '<';
- break;
- case 62:
- escape = '>';
- break;
- default:
- continue;
- }
- if (lastIndex !== i) result += html.substring(lastIndex, i);
- lastIndex = i + 1;
- result += escape;
- }
- if (lastIndex !== i) return result + html.substring(lastIndex, i);
- else return result;
-}
-
-/**
- * Re-throw the given `err` in context to the
- * the pug in `filename` at the given `lineno`.
- *
- * @param {Error} err
- * @param {String} filename
- * @param {String} lineno
- * @param {String} str original source
- * @api private
- */
-
-exports.rethrow = pug_rethrow;
-function pug_rethrow(err, filename, lineno, str) {
- if (!(err instanceof Error)) throw err;
- if ((typeof window != 'undefined' || !filename) && !str) {
- err.message += ' on line ' + lineno;
- throw err;
- }
- var context, lines, start, end;
- try {
- str = str || (__nccwpck_require__(57147).readFileSync)(filename, {encoding: 'utf8'});
- context = 3;
- lines = str.split('\n');
- start = Math.max(lineno - context, 0);
- end = Math.min(lines.length, lineno + context);
- } catch (ex) {
- err.message +=
- ' - could not read from ' + filename + ' (' + ex.message + ')';
- pug_rethrow(err, null, lineno);
- return;
- }
-
- // Error context
- context = lines
- .slice(start, end)
- .map(function(line, i) {
- var curr = i + start + 1;
- return (curr == lineno ? ' > ' : ' ') + curr + '| ' + line;
- })
- .join('\n');
-
- // Alter exception message
- err.path = filename;
- try {
- err.message =
- (filename || 'Pug') +
- ':' +
- lineno +
- '\n' +
- context +
- '\n\n' +
- err.message;
- } catch (e) {}
- throw err;
-}
-
-
-/***/ }),
-
-/***/ 41222:
-/***/ ((module) => {
-
-module.exports = {
- "has_own_property": [],
- "merge": [
- "style"
- ],
- "classes_array": [
- "classes",
- "escape"
- ],
- "classes_object": [
- "has_own_property"
- ],
- "classes": [
- "classes_array",
- "classes_object"
- ],
- "style": [
- "has_own_property"
- ],
- "attr": [
- "escape"
- ],
- "attrs": [
- "attr",
- "classes",
- "has_own_property",
- "style"
- ],
- "match_html": [],
- "escape": [
- "match_html"
- ],
- "rethrow": []
-}
-
-
-/***/ }),
-
-/***/ 373:
-/***/ ((module) => {
-
-module.exports = {
- "dependencies": true,
- "internals": true,
- "has_own_property": true,
- "classes_array": true,
- "classes_object": true,
- "match_html": true
-}
-
-
-/***/ }),
-
-/***/ 21003:
-/***/ ((module) => {
-
-module.exports = {
- "has_own_property": "var pug_has_own_property=Object.prototype.hasOwnProperty;",
- "merge": "function pug_merge(e,r){if(1===arguments.length){for(var t=e[0],g=1;g]/;",
- "escape": "function pug_escape(e){var a=\"\"+e,t=pug_match_html.exec(a);if(!t)return e;var r,c,n,s=\"\";for(r=t.index,c=0;r \":\" \")+t+\"| \"+e}).join(\"\\n\"),e.path=n;try{e.message=(n||\"Pug\")+\":\"+r+\"\\n\"+o+\"\\n\\n\"+e.message}catch(e){}throw e}"
-}
-
-
-/***/ }),
-
-/***/ 60010:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var runtime = __nccwpck_require__(27596);
-
-module.exports = wrap;
-function wrap(template, templateName) {
- templateName = templateName || 'template';
- return Function(
- 'pug',
- template + '\n' + 'return ' + templateName + ';'
- )(runtime);
-}
-
-
-/***/ }),
-
-/***/ 45413:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var error = __nccwpck_require__(11449);
-
-module.exports = stripComments;
-
-function unexpectedToken(type, occasion, filename, line) {
- var msg = '`' + type + '` encountered when ' + occasion;
- throw error('UNEXPECTED_TOKEN', msg, {filename: filename, line: line});
-}
-
-function stripComments(input, options) {
- options = options || {};
-
- // Default: strip unbuffered comments and leave buffered ones alone
- var stripUnbuffered = options.stripUnbuffered !== false;
- var stripBuffered = options.stripBuffered === true;
- var filename = options.filename;
-
- var out = [];
- // If we have encountered a comment token and are not sure if we have gotten
- // out of the comment or not
- var inComment = false;
- // If we are sure that we are in a block comment and all tokens except
- // `end-pipeless-text` should be ignored
- var inPipelessText = false;
-
- return input.filter(function(tok) {
- switch (tok.type) {
- case 'comment':
- if (inComment) {
- unexpectedToken(
- 'comment',
- 'already in a comment',
- filename,
- tok.line
- );
- } else {
- inComment = tok.buffer ? stripBuffered : stripUnbuffered;
- return !inComment;
- }
- case 'start-pipeless-text':
- if (!inComment) return true;
- if (inPipelessText) {
- unexpectedToken(
- 'start-pipeless-text',
- 'already in pipeless text mode',
- filename,
- tok.line
- );
- }
- inPipelessText = true;
- return false;
- case 'end-pipeless-text':
- if (!inComment) return true;
- if (!inPipelessText) {
- unexpectedToken(
- 'end-pipeless-text',
- 'not in pipeless text mode',
- filename,
- tok.line
- );
- }
- inPipelessText = false;
- inComment = false;
- return false;
- // There might be a `text` right after `comment` but before
- // `start-pipeless-text`. Treat it accordingly.
- case 'text':
- return !inComment;
- default:
- if (inPipelessText) return false;
- inComment = false;
- return true;
- }
- });
-}
-
-
-/***/ }),
-
-/***/ 60283:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = walkAST;
-function walkAST(ast, before, after, options) {
- if (after && typeof after === 'object' && typeof options === 'undefined') {
- options = after;
- after = null;
- }
- options = options || {includeDependencies: false};
- var parents = (options.parents = options.parents || []);
-
- var replace = function replace(replacement) {
- if (Array.isArray(replacement) && !replace.arrayAllowed) {
- throw new Error(
- 'replace() can only be called with an array if the last parent is a Block or NamedBlock'
- );
- }
- ast = replacement;
- };
- replace.arrayAllowed =
- parents[0] &&
- (/^(Named)?Block$/.test(parents[0].type) ||
- (parents[0].type === 'RawInclude' && ast.type === 'IncludeFilter'));
-
- if (before) {
- var result = before(ast, replace);
- if (result === false) {
- return ast;
- } else if (Array.isArray(ast)) {
- // return right here to skip after() call on array
- return walkAndMergeNodes(ast);
- }
- }
-
- parents.unshift(ast);
-
- switch (ast.type) {
- case 'NamedBlock':
- case 'Block':
- ast.nodes = walkAndMergeNodes(ast.nodes);
- break;
- case 'Case':
- case 'Filter':
- case 'Mixin':
- case 'Tag':
- case 'InterpolatedTag':
- case 'When':
- case 'Code':
- case 'While':
- if (ast.block) {
- ast.block = walkAST(ast.block, before, after, options);
- }
- break;
- case 'Each':
- if (ast.block) {
- ast.block = walkAST(ast.block, before, after, options);
- }
- if (ast.alternate) {
- ast.alternate = walkAST(ast.alternate, before, after, options);
- }
- break;
- case 'EachOf':
- if (ast.block) {
- ast.block = walkAST(ast.block, before, after, options);
- }
- break;
- case 'Conditional':
- if (ast.consequent) {
- ast.consequent = walkAST(ast.consequent, before, after, options);
- }
- if (ast.alternate) {
- ast.alternate = walkAST(ast.alternate, before, after, options);
- }
- break;
- case 'Include':
- walkAST(ast.block, before, after, options);
- walkAST(ast.file, before, after, options);
- break;
- case 'Extends':
- walkAST(ast.file, before, after, options);
- break;
- case 'RawInclude':
- ast.filters = walkAndMergeNodes(ast.filters);
- walkAST(ast.file, before, after, options);
- break;
- case 'Attrs':
- case 'BlockComment':
- case 'Comment':
- case 'Doctype':
- case 'IncludeFilter':
- case 'MixinBlock':
- case 'YieldBlock':
- case 'Text':
- break;
- case 'FileReference':
- if (options.includeDependencies && ast.ast) {
- walkAST(ast.ast, before, after, options);
- }
- break;
- default:
- throw new Error('Unexpected node type ' + ast.type);
- break;
- }
-
- parents.shift();
-
- after && after(ast, replace);
- return ast;
-
- function walkAndMergeNodes(nodes) {
- return nodes.reduce(function(nodes, node) {
- var result = walkAST(node, before, after, options);
- if (Array.isArray(result)) {
- return nodes.concat(result);
- } else {
- return nodes.concat([result]);
- }
- }, []);
- }
-}
-
-
-/***/ }),
-
-/***/ 40316:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-/*!
- * Pug
- * Copyright(c) 2010 TJ Holowaychuk
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var fs = __nccwpck_require__(57147);
-var path = __nccwpck_require__(71017);
-var lex = __nccwpck_require__(32428);
-var stripComments = __nccwpck_require__(45413);
-var parse = __nccwpck_require__(40558);
-var load = __nccwpck_require__(44254);
-var filters = __nccwpck_require__(69309);
-var link = __nccwpck_require__(63234);
-var generateCode = __nccwpck_require__(90331);
-var runtime = __nccwpck_require__(27596);
-var runtimeWrap = __nccwpck_require__(60010);
-
-/**
- * Name for detection
- */
-
-exports.name = 'Pug';
-
-/**
- * Pug runtime helpers.
- */
-
-exports.runtime = runtime;
-
-/**
- * Template function cache.
- */
-
-exports.cache = {};
-
-function applyPlugins(value, options, plugins, name) {
- return plugins.reduce(function(value, plugin) {
- return plugin[name] ? plugin[name](value, options) : value;
- }, value);
-}
-
-function findReplacementFunc(plugins, name) {
- var eligiblePlugins = plugins.filter(function(plugin) {
- return plugin[name];
- });
-
- if (eligiblePlugins.length > 1) {
- throw new Error('Two or more plugins all implement ' + name + ' method.');
- } else if (eligiblePlugins.length) {
- return eligiblePlugins[0][name].bind(eligiblePlugins[0]);
- }
- return null;
-}
-
-/**
- * Object for global custom filters. Note that you can also just pass a `filters`
- * option to any other method.
- */
-exports.filters = {};
-
-/**
- * Compile the given `str` of pug and return a function body.
- *
- * @param {String} str
- * @param {Object} options
- * @return {Object}
- * @api private
- */
-
-function compileBody(str, options) {
- var debug_sources = {};
- debug_sources[options.filename] = str;
- var dependencies = [];
- var plugins = options.plugins || [];
- var ast = load.string(str, {
- filename: options.filename,
- basedir: options.basedir,
- lex: function(str, options) {
- var lexOptions = {};
- Object.keys(options).forEach(function(key) {
- lexOptions[key] = options[key];
- });
- lexOptions.plugins = plugins
- .filter(function(plugin) {
- return !!plugin.lex;
- })
- .map(function(plugin) {
- return plugin.lex;
- });
- var contents = applyPlugins(
- str,
- {filename: options.filename},
- plugins,
- 'preLex'
- );
- return applyPlugins(
- lex(contents, lexOptions),
- options,
- plugins,
- 'postLex'
- );
- },
- parse: function(tokens, options) {
- tokens = tokens.map(function(token) {
- if (token.type === 'path' && path.extname(token.val) === '') {
- return {
- type: 'path',
- loc: token.loc,
- val: token.val + '.pug',
- };
- }
- return token;
- });
- tokens = stripComments(tokens, options);
- tokens = applyPlugins(tokens, options, plugins, 'preParse');
- var parseOptions = {};
- Object.keys(options).forEach(function(key) {
- parseOptions[key] = options[key];
- });
- parseOptions.plugins = plugins
- .filter(function(plugin) {
- return !!plugin.parse;
- })
- .map(function(plugin) {
- return plugin.parse;
- });
-
- return applyPlugins(
- applyPlugins(
- parse(tokens, parseOptions),
- options,
- plugins,
- 'postParse'
- ),
- options,
- plugins,
- 'preLoad'
- );
- },
- resolve: function(filename, source, loadOptions) {
- var replacementFunc = findReplacementFunc(plugins, 'resolve');
- if (replacementFunc) {
- return replacementFunc(filename, source, options);
- }
-
- return load.resolve(filename, source, loadOptions);
- },
- read: function(filename, loadOptions) {
- dependencies.push(filename);
-
- var contents;
-
- var replacementFunc = findReplacementFunc(plugins, 'read');
- if (replacementFunc) {
- contents = replacementFunc(filename, options);
- } else {
- contents = load.read(filename, loadOptions);
- }
-
- debug_sources[filename] = Buffer.isBuffer(contents)
- ? contents.toString('utf8')
- : contents;
- return contents;
- },
- });
- ast = applyPlugins(ast, options, plugins, 'postLoad');
- ast = applyPlugins(ast, options, plugins, 'preFilters');
-
- var filtersSet = {};
- Object.keys(exports.filters).forEach(function(key) {
- filtersSet[key] = exports.filters[key];
- });
- if (options.filters) {
- Object.keys(options.filters).forEach(function(key) {
- filtersSet[key] = options.filters[key];
- });
- }
- ast = filters.handleFilters(
- ast,
- filtersSet,
- options.filterOptions,
- options.filterAliases
- );
-
- ast = applyPlugins(ast, options, plugins, 'postFilters');
- ast = applyPlugins(ast, options, plugins, 'preLink');
- ast = link(ast);
- ast = applyPlugins(ast, options, plugins, 'postLink');
-
- // Compile
- ast = applyPlugins(ast, options, plugins, 'preCodeGen');
- var js = (findReplacementFunc(plugins, 'generateCode') || generateCode)(ast, {
- pretty: options.pretty,
- compileDebug: options.compileDebug,
- doctype: options.doctype,
- inlineRuntimeFunctions: options.inlineRuntimeFunctions,
- globals: options.globals,
- self: options.self,
- includeSources: options.includeSources ? debug_sources : false,
- templateName: options.templateName,
- });
- js = applyPlugins(js, options, plugins, 'postCodeGen');
-
- // Debug compiler
- if (options.debug) {
- console.error(
- '\nCompiled Function:\n\n\u001b[90m%s\u001b[0m',
- js.replace(/^/gm, ' ')
- );
- }
-
- return {body: js, dependencies: dependencies};
-}
-
-/**
- * Get the template from a string or a file, either compiled on-the-fly or
- * read from cache (if enabled), and cache the template if needed.
- *
- * If `str` is not set, the file specified in `options.filename` will be read.
- *
- * If `options.cache` is true, this function reads the file from
- * `options.filename` so it must be set prior to calling this function.
- *
- * @param {Object} options
- * @param {String=} str
- * @return {Function}
- * @api private
- */
-function handleTemplateCache(options, str) {
- var key = options.filename;
- if (options.cache && exports.cache[key]) {
- return exports.cache[key];
- } else {
- if (str === undefined) str = fs.readFileSync(options.filename, 'utf8');
- var templ = exports.compile(str, options);
- if (options.cache) exports.cache[key] = templ;
- return templ;
- }
-}
-
-/**
- * Compile a `Function` representation of the given pug `str`.
- *
- * Options:
- *
- * - `compileDebug` when `false` debugging code is stripped from the compiled
- template, when it is explicitly `true`, the source code is included in
- the compiled template for better accuracy.
- * - `filename` used to improve errors when `compileDebug` is not `false` and to resolve imports/extends
- *
- * @param {String} str
- * @param {Options} options
- * @return {Function}
- * @api public
- */
-
-exports.compile = function(str, options) {
- var options = options || {};
-
- str = String(str);
-
- var parsed = compileBody(str, {
- compileDebug: options.compileDebug !== false,
- filename: options.filename,
- basedir: options.basedir,
- pretty: options.pretty,
- doctype: options.doctype,
- inlineRuntimeFunctions: options.inlineRuntimeFunctions,
- globals: options.globals,
- self: options.self,
- includeSources: options.compileDebug === true,
- debug: options.debug,
- templateName: 'template',
- filters: options.filters,
- filterOptions: options.filterOptions,
- filterAliases: options.filterAliases,
- plugins: options.plugins,
- });
-
- var res = options.inlineRuntimeFunctions
- ? new Function('', parsed.body + ';return template;')()
- : runtimeWrap(parsed.body);
-
- res.dependencies = parsed.dependencies;
-
- return res;
-};
-
-/**
- * Compile a JavaScript source representation of the given pug `str`.
- *
- * Options:
- *
- * - `compileDebug` When it is `true`, the source code is included in
- * the compiled template for better error messages.
- * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends
- * - `name` the name of the resulting function (defaults to "template")
- * - `module` when it is explicitly `true`, the source code include export module syntax
- *
- * @param {String} str
- * @param {Options} options
- * @return {Object}
- * @api public
- */
-
-exports.compileClientWithDependenciesTracked = function(str, options) {
- var options = options || {};
-
- str = String(str);
- var parsed = compileBody(str, {
- compileDebug: options.compileDebug,
- filename: options.filename,
- basedir: options.basedir,
- pretty: options.pretty,
- doctype: options.doctype,
- inlineRuntimeFunctions: options.inlineRuntimeFunctions !== false,
- globals: options.globals,
- self: options.self,
- includeSources: options.compileDebug,
- debug: options.debug,
- templateName: options.name || 'template',
- filters: options.filters,
- filterOptions: options.filterOptions,
- filterAliases: options.filterAliases,
- plugins: options.plugins,
- });
-
- var body = parsed.body;
-
- if (options.module) {
- if (options.inlineRuntimeFunctions === false) {
- body = 'var pug = require("pug-runtime");' + body;
- }
- body += ' module.exports = ' + (options.name || 'template') + ';';
- }
-
- return {body: body, dependencies: parsed.dependencies};
-};
-
-/**
- * Compile a JavaScript source representation of the given pug `str`.
- *
- * Options:
- *
- * - `compileDebug` When it is `true`, the source code is included in
- * the compiled template for better error messages.
- * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends
- * - `name` the name of the resulting function (defaults to "template")
- *
- * @param {String} str
- * @param {Options} options
- * @return {String}
- * @api public
- */
-exports.compileClient = function(str, options) {
- return exports.compileClientWithDependenciesTracked(str, options).body;
-};
-
-/**
- * Compile a `Function` representation of the given pug file.
- *
- * Options:
- *
- * - `compileDebug` when `false` debugging code is stripped from the compiled
- template, when it is explicitly `true`, the source code is included in
- the compiled template for better accuracy.
- *
- * @param {String} path
- * @param {Options} options
- * @return {Function}
- * @api public
- */
-exports.compileFile = function(path, options) {
- options = options || {};
- options.filename = path;
- return handleTemplateCache(options);
-};
-
-/**
- * Render the given `str` of pug.
- *
- * Options:
- *
- * - `cache` enable template caching
- * - `filename` filename required for `include` / `extends` and caching
- *
- * @param {String} str
- * @param {Object|Function} options or fn
- * @param {Function|undefined} fn
- * @returns {String}
- * @api public
- */
-
-exports.render = function(str, options, fn) {
- // support callback API
- if ('function' == typeof options) {
- (fn = options), (options = undefined);
- }
- if (typeof fn === 'function') {
- var res;
- try {
- res = exports.render(str, options);
- } catch (ex) {
- return fn(ex);
- }
- return fn(null, res);
- }
-
- options = options || {};
-
- // cache requires .filename
- if (options.cache && !options.filename) {
- throw new Error('the "filename" option is required for caching');
- }
-
- return handleTemplateCache(options, str)(options);
-};
-
-/**
- * Render a Pug file at the given `path`.
- *
- * @param {String} path
- * @param {Object|Function} options or callback
- * @param {Function|undefined} fn
- * @returns {String}
- * @api public
- */
-
-exports.renderFile = function(path, options, fn) {
- // support callback API
- if ('function' == typeof options) {
- (fn = options), (options = undefined);
- }
- if (typeof fn === 'function') {
- var res;
- try {
- res = exports.renderFile(path, options);
- } catch (ex) {
- return fn(ex);
- }
- return fn(null, res);
- }
-
- options = options || {};
-
- options.filename = path;
- return handleTemplateCache(options)(options);
-};
-
-/**
- * Compile a Pug file at the given `path` for use on the client.
- *
- * @param {String} path
- * @param {Object} options
- * @returns {String}
- * @api public
- */
-
-exports.compileFileClient = function(path, options) {
- var key = path + ':client';
- options = options || {};
-
- options.filename = path;
-
- if (options.cache && exports.cache[key]) {
- return exports.cache[key];
- }
-
- var str = fs.readFileSync(options.filename, 'utf8');
- var out = exports.compileClient(str, options);
- if (options.cache) exports.cache[key] = out;
- return out;
-};
-
-/**
- * Express support.
- */
-
-exports.__express = function(path, options, fn) {
- if (
- options.compileDebug == undefined &&
- process.env.NODE_ENV === 'production'
- ) {
- options.compileDebug = false;
- }
- exports.renderFile(path, options, fn);
-};
-
-
-/***/ }),
-
-/***/ 18341:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var once = __nccwpck_require__(1223)
-var eos = __nccwpck_require__(81205)
-var fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes
-
-var noop = function () {}
-var ancient = /^v?\.0/.test(process.version)
-
-var isFn = function (fn) {
- return typeof fn === 'function'
-}
-
-var isFS = function (stream) {
- if (!ancient) return false // newer node version do not need to care about fs is a special way
- if (!fs) return false // browser
- return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
-}
-
-var isRequest = function (stream) {
- return stream.setHeader && isFn(stream.abort)
-}
-
-var destroyer = function (stream, reading, writing, callback) {
- callback = once(callback)
-
- var closed = false
- stream.on('close', function () {
- closed = true
- })
-
- eos(stream, {readable: reading, writable: writing}, function (err) {
- if (err) return callback(err)
- closed = true
- callback()
- })
-
- var destroyed = false
- return function (err) {
- if (closed) return
- if (destroyed) return
- destroyed = true
-
- if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
- if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
-
- if (isFn(stream.destroy)) return stream.destroy()
-
- callback(err || new Error('stream was destroyed'))
- }
-}
-
-var call = function (fn) {
- fn()
-}
-
-var pipe = function (from, to) {
- return from.pipe(to)
-}
-
-var pump = function () {
- var streams = Array.prototype.slice.call(arguments)
- var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
-
- if (Array.isArray(streams[0])) streams = streams[0]
- if (streams.length < 2) throw new Error('pump requires two streams per minimum')
-
- var error
- var destroys = streams.map(function (stream, i) {
- var reading = i < streams.length - 1
- var writing = i > 0
- return destroyer(stream, reading, writing, function (err) {
- if (!error) error = err
- if (err) destroys.forEach(call)
- if (reading) return
- destroys.forEach(call)
- callback(error)
- })
- })
-
- return streams.reduce(pipe)
-}
-
-module.exports = pump
-
-
-/***/ }),
-
-/***/ 89795:
-/***/ ((module) => {
-
-/*! queue-microtask. MIT License. Feross Aboukhadijeh */
-let promise
-
-module.exports = typeof queueMicrotask === 'function'
- ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
- // reuse resolved promise, and allocate it lazily
- : cb => (promise || (promise = Promise.resolve()))
- .then(cb)
- .catch(err => setTimeout(() => { throw err }, 0))
-
-
-/***/ }),
-
-/***/ 96976:
-/***/ ((module) => {
-
-"use strict";
-/*!
- * repeat-string
- *
- * Copyright (c) 2014-2015, Jon Schlinkert.
- * Licensed under the MIT License.
- */
-
-
-
-/**
- * Results cache
- */
-
-var res = '';
-var cache;
-
-/**
- * Expose `repeat`
- */
-
-module.exports = repeat;
-
-/**
- * Repeat the given `string` the specified `number`
- * of times.
- *
- * **Example:**
- *
- * ```js
- * var repeat = require('repeat-string');
- * repeat('A', 5);
- * //=> AAAAA
- * ```
- *
- * @param {String} `string` The string to repeat
- * @param {Number} `number` The number of times to repeat the string
- * @return {String} Repeated string
- * @api public
- */
-
-function repeat(str, num) {
- if (typeof str !== 'string') {
- throw new TypeError('expected a string');
- }
-
- // cover common, quick use cases
- if (num === 1) return str;
- if (num === 2) return str + str;
-
- var max = str.length * num;
- if (cache !== str || typeof cache === 'undefined') {
- cache = str;
- res = '';
- } else if (res.length >= max) {
- return res.substr(0, max);
- }
-
- while (max > res.length && num > 1) {
- if (num & 1) {
- res += str;
- }
-
- num >>= 1;
- str += str;
- }
-
- res += str;
- res = res.substr(0, max);
- return res;
-}
-
-
-/***/ }),
-
-/***/ 65444:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'abap',
- init: function init(Prism) {
- Prism.languages.abap = {
- comment: /^\*.*/m,
- string: /(`|')(?:\\.|(?!\1)[^\\\r\n])*\1/m,
- 'string-template': {
- pattern: /([|}])(?:\\.|[^\\|{\r\n])*(?=[|{])/,
- lookbehind: true,
- alias: 'string'
- },
- /* End Of Line comments should not interfere with strings when the
- quote character occurs within them. We assume a string being highlighted
- inside an EOL comment is more acceptable than the opposite.
- */
- 'eol-comment': {
- pattern: /(^|\s)".*/m,
- lookbehind: true,
- alias: 'comment'
- },
- keyword: {
- pattern: /(\s|\.|^)(?:SCIENTIFIC_WITH_LEADING_ZERO|SCALE_PRESERVING_SCIENTIFIC|RMC_COMMUNICATION_FAILURE|END-ENHANCEMENT-SECTION|MULTIPLY-CORRESPONDING|SUBTRACT-CORRESPONDING|VERIFICATION-MESSAGE|DIVIDE-CORRESPONDING|ENHANCEMENT-SECTION|CURRENCY_CONVERSION|RMC_SYSTEM_FAILURE|START-OF-SELECTION|MOVE-CORRESPONDING|RMC_INVALID_STATUS|CUSTOMER-FUNCTION|END-OF-DEFINITION|ENHANCEMENT-POINT|SYSTEM-EXCEPTIONS|ADD-CORRESPONDING|SCALE_PRESERVING|SELECTION-SCREEN|CURSOR-SELECTION|END-OF-SELECTION|LOAD-OF-PROGRAM|SCROLL-BOUNDARY|SELECTION-TABLE|EXCEPTION-TABLE|IMPLEMENTATIONS|PARAMETER-TABLE|RIGHT-JUSTIFIED|UNIT_CONVERSION|AUTHORITY-CHECK|LIST-PROCESSING|SIGN_AS_POSTFIX|COL_BACKGROUND|IMPLEMENTATION|INTERFACE-POOL|TRANSFORMATION|IDENTIFICATION|ENDENHANCEMENT|LINE-SELECTION|INITIALIZATION|LEFT-JUSTIFIED|SELECT-OPTIONS|SELECTION-SETS|COMMUNICATION|CORRESPONDING|DECIMAL_SHIFT|PRINT-CONTROL|VALUE-REQUEST|CHAIN-REQUEST|FUNCTION-POOL|FIELD-SYMBOLS|FUNCTIONALITY|INVERTED-DATE|SELECTION-SET|CLASS-METHODS|OUTPUT-LENGTH|CLASS-CODING|COL_NEGATIVE|ERRORMESSAGE|FIELD-GROUPS|HELP-REQUEST|NO-EXTENSION|NO-TOPOFPAGE|REDEFINITION|DISPLAY-MODE|ENDINTERFACE|EXIT-COMMAND|FIELD-SYMBOL|NO-SCROLLING|SHORTDUMP-ID|ACCESSPOLICY|CLASS-EVENTS|COL_POSITIVE|DECLARATIONS|ENHANCEMENTS|FILTER-TABLE|SWITCHSTATES|SYNTAX-CHECK|TRANSPORTING|ASYNCHRONOUS|SYNTAX-TRACE|TOKENIZATION|USER-COMMAND|WITH-HEADING|ABAP-SOURCE|BREAK-POINT|CHAIN-INPUT|COMPRESSION|FIXED-POINT|NEW-SECTION|NON-UNICODE|OCCURRENCES|RESPONSIBLE|SYSTEM-CALL|TRACE-TABLE|ABBREVIATED|CHAR-TO-HEX|END-OF-FILE|ENDFUNCTION|ENVIRONMENT|ASSOCIATION|COL_HEADING|EDITOR-CALL|END-OF-PAGE|ENGINEERING|IMPLEMENTED|INTENSIFIED|RADIOBUTTON|SYSTEM-EXIT|TOP-OF-PAGE|TRANSACTION|APPLICATION|CONCATENATE|DESTINATION|ENHANCEMENT|IMMEDIATELY|NO-GROUPING|PRECOMPILED|REPLACEMENT|TITLE-LINES|ACTIVATION|BYTE-ORDER|CLASS-POOL|CONNECTION|CONVERSION|DEFINITION|DEPARTMENT|EXPIRATION|INHERITING|MESSAGE-ID|NO-HEADING|PERFORMING|QUEUE-ONLY|RIGHTSPACE|SCIENTIFIC|STATUSINFO|STRUCTURES|SYNCPOINTS|WITH-TITLE|ATTRIBUTES|BOUNDARIES|CLASS-DATA|COL_NORMAL|DD\/MM\/YYYY|DESCENDING|INTERFACES|LINE-COUNT|MM\/DD\/YYYY|NON-UNIQUE|PRESERVING|SELECTIONS|STATEMENTS|SUBROUTINE|TRUNCATION|TYPE-POOLS|ARITHMETIC|BACKGROUND|ENDPROVIDE|EXCEPTIONS|IDENTIFIER|INDEX-LINE|OBLIGATORY|PARAMETERS|PERCENTAGE|PUSHBUTTON|RESOLUTION|COMPONENTS|DEALLOCATE|DISCONNECT|DUPLICATES|FIRST-LINE|HEAD-LINES|NO-DISPLAY|OCCURRENCE|RESPECTING|RETURNCODE|SUBMATCHES|TRACE-FILE|ASCENDING|BYPASSING|ENDMODULE|EXCEPTION|EXCLUDING|EXPORTING|INCREMENT|MATCHCODE|PARAMETER|PARTIALLY|PREFERRED|REFERENCE|REPLACING|RETURNING|SELECTION|SEPARATED|SPECIFIED|STATEMENT|TIMESTAMP|TYPE-POOL|ACCEPTING|APPENDAGE|ASSIGNING|COL_GROUP|COMPARING|CONSTANTS|DANGEROUS|IMPORTING|INSTANCES|LEFTSPACE|LOG-POINT|QUICKINFO|READ-ONLY|SCROLLING|SQLSCRIPT|STEP-LOOP|TOP-LINES|TRANSLATE|APPENDING|AUTHORITY|CHARACTER|COMPONENT|CONDITION|DIRECTORY|DUPLICATE|MESSAGING|RECEIVING|SUBSCREEN|ACCORDING|COL_TOTAL|END-LINES|ENDMETHOD|ENDSELECT|EXPANDING|EXTENSION|INCLUDING|INFOTYPES|INTERFACE|INTERVALS|LINE-SIZE|PF-STATUS|PROCEDURE|PROTECTED|REQUESTED|RESUMABLE|RIGHTPLUS|SAP-SPOOL|SECONDARY|STRUCTURE|SUBSTRING|TABLEVIEW|NUMOFCHAR|ADJACENT|ANALYSIS|ASSIGNED|BACKWARD|CHANNELS|CHECKBOX|CONTINUE|CRITICAL|DATAINFO|DD\/MM\/YY|DURATION|ENCODING|ENDCLASS|FUNCTION|LEFTPLUS|LINEFEED|MM\/DD\/YY|OVERFLOW|RECEIVED|SKIPPING|SORTABLE|STANDARD|SUBTRACT|SUPPRESS|TABSTRIP|TITLEBAR|TRUNCATE|UNASSIGN|WHENEVER|ANALYZER|COALESCE|COMMENTS|CONDENSE|DECIMALS|DEFERRED|ENDWHILE|EXPLICIT|KEYWORDS|MESSAGES|POSITION|PRIORITY|RECEIVER|RENAMING|TIMEZONE|TRAILING|ALLOCATE|CENTERED|CIRCULAR|CONTROLS|CURRENCY|DELETING|DESCRIBE|DISTANCE|ENDCATCH|EXPONENT|EXTENDED|GENERATE|IGNORING|INCLUDES|INTERNAL|MAJOR-ID|MODIFIER|NEW-LINE|OPTIONAL|PROPERTY|ROLLBACK|STARTING|SUPPLIED|ABSTRACT|CHANGING|CONTEXTS|CREATING|CUSTOMER|DATABASE|DAYLIGHT|DEFINING|DISTINCT|DIVISION|ENABLING|ENDCHAIN|ESCAPING|HARMLESS|IMPLICIT|INACTIVE|LANGUAGE|MINOR-ID|MULTIPLY|NEW-PAGE|NO-TITLE|POS_HIGH|SEPARATE|TEXTPOOL|TRANSFER|SELECTOR|DBMAXLEN|ITERATOR|SELECTOR|ARCHIVE|BIT-XOR|BYTE-CO|COLLECT|COMMENT|CURRENT|DEFAULT|DISPLAY|ENDFORM|EXTRACT|LEADING|LISTBOX|LOCATOR|MEMBERS|METHODS|NESTING|POS_LOW|PROCESS|PROVIDE|RAISING|RESERVE|SECONDS|SUMMARY|VISIBLE|BETWEEN|BIT-AND|BYTE-CS|CLEANUP|COMPUTE|CONTROL|CONVERT|DATASET|ENDCASE|FORWARD|HEADERS|HOTSPOT|INCLUDE|INVERSE|KEEPING|NO-ZERO|OBJECTS|OVERLAY|PADDING|PATTERN|PROGRAM|REFRESH|SECTION|SUMMING|TESTING|VERSION|WINDOWS|WITHOUT|BIT-NOT|BYTE-CA|BYTE-NA|CASTING|CONTEXT|COUNTRY|DYNAMIC|ENABLED|ENDLOOP|EXECUTE|FRIENDS|HANDLER|HEADING|INITIAL|\*-INPUT|LOGFILE|MAXIMUM|MINIMUM|NO-GAPS|NO-SIGN|PRAGMAS|PRIMARY|PRIVATE|REDUCED|REPLACE|REQUEST|RESULTS|UNICODE|WARNING|ALIASES|BYTE-CN|BYTE-NS|CALLING|COL_KEY|COLUMNS|CONNECT|ENDEXEC|ENTRIES|EXCLUDE|FILTERS|FURTHER|HELP-ID|LOGICAL|MAPPING|MESSAGE|NAMETAB|OPTIONS|PACKAGE|PERFORM|RECEIVE|STATICS|VARYING|BINDING|CHARLEN|GREATER|XSTRLEN|ACCEPT|APPEND|DETAIL|ELSEIF|ENDING|ENDTRY|FORMAT|FRAMES|GIVING|HASHED|HEADER|IMPORT|INSERT|MARGIN|MODULE|NATIVE|OBJECT|OFFSET|REMOTE|RESUME|SAVING|SIMPLE|SUBMIT|TABBED|TOKENS|UNIQUE|UNPACK|UPDATE|WINDOW|YELLOW|ACTUAL|ASPECT|CENTER|CURSOR|DELETE|DIALOG|DIVIDE|DURING|ERRORS|EVENTS|EXTEND|FILTER|HANDLE|HAVING|IGNORE|LITTLE|MEMORY|NO-GAP|OCCURS|OPTION|PERSON|PLACES|PUBLIC|REDUCE|REPORT|RESULT|SINGLE|SORTED|SWITCH|SYNTAX|TARGET|VALUES|WRITER|ASSERT|BLOCKS|BOUNDS|BUFFER|CHANGE|COLUMN|COMMIT|CONCAT|COPIES|CREATE|DDMMYY|DEFINE|ENDIAN|ESCAPE|EXPAND|KERNEL|LAYOUT|LEGACY|LEVELS|MMDDYY|NUMBER|OUTPUT|RANGES|READER|RETURN|SCREEN|SEARCH|SELECT|SHARED|SOURCE|STABLE|STATIC|SUBKEY|SUFFIX|TABLES|UNWIND|YYMMDD|ASSIGN|BACKUP|BEFORE|BINARY|BIT-OR|BLANKS|CLIENT|CODING|COMMON|DEMAND|DYNPRO|EXCEPT|EXISTS|EXPORT|FIELDS|GLOBAL|GROUPS|LENGTH|LOCALE|MEDIUM|METHOD|MODIFY|NESTED|OTHERS|REJECT|SCROLL|SUPPLY|SYMBOL|ENDFOR|STRLEN|ALIGN|BEGIN|BOUND|ENDAT|ENTRY|EVENT|FINAL|FLUSH|GRANT|INNER|SHORT|USING|WRITE|AFTER|BLACK|BLOCK|CLOCK|COLOR|COUNT|DUMMY|EMPTY|ENDDO|ENDON|GREEN|INDEX|INOUT|LEAVE|LEVEL|LINES|MODIF|ORDER|OUTER|RANGE|RESET|RETRY|RIGHT|SMART|SPLIT|STYLE|TABLE|THROW|UNDER|UNTIL|UPPER|UTF-8|WHERE|ALIAS|BLANK|CLEAR|CLOSE|EXACT|FETCH|FIRST|FOUND|GROUP|LLANG|LOCAL|OTHER|REGEX|SPOOL|TITLE|TYPES|VALID|WHILE|ALPHA|BOXED|CATCH|CHAIN|CHECK|CLASS|COVER|ENDIF|EQUIV|FIELD|FLOOR|FRAME|INPUT|LOWER|MATCH|NODES|PAGES|PRINT|RAISE|ROUND|SHIFT|SPACE|SPOTS|STAMP|STATE|TASKS|TIMES|TRMAC|ULINE|UNION|VALUE|WIDTH|EQUAL|LOG10|TRUNC|BLOB|CASE|CEIL|CLOB|COND|EXIT|FILE|GAPS|HOLD|INCL|INTO|KEEP|KEYS|LAST|LINE|LONG|LPAD|MAIL|MODE|OPEN|PINK|READ|ROWS|TEST|THEN|ZERO|AREA|BACK|BADI|BYTE|CAST|EDIT|EXEC|FAIL|FIND|FKEQ|FONT|FREE|GKEQ|HIDE|INIT|ITNO|LATE|LOOP|MAIN|MARK|MOVE|NEXT|NULL|RISK|ROLE|UNIT|WAIT|ZONE|BASE|CALL|CODE|DATA|DATE|FKGE|GKGE|HIGH|KIND|LEFT|LIST|MASK|MESH|NAME|NODE|PACK|PAGE|POOL|SEND|SIGN|SIZE|SOME|STOP|TASK|TEXT|TIME|USER|VARY|WITH|WORD|BLUE|CONV|COPY|DEEP|ELSE|FORM|FROM|HINT|ICON|JOIN|LIKE|LOAD|ONLY|PART|SCAN|SKIP|SORT|TYPE|UNIX|VIEW|WHEN|WORK|ACOS|ASIN|ATAN|COSH|EACH|FRAC|LESS|RTTI|SINH|SQRT|TANH|AVG|BIT|DIV|ISO|LET|OUT|PAD|SQL|ALL|CI_|CPI|END|LOB|LPI|MAX|MIN|NEW|OLE|RUN|SET|\?TO|YES|ABS|ADD|AND|BIG|FOR|HDB|JOB|LOW|NOT|SAP|TRY|VIA|XML|ANY|GET|IDS|KEY|MOD|OFF|PUT|RAW|RED|REF|SUM|TAB|XSD|CNT|COS|EXP|LOG|SIN|TAN|XOR|AT|CO|CP|DO|GT|ID|IF|NS|OR|BT|CA|CS|GE|NA|NB|EQ|IN|LT|NE|NO|OF|ON|PF|TO|AS|BY|CN|IS|LE|NP|UP|E|I|M|O|Z|C|X)\b/i,
- lookbehind: true
- },
- /* Numbers can be only integers. Decimal or Hex appear only as strings */
- number: /\b\d+\b/,
- /* Operators must always be surrounded by whitespace, they cannot be put
- adjacent to operands.
- */
- operator: {
- pattern: /(\s)(?:\*\*?|<[=>]?|>=?|\?=|[-+\/=])(?=\s)/,
- lookbehind: true
- },
- 'string-operator': {
- pattern: /(\s)&&?(?=\s)/,
- lookbehind: true,
- /* The official editor highlights */
- alias: 'keyword'
- },
- 'token-operator': [{
- /* Special operators used to access structure components, class methods/attributes, etc. */
- pattern: /(\w)(?:->?|=>|[~|{}])(?=\w)/,
- lookbehind: true,
- alias: 'punctuation'
- }, {
- /* Special tokens used do delimit string templates */
- pattern: /[|{}]/,
- alias: 'punctuation'
- }],
- punctuation: /[,.:()]/
- };
- }
-};
-
-/***/ }),
-
-/***/ 21019:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'actionscript',
- init: function init(Prism) {
- Prism.languages.actionscript = Prism.languages.extend('javascript', {
- keyword: /\b(?:as|break|case|catch|class|const|default|delete|do|else|extends|finally|for|function|if|implements|import|in|instanceof|interface|internal|is|native|new|null|package|private|protected|public|return|super|switch|this|throw|try|typeof|use|var|void|while|with|dynamic|each|final|get|include|namespace|native|override|set|static)\b/,
- operator: /\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<|>>?>?|[!=]=?)=?|[~?@]/
- });
- Prism.languages.actionscript['class-name'].alias = 'function';
-
- if (Prism.languages.markup) {
- Prism.languages.insertBefore('actionscript', 'string', {
- xml: {
- pattern: /(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\[\s\S]|(?!\2)[^\\])*\2)*\s*\/?>/,
- lookbehind: true,
- inside: {
- rest: Prism.languages.markup
- }
- }
- });
- }
- }
-};
-
-/***/ }),
-
-/***/ 99040:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'ada',
- init: function init(Prism) {
- Prism.languages.ada = {
- comment: /--.*/,
- string: /"(?:""|[^"\r\f\n])*"/i,
- number: [{
- pattern: /\b\d(?:_?\d)*#[\dA-F](?:_?[\dA-F])*(?:\.[\dA-F](?:_?[\dA-F])*)?#(?:E[+-]?\d(?:_?\d)*)?/i
- }, {
- pattern: /\b\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:E[+-]?\d(?:_?\d)*)?\b/i
- }],
- 'attr-name': /\b'\w+/i,
- keyword: /\b(?:abort|abs|abstract|accept|access|aliased|all|and|array|at|begin|body|case|constant|declare|delay|delta|digits|do|else|new|return|elsif|end|entry|exception|exit|for|function|generic|goto|if|in|interface|is|limited|loop|mod|not|null|of|others|out|overriding|package|pragma|private|procedure|protected|raise|range|record|rem|renames|requeue|reverse|select|separate|some|subtype|synchronized|tagged|task|terminate|then|type|until|use|when|while|with|xor)\b/i,
- boolean: /\b(?:true|false)\b/i,
- operator: /<[=>]?|>=?|=>?|:=|\/=?|\*\*?|[&+-]/,
- punctuation: /\.\.?|[,;():]/,
- char: /'.'/,
- variable: /\b[a-z](?:[_a-z\d])*\b/i
- };
- }
-};
-
-/***/ }),
-
-/***/ 70629:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'apacheconf',
- init: function init(Prism) {
- Prism.languages.apacheconf = {
- comment: /#.*/,
- 'directive-inline': {
- pattern: /^(\s*)\b(?:AcceptFilter|AcceptPathInfo|AccessFileName|Action|AddAlt|AddAltByEncoding|AddAltByType|AddCharset|AddDefaultCharset|AddDescription|AddEncoding|AddHandler|AddIcon|AddIconByEncoding|AddIconByType|AddInputFilter|AddLanguage|AddModuleInfo|AddOutputFilter|AddOutputFilterByType|AddType|Alias|AliasMatch|Allow|AllowCONNECT|AllowEncodedSlashes|AllowMethods|AllowOverride|AllowOverrideList|Anonymous|Anonymous_LogEmail|Anonymous_MustGiveEmail|Anonymous_NoUserID|Anonymous_VerifyEmail|AsyncRequestWorkerFactor|AuthBasicAuthoritative|AuthBasicFake|AuthBasicProvider|AuthBasicUseDigestAlgorithm|AuthDBDUserPWQuery|AuthDBDUserRealmQuery|AuthDBMGroupFile|AuthDBMType|AuthDBMUserFile|AuthDigestAlgorithm|AuthDigestDomain|AuthDigestNonceLifetime|AuthDigestProvider|AuthDigestQop|AuthDigestShmemSize|AuthFormAuthoritative|AuthFormBody|AuthFormDisableNoStore|AuthFormFakeBasicAuth|AuthFormLocation|AuthFormLoginRequiredLocation|AuthFormLoginSuccessLocation|AuthFormLogoutLocation|AuthFormMethod|AuthFormMimetype|AuthFormPassword|AuthFormProvider|AuthFormSitePassphrase|AuthFormSize|AuthFormUsername|AuthGroupFile|AuthLDAPAuthorizePrefix|AuthLDAPBindAuthoritative|AuthLDAPBindDN|AuthLDAPBindPassword|AuthLDAPCharsetConfig|AuthLDAPCompareAsUser|AuthLDAPCompareDNOnServer|AuthLDAPDereferenceAliases|AuthLDAPGroupAttribute|AuthLDAPGroupAttributeIsDN|AuthLDAPInitialBindAsUser|AuthLDAPInitialBindPattern|AuthLDAPMaxSubGroupDepth|AuthLDAPRemoteUserAttribute|AuthLDAPRemoteUserIsDN|AuthLDAPSearchAsUser|AuthLDAPSubGroupAttribute|AuthLDAPSubGroupClass|AuthLDAPUrl|AuthMerging|AuthName|AuthnCacheContext|AuthnCacheEnable|AuthnCacheProvideFor|AuthnCacheSOCache|AuthnCacheTimeout|AuthnzFcgiCheckAuthnProvider|AuthnzFcgiDefineProvider|AuthType|AuthUserFile|AuthzDBDLoginToReferer|AuthzDBDQuery|AuthzDBDRedirectQuery|AuthzDBMType|AuthzSendForbiddenOnFailure|BalancerGrowth|BalancerInherit|BalancerMember|BalancerPersist|BrowserMatch|BrowserMatchNoCase|BufferedLogs|BufferSize|CacheDefaultExpire|CacheDetailHeader|CacheDirLength|CacheDirLevels|CacheDisable|CacheEnable|CacheFile|CacheHeader|CacheIgnoreCacheControl|CacheIgnoreHeaders|CacheIgnoreNoLastMod|CacheIgnoreQueryString|CacheIgnoreURLSessionIdentifiers|CacheKeyBaseURL|CacheLastModifiedFactor|CacheLock|CacheLockMaxAge|CacheLockPath|CacheMaxExpire|CacheMaxFileSize|CacheMinExpire|CacheMinFileSize|CacheNegotiatedDocs|CacheQuickHandler|CacheReadSize|CacheReadTime|CacheRoot|CacheSocache|CacheSocacheMaxSize|CacheSocacheMaxTime|CacheSocacheMinTime|CacheSocacheReadSize|CacheSocacheReadTime|CacheStaleOnError|CacheStoreExpired|CacheStoreNoStore|CacheStorePrivate|CGIDScriptTimeout|CGIMapExtension|CharsetDefault|CharsetOptions|CharsetSourceEnc|CheckCaseOnly|CheckSpelling|ChrootDir|ContentDigest|CookieDomain|CookieExpires|CookieName|CookieStyle|CookieTracking|CoreDumpDirectory|CustomLog|Dav|DavDepthInfinity|DavGenericLockDB|DavLockDB|DavMinTimeout|DBDExptime|DBDInitSQL|DBDKeep|DBDMax|DBDMin|DBDParams|DBDPersist|DBDPrepareSQL|DBDriver|DefaultIcon|DefaultLanguage|DefaultRuntimeDir|DefaultType|Define|DeflateBufferSize|DeflateCompressionLevel|DeflateFilterNote|DeflateInflateLimitRequestBody|DeflateInflateRatioBurst|DeflateInflateRatioLimit|DeflateMemLevel|DeflateWindowSize|Deny|DirectoryCheckHandler|DirectoryIndex|DirectoryIndexRedirect|DirectorySlash|DocumentRoot|DTracePrivileges|DumpIOInput|DumpIOOutput|EnableExceptionHook|EnableMMAP|EnableSendfile|Error|ErrorDocument|ErrorLog|ErrorLogFormat|Example|ExpiresActive|ExpiresByType|ExpiresDefault|ExtendedStatus|ExtFilterDefine|ExtFilterOptions|FallbackResource|FileETag|FilterChain|FilterDeclare|FilterProtocol|FilterProvider|FilterTrace|ForceLanguagePriority|ForceType|ForensicLog|GprofDir|GracefulShutdownTimeout|Group|Header|HeaderName|HeartbeatAddress|HeartbeatListen|HeartbeatMaxServers|HeartbeatStorage|HeartbeatStorage|HostnameLookups|IdentityCheck|IdentityCheckTimeout|ImapBase|ImapDefault|ImapMenu|Include|IncludeOptional|IndexHeadInsert|IndexIgnore|IndexIgnoreReset|IndexOptions|IndexOrderDefault|IndexStyleSheet|InputSed|ISAPIAppendLogToErrors|ISAPIAppendLogToQuery|ISAPICacheFile|ISAPIFakeAsync|ISAPILogNotSupported|ISAPIReadAheadBuffer|KeepAlive|KeepAliveTimeout|KeptBodySize|LanguagePriority|LDAPCacheEntries|LDAPCacheTTL|LDAPConnectionPoolTTL|LDAPConnectionTimeout|LDAPLibraryDebug|LDAPOpCacheEntries|LDAPOpCacheTTL|LDAPReferralHopLimit|LDAPReferrals|LDAPRetries|LDAPRetryDelay|LDAPSharedCacheFile|LDAPSharedCacheSize|LDAPTimeout|LDAPTrustedClientCert|LDAPTrustedGlobalCert|LDAPTrustedMode|LDAPVerifyServerCert|LimitInternalRecursion|LimitRequestBody|LimitRequestFields|LimitRequestFieldSize|LimitRequestLine|LimitXMLRequestBody|Listen|ListenBackLog|LoadFile|LoadModule|LogFormat|LogLevel|LogMessage|LuaAuthzProvider|LuaCodeCache|LuaHookAccessChecker|LuaHookAuthChecker|LuaHookCheckUserID|LuaHookFixups|LuaHookInsertFilter|LuaHookLog|LuaHookMapToStorage|LuaHookTranslateName|LuaHookTypeChecker|LuaInherit|LuaInputFilter|LuaMapHandler|LuaOutputFilter|LuaPackageCPath|LuaPackagePath|LuaQuickHandler|LuaRoot|LuaScope|MaxConnectionsPerChild|MaxKeepAliveRequests|MaxMemFree|MaxRangeOverlaps|MaxRangeReversals|MaxRanges|MaxRequestWorkers|MaxSpareServers|MaxSpareThreads|MaxThreads|MergeTrailers|MetaDir|MetaFiles|MetaSuffix|MimeMagicFile|MinSpareServers|MinSpareThreads|MMapFile|ModemStandard|ModMimeUsePathInfo|MultiviewsMatch|Mutex|NameVirtualHost|NoProxy|NWSSLTrustedCerts|NWSSLUpgradeable|Options|Order|OutputSed|PassEnv|PidFile|PrivilegesMode|Protocol|ProtocolEcho|ProxyAddHeaders|ProxyBadHeader|ProxyBlock|ProxyDomain|ProxyErrorOverride|ProxyExpressDBMFile|ProxyExpressDBMType|ProxyExpressEnable|ProxyFtpDirCharset|ProxyFtpEscapeWildcards|ProxyFtpListOnWildcard|ProxyHTMLBufSize|ProxyHTMLCharsetOut|ProxyHTMLDocType|ProxyHTMLEnable|ProxyHTMLEvents|ProxyHTMLExtended|ProxyHTMLFixups|ProxyHTMLInterp|ProxyHTMLLinks|ProxyHTMLMeta|ProxyHTMLStripComments|ProxyHTMLURLMap|ProxyIOBufferSize|ProxyMaxForwards|ProxyPass|ProxyPassInherit|ProxyPassInterpolateEnv|ProxyPassMatch|ProxyPassReverse|ProxyPassReverseCookieDomain|ProxyPassReverseCookiePath|ProxyPreserveHost|ProxyReceiveBufferSize|ProxyRemote|ProxyRemoteMatch|ProxyRequests|ProxySCGIInternalRedirect|ProxySCGISendfile|ProxySet|ProxySourceAddress|ProxyStatus|ProxyTimeout|ProxyVia|ReadmeName|ReceiveBufferSize|Redirect|RedirectMatch|RedirectPermanent|RedirectTemp|ReflectorHeader|RemoteIPHeader|RemoteIPInternalProxy|RemoteIPInternalProxyList|RemoteIPProxiesHeader|RemoteIPTrustedProxy|RemoteIPTrustedProxyList|RemoveCharset|RemoveEncoding|RemoveHandler|RemoveInputFilter|RemoveLanguage|RemoveOutputFilter|RemoveType|RequestHeader|RequestReadTimeout|Require|RewriteBase|RewriteCond|RewriteEngine|RewriteMap|RewriteOptions|RewriteRule|RLimitCPU|RLimitMEM|RLimitNPROC|Satisfy|ScoreBoardFile|Script|ScriptAlias|ScriptAliasMatch|ScriptInterpreterSource|ScriptLog|ScriptLogBuffer|ScriptLogLength|ScriptSock|SecureListen|SeeRequestTail|SendBufferSize|ServerAdmin|ServerAlias|ServerLimit|ServerName|ServerPath|ServerRoot|ServerSignature|ServerTokens|Session|SessionCookieName|SessionCookieName2|SessionCookieRemove|SessionCryptoCipher|SessionCryptoDriver|SessionCryptoPassphrase|SessionCryptoPassphraseFile|SessionDBDCookieName|SessionDBDCookieName2|SessionDBDCookieRemove|SessionDBDDeleteLabel|SessionDBDInsertLabel|SessionDBDPerUser|SessionDBDSelectLabel|SessionDBDUpdateLabel|SessionEnv|SessionExclude|SessionHeader|SessionInclude|SessionMaxAge|SetEnv|SetEnvIf|SetEnvIfExpr|SetEnvIfNoCase|SetHandler|SetInputFilter|SetOutputFilter|SSIEndTag|SSIErrorMsg|SSIETag|SSILastModified|SSILegacyExprParser|SSIStartTag|SSITimeFormat|SSIUndefinedEcho|SSLCACertificateFile|SSLCACertificatePath|SSLCADNRequestFile|SSLCADNRequestPath|SSLCARevocationCheck|SSLCARevocationFile|SSLCARevocationPath|SSLCertificateChainFile|SSLCertificateFile|SSLCertificateKeyFile|SSLCipherSuite|SSLCompression|SSLCryptoDevice|SSLEngine|SSLFIPS|SSLHonorCipherOrder|SSLInsecureRenegotiation|SSLOCSPDefaultResponder|SSLOCSPEnable|SSLOCSPOverrideResponder|SSLOCSPResponderTimeout|SSLOCSPResponseMaxAge|SSLOCSPResponseTimeSkew|SSLOCSPUseRequestNonce|SSLOpenSSLConfCmd|SSLOptions|SSLPassPhraseDialog|SSLProtocol|SSLProxyCACertificateFile|SSLProxyCACertificatePath|SSLProxyCARevocationCheck|SSLProxyCARevocationFile|SSLProxyCARevocationPath|SSLProxyCheckPeerCN|SSLProxyCheckPeerExpire|SSLProxyCheckPeerName|SSLProxyCipherSuite|SSLProxyEngine|SSLProxyMachineCertificateChainFile|SSLProxyMachineCertificateFile|SSLProxyMachineCertificatePath|SSLProxyProtocol|SSLProxyVerify|SSLProxyVerifyDepth|SSLRandomSeed|SSLRenegBufferSize|SSLRequire|SSLRequireSSL|SSLSessionCache|SSLSessionCacheTimeout|SSLSessionTicketKeyFile|SSLSRPUnknownUserSeed|SSLSRPVerifierFile|SSLStaplingCache|SSLStaplingErrorCacheTimeout|SSLStaplingFakeTryLater|SSLStaplingForceURL|SSLStaplingResponderTimeout|SSLStaplingResponseMaxAge|SSLStaplingResponseTimeSkew|SSLStaplingReturnResponderErrors|SSLStaplingStandardCacheTimeout|SSLStrictSNIVHostCheck|SSLUserName|SSLUseStapling|SSLVerifyClient|SSLVerifyDepth|StartServers|StartThreads|Substitute|Suexec|SuexecUserGroup|ThreadLimit|ThreadsPerChild|ThreadStackSize|TimeOut|TraceEnable|TransferLog|TypesConfig|UnDefine|UndefMacro|UnsetEnv|Use|UseCanonicalName|UseCanonicalPhysicalPort|User|UserDir|VHostCGIMode|VHostCGIPrivs|VHostGroup|VHostPrivs|VHostSecure|VHostUser|VirtualDocumentRoot|VirtualDocumentRootIP|VirtualScriptAlias|VirtualScriptAliasIP|WatchdogInterval|XBitHack|xml2EncAlias|xml2EncDefault|xml2StartParse)\b/im,
- lookbehind: true,
- alias: 'property'
- },
- 'directive-block': {
- pattern: /<\/?\b(?:AuthnProviderAlias|AuthzProviderAlias|Directory|DirectoryMatch|Else|ElseIf|Files|FilesMatch|If|IfDefine|IfModule|IfVersion|Limit|LimitExcept|Location|LocationMatch|Macro|Proxy|RequireAll|RequireAny|RequireNone|VirtualHost)\b *.*>/i,
- inside: {
- 'directive-block': {
- pattern: /^<\/?\w+/,
- inside: {
- punctuation: /^<\/?/
- },
- alias: 'tag'
- },
- 'directive-block-parameter': {
- pattern: /.*[^>]/,
- inside: {
- punctuation: /:/,
- string: {
- pattern: /("|').*\1/,
- inside: {
- variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/
- }
- }
- },
- alias: 'attr-value'
- },
- punctuation: />/
- },
- alias: 'tag'
- },
- 'directive-flags': {
- pattern: /\[(?:\w,?)+\]/,
- alias: 'keyword'
- },
- string: {
- pattern: /("|').*\1/,
- inside: {
- variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/
- }
- },
- variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/,
- regex: /\^?.*\$|\^.*\$?/
- };
- }
-};
-
-/***/ }),
-
-/***/ 13529:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'apl',
- init: function init(Prism) {
- Prism.languages.apl = {
- comment: /(?:⍝|#[! ]).*$/m,
- string: {
- pattern: /'(?:[^'\r\n]|'')*'/,
- greedy: true
- },
- number: /¯?(?:\d*\.?\d+(?:e[+¯]?\d+)?|¯|∞)(?:j¯?(?:\d*\.?\d+(?:e[+¯]?\d+)?|¯|∞))?/i,
- statement: /:[A-Z][a-z][A-Za-z]*\b/,
- 'system-function': {
- pattern: /⎕[A-Z]+/i,
- alias: 'function'
- },
- constant: /[⍬⌾#⎕⍞]/,
- function: /[-+×÷⌈⌊∣|⍳⍸?*⍟○!⌹<≤=>≥≠≡≢∊⍷∪∩~∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⊆⊇⌷⍋⍒⊤⊥⍕⍎⊣⊢⍁⍂≈⍯↗¤→]/,
- 'monadic-operator': {
- pattern: /[\\\/⌿⍀¨⍨⌶&∥]/,
- alias: 'operator'
- },
- 'dyadic-operator': {
- pattern: /[.⍣⍠⍤∘⌸@⌺]/,
- alias: 'operator'
- },
- assignment: {
- pattern: /←/,
- alias: 'keyword'
- },
- punctuation: /[\[;\]()◇⋄]/,
- dfn: {
- pattern: /[{}⍺⍵⍶⍹∇⍫:]/,
- alias: 'builtin'
- }
- };
- }
-};
-
-/***/ }),
-
-/***/ 95394:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'applescript',
- init: function init(Prism) {
- Prism.languages.applescript = {
- comment: [
- // Allow one level of nesting
- /\(\*(?:\(\*[\s\S]*?\*\)|[\s\S])*?\*\)/, /--.+/, /#.+/],
- string: /"(?:\\.|[^"\\\r\n])*"/,
- number: /(?:\b\d+\.?\d*|\B\.\d+)(?:e-?\d+)?\b/i,
- operator: [/[&=≠≤≥*+\-\/÷^]|[<>]=?/, /\b(?:(?:start|begin|end)s? with|(?:(?:does not|doesn't) contain|contains?)|(?:is|isn't|is not) (?:in|contained by)|(?:(?:is|isn't|is not) )?(?:greater|less) than(?: or equal)?(?: to)?|(?:(?:does not|doesn't) come|comes) (?:before|after)|(?:is|isn't|is not) equal(?: to)?|(?:(?:does not|doesn't) equal|equals|equal to|isn't|is not)|(?:a )?(?:ref(?: to)?|reference to)|(?:and|or|div|mod|as|not))\b/],
- keyword: /\b(?:about|above|after|against|apart from|around|aside from|at|back|before|beginning|behind|below|beneath|beside|between|but|by|considering|continue|copy|does|eighth|else|end|equal|error|every|exit|false|fifth|first|for|fourth|from|front|get|given|global|if|ignoring|in|instead of|into|is|it|its|last|local|me|middle|my|ninth|of|on|onto|out of|over|prop|property|put|repeat|return|returning|second|set|seventh|since|sixth|some|tell|tenth|that|the|then|third|through|thru|timeout|times|to|transaction|true|try|until|where|while|whose|with|without)\b/,
- class: {
- pattern: /\b(?:alias|application|boolean|class|constant|date|file|integer|list|number|POSIX file|real|record|reference|RGB color|script|text|centimetres|centimeters|feet|inches|kilometres|kilometers|metres|meters|miles|yards|square feet|square kilometres|square kilometers|square metres|square meters|square miles|square yards|cubic centimetres|cubic centimeters|cubic feet|cubic inches|cubic metres|cubic meters|cubic yards|gallons|litres|liters|quarts|grams|kilograms|ounces|pounds|degrees Celsius|degrees Fahrenheit|degrees Kelvin)\b/,
- alias: 'builtin'
- },
- punctuation: /[{}():,¬«»《》]/
- };
- }
-};
-
-/***/ }),
-
-/***/ 56245:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'arff',
- init: function init(Prism) {
- Prism.languages.arff = {
- comment: /%.*/,
- string: {
- pattern: /(["'])(?:\\.|(?!\1)[^\\\r\n])*\1/,
- greedy: true
- },
- keyword: /@(?:attribute|data|end|relation)\b/i,
- number: /\b\d+(?:\.\d+)?\b/,
- punctuation: /[{},]/
- };
- }
-};
-
-/***/ }),
-
-/***/ 86002:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'asciidoc',
- init: function init(Prism) {
- (function (Prism) {
- var attributes = {
- pattern: /(^[ \t]*)\[(?!\[)(?:(["'$`])(?:(?!\2)[^\\]|\\.)*\2|\[(?:[^\]\\]|\\.)*\]|[^\]\\]|\\.)*\]/m,
- lookbehind: true,
- inside: {
- quoted: {
- pattern: /([$`])(?:(?!\1)[^\\]|\\.)*\1/,
- inside: {
- punctuation: /^[$`]|[$`]$/
- }
- },
- interpreted: {
- pattern: /'(?:[^'\\]|\\.)*'/,
- inside: {
- punctuation: /^'|'$/
- // See rest below
- }
- },
- string: /"(?:[^"\\]|\\.)*"/,
- variable: /\w+(?==)/,
- punctuation: /^\[|\]$|,/,
- operator: /=/,
- // The negative look-ahead prevents blank matches
- 'attr-value': /(?!^\s+$).+/
- }
- };
- Prism.languages.asciidoc = {
- 'comment-block': {
- pattern: /^(\/{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1/m,
- alias: 'comment'
- },
- table: {
- pattern: /^\|={3,}(?:(?:\r?\n|\r).*)*?(?:\r?\n|\r)\|={3,}$/m,
- inside: {
- specifiers: {
- pattern: /(?!\|)(?:(?:(?:\d+(?:\.\d+)?|\.\d+)[+*])?(?:[<^>](?:\.[<^>])?|\.[<^>])?[a-z]*)(?=\|)/,
- alias: 'attr-value'
- },
- punctuation: {
- pattern: /(^|[^\\])[|!]=*/,
- lookbehind: true
- }
- // See rest below
- }
- },
-
- 'passthrough-block': {
- pattern: /^(\+{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m,
- inside: {
- punctuation: /^\++|\++$/
- // See rest below
- }
- },
- // Literal blocks and listing blocks
- 'literal-block': {
- pattern: /^(-{4,}|\.{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m,
- inside: {
- punctuation: /^(?:-+|\.+)|(?:-+|\.+)$/
- // See rest below
- }
- },
- // Sidebar blocks, quote blocks, example blocks and open blocks
- 'other-block': {
- pattern: /^(--|\*{4,}|_{4,}|={4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m,
- inside: {
- punctuation: /^(?:-+|\*+|_+|=+)|(?:-+|\*+|_+|=+)$/
- // See rest below
- }
- },
-
- // list-punctuation and list-label must appear before indented-block
- 'list-punctuation': {
- pattern: /(^[ \t]*)(?:-|\*{1,5}|\.{1,5}|(?:[a-z]|\d+)\.|[xvi]+\))(?= )/im,
- lookbehind: true,
- alias: 'punctuation'
- },
- 'list-label': {
- pattern: /(^[ \t]*)[a-z\d].+(?::{2,4}|;;)(?=\s)/im,
- lookbehind: true,
- alias: 'symbol'
- },
- 'indented-block': {
- pattern: /((\r?\n|\r)\2)([ \t]+)\S.*(?:(?:\r?\n|\r)\3.+)*(?=\2{2}|$)/,
- lookbehind: true
- },
-
- comment: /^\/\/.*/m,
- title: {
- pattern: /^.+(?:\r?\n|\r)(?:={3,}|-{3,}|~{3,}|\^{3,}|\+{3,})$|^={1,5} +.+|^\.(?![\s.]).*/m,
- alias: 'important',
- inside: {
- punctuation: /^(?:\.|=+)|(?:=+|-+|~+|\^+|\++)$/
- // See rest below
- }
- },
- 'attribute-entry': {
- pattern: /^:[^:\r\n]+:(?: .*?(?: \+(?:\r?\n|\r).*?)*)?$/m,
- alias: 'tag'
- },
- attributes: attributes,
- hr: {
- pattern: /^'{3,}$/m,
- alias: 'punctuation'
- },
- 'page-break': {
- pattern: /^<{3,}$/m,
- alias: 'punctuation'
- },
- admonition: {
- pattern: /^(?:TIP|NOTE|IMPORTANT|WARNING|CAUTION):/m,
- alias: 'keyword'
- },
- callout: [{
- pattern: /(^[ \t]*)\d*>/m,
- lookbehind: true,
- alias: 'symbol'
- }, {
- pattern: /<\d+>/,
- alias: 'symbol'
- }],
- macro: {
- pattern: /\b[a-z\d][a-z\d-]*::?(?:(?:\S+)??\[(?:[^\]\\"]|(["'])(?:(?!\1)[^\\]|\\.)*\1|\\.)*\])/,
- inside: {
- function: /^[a-z\d-]+(?=:)/,
- punctuation: /^::?/,
- attributes: {
- pattern: /(?:\[(?:[^\]\\"]|(["'])(?:(?!\1)[^\\]|\\.)*\1|\\.)*\])/,
- inside: attributes.inside
- }
- }
- },
- inline: {
- /*
- The initial look-behind prevents the highlighting of escaped quoted text.
- Quoted text can be multi-line but cannot span an empty line.
- All quoted text can have attributes before [foobar, 'foobar', baz="bar"].
- First, we handle the constrained quotes.
- Those must be bounded by non-word chars and cannot have spaces between the delimiter and the first char.
- They are, in order: _emphasis_, ``double quotes'', `single quotes', `monospace`, 'emphasis', *strong*, +monospace+ and #unquoted#
- Then we handle the unconstrained quotes.
- Those do not have the restrictions of the constrained quotes.
- They are, in order: __emphasis__, **strong**, ++monospace++, +++passthrough+++, ##unquoted##, $$passthrough$$, ~subscript~, ^superscript^, {attribute-reference}, [[anchor]], [[[bibliography anchor]]], <>, (((indexes))) and ((indexes))
- */
- pattern: /(^|[^\\])(?:(?:\B\[(?:[^\]\\"]|(["'])(?:(?!\2)[^\\]|\\.)*\2|\\.)*\])?(?:\b_(?!\s)(?: _|[^_\\\r\n]|\\.)+(?:(?:\r?\n|\r)(?: _|[^_\\\r\n]|\\.)+)*_\b|\B``(?!\s).+?(?:(?:\r?\n|\r).+?)*''\B|\B`(?!\s)(?: ['`]|.)+?(?:(?:\r?\n|\r)(?: ['`]|.)+?)*['`]\B|\B(['*+#])(?!\s)(?: \3|(?!\3)[^\\\r\n]|\\.)+(?:(?:\r?\n|\r)(?: \3|(?!\3)[^\\\r\n]|\\.)+)*\3\B)|(?:\[(?:[^\]\\"]|(["'])(?:(?!\4)[^\\]|\\.)*\4|\\.)*\])?(?:(__|\*\*|\+\+\+?|##|\$\$|[~^]).+?(?:(?:\r?\n|\r).+?)*\5|\{[^}\r\n]+\}|\[\[\[?.+?(?:(?:\r?\n|\r).+?)*\]?\]\]|<<.+?(?:(?:\r?\n|\r).+?)*>>|\(\(\(?.+?(?:(?:\r?\n|\r).+?)*\)?\)\)))/m,
- lookbehind: true,
- inside: {
- attributes: attributes,
- url: {
- pattern: /^(?:\[\[\[?.+?\]?\]\]|<<.+?>>)$/,
- inside: {
- punctuation: /^(?:\[\[\[?|<<)|(?:\]\]\]?|>>)$/
- }
- },
- 'attribute-ref': {
- pattern: /^\{.+\}$/,
- inside: {
- variable: {
- pattern: /(^\{)[a-z\d,+_-]+/,
- lookbehind: true
- },
- operator: /^[=?!#%@$]|!(?=[:}])/,
- punctuation: /^\{|\}$|::?/
- }
- },
- italic: {
- pattern: /^(['_])[\s\S]+\1$/,
- inside: {
- punctuation: /^(?:''?|__?)|(?:''?|__?)$/
- }
- },
- bold: {
- pattern: /^\*[\s\S]+\*$/,
- inside: {
- punctuation: /^\*\*?|\*\*?$/
- }
- },
- punctuation: /^(?:``?|\+{1,3}|##?|\$\$|[~^]|\(\(\(?)|(?:''?|\+{1,3}|##?|\$\$|[~^`]|\)?\)\))$/
- }
- },
- replacement: {
- pattern: /\((?:C|TM|R)\)/,
- alias: 'builtin'
- },
- entity: /?[\da-z]{1,8};/i,
- 'line-continuation': {
- pattern: /(^| )\+$/m,
- lookbehind: true,
- alias: 'punctuation'
- }
-
- // Allow some nesting. There is no recursion though, so cloning should not be needed.
-
- };attributes.inside.interpreted.inside.rest = {
- macro: Prism.languages.asciidoc.macro,
- inline: Prism.languages.asciidoc.inline,
- replacement: Prism.languages.asciidoc.replacement,
- entity: Prism.languages.asciidoc.entity
- };
-
- Prism.languages.asciidoc['passthrough-block'].inside.rest = {
- macro: Prism.languages.asciidoc.macro
- };
-
- Prism.languages.asciidoc['literal-block'].inside.rest = {
- callout: Prism.languages.asciidoc.callout
- };
-
- Prism.languages.asciidoc.table.inside.rest = {
- 'comment-block': Prism.languages.asciidoc['comment-block'],
- 'passthrough-block': Prism.languages.asciidoc['passthrough-block'],
- 'literal-block': Prism.languages.asciidoc['literal-block'],
- 'other-block': Prism.languages.asciidoc['other-block'],
- 'list-punctuation': Prism.languages.asciidoc['list-punctuation'],
- 'indented-block': Prism.languages.asciidoc['indented-block'],
- comment: Prism.languages.asciidoc.comment,
- title: Prism.languages.asciidoc.title,
- 'attribute-entry': Prism.languages.asciidoc['attribute-entry'],
- attributes: Prism.languages.asciidoc.attributes,
- hr: Prism.languages.asciidoc.hr,
- 'page-break': Prism.languages.asciidoc['page-break'],
- admonition: Prism.languages.asciidoc.admonition,
- 'list-label': Prism.languages.asciidoc['list-label'],
- callout: Prism.languages.asciidoc.callout,
- macro: Prism.languages.asciidoc.macro,
- inline: Prism.languages.asciidoc.inline,
- replacement: Prism.languages.asciidoc.replacement,
- entity: Prism.languages.asciidoc.entity,
- 'line-continuation': Prism.languages.asciidoc['line-continuation']
- };
-
- Prism.languages.asciidoc['other-block'].inside.rest = {
- table: Prism.languages.asciidoc.table,
- 'list-punctuation': Prism.languages.asciidoc['list-punctuation'],
- 'indented-block': Prism.languages.asciidoc['indented-block'],
- comment: Prism.languages.asciidoc.comment,
- 'attribute-entry': Prism.languages.asciidoc['attribute-entry'],
- attributes: Prism.languages.asciidoc.attributes,
- hr: Prism.languages.asciidoc.hr,
- 'page-break': Prism.languages.asciidoc['page-break'],
- admonition: Prism.languages.asciidoc.admonition,
- 'list-label': Prism.languages.asciidoc['list-label'],
- macro: Prism.languages.asciidoc.macro,
- inline: Prism.languages.asciidoc.inline,
- replacement: Prism.languages.asciidoc.replacement,
- entity: Prism.languages.asciidoc.entity,
- 'line-continuation': Prism.languages.asciidoc['line-continuation']
- };
-
- Prism.languages.asciidoc.title.inside.rest = {
- macro: Prism.languages.asciidoc.macro,
- inline: Prism.languages.asciidoc.inline,
- replacement: Prism.languages.asciidoc.replacement,
- entity: Prism.languages.asciidoc.entity
-
- // Plugin to make entity title show the real entity, idea by Roman Komarov
- };Prism.hooks.add('wrap', function (env) {
- if (env.type === 'entity') {
- env.attributes.title = env.content.replace(/&/, '&');
- }
- });
- })(Prism);
- }
-};
-
-/***/ }),
-
-/***/ 68737:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'asm6502',
- init: function init(Prism) {
- Prism.languages.asm6502 = {
- comment: /;.*/,
- directive: {
- pattern: /\.\w+(?= )/,
- alias: 'keyword'
- },
- string: /(["'`])(?:\\.|(?!\1)[^\\\r\n])*\1/,
- opcode: {
- pattern: /\b(?:adc|and|asl|bcc|bcs|beq|bit|bmi|bne|bpl|brk|bvc|bvs|clc|cld|cli|clv|cmp|cpx|cpy|dec|dex|dey|eor|inc|inx|iny|jmp|jsr|lda|ldx|ldy|lsr|nop|ora|pha|php|pla|plp|rol|ror|rti|rts|sbc|sec|sed|sei|sta|stx|sty|tax|tay|tsx|txa|txs|tya|ADC|AND|ASL|BCC|BCS|BEQ|BIT|BMI|BNE|BPL|BRK|BVC|BVS|CLC|CLD|CLI|CLV|CMP|CPX|CPY|DEC|DEX|DEY|EOR|INC|INX|INY|JMP|JSR|LDA|LDX|LDY|LSR|NOP|ORA|PHA|PHP|PLA|PLP|ROL|ROR|RTI|RTS|SBC|SEC|SED|SEI|STA|STX|STY|TAX|TAY|TSX|TXA|TXS|TYA)\b/,
- alias: 'property'
- },
- hexnumber: {
- pattern: /#?\$[\da-f]{2,4}/i,
- alias: 'string'
- },
- binarynumber: {
- pattern: /#?%[01]+/,
- alias: 'string'
- },
- decimalnumber: {
- pattern: /#?\d+/,
- alias: 'string'
- },
- register: {
- pattern: /\b[xya]\b/i,
- alias: 'variable'
- }
- };
- }
-};
-
-/***/ }),
-
-/***/ 16326:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", ({
- value: true
-}));
-exports["default"] = {
- language: 'aspnet',
- init: function init(Prism) {
- Prism.languages.aspnet = Prism.languages.extend('markup', {
- 'page-directive tag': {
- pattern: /<%\s*@.*%>/i,
- inside: {
- 'page-directive tag': /<%\s*@\s*(?:Assembly|Control|Implements|Import|Master(?:Type)?|OutputCache|Page|PreviousPageType|Reference|Register)?|%>/i,
- rest: Prism.languages.markup.tag.inside
- }
- },
- 'directive tag': {
- pattern: /<%.*%>/i,
- inside: {
- 'directive tag': /<%\s*?[$=%#:]{0,2}|%>/i,
- rest: Prism.languages.csharp
- }
- }
- });
- // Regexp copied from prism-markup, with a negative look-ahead added
- Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i;
-
- // match directives of attribute value foo="<% Bar %>"
- Prism.languages.insertBefore('inside', 'punctuation', {
- 'directive tag': Prism.languages.aspnet['directive tag']
- }, Prism.languages.aspnet.tag.inside['attr-value']);
-
- Prism.languages.insertBefore('aspnet', 'comment', {
- 'asp comment': /<%--[\s\S]*?--%>/
- });
-
- // script runat="server" contains csharp, not javascript
- Prism.languages.insertBefore('aspnet', Prism.languages.javascript ? 'script' : 'tag', {
- 'asp script': {
- pattern: /(