UNPKG

@cloudsnorkel/cdk-github-runners

Version:

CDK construct to create GitHub Actions self-hosted runners. Creates ephemeral runners on demand. Easy to deploy and highly customizable.

1,531 lines (1,515 loc) 93.7 kB
"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 __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; 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); // node_modules/universal-user-agent/index.js function getUserAgent() { if (typeof navigator === "object" && "userAgent" in navigator) { return navigator.userAgent; } if (typeof process === "object" && process.version !== void 0) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } return "<environment undetectable>"; } var init_universal_user_agent = __esm({ "node_modules/universal-user-agent/index.js"() { "use strict"; } }); // node_modules/before-after-hook/lib/register.js function register(state, name, method, options) { if (typeof method !== "function") { throw new Error("method for before hook must be a function"); } if (!options) { options = {}; } if (Array.isArray(name)) { return name.reverse().reduce((callback, name2) => { return register.bind(null, state, name2, callback, options); }, method)(); } return Promise.resolve().then(() => { if (!state.registry[name]) { return method(options); } return state.registry[name].reduce((method2, registered) => { return registered.hook.bind(null, method2, options); }, method)(); }); } var init_register = __esm({ "node_modules/before-after-hook/lib/register.js"() { "use strict"; } }); // node_modules/before-after-hook/lib/add.js function addHook(state, kind, name, hook6) { const orig = hook6; if (!state.registry[name]) { state.registry[name] = []; } if (kind === "before") { hook6 = (method, options) => { return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); }; } if (kind === "after") { hook6 = (method, options) => { let result; return Promise.resolve().then(method.bind(null, options)).then((result_) => { result = result_; return orig(result, options); }).then(() => { return result; }); }; } if (kind === "error") { hook6 = (method, options) => { return Promise.resolve().then(method.bind(null, options)).catch((error) => { return orig(error, options); }); }; } state.registry[name].push({ hook: hook6, orig }); } var init_add = __esm({ "node_modules/before-after-hook/lib/add.js"() { "use strict"; } }); // node_modules/before-after-hook/lib/remove.js function removeHook(state, name, method) { if (!state.registry[name]) { return; } const index = state.registry[name].map((registered) => { return registered.orig; }).indexOf(method); if (index === -1) { return; } state.registry[name].splice(index, 1); } var init_remove = __esm({ "node_modules/before-after-hook/lib/remove.js"() { "use strict"; } }); // node_modules/before-after-hook/index.js function bindApi(hook6, state, name) { const removeHookRef = bindable(removeHook, null).apply( null, name ? [state, name] : [state] ); hook6.api = { remove: removeHookRef }; hook6.remove = removeHookRef; ["before", "error", "after", "wrap"].forEach((kind) => { const args = name ? [state, kind, name] : [state, kind]; hook6[kind] = hook6.api[kind] = bindable(addHook, null).apply(null, args); }); } function Singular() { const singularHookName = /* @__PURE__ */ Symbol("Singular"); const singularHookState = { registry: {} }; const singularHook = register.bind(null, singularHookState, singularHookName); bindApi(singularHook, singularHookState, singularHookName); return singularHook; } function Collection() { const state = { registry: {} }; const hook6 = register.bind(null, state); bindApi(hook6, state); return hook6; } var bind, bindable, before_after_hook_default; var init_before_after_hook = __esm({ "node_modules/before-after-hook/index.js"() { "use strict"; init_register(); init_add(); init_remove(); bind = Function.bind; bindable = bind.bind(bind); before_after_hook_default = { Singular, Collection }; } }); // node_modules/@octokit/endpoint/dist-bundle/index.js function lowercaseKeys(object) { if (!object) { return {}; } return Object.keys(object).reduce((newObj, key) => { newObj[key.toLowerCase()] = object[key]; return newObj; }, {}); } function isPlainObject(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } function mergeDeep(defaults, options) { const result = Object.assign({}, defaults); Object.keys(options).forEach((key) => { if (isPlainObject(options[key])) { if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); else result[key] = mergeDeep(defaults[key], options[key]); } else { Object.assign(result, { [key]: options[key] }); } }); return result; } function removeUndefinedProperties(obj) { for (const key in obj) { if (obj[key] === void 0) { delete obj[key]; } } return obj; } 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; } 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("&"); } function removeNonChars(variableName) { return variableName.replace(/(?:^\W+)|(?:(?<!\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 omit(object, keysToOmit) { const result = { __proto__: null }; for (const key of Object.keys(object)) { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } } return result; } 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)); } result.push( encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); } 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 = ["+", "#", ".", "/", ";", "?", "&"]; template = template.replace( /\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { let operator = ""; const values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); }); if (operator && operator !== "+") { var separator = ","; if (operator === "?") { separator = "&"; } else if (operator !== "#") { separator = operator; } return (values.length !== 0 ? operator : "") + values.join(separator); } else { return values.join(","); } } else { return encodeReserved(literal); } } ); if (template === "/") { return template; } else { return template.replace(/\/$/, ""); } } 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-])[\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 (!headers["content-type"] && typeof body !== "undefined") { headers["content-type"] = "application/json; charset=utf-8"; } if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { body = ""; } return Object.assign( { method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null ); } function endpointWithDefaults(defaults, route, options) { return parse(merge(defaults, route, options)); } 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 }); } var VERSION, userAgent, DEFAULTS, urlVariableRegex, endpoint; var init_dist_bundle = __esm({ "node_modules/@octokit/endpoint/dist-bundle/index.js"() { "use strict"; init_universal_user_agent(); VERSION = "0.0.0-development"; userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; DEFAULTS = { method: "GET", baseUrl: "https://api.github.com", headers: { accept: "application/vnd.github.v3+json", "user-agent": userAgent }, mediaType: { format: "" } }; urlVariableRegex = /\{[^{}}]+\}/g; endpoint = withDefaults(null, DEFAULTS); } }); // node_modules/fast-content-type-parse/index.js var require_fast_content_type_parse = __commonJS({ "node_modules/fast-content-type-parse/index.js"(exports2, module2) { "use strict"; var NullObject = function NullObject2() { }; NullObject.prototype = /* @__PURE__ */ Object.create(null); var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu; var quotedPairRE = /\\([\v\u0020-\u00ff])/gu; var mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u; var defaultContentType = { type: "", parameters: new NullObject() }; Object.freeze(defaultContentType.parameters); Object.freeze(defaultContentType); function parse2(header) { if (typeof header !== "string") { throw new TypeError("argument header is required and must be a string"); } let index = header.indexOf(";"); const type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (mediaTypeRE.test(type) === false) { throw new TypeError("invalid media type"); } const result = { type: type.toLowerCase(), parameters: new NullObject() }; if (index === -1) { return result; } let key; let match; let value; paramRE.lastIndex = index; while (match = paramRE.exec(header)) { if (match.index !== index) { throw new TypeError("invalid parameter format"); } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value[0] === '"') { value = value.slice(1, value.length - 1); quotedPairRE.test(value) && (value = value.replace(quotedPairRE, "$1")); } result.parameters[key] = value; } if (index !== header.length) { throw new TypeError("invalid parameter format"); } return result; } function safeParse2(header) { if (typeof header !== "string") { return defaultContentType; } let index = header.indexOf(";"); const type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (mediaTypeRE.test(type) === false) { return defaultContentType; } const result = { type: type.toLowerCase(), parameters: new NullObject() }; if (index === -1) { return result; } let key; let match; let value; paramRE.lastIndex = index; while (match = paramRE.exec(header)) { if (match.index !== index) { return defaultContentType; } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value[0] === '"') { value = value.slice(1, value.length - 1); quotedPairRE.test(value) && (value = value.replace(quotedPairRE, "$1")); } result.parameters[key] = value; } if (index !== header.length) { return defaultContentType; } return result; } module2.exports.default = { parse: parse2, safeParse: safeParse2 }; module2.exports.parse = parse2; module2.exports.safeParse = safeParse2; module2.exports.defaultContentType = defaultContentType; } }); // node_modules/@octokit/request-error/dist-src/index.js var RequestError; var init_dist_src = __esm({ "node_modules/@octokit/request-error/dist-src/index.js"() { "use strict"; RequestError = class extends Error { name; /** * http status code */ status; /** * Request options that lead to the error. */ request; /** * Response object if a response was received */ response; constructor(message, statusCode, options) { super(message, { cause: options.cause }); this.name = "HttpError"; this.status = Number.parseInt(statusCode); if (Number.isNaN(this.status)) { this.status = 0; } if ("response" in options) { this.response = options.response; } 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; } }; } }); // node_modules/@octokit/request/dist-bundle/index.js function isPlainObject2(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } async function fetchWrapper(requestOptions) { const fetch = requestOptions.request?.fetch || globalThis.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" ); } const log = requestOptions.request?.log || console; const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; const body = isPlainObject2(requestOptions.body) || Array.isArray(requestOptions.body) ? JSON.stringify(requestOptions.body) : requestOptions.body; const requestHeaders = Object.fromEntries( Object.entries(requestOptions.headers).map(([name, value]) => [ name, String(value) ]) ); let fetchResponse; try { fetchResponse = await fetch(requestOptions.url, { method: requestOptions.method, body, redirect: requestOptions.request?.redirect, headers: requestHeaders, signal: requestOptions.request?.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" } }); } catch (error) { let message = "Unknown Error"; if (error instanceof Error) { if (error.name === "AbortError") { error.status = 500; throw error; } 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; } } } const requestError = new RequestError(message, 500, { request: requestOptions }); requestError.cause = error; throw requestError; } const status = fetchResponse.status; const url = fetchResponse.url; const responseHeaders = {}; for (const [key, value] of fetchResponse.headers) { responseHeaders[key] = value; } const octokitResponse = { url, status, headers: responseHeaders, data: "" }; if ("deprecation" in responseHeaders) { const matches = responseHeaders.link && responseHeaders.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 ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` ); } if (status === 204 || status === 205) { return octokitResponse; } if (requestOptions.method === "HEAD") { if (status < 400) { return octokitResponse; } throw new RequestError(fetchResponse.statusText, status, { response: octokitResponse, request: requestOptions }); } if (status === 304) { octokitResponse.data = await getResponseData(fetchResponse); throw new RequestError("Not modified", status, { response: octokitResponse, request: requestOptions }); } if (status >= 400) { octokitResponse.data = await getResponseData(fetchResponse); throw new RequestError(toErrorMessage(octokitResponse.data), status, { response: octokitResponse, request: requestOptions }); } octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; return octokitResponse; } async function getResponseData(response) { const contentType = response.headers.get("content-type"); if (!contentType) { return response.text().catch(noop); } const mimetype = (0, import_fast_content_type_parse.safeParse)(contentType); if (isJSONResponse(mimetype)) { let text = ""; try { text = await response.text(); return JSON.parse(text); } catch (err) { return text; } } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { return response.text().catch(noop); } else { return response.arrayBuffer().catch( /* v8 ignore next -- @preserve */ () => new ArrayBuffer(0) ); } } function isJSONResponse(mimetype) { return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; } function toErrorMessage(data) { if (typeof data === "string") { return data; } if (data instanceof ArrayBuffer) { return "Unknown error"; } if ("message" in data) { const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`; } return `Unknown error: ${JSON.stringify(data)}`; } function withDefaults2(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: withDefaults2.bind(null, endpoint2) }); return endpointOptions.request.hook(request2, endpointOptions); }; return Object.assign(newApi, { endpoint: endpoint2, defaults: withDefaults2.bind(null, endpoint2) }); } var import_fast_content_type_parse, VERSION2, defaults_default, noop, request; var init_dist_bundle2 = __esm({ "node_modules/@octokit/request/dist-bundle/index.js"() { "use strict"; init_dist_bundle(); init_universal_user_agent(); import_fast_content_type_parse = __toESM(require_fast_content_type_parse(), 1); init_dist_src(); VERSION2 = "10.0.7"; defaults_default = { headers: { "user-agent": `octokit-request.js/${VERSION2} ${getUserAgent()}` } }; noop = () => ""; request = withDefaults2(endpoint, defaults_default); } }); // node_modules/@octokit/graphql/dist-bundle/index.js function _buildMessageForResponseErrors(data) { return `Request failed due to following response errors: ` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } 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; }); } function withDefaults3(request2, newDefaults) { const newRequest = request2.defaults(newDefaults); const newApi = (query, options) => { return graphql(newRequest, query, options); }; return Object.assign(newApi, { defaults: withDefaults3.bind(null, newRequest), endpoint: newRequest.endpoint }); } function withCustomRequest(customRequest) { return withDefaults3(customRequest, { method: "POST", url: "/graphql" }); } var VERSION3, GraphqlResponseError, NON_VARIABLE_OPTIONS, FORBIDDEN_VARIABLE_OPTIONS, GHES_V3_SUFFIX_REGEX, graphql2; var init_dist_bundle3 = __esm({ "node_modules/@octokit/graphql/dist-bundle/index.js"() { "use strict"; init_dist_bundle2(); init_universal_user_agent(); VERSION3 = "0.0.0-development"; GraphqlResponseError = class extends Error { constructor(request2, headers, response) { super(_buildMessageForResponseErrors(response)); this.request = request2; this.headers = headers; this.response = response; this.errors = response.errors; this.data = response.data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } name = "GraphqlResponseError"; errors; data; }; NON_VARIABLE_OPTIONS = [ "method", "baseUrl", "url", "headers", "request", "query", "mediaType", "operationName" ]; FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; graphql2 = withDefaults3(request, { headers: { "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` }, method: "POST", url: "/graphql" }); } }); // node_modules/@octokit/auth-token/dist-bundle/index.js async function auth(token) { const isApp = isJWT(token); const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); const isUserToServer = token.startsWith("ghu_"); const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; return { type: "token", token, tokenType }; } function withAuthorizationPrefix(token) { if (token.split(/\./).length === 3) { return `bearer ${token}`; } return `token ${token}`; } async function hook(token, request2, route, parameters) { const endpoint2 = request2.endpoint.merge( route, parameters ); endpoint2.headers.authorization = withAuthorizationPrefix(token); return request2(endpoint2); } var b64url, sep, jwtRE, isJWT, createTokenAuth; var init_dist_bundle4 = __esm({ "node_modules/@octokit/auth-token/dist-bundle/index.js"() { "use strict"; b64url = "(?:[a-zA-Z0-9_-]+)"; sep = "\\."; jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); isJWT = jwtRE.test.bind(jwtRE); 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) }); }; } }); // node_modules/@octokit/core/dist-src/version.js var VERSION4; var init_version = __esm({ "node_modules/@octokit/core/dist-src/version.js"() { "use strict"; VERSION4 = "7.0.6"; } }); // node_modules/@octokit/core/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { Octokit: () => Octokit }); function createLogger(logger = {}) { if (typeof logger.debug !== "function") { logger.debug = noop2; } if (typeof logger.info !== "function") { logger.info = noop2; } if (typeof logger.warn !== "function") { logger.warn = consoleWarn; } if (typeof logger.error !== "function") { logger.error = consoleError; } return logger; } var noop2, consoleWarn, consoleError, userAgentTrail, Octokit; var init_dist_src2 = __esm({ "node_modules/@octokit/core/dist-src/index.js"() { "use strict"; init_universal_user_agent(); init_before_after_hook(); init_dist_bundle2(); init_dist_bundle3(); init_dist_bundle4(); init_version(); noop2 = () => { }; consoleWarn = console.warn.bind(console); consoleError = console.error.bind(console); userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; Octokit = class { static VERSION = VERSION4; 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 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 plugins = currentPlugins.concat( newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) ); }; return NewOctokit; } constructor(options = {}) { const hook6 = new before_after_hook_default.Collection(); const requestDefaults = { baseUrl: request.endpoint.DEFAULTS.baseUrl, headers: {}, request: Object.assign({}, options.request, { // @ts-ignore internal usage only, no need to type hook: hook6.bind(null, "request") }), mediaType: { previews: [], format: "" } }; requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; 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 = request.defaults(requestDefaults); this.graphql = withCustomRequest(this.request).defaults(requestDefaults); this.log = createLogger(options.log); this.hook = hook6; if (!options.authStrategy) { if (!options.auth) { this.auth = async () => ({ type: "unauthenticated" }); } else { const auth6 = createTokenAuth(options.auth); hook6.wrap("request", auth6.hook); this.auth = auth6; } } else { const { authStrategy, ...otherOptions } = options; const auth6 = 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 ) ); hook6.wrap("request", auth6.hook); this.auth = auth6; } const classConstructor = this.constructor; for (let i = 0; i < classConstructor.plugins.length; ++i) { Object.assign(this, classConstructor.plugins[i](this, options)); } } // assigned during constructor request; graphql; log; hook; // TODO: type `octokit.auth` based on passed options.authStrategy auth; }; } }); // node_modules/@octokit/oauth-methods/dist-bundle/index.js function requestToOAuthBaseUrl(request2) { const endpointDefaults = request2.endpoint.DEFAULTS; return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); } async function oauthRequest(request2, route, parameters) { const withOAuthParameters = { baseUrl: requestToOAuthBaseUrl(request2), headers: { accept: "application/json" }, ...parameters }; const response = await request2(route, withOAuthParameters); if ("error" in response.data) { const error = new RequestError( `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { request: request2.endpoint.merge( route, withOAuthParameters ) } ); error.response = response; throw error; } return response; } async function exchangeWebFlowCode(options) { const request2 = options.request || request; const response = await oauthRequest( request2, "POST /login/oauth/access_token", { client_id: options.clientId, client_secret: options.clientSecret, code: options.code, redirect_uri: options.redirectUrl } ); const authentication = { clientType: options.clientType, clientId: options.clientId, clientSecret: options.clientSecret, token: response.data.access_token, scopes: response.data.scope.split(/\s+/).filter(Boolean) }; if (options.clientType === "github-app") { if ("refresh_token" in response.data) { const apiTimeInMs = new Date(response.headers.date).getTime(); authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp( apiTimeInMs, response.data.expires_in ), authentication.refreshTokenExpiresAt = toTimestamp( apiTimeInMs, response.data.refresh_token_expires_in ); } delete authentication.scopes; } return { ...response, authentication }; } function toTimestamp(apiTimeInMs, expirationInSeconds) { return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } async function createDeviceCode(options) { const request2 = options.request || request; const parameters = { client_id: options.clientId }; if ("scopes" in options && Array.isArray(options.scopes)) { parameters.scope = options.scopes.join(" "); } return oauthRequest(request2, "POST /login/device/code", parameters); } async function exchangeDeviceCode(options) { const request2 = options.request || request; const response = await oauthRequest( request2, "POST /login/oauth/access_token", { client_id: options.clientId, device_code: options.code, grant_type: "urn:ietf:params:oauth:grant-type:device_code" } ); const authentication = { clientType: options.clientType, clientId: options.clientId, token: response.data.access_token, scopes: response.data.scope.split(/\s+/).filter(Boolean) }; if ("clientSecret" in options) { authentication.clientSecret = options.clientSecret; } if (options.clientType === "github-app") { if ("refresh_token" in response.data) { const apiTimeInMs = new Date(response.headers.date).getTime(); authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp2( apiTimeInMs, response.data.expires_in ), authentication.refreshTokenExpiresAt = toTimestamp2( apiTimeInMs, response.data.refresh_token_expires_in ); } delete authentication.scopes; } return { ...response, authentication }; } function toTimestamp2(apiTimeInMs, expirationInSeconds) { return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } async function checkToken(options) { const request2 = options.request || request; const response = await request2("POST /applications/{client_id}/token", { headers: { authorization: `basic ${btoa( `${options.clientId}:${options.clientSecret}` )}` }, client_id: options.clientId, access_token: options.token }); const authentication = { clientType: options.clientType, clientId: options.clientId, clientSecret: options.clientSecret, token: options.token, scopes: response.data.scopes }; if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; if (options.clientType === "github-app") { delete authentication.scopes; } return { ...response, authentication }; } async function refreshToken(options) { const request2 = options.request || request; const response = await oauthRequest( request2, "POST /login/oauth/access_token", { client_id: options.clientId, client_secret: options.clientSecret, grant_type: "refresh_token", refresh_token: options.refreshToken } ); const apiTimeInMs = new Date(response.headers.date).getTime(); const authentication = { clientType: "github-app", clientId: options.clientId, clientSecret: options.clientSecret, token: response.data.access_token, refreshToken: response.data.refresh_token, expiresAt: toTimestamp3(apiTimeInMs, response.data.expires_in), refreshTokenExpiresAt: toTimestamp3( apiTimeInMs, response.data.refresh_token_expires_in ) }; return { ...response, authentication }; } function toTimestamp3(apiTimeInMs, expirationInSeconds) { return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } async function resetToken(options) { const request2 = options.request || request; const auth6 = btoa(`${options.clientId}:${options.clientSecret}`); const response = await request2( "PATCH /applications/{client_id}/token", { headers: { authorization: `basic ${auth6}` }, client_id: options.clientId, access_token: options.token } ); const authentication = { clientType: options.clientType, clientId: options.clientId, clientSecret: options.clientSecret, token: response.data.token, scopes: response.data.scopes }; if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; if (options.clientType === "github-app") { delete authentication.scopes; } return { ...response, authentication }; } async function deleteToken(options) { const request2 = options.request || request; const auth6 = btoa(`${options.clientId}:${options.clientSecret}`); return request2( "DELETE /applications/{client_id}/token", { headers: { authorization: `basic ${auth6}` }, client_id: options.clientId, access_token: options.token } ); } async function deleteAuthorization(options) { const request2 = options.request || request; const auth6 = btoa(`${options.clientId}:${options.clientSecret}`); return request2( "DELETE /applications/{client_id}/grant", { headers: { authorization: `basic ${auth6}` }, client_id: options.clientId, access_token: options.token } ); } var init_dist_bundle5 = __esm({ "node_modules/@octokit/oauth-methods/dist-bundle/index.js"() { "use strict"; init_dist_src(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); init_dist_bundle2(); } }); // node_modules/@octokit/auth-oauth-device/dist-bundle/index.js async function getOAuthAccessToken(state, options) { const cachedAuthentication = getCachedAuthentication(state, options.auth); if (cachedAuthentication) return cachedAuthentication; const { data: verification } = await createDeviceCode({ clientType: state.clientType, clientId: state.clientId, request: options.request || state.request, // @ts-expect-error the extra code to make TS happy is not worth it scopes: options.auth.scopes || state.scopes }); await state.onVerification(verification); const authentication = await waitForAccessToken( options.request || state.request, state.clientId, state.clientType, verification ); state.authentication = authentication; return authentication; } function getCachedAuthentication(state, auth22) { if (auth22.refresh === true) return false; if (!state.authentication) return false; if (state.clientType === "github-app") { return state.authentication; } const authentication = state.authentication; const newScope = ("scopes" in auth22 && auth22.scopes || state.scopes).join( " " ); const currentScope = authentication.scopes.join(" "); return newScope === currentScope ? authentication : false; } async function wait(seconds) { await new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); } async function waitForAccessToken(request2, clientId, clientType, verification) { try { const options = { clientId, request: request2, code: verification.device_code }; const { authentication } = clientType === "oauth-app" ? await exchangeDeviceCode({ ...options, clientType: "oauth-app" }) : await exchangeDeviceCode({ ...options, clientType: "github-app" }); return { type: "token", tokenType: "oauth", ...authentication }; } catch (error) { if (!error.response) throw error; const errorType = error.response.data.error; if (errorType === "authorization_pending") { await wait(verification.interval); return waitForAccessToken(request2, clientId, clientType, verification); } if (errorType === "slow_down") { await wait(verification.interval + 7); return waitForAccessToken(request2, clientId, clientType, verification); } throw error; } } async function auth2(state, authOptions) { return getOAuthAccessToken(state, { auth: authOptions }); } async function hook2(state, request2, route, parameters) { let endpoint2 = request2.endpoint.merge( route, parameters ); if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint2.url)) { return request2(endpoint2); } const { token } = await getOAuthAccessToken(state, { request: request2, auth: { type: "oauth" } }); endpoint2.headers.authorization = `token ${token}`; return request2(endpoint2); } function createOAuthDeviceAuth(options) { const requestWithDefaults = options.request || request.defaults({ headers: { "user-agent": `octokit-auth-oauth-device.js/${VERSION5} ${getUserAgent()}` } }); const { request: request2 = requestWithDefaults, ...otherOptions } = options; const state = options.clientType === "github-app" ? { ...otherOptions, clientType: "github-app", request: request2 } : { ...otherOptions, clientType: "oauth-app", request: request2, scopes: options.scopes || [] }; if (!options.clientId) { throw new Error( '[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)' ); } if (!options.onVerification) { throw new Error( '[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)' ); } return Object.assign(auth2.bind(null, state), { hook: hook2.bind(null, state) }); } var VERSION5; var init_dist_bundle6 = __esm({ "node_modules/@octokit/auth-oauth-device/dist-bundle/index.js"() { "use strict"; init_universal_user_agent(); init_dist_bundle2(); init_dist_bundle5(); VERSION5 = "0.0.0-development"; } }); // node_modules/@octokit/auth-oauth-user/dist-bundle/index.js async function getAuthentication(state) { if ("code" in state.strategyOptions) { const { authentication } = await exchangeWebFlowCod