From 6e9652ef0e71eb40edf72ea238ffce01bc27298f Mon Sep 17 00:00:00 2001 From: Sora Morimoto Date: Sat, 4 Nov 2023 22:26:14 +0900 Subject: [PATCH] Use `core.group` instead for more strict grouping Signed-off-by: Sora Morimoto --- dist/index.js | 725 ++++++++++++++------------ dist/post/index.js | 665 ++++++++++++----------- lint-doc/dist/index.js | 160 +++--- lint-fmt/dist/index.js | 148 +++--- lint-opam/dist/index.js | 166 +++--- packages/lint-doc/src/opam.ts | 18 +- packages/lint-fmt/src/opam.ts | 6 +- packages/lint-opam/src/opam.ts | 24 +- packages/setup-ocaml/src/cache.ts | 100 ++-- packages/setup-ocaml/src/depext.ts | 41 +- packages/setup-ocaml/src/dune.ts | 49 +- packages/setup-ocaml/src/installer.ts | 24 +- packages/setup-ocaml/src/opam.ts | 194 +++---- 13 files changed, 1280 insertions(+), 1040 deletions(-) diff --git a/dist/index.js b/dist/index.js index 2e0090af..bb9ffc76 100644 --- a/dist/index.js +++ b/dist/index.js @@ -19171,12 +19171,11 @@ exports.setSpanContext = setSpanContext; "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - var abortController = __nccwpck_require__(86455); var crypto = __nccwpck_require__(6113); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Creates an abortable promise. * @param buildPromise - A function that takes the resolve and reject functions as parameters. @@ -19217,6 +19216,7 @@ function createAbortablePromise(buildPromise, options) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. const StandardAbortMessage = "The delay was aborted."; /** * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. @@ -19237,6 +19237,7 @@ function delay(timeInMs, options) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * promise.race() wrapper that aborts rest of promises as soon as the first promise settles. */ @@ -19292,6 +19293,7 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Typeguard for an error object shape (has name and message) * @param e - Something caught by a catch clause. @@ -19332,6 +19334,7 @@ function getErrorMessage(e) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Generates a SHA-256 HMAC signature. * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. @@ -19456,16 +19459,20 @@ const isWebWorker = typeof self === "object" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); -/** - * A constant that indicates whether the environment the code is running is Node.JS. - */ -const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node); /** * A constant that indicates whether the environment the code is running is Deno. */ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && + Boolean(process.version) && + Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node) && + // Deno thought it was a good idea to spoof process.versions.node, see https://deno.land/std@0.177.0/node/process.ts?s=versions + !isDeno; /** * A constant that indicates whether the environment the code is running is Bun.sh. */ @@ -19485,14 +19492,7 @@ const isReactNative = typeof navigator !== "undefined" && (navigator === null || * @returns a string of the encoded string */ function uint8ArrayToString(bytes, format) { - switch (format) { - case "utf-8": - return uint8ArrayToUtf8String(bytes); - case "base64": - return uint8ArrayToBase64(bytes); - case "base64url": - return uint8ArrayToBase64Url(bytes); - } + return Buffer.from(bytes).toString(format); } /** * The helper that transforms string to specific character encoded bytes array. @@ -19501,56 +19501,7 @@ function uint8ArrayToString(bytes, format) { * @returns a uint8array */ function stringToUint8Array(value, format) { - switch (format) { - case "utf-8": - return utf8StringToUint8Array(value); - case "base64": - return base64ToUint8Array(value); - case "base64url": - return base64UrlToUint8Array(value); - } -} -/** - * Decodes a Uint8Array into a Base64 string. - * @internal - */ -function uint8ArrayToBase64(bytes) { - return Buffer.from(bytes).toString("base64"); -} -/** - * Decodes a Uint8Array into a Base64Url string. - * @internal - */ -function uint8ArrayToBase64Url(bytes) { - return Buffer.from(bytes).toString("base64url"); -} -/** - * Decodes a Uint8Array into a javascript string. - * @internal - */ -function uint8ArrayToUtf8String(bytes) { - return Buffer.from(bytes).toString("utf-8"); -} -/** - * Encodes a JavaScript string into a Uint8Array. - * @internal - */ -function utf8StringToUint8Array(value) { - return Buffer.from(value); -} -/** - * Encodes a Base64 string into a Uint8Array. - * @internal - */ -function base64ToUint8Array(value) { - return Buffer.from(value, "base64"); -} -/** - * Encodes a Base64Url string into a Uint8Array. - * @internal - */ -function base64UrlToUint8Array(value) { - return Buffer.from(value, "base64url"); + return Buffer.from(value, format); } exports.cancelablePromiseRace = cancelablePromiseRace; @@ -46635,7 +46586,7 @@ module.exports = __toCommonJS(dist_src_exports); var import_universal_user_agent = __nccwpck_require__(65212); // pkg/dist-src/version.js -var VERSION = "9.0.1"; +var VERSION = "9.0.2"; // pkg/dist-src/defaults.js var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; @@ -46843,7 +46794,7 @@ function parseUrl(template) { } function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace( + template = template.replace( /\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { @@ -46873,6 +46824,11 @@ function expand(template, context) { } } ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } } // pkg/dist-src/parse.js @@ -47157,7 +47113,7 @@ __export(dist_src_exports, { module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js -var VERSION = "9.0.0"; +var VERSION = "9.1.2"; // pkg/dist-src/normalize-paginated-list-response.js function normalizePaginatedListResponse(response) { @@ -47326,9 +47282,11 @@ var paginatingEndpoints = [ "GET /orgs/{org}/personal-access-tokens", "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/security-advisories", "GET /orgs/{org}/teams", @@ -47420,6 +47378,7 @@ var paginatingEndpoints = [ "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", "GET /repos/{owner}/{repo}/rules/branches/{branch}", "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", "GET /repos/{owner}/{repo}/security-advisories", @@ -47551,7 +47510,7 @@ __export(dist_src_exports, { module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js -var VERSION = "10.0.1"; +var VERSION = "10.1.2"; // pkg/dist-src/generated/endpoints.js var Endpoints = { @@ -47656,6 +47615,9 @@ var Endpoints = { enableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], generateRunnerJitconfigForOrg: [ "POST /orgs/{org}/actions/runners/generate-jitconfig" ], @@ -48065,6 +48027,9 @@ var Endpoints = { addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], codespaceMachinesForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/machines" ], @@ -48182,7 +48147,7 @@ var Endpoints = { "DELETE /orgs/{org}/copilot/billing/selected_users" ], getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatAssignmentDetailsForUser: [ + getCopilotSeatDetailsForUser: [ "GET /orgs/{org}/members/{username}/copilot" ], listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] @@ -48395,7 +48360,13 @@ var Endpoints = { root: ["GET /"] }, migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], deleteArchiveForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/archive" ], @@ -48408,9 +48379,27 @@ var Endpoints = { 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"], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], listForAuthenticatedUser: ["GET /user/migrations"], @@ -48424,18 +48413,42 @@ var Endpoints = { {}, { renamed: ["migrations", "listReposForAuthenticatedUser"] } ], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-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"] + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] }, orgs: { addSecurityManagerTeam: [ @@ -48450,6 +48463,13 @@ var Endpoints = { "PUT /orgs/{org}/outside_collaborators/{username}" ], createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], createWebhook: ["POST /orgs/{org}/hooks"], delete: ["DELETE /orgs/{org}"], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], @@ -48457,6 +48477,10 @@ var Endpoints = { "POST /orgs/{org}/{security_product}/{enablement}" ], get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], @@ -48467,6 +48491,7 @@ var Endpoints = { list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], @@ -48491,6 +48516,9 @@ var Endpoints = { redeliverWebhookDelivery: [ "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], removeOutsideCollaborator: [ @@ -48971,6 +48999,7 @@ var Endpoints = { getCustomDeploymentProtectionRule: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], getDeploymentBranchPolicy: [ @@ -48984,6 +49013,8 @@ var Endpoints = { ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], @@ -48999,6 +49030,10 @@ var Endpoints = { 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}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], getStatusChecksProtection: [ @@ -94683,6 +94718,14 @@ class Request { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } } onConnect (abort) { @@ -95736,6 +95779,8 @@ let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { @@ -95759,7 +95804,7 @@ function extractBody (object, keepalive = false) { stream = new ReadableStream({ async pull (controller) { controller.enqueue( - typeof source === 'string' ? new TextEncoder().encode(source) : source + typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, @@ -95829,7 +95874,6 @@ function extractBody (object, keepalive = false) { // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. - const enc = new TextEncoder() const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 @@ -95837,13 +95881,13 @@ function extractBody (object, keepalive = false) { for (const [name, value] of object) { if (typeof value === 'string') { - const chunk = enc.encode(prefix + + const chunk = textEncoder.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))}"` + + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' @@ -95857,7 +95901,7 @@ function extractBody (object, keepalive = false) { } } - const chunk = enc.encode(`--${boundary}--`) + const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { @@ -96153,14 +96197,16 @@ function bodyMixinMethods (instance) { 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 }) + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = 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 += streamingDecoder.decode(chunk, { stream: true }) } - text += textDecoder.decode() + text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. @@ -96275,7 +96321,7 @@ function utf8DecodeBytes (buffer) { // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". - const output = new TextDecoder().decode(buffer) + const output = textDecoder.decode(buffer) // 4. Return output. return output @@ -96323,10 +96369,12 @@ module.exports = { const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(71267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ @@ -96338,6 +96386,8 @@ const badPorts = [ '10080' ] +const badPortsSet = new Set(badPorts) + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', @@ -96350,10 +96400,12 @@ const referrerPolicy = [ 'strict-origin-when-cross-origin', 'unsafe-url' ] +const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] @@ -96388,6 +96440,7 @@ const requestDuplex = [ // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', @@ -96403,6 +96456,7 @@ const subresource = [ 'xslt', '' ] +const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { @@ -96452,7 +96506,14 @@ module.exports = { nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } @@ -97108,6 +97169,7 @@ const { isBlobLike } = __nccwpck_require__(3640) const { webidl } = __nccwpck_require__(35989) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(68093) const { kEnumerableProperty } = __nccwpck_require__(5499) +const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { @@ -97381,7 +97443,7 @@ function processBlobParts (parts, options) { } // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(new TextEncoder().encode(s)) + bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) @@ -98379,11 +98441,11 @@ const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(88246) const assert = __nccwpck_require__(39491) const { safelyExtractBody } = __nccwpck_require__(92256) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException } = __nccwpck_require__(69602) const { kHeadersList } = __nccwpck_require__(65574) @@ -98395,6 +98457,7 @@ const { TransformStream } = __nccwpck_require__(35356) const { getGlobalDispatcher } = __nccwpck_require__(45377) const { webidl } = __nccwpck_require__(35989) const { STATUS_CODES } = __nccwpck_require__(13685) +const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -98454,7 +98517,7 @@ class Fetch extends EE { } // https://fetch.spec.whatwg.org/#fetch-method -async function fetch (input, init = {}) { +function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. @@ -98537,7 +98600,7 @@ async function fetch (input, init = {}) { const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { - return + return Promise.resolve() } // 2. If response’s aborted flag is set, then: @@ -98550,7 +98613,7 @@ async function fetch (input, init = {}) { // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) - return + return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError @@ -98559,7 +98622,7 @@ async function fetch (input, init = {}) { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) - return + return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, @@ -98842,7 +98905,7 @@ function fetching ({ } // 15. If request is a subresource request, then: - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { // TODO } @@ -99109,13 +99172,13 @@ async function mainFetch (fetchParams, recursive = false) { // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams -async function schemeFetch (fetchParams) { +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) + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. @@ -99131,7 +99194,7 @@ async function schemeFetch (fetchParams) { // and body is the empty byte sequence as a body. // Otherwise, return a network error. - return makeNetworkError('about scheme is not supported') + return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { @@ -99144,7 +99207,7 @@ async function schemeFetch (fetchParams) { // 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.') + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) @@ -99152,7 +99215,7 @@ async function schemeFetch (fetchParams) { // 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') + return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. @@ -99179,7 +99242,7 @@ async function schemeFetch (fetchParams) { response.body = body - return response + return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the @@ -99190,7 +99253,7 @@ async function schemeFetch (fetchParams) { // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { - return makeNetworkError('failed to fetch the data URL') + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. @@ -99199,28 +99262,28 @@ async function schemeFetch (fetchParams) { // 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({ + return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }) + })) } 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...') + return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) + return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { - return makeNetworkError('unknown scheme') + return Promise.resolve(makeNetworkError('unknown scheme')) } } } @@ -99239,7 +99302,7 @@ function finalizeResponse (fetchParams, response) { } // https://fetch.spec.whatwg.org/#fetch-finale -async function fetchFinale (fetchParams, response) { +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] ». @@ -99323,8 +99386,9 @@ async function fetchFinale (fetchParams, response) { } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. - await fullyReadBody(response.body, processBody, processBodyError) + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() } } @@ -99395,7 +99459,7 @@ async function httpFetch (fetchParams) { } // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(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. @@ -99432,7 +99496,7 @@ async function httpFetch (fetchParams) { } // https://fetch.spec.whatwg.org/#http-redirect-fetch -async function httpRedirectFetch (fetchParams, response) { +function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request @@ -99458,18 +99522,18 @@ async function httpRedirectFetch (fetchParams, response) { } } catch (err) { // 5. If locationURL is failure, then return a network error. - return makeNetworkError(err) + return Promise.resolve(makeNetworkError(err)) } // 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') + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { - return makeNetworkError('redirect count exceeded') + return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. @@ -99483,7 +99547,7 @@ async function httpRedirectFetch (fetchParams, response) { (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { - return makeNetworkError('cross origin not allowed for request mode "cors"') + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes @@ -99492,9 +99556,9 @@ async function httpRedirectFetch (fetchParams, response) { request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ) + )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, @@ -99504,7 +99568,7 @@ async function httpRedirectFetch (fetchParams, response) { request.body != null && request.body.source == null ) { - return makeNetworkError() + return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true @@ -99513,7 +99577,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEAD'].includes(request.method)) + !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. @@ -99797,7 +99861,7 @@ async function httpNetworkOrCacheFetch ( // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( - !safeMethods.includes(httpRequest.method) && + !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { @@ -100357,7 +100421,7 @@ async function httpNetworkFetch ( const willFollow = request.redirect === 'follow' && location && - redirectStatus.includes(status) + redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { @@ -100497,8 +100561,8 @@ const { makePolicyContainer } = __nccwpck_require__(3640) const { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -100803,7 +100867,7 @@ class Request { throw TypeError(`'${init.method}' is not a valid HTTP method.`) } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + if (forbiddenMethodsSet.has(method.toUpperCase())) { throw TypeError(`'${init.method}' HTTP method is unsupported.`) } @@ -100888,7 +100952,7 @@ class Request { 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)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) @@ -101450,7 +101514,7 @@ const { isomorphicEncode } = __nccwpck_require__(3640) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(69602) @@ -101464,6 +101528,7 @@ const assert = __nccwpck_require__(39491) const { types } = __nccwpck_require__(73837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { @@ -101493,7 +101558,7 @@ class Response { } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = new TextEncoder('utf-8').encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) @@ -101538,7 +101603,7 @@ class Response { } // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } @@ -102036,7 +102101,7 @@ module.exports = { "use strict"; -const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(69602) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(69602) const { getGlobalOrigin } = __nccwpck_require__(13913) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(5499) @@ -102065,7 +102130,7 @@ function responseURL (response) { // 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)) { + if (!redirectStatusSet.has(response.status)) { return null } @@ -102100,7 +102165,7 @@ function requestBadPort (request) { // 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)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } @@ -102242,7 +102307,7 @@ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 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)) { + if (referrerPolicyTokens.has(token)) { policy = token break } @@ -120457,7 +120522,7 @@ class Directives { onError('Verbatim tags must end with a >'); return verbatim; } - const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/); + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); if (!suffix) onError(`The ${source} tag has no suffix`); const prefix = this.tags[handle]; @@ -144368,12 +144433,12 @@ async function initializeOpamUnix() { ]); } async function setupOpamUnix() { - lib_core.startGroup("Install opam"); - await acquireOpamUnix(); - lib_core.endGroup(); - lib_core.startGroup("Initialise the opam state"); - await initializeOpamUnix(); - lib_core.endGroup(); + await lib_core.group("Install opam", async () => { + await acquireOpamUnix(); + }); + await lib_core.group("Initialise the opam state", async () => { + await initializeOpamUnix(); + }); } async function setupCygwin() { const version = await getCygwinVersion(); @@ -144451,25 +144516,25 @@ async function initializeOpamWindows() { await external_node_fs_namespaceObject.promises.writeFile(opamCmd, data, { mode: 0o755 }); } async function setupOpamWindows() { - lib_core.startGroup("Prepare the Cygwin environment"); - lib_core.exportVariable("CYGWIN", "winsymlinks:native"); - lib_core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); - lib_core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); - lib_core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); - lib_core.addPath(CYGWIN_ROOT_WRAPPERBIN); - await setupCygwin(); - lib_core.endGroup(); + await lib_core.group("Prepare the Cygwin environment", async () => { + lib_core.exportVariable("CYGWIN", "winsymlinks:native"); + lib_core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); + lib_core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); + lib_core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); + lib_core.addPath(CYGWIN_ROOT_WRAPPERBIN); + await setupCygwin(); + }); await saveCygwinCache(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const originalPath = external_node_process_namespaceObject.env.PATH.split(external_node_path_namespaceObject.delimiter); const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; external_node_process_namespaceObject.env.PATH = patchedPath.join(external_node_path_namespaceObject.delimiter); - lib_core.startGroup("Install opam"); - await acquireOpamWindows(); - lib_core.endGroup(); - lib_core.startGroup("Initialise the opam state"); - await initializeOpamWindows(); - lib_core.endGroup(); + await lib_core.group("Install opam", async () => { + await acquireOpamWindows(); + }); + await lib_core.group("Initialise the opam state", async () => { + await initializeOpamWindows(); + }); external_node_process_namespaceObject.env.PATH = originalPath.join(external_node_path_namespaceObject.delimiter); } async function setupOpam() { @@ -144482,46 +144547,46 @@ async function setupOpam() { } } async function installOcaml(ocamlCompiler) { - lib_core.startGroup("Install OCaml"); - const platform = getPlatform(); - if (platform === Platform.Win32) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalPath = external_node_process_namespaceObject.env.PATH.split(external_node_path_namespaceObject.delimiter); - const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; - external_node_process_namespaceObject.env.PATH = patchedPath.join(external_node_path_namespaceObject.delimiter); - await (0,lib_exec.exec)("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - external_node_process_namespaceObject.env.PATH = originalPath.join(external_node_path_namespaceObject.delimiter); - } - else { - await (0,lib_exec.exec)("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - } - lib_core.endGroup(); + await lib_core.group("Install OCaml", async () => { + const platform = getPlatform(); + if (platform === Platform.Win32) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalPath = external_node_process_namespaceObject.env.PATH.split(external_node_path_namespaceObject.delimiter); + const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; + external_node_process_namespaceObject.env.PATH = patchedPath.join(external_node_path_namespaceObject.delimiter); + await (0,lib_exec.exec)("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + external_node_process_namespaceObject.env.PATH = originalPath.join(external_node_path_namespaceObject.delimiter); + } + else { + await (0,lib_exec.exec)("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + } + }); } async function pin(fpaths) { - lib_core.startGroup("Pin local packages"); - const opam = await findOpam(); - for (const fpath of fpaths) { - const fname = external_node_path_namespaceObject.basename(fpath, ".opam"); - const dname = external_node_path_namespaceObject.dirname(fpath); - await (0,lib_exec.exec)(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { - cwd: dname, - }); - } - lib_core.endGroup(); + await lib_core.group("Pin local packages", async () => { + const opam = await findOpam(); + for (const fpath of fpaths) { + const fname = external_node_path_namespaceObject.basename(fpath, ".opam"); + const dname = external_node_path_namespaceObject.dirname(fpath); + await (0,lib_exec.exec)(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { + cwd: dname, + }); + } + }); } async function repositoryAdd(name, address) { const opam = await findOpam(); @@ -144535,40 +144600,40 @@ async function repositoryAdd(name, address) { ]); } async function repositoryAddAll(repositories) { - const platform = getPlatform(); - let restore_autocrlf; - lib_core.startGroup("Initialise the opam repositories"); - // Works around the lack of https://github.com/ocaml/opam/pull/3882 when - // adding ocaml/opam-repository on Windows. Can be removed when the action - // switches to opam 2.2 - if (platform === Platform.Win32) { - const autocrlf = await (0,lib_exec.getExecOutput)("git", ["config", "--global", "core.autocrlf"], { ignoreReturnCode: true }); - if (autocrlf.stdout.trim() !== "input") { - if (autocrlf.exitCode === 0) { - restore_autocrlf = autocrlf.stdout.trim(); - } - else { - // eslint-disable-next-line unicorn/no-null - restore_autocrlf = null; // Unset the value at the end + await lib_core.group("Initialise the opam repositories", async () => { + const platform = getPlatform(); + let restore_autocrlf; + // Works around the lack of https://github.com/ocaml/opam/pull/3882 when + // adding ocaml/opam-repository on Windows. Can be removed when the action + // switches to opam 2.2 + if (platform === Platform.Win32) { + const autocrlf = await (0,lib_exec.getExecOutput)("git", ["config", "--global", "core.autocrlf"], { ignoreReturnCode: true }); + if (autocrlf.stdout.trim() !== "input") { + if (autocrlf.exitCode === 0) { + restore_autocrlf = autocrlf.stdout.trim(); + } + else { + // eslint-disable-next-line unicorn/no-null + restore_autocrlf = null; // Unset the value at the end + } } + await (0,lib_exec.exec)("git", ["config", "--global", "core.autocrlf", "input"]); } - await (0,lib_exec.exec)("git", ["config", "--global", "core.autocrlf", "input"]); - } - for (const [name, address] of repositories) { - await repositoryAdd(name, address); - } - if (restore_autocrlf === null) { - await (0,lib_exec.exec)("git", ["config", "--global", "--unset", "core.autocrlf"]); - } - else if (restore_autocrlf !== undefined) { - await (0,lib_exec.exec)("git", [ - "config", - "--global", - "core.autocrlf", - restore_autocrlf, - ]); - } - lib_core.endGroup(); + for (const [name, address] of repositories) { + await repositoryAdd(name, address); + } + if (restore_autocrlf === null) { + await (0,lib_exec.exec)("git", ["config", "--global", "--unset", "core.autocrlf"]); + } + else if (restore_autocrlf !== undefined) { + await (0,lib_exec.exec)("git", [ + "config", + "--global", + "core.autocrlf", + restore_autocrlf, + ]); + } + }); } async function repositoryRemove(name) { const opam = await findOpam(); @@ -144588,12 +144653,12 @@ async function repositoryList() { } } async function repositoryRemoveAll() { - lib_core.startGroup("Remove the opam repositories"); - const repositories = await repositoryList(); - for (const repository of repositories) { - await repositoryRemove(repository); - } - lib_core.endGroup(); + await lib_core.group("Remove the opam repositories", async () => { + const repositories = await repositoryList(); + for (const repository of repositories) { + await repositoryRemove(repository); + } + }); } ;// CONCATENATED MODULE: ./src/version.ts @@ -144844,70 +144909,70 @@ async function saveCache(key, paths) { } } async function restoreCygwinCache() { - lib_core.startGroup("Retrieve the Cygwin cache"); - const { key, restoreKeys } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await restoreCache(key, restoreKeys, paths); - lib_core.endGroup(); + await lib_core.group("Retrieve the Cygwin cache", async () => { + const { key, restoreKeys } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } async function saveCygwinCache() { - lib_core.startGroup("Save the Cygwin cache"); - const { key } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await saveCache(key, paths); - lib_core.endGroup(); + await lib_core.group("Save the Cygwin cache", async () => { + const { key } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await saveCache(key, paths); + }); } async function restoreDuneCache() { - lib_core.startGroup("Retrieve the dune cache"); - const { key, restoreKeys } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await restoreCache(key, restoreKeys, paths); - lib_core.endGroup(); + await lib_core.group("Retrieve the dune cache", async () => { + const { key, restoreKeys } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } async function saveDuneCache() { - core.startGroup("Save the dune cache"); - const { key } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the dune cache", async () => { + const { key } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await saveCache(key, paths); + }); } async function restoreOpamCache() { - lib_core.startGroup("Retrieve the opam cache"); - const { key, restoreKeys } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - lib_core.endGroup(); - return cacheKey; + return await lib_core.group("Retrieve the opam cache", async () => { + const { key, restoreKeys } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } async function saveOpamCache() { - lib_core.startGroup("Save the opam cache"); - await (0,lib_exec.exec)("opam", [ - "clean", - "--all-switches", - "--download-cache", - "--logs", - "--repo-cache", - "--unused-repositories", - ]); - const { key } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - await saveCache(key, paths); - lib_core.endGroup(); + await lib_core.group("Save the opam cache", async () => { + await (0,lib_exec.exec)("opam", [ + "clean", + "--all-switches", + "--download-cache", + "--logs", + "--repo-cache", + "--unused-repositories", + ]); + const { key } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + await saveCache(key, paths); + }); } async function restoreOpamDownloadCache() { - lib_core.startGroup("Retrieve the opam download cache"); - const { key, restoreKeys } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - lib_core.endGroup(); - return cacheKey; + return await lib_core.group("Retrieve the opam download cache", async () => { + const { key, restoreKeys } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } async function saveOpamDownloadCache() { - core.startGroup("Save the opam download cache"); - const { key } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the opam download cache", async () => { + const { key } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + await saveCache(key, paths); + }); } ;// CONCATENATED MODULE: ./src/depext.ts @@ -144917,27 +144982,27 @@ async function saveOpamDownloadCache() { async function installDepext(ocamlVersion) { - lib_core.startGroup("Install depext"); - const platform = getPlatform(); - const depextCygwinports = platform === Platform.Win32 ? ["depext-cygwinports"] : []; - await (0,lib_exec.exec)("opam", ["install", "opam-depext", ...depextCygwinports]); - if (platform === Platform.Win32) { - let base = ""; - if (ocamlVersion.includes("mingw64")) { - base = "x86_64-w64-mingw32"; - } - else if (ocamlVersion.includes("mingw32")) { - base = "i686-w64-mingw32"; + await lib_core.group("Install depext", async () => { + const platform = getPlatform(); + const depextCygwinports = platform === Platform.Win32 ? ["depext-cygwinports"] : []; + await (0,lib_exec.exec)("opam", ["install", "opam-depext", ...depextCygwinports]); + if (platform === Platform.Win32) { + let base = ""; + if (ocamlVersion.includes("mingw64")) { + base = "x86_64-w64-mingw32"; + } + else if (ocamlVersion.includes("mingw32")) { + base = "i686-w64-mingw32"; + } + lib_core.addPath(external_node_path_namespaceObject.posix.join("/", "usr", base, "sys-root", "mingw", "bin")); } - lib_core.addPath(external_node_path_namespaceObject.posix.join("/", "usr", base, "sys-root", "mingw", "bin")); - } - lib_core.endGroup(); + }); } async function installDepextPackages(fpaths) { - lib_core.startGroup("Install system packages required by opam packages"); - const fnames = fpaths.map((fpath) => external_node_path_namespaceObject.basename(fpath, ".opam")); - await (0,lib_exec.exec)("opam", ["depext", ...fnames, ...OPAM_DEPEXT_FLAGS]); - lib_core.endGroup(); + await lib_core.group("Install system packages required by opam packages", async () => { + const fnames = fpaths.map((fpath) => external_node_path_namespaceObject.basename(fpath, ".opam")); + await (0,lib_exec.exec)("opam", ["depext", ...fnames, ...OPAM_DEPEXT_FLAGS]); + }); } ;// CONCATENATED MODULE: ./src/dune.ts @@ -144947,29 +145012,29 @@ async function installDepextPackages(fpaths) { const { repo: { owner, repo }, runId: run_id, } = lib_github.context; async function installDune() { - lib_core.startGroup("Install dune"); - await (0,lib_exec.exec)("opam", ["depext", "--install", "dune"]); - lib_core.endGroup(); + await lib_core.group("Install dune", async () => { + await (0,lib_exec.exec)("opam", ["depext", "--install", "dune"]); + }); } async function trimDuneCache() { - core.startGroup("Remove oldest files from the dune cache to free space"); - const octokit = github.getOctokit(GITHUB_TOKEN); - const { data: { total_count: totalCount }, } = await octokit.rest.actions.listJobsForWorkflowRun({ - owner, - repo, - run_id, + await core.group("Remove oldest files from the dune cache to free space", async () => { + const octokit = github.getOctokit(GITHUB_TOKEN); + const { data: { total_count: totalCount }, } = await octokit.rest.actions.listJobsForWorkflowRun({ + owner, + repo, + run_id, + }); + const cacheSize = Math.floor(5000 / totalCount); + await exec("opam", [ + "exec", + "--", + "dune", + "cache", + "trim", + "--size", + `${cacheSize}MB`, + ]); }); - const cacheSize = Math.floor(5000 / totalCount); - await exec("opam", [ - "exec", - "--", - "dune", - "cache", - "trim", - "--size", - `${cacheSize}MB`, - ]); - core.endGroup(); } // EXTERNAL MODULE: ../../node_modules/@actions/glob/lib/glob.js @@ -145017,18 +145082,18 @@ async function installer() { lib_core.exportVariable("OPAMROOT", opamRoot); } if (platform === Platform.Win32) { - lib_core.startGroup("Change the file system behavior parameters"); - await (0,lib_exec.exec)("fsutil", ["behavior", "query", "SymlinkEvaluation"]); - // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-behavior - await (0,lib_exec.exec)("fsutil", [ - "behavior", - "set", - "symlinkEvaluation", - "R2L:1", - "R2R:1", - ]); - await (0,lib_exec.exec)("fsutil", ["behavior", "query", "SymlinkEvaluation"]); - lib_core.endGroup(); + await lib_core.group("Change the file system behavior parameters", async () => { + await (0,lib_exec.exec)("fsutil", ["behavior", "query", "SymlinkEvaluation"]); + // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-behavior + await (0,lib_exec.exec)("fsutil", [ + "behavior", + "set", + "symlinkEvaluation", + "R2L:1", + "R2R:1", + ]); + await (0,lib_exec.exec)("fsutil", ["behavior", "query", "SymlinkEvaluation"]); + }); } if (platform === Platform.Win32) { lib_core.exportVariable("HOME", external_node_process_namespaceObject.env.USERPROFILE); diff --git a/dist/post/index.js b/dist/post/index.js index efd59c6c..da077392 100644 --- a/dist/post/index.js +++ b/dist/post/index.js @@ -17979,12 +17979,11 @@ exports.setSpanContext = setSpanContext; "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - var abortController = __nccwpck_require__(86455); var crypto = __nccwpck_require__(6113); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Creates an abortable promise. * @param buildPromise - A function that takes the resolve and reject functions as parameters. @@ -18025,6 +18024,7 @@ function createAbortablePromise(buildPromise, options) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. const StandardAbortMessage = "The delay was aborted."; /** * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. @@ -18045,6 +18045,7 @@ function delay(timeInMs, options) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * promise.race() wrapper that aborts rest of promises as soon as the first promise settles. */ @@ -18100,6 +18101,7 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Typeguard for an error object shape (has name and message) * @param e - Something caught by a catch clause. @@ -18140,6 +18142,7 @@ function getErrorMessage(e) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Generates a SHA-256 HMAC signature. * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. @@ -18264,16 +18267,20 @@ const isWebWorker = typeof self === "object" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); -/** - * A constant that indicates whether the environment the code is running is Node.JS. - */ -const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node); /** * A constant that indicates whether the environment the code is running is Deno. */ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && + Boolean(process.version) && + Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node) && + // Deno thought it was a good idea to spoof process.versions.node, see https://deno.land/std@0.177.0/node/process.ts?s=versions + !isDeno; /** * A constant that indicates whether the environment the code is running is Bun.sh. */ @@ -18293,14 +18300,7 @@ const isReactNative = typeof navigator !== "undefined" && (navigator === null || * @returns a string of the encoded string */ function uint8ArrayToString(bytes, format) { - switch (format) { - case "utf-8": - return uint8ArrayToUtf8String(bytes); - case "base64": - return uint8ArrayToBase64(bytes); - case "base64url": - return uint8ArrayToBase64Url(bytes); - } + return Buffer.from(bytes).toString(format); } /** * The helper that transforms string to specific character encoded bytes array. @@ -18309,56 +18309,7 @@ function uint8ArrayToString(bytes, format) { * @returns a uint8array */ function stringToUint8Array(value, format) { - switch (format) { - case "utf-8": - return utf8StringToUint8Array(value); - case "base64": - return base64ToUint8Array(value); - case "base64url": - return base64UrlToUint8Array(value); - } -} -/** - * Decodes a Uint8Array into a Base64 string. - * @internal - */ -function uint8ArrayToBase64(bytes) { - return Buffer.from(bytes).toString("base64"); -} -/** - * Decodes a Uint8Array into a Base64Url string. - * @internal - */ -function uint8ArrayToBase64Url(bytes) { - return Buffer.from(bytes).toString("base64url"); -} -/** - * Decodes a Uint8Array into a javascript string. - * @internal - */ -function uint8ArrayToUtf8String(bytes) { - return Buffer.from(bytes).toString("utf-8"); -} -/** - * Encodes a JavaScript string into a Uint8Array. - * @internal - */ -function utf8StringToUint8Array(value) { - return Buffer.from(value); -} -/** - * Encodes a Base64 string into a Uint8Array. - * @internal - */ -function base64ToUint8Array(value) { - return Buffer.from(value, "base64"); -} -/** - * Encodes a Base64Url string into a Uint8Array. - * @internal - */ -function base64UrlToUint8Array(value) { - return Buffer.from(value, "base64url"); + return Buffer.from(value, format); } exports.cancelablePromiseRace = cancelablePromiseRace; @@ -45443,7 +45394,7 @@ module.exports = __toCommonJS(dist_src_exports); var import_universal_user_agent = __nccwpck_require__(65212); // pkg/dist-src/version.js -var VERSION = "9.0.1"; +var VERSION = "9.0.2"; // pkg/dist-src/defaults.js var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; @@ -45651,7 +45602,7 @@ function parseUrl(template) { } function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace( + template = template.replace( /\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { @@ -45681,6 +45632,11 @@ function expand(template, context) { } } ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } } // pkg/dist-src/parse.js @@ -45965,7 +45921,7 @@ __export(dist_src_exports, { module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js -var VERSION = "9.0.0"; +var VERSION = "9.1.2"; // pkg/dist-src/normalize-paginated-list-response.js function normalizePaginatedListResponse(response) { @@ -46134,9 +46090,11 @@ var paginatingEndpoints = [ "GET /orgs/{org}/personal-access-tokens", "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/security-advisories", "GET /orgs/{org}/teams", @@ -46228,6 +46186,7 @@ var paginatingEndpoints = [ "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", "GET /repos/{owner}/{repo}/rules/branches/{branch}", "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", "GET /repos/{owner}/{repo}/security-advisories", @@ -46359,7 +46318,7 @@ __export(dist_src_exports, { module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/version.js -var VERSION = "10.0.1"; +var VERSION = "10.1.2"; // pkg/dist-src/generated/endpoints.js var Endpoints = { @@ -46464,6 +46423,9 @@ var Endpoints = { enableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], generateRunnerJitconfigForOrg: [ "POST /orgs/{org}/actions/runners/generate-jitconfig" ], @@ -46873,6 +46835,9 @@ var Endpoints = { addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], codespaceMachinesForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/machines" ], @@ -46990,7 +46955,7 @@ var Endpoints = { "DELETE /orgs/{org}/copilot/billing/selected_users" ], getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatAssignmentDetailsForUser: [ + getCopilotSeatDetailsForUser: [ "GET /orgs/{org}/members/{username}/copilot" ], listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] @@ -47203,7 +47168,13 @@ var Endpoints = { root: ["GET /"] }, migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], deleteArchiveForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/archive" ], @@ -47216,9 +47187,27 @@ var Endpoints = { 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"], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], listForAuthenticatedUser: ["GET /user/migrations"], @@ -47232,18 +47221,42 @@ var Endpoints = { {}, { renamed: ["migrations", "listReposForAuthenticatedUser"] } ], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-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"] + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] }, orgs: { addSecurityManagerTeam: [ @@ -47258,6 +47271,13 @@ var Endpoints = { "PUT /orgs/{org}/outside_collaborators/{username}" ], createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], createWebhook: ["POST /orgs/{org}/hooks"], delete: ["DELETE /orgs/{org}"], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], @@ -47265,6 +47285,10 @@ var Endpoints = { "POST /orgs/{org}/{security_product}/{enablement}" ], get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], @@ -47275,6 +47299,7 @@ var Endpoints = { list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], @@ -47299,6 +47324,9 @@ var Endpoints = { redeliverWebhookDelivery: [ "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], removeOutsideCollaborator: [ @@ -47779,6 +47807,7 @@ var Endpoints = { getCustomDeploymentProtectionRule: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], getDeploymentBranchPolicy: [ @@ -47792,6 +47821,8 @@ var Endpoints = { ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], @@ -47807,6 +47838,10 @@ var Endpoints = { 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}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], getStatusChecksProtection: [ @@ -93491,6 +93526,14 @@ class Request { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } } onConnect (abort) { @@ -94544,6 +94587,8 @@ let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { @@ -94567,7 +94612,7 @@ function extractBody (object, keepalive = false) { stream = new ReadableStream({ async pull (controller) { controller.enqueue( - typeof source === 'string' ? new TextEncoder().encode(source) : source + typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, @@ -94637,7 +94682,6 @@ function extractBody (object, keepalive = false) { // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. - const enc = new TextEncoder() const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 @@ -94645,13 +94689,13 @@ function extractBody (object, keepalive = false) { for (const [name, value] of object) { if (typeof value === 'string') { - const chunk = enc.encode(prefix + + const chunk = textEncoder.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))}"` + + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' @@ -94665,7 +94709,7 @@ function extractBody (object, keepalive = false) { } } - const chunk = enc.encode(`--${boundary}--`) + const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { @@ -94961,14 +95005,16 @@ function bodyMixinMethods (instance) { 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 }) + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = 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 += streamingDecoder.decode(chunk, { stream: true }) } - text += textDecoder.decode() + text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. @@ -95083,7 +95129,7 @@ function utf8DecodeBytes (buffer) { // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". - const output = new TextDecoder().decode(buffer) + const output = textDecoder.decode(buffer) // 4. Return output. return output @@ -95131,10 +95177,12 @@ module.exports = { const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(71267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ @@ -95146,6 +95194,8 @@ const badPorts = [ '10080' ] +const badPortsSet = new Set(badPorts) + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', @@ -95158,10 +95208,12 @@ const referrerPolicy = [ 'strict-origin-when-cross-origin', 'unsafe-url' ] +const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] @@ -95196,6 +95248,7 @@ const requestDuplex = [ // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', @@ -95211,6 +95264,7 @@ const subresource = [ 'xslt', '' ] +const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { @@ -95260,7 +95314,14 @@ module.exports = { nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } @@ -95916,6 +95977,7 @@ const { isBlobLike } = __nccwpck_require__(3640) const { webidl } = __nccwpck_require__(35989) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(68093) const { kEnumerableProperty } = __nccwpck_require__(5499) +const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { @@ -96189,7 +96251,7 @@ function processBlobParts (parts, options) { } // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(new TextEncoder().encode(s)) + bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) @@ -97187,11 +97249,11 @@ const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(88246) const assert = __nccwpck_require__(39491) const { safelyExtractBody } = __nccwpck_require__(92256) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException } = __nccwpck_require__(69602) const { kHeadersList } = __nccwpck_require__(65574) @@ -97203,6 +97265,7 @@ const { TransformStream } = __nccwpck_require__(35356) const { getGlobalDispatcher } = __nccwpck_require__(45377) const { webidl } = __nccwpck_require__(35989) const { STATUS_CODES } = __nccwpck_require__(13685) +const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -97262,7 +97325,7 @@ class Fetch extends EE { } // https://fetch.spec.whatwg.org/#fetch-method -async function fetch (input, init = {}) { +function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. @@ -97345,7 +97408,7 @@ async function fetch (input, init = {}) { const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { - return + return Promise.resolve() } // 2. If response’s aborted flag is set, then: @@ -97358,7 +97421,7 @@ async function fetch (input, init = {}) { // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) - return + return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError @@ -97367,7 +97430,7 @@ async function fetch (input, init = {}) { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) - return + return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, @@ -97650,7 +97713,7 @@ function fetching ({ } // 15. If request is a subresource request, then: - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { // TODO } @@ -97917,13 +97980,13 @@ async function mainFetch (fetchParams, recursive = false) { // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams -async function schemeFetch (fetchParams) { +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) + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. @@ -97939,7 +98002,7 @@ async function schemeFetch (fetchParams) { // and body is the empty byte sequence as a body. // Otherwise, return a network error. - return makeNetworkError('about scheme is not supported') + return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { @@ -97952,7 +98015,7 @@ async function schemeFetch (fetchParams) { // 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.') + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) @@ -97960,7 +98023,7 @@ async function schemeFetch (fetchParams) { // 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') + return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. @@ -97987,7 +98050,7 @@ async function schemeFetch (fetchParams) { response.body = body - return response + return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the @@ -97998,7 +98061,7 @@ async function schemeFetch (fetchParams) { // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { - return makeNetworkError('failed to fetch the data URL') + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. @@ -98007,28 +98070,28 @@ async function schemeFetch (fetchParams) { // 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({ + return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }) + })) } 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...') + return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) + return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { - return makeNetworkError('unknown scheme') + return Promise.resolve(makeNetworkError('unknown scheme')) } } } @@ -98047,7 +98110,7 @@ function finalizeResponse (fetchParams, response) { } // https://fetch.spec.whatwg.org/#fetch-finale -async function fetchFinale (fetchParams, response) { +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] ». @@ -98131,8 +98194,9 @@ async function fetchFinale (fetchParams, response) { } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. - await fullyReadBody(response.body, processBody, processBodyError) + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() } } @@ -98203,7 +98267,7 @@ async function httpFetch (fetchParams) { } // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(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. @@ -98240,7 +98304,7 @@ async function httpFetch (fetchParams) { } // https://fetch.spec.whatwg.org/#http-redirect-fetch -async function httpRedirectFetch (fetchParams, response) { +function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request @@ -98266,18 +98330,18 @@ async function httpRedirectFetch (fetchParams, response) { } } catch (err) { // 5. If locationURL is failure, then return a network error. - return makeNetworkError(err) + return Promise.resolve(makeNetworkError(err)) } // 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') + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { - return makeNetworkError('redirect count exceeded') + return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. @@ -98291,7 +98355,7 @@ async function httpRedirectFetch (fetchParams, response) { (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { - return makeNetworkError('cross origin not allowed for request mode "cors"') + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes @@ -98300,9 +98364,9 @@ async function httpRedirectFetch (fetchParams, response) { request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ) + )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, @@ -98312,7 +98376,7 @@ async function httpRedirectFetch (fetchParams, response) { request.body != null && request.body.source == null ) { - return makeNetworkError() + return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true @@ -98321,7 +98385,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEAD'].includes(request.method)) + !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. @@ -98605,7 +98669,7 @@ async function httpNetworkOrCacheFetch ( // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( - !safeMethods.includes(httpRequest.method) && + !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { @@ -99165,7 +99229,7 @@ async function httpNetworkFetch ( const willFollow = request.redirect === 'follow' && location && - redirectStatus.includes(status) + redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { @@ -99305,8 +99369,8 @@ const { makePolicyContainer } = __nccwpck_require__(3640) const { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -99611,7 +99675,7 @@ class Request { throw TypeError(`'${init.method}' is not a valid HTTP method.`) } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + if (forbiddenMethodsSet.has(method.toUpperCase())) { throw TypeError(`'${init.method}' HTTP method is unsupported.`) } @@ -99696,7 +99760,7 @@ class Request { 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)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) @@ -100258,7 +100322,7 @@ const { isomorphicEncode } = __nccwpck_require__(3640) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(69602) @@ -100272,6 +100336,7 @@ const assert = __nccwpck_require__(39491) const { types } = __nccwpck_require__(73837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { @@ -100301,7 +100366,7 @@ class Response { } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = new TextEncoder('utf-8').encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) @@ -100346,7 +100411,7 @@ class Response { } // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } @@ -100844,7 +100909,7 @@ module.exports = { "use strict"; -const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(69602) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(69602) const { getGlobalOrigin } = __nccwpck_require__(13913) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(5499) @@ -100873,7 +100938,7 @@ function responseURL (response) { // 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)) { + if (!redirectStatusSet.has(response.status)) { return null } @@ -100908,7 +100973,7 @@ function requestBadPort (request) { // 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)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } @@ -101050,7 +101115,7 @@ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 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)) { + if (referrerPolicyTokens.has(token)) { policy = token break } @@ -119265,7 +119330,7 @@ class Directives { onError('Verbatim tags must end with a >'); return verbatim; } - const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/); + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); if (!suffix) onError(`The ${source} tag has no suffix`); const prefix = this.tags[handle]; @@ -143176,12 +143241,12 @@ async function initializeOpamUnix() { ]); } async function setupOpamUnix() { - core.startGroup("Install opam"); - await acquireOpamUnix(); - core.endGroup(); - core.startGroup("Initialise the opam state"); - await initializeOpamUnix(); - core.endGroup(); + await core.group("Install opam", async () => { + await acquireOpamUnix(); + }); + await core.group("Initialise the opam state", async () => { + await initializeOpamUnix(); + }); } async function setupCygwin() { const version = await getCygwinVersion(); @@ -143259,25 +143324,25 @@ async function initializeOpamWindows() { await fs.writeFile(opamCmd, data, { mode: 0o755 }); } async function setupOpamWindows() { - core.startGroup("Prepare the Cygwin environment"); - core.exportVariable("CYGWIN", "winsymlinks:native"); - core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); - core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); - core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); - core.addPath(CYGWIN_ROOT_WRAPPERBIN); - await setupCygwin(); - core.endGroup(); + await core.group("Prepare the Cygwin environment", async () => { + core.exportVariable("CYGWIN", "winsymlinks:native"); + core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); + core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); + core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); + core.addPath(CYGWIN_ROOT_WRAPPERBIN); + await setupCygwin(); + }); await saveCygwinCache(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const originalPath = process.env["PATH"].split(path.delimiter); const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; process.env["PATH"] = patchedPath.join(path.delimiter); - core.startGroup("Install opam"); - await acquireOpamWindows(); - core.endGroup(); - core.startGroup("Initialise the opam state"); - await initializeOpamWindows(); - core.endGroup(); + await core.group("Install opam", async () => { + await acquireOpamWindows(); + }); + await core.group("Initialise the opam state", async () => { + await initializeOpamWindows(); + }); process.env["PATH"] = originalPath.join(path.delimiter); } async function setupOpam() { @@ -143290,46 +143355,46 @@ async function setupOpam() { } } async function installOcaml(ocamlCompiler) { - core.startGroup("Install OCaml"); - const platform = getPlatform(); - if (platform === Platform.Win32) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalPath = process.env["PATH"].split(path.delimiter); - const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; - process.env["PATH"] = patchedPath.join(path.delimiter); - await exec("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - process.env["PATH"] = originalPath.join(path.delimiter); - } - else { - await exec("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - } - core.endGroup(); + await core.group("Install OCaml", async () => { + const platform = getPlatform(); + if (platform === Platform.Win32) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalPath = process.env["PATH"].split(path.delimiter); + const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; + process.env["PATH"] = patchedPath.join(path.delimiter); + await exec("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + process.env["PATH"] = originalPath.join(path.delimiter); + } + else { + await exec("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + } + }); } async function pin(fpaths) { - core.startGroup("Pin local packages"); - const opam = await findOpam(); - for (const fpath of fpaths) { - const fname = path.basename(fpath, ".opam"); - const dname = path.dirname(fpath); - await exec(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { - cwd: dname, - }); - } - core.endGroup(); + await core.group("Pin local packages", async () => { + const opam = await findOpam(); + for (const fpath of fpaths) { + const fname = path.basename(fpath, ".opam"); + const dname = path.dirname(fpath); + await exec(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { + cwd: dname, + }); + } + }); } async function repositoryAdd(name, address) { const opam = await findOpam(); @@ -143343,40 +143408,40 @@ async function repositoryAdd(name, address) { ]); } async function repositoryAddAll(repositories) { - const platform = getPlatform(); - let restore_autocrlf; - core.startGroup("Initialise the opam repositories"); - // Works around the lack of https://github.com/ocaml/opam/pull/3882 when - // adding ocaml/opam-repository on Windows. Can be removed when the action - // switches to opam 2.2 - if (platform === Platform.Win32) { - const autocrlf = await getExecOutput("git", ["config", "--global", "core.autocrlf"], { ignoreReturnCode: true }); - if (autocrlf.stdout.trim() !== "input") { - if (autocrlf.exitCode === 0) { - restore_autocrlf = autocrlf.stdout.trim(); - } - else { - // eslint-disable-next-line unicorn/no-null - restore_autocrlf = null; // Unset the value at the end + await core.group("Initialise the opam repositories", async () => { + const platform = getPlatform(); + let restore_autocrlf; + // Works around the lack of https://github.com/ocaml/opam/pull/3882 when + // adding ocaml/opam-repository on Windows. Can be removed when the action + // switches to opam 2.2 + if (platform === Platform.Win32) { + const autocrlf = await getExecOutput("git", ["config", "--global", "core.autocrlf"], { ignoreReturnCode: true }); + if (autocrlf.stdout.trim() !== "input") { + if (autocrlf.exitCode === 0) { + restore_autocrlf = autocrlf.stdout.trim(); + } + else { + // eslint-disable-next-line unicorn/no-null + restore_autocrlf = null; // Unset the value at the end + } } + await exec("git", ["config", "--global", "core.autocrlf", "input"]); } - await exec("git", ["config", "--global", "core.autocrlf", "input"]); - } - for (const [name, address] of repositories) { - await repositoryAdd(name, address); - } - if (restore_autocrlf === null) { - await exec("git", ["config", "--global", "--unset", "core.autocrlf"]); - } - else if (restore_autocrlf !== undefined) { - await exec("git", [ - "config", - "--global", - "core.autocrlf", - restore_autocrlf, - ]); - } - core.endGroup(); + for (const [name, address] of repositories) { + await repositoryAdd(name, address); + } + if (restore_autocrlf === null) { + await exec("git", ["config", "--global", "--unset", "core.autocrlf"]); + } + else if (restore_autocrlf !== undefined) { + await exec("git", [ + "config", + "--global", + "core.autocrlf", + restore_autocrlf, + ]); + } + }); } async function repositoryRemove(name) { const opam = await findOpam(); @@ -143396,12 +143461,12 @@ async function repositoryList() { } } async function repositoryRemoveAll() { - core.startGroup("Remove the opam repositories"); - const repositories = await repositoryList(); - for (const repository of repositories) { - await repositoryRemove(repository); - } - core.endGroup(); + await core.group("Remove the opam repositories", async () => { + const repositories = await repositoryList(); + for (const repository of repositories) { + await repositoryRemove(repository); + } + }); } ;// CONCATENATED MODULE: ./src/version.ts @@ -143652,70 +143717,70 @@ async function saveCache(key, paths) { } } async function restoreCygwinCache() { - core.startGroup("Retrieve the Cygwin cache"); - const { key, restoreKeys } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await restoreCache(key, restoreKeys, paths); - core.endGroup(); + await core.group("Retrieve the Cygwin cache", async () => { + const { key, restoreKeys } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } async function cache_saveCygwinCache() { - core.startGroup("Save the Cygwin cache"); - const { key } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the Cygwin cache", async () => { + const { key } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await saveCache(key, paths); + }); } async function restoreDuneCache() { - core.startGroup("Retrieve the dune cache"); - const { key, restoreKeys } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await restoreCache(key, restoreKeys, paths); - core.endGroup(); + await core.group("Retrieve the dune cache", async () => { + const { key, restoreKeys } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } async function saveDuneCache() { - lib_core.startGroup("Save the dune cache"); - const { key } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await saveCache(key, paths); - lib_core.endGroup(); + await lib_core.group("Save the dune cache", async () => { + const { key } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await saveCache(key, paths); + }); } async function restoreOpamCache() { - core.startGroup("Retrieve the opam cache"); - const { key, restoreKeys } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - core.endGroup(); - return cacheKey; + return await core.group("Retrieve the opam cache", async () => { + const { key, restoreKeys } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } async function saveOpamCache() { - core.startGroup("Save the opam cache"); - await exec("opam", [ - "clean", - "--all-switches", - "--download-cache", - "--logs", - "--repo-cache", - "--unused-repositories", - ]); - const { key } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the opam cache", async () => { + await exec("opam", [ + "clean", + "--all-switches", + "--download-cache", + "--logs", + "--repo-cache", + "--unused-repositories", + ]); + const { key } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + await saveCache(key, paths); + }); } async function restoreOpamDownloadCache() { - core.startGroup("Retrieve the opam download cache"); - const { key, restoreKeys } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - core.endGroup(); - return cacheKey; + return await core.group("Retrieve the opam download cache", async () => { + const { key, restoreKeys } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } async function saveOpamDownloadCache() { - lib_core.startGroup("Save the opam download cache"); - const { key } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - await saveCache(key, paths); - lib_core.endGroup(); + await lib_core.group("Save the opam download cache", async () => { + const { key } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + await saveCache(key, paths); + }); } ;// CONCATENATED MODULE: ./src/dune.ts @@ -143725,29 +143790,29 @@ async function saveOpamDownloadCache() { const { repo: { owner, repo }, runId: run_id, } = lib_github.context; async function installDune() { - core.startGroup("Install dune"); - await exec("opam", ["depext", "--install", "dune"]); - core.endGroup(); + await core.group("Install dune", async () => { + await exec("opam", ["depext", "--install", "dune"]); + }); } async function trimDuneCache() { - lib_core.startGroup("Remove oldest files from the dune cache to free space"); - const octokit = lib_github.getOctokit(constants_GITHUB_TOKEN); - const { data: { total_count: totalCount }, } = await octokit.rest.actions.listJobsForWorkflowRun({ - owner, - repo, - run_id, + await lib_core.group("Remove oldest files from the dune cache to free space", async () => { + const octokit = lib_github.getOctokit(constants_GITHUB_TOKEN); + const { data: { total_count: totalCount }, } = await octokit.rest.actions.listJobsForWorkflowRun({ + owner, + repo, + run_id, + }); + const cacheSize = Math.floor(5000 / totalCount); + await (0,lib_exec.exec)("opam", [ + "exec", + "--", + "dune", + "cache", + "trim", + "--size", + `${cacheSize}MB`, + ]); }); - const cacheSize = Math.floor(5000 / totalCount); - await (0,lib_exec.exec)("opam", [ - "exec", - "--", - "dune", - "cache", - "trim", - "--size", - `${cacheSize}MB`, - ]); - lib_core.endGroup(); } ;// CONCATENATED MODULE: ./src/post.ts diff --git a/lint-doc/dist/index.js b/lint-doc/dist/index.js index 14cd107d..d6ff06da 100644 --- a/lint-doc/dist/index.js +++ b/lint-doc/dist/index.js @@ -11544,6 +11544,14 @@ class Request { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } } onConnect (abort) { @@ -12597,6 +12605,8 @@ let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { @@ -12620,7 +12630,7 @@ function extractBody (object, keepalive = false) { stream = new ReadableStream({ async pull (controller) { controller.enqueue( - typeof source === 'string' ? new TextEncoder().encode(source) : source + typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, @@ -12690,7 +12700,6 @@ function extractBody (object, keepalive = false) { // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. - const enc = new TextEncoder() const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 @@ -12698,13 +12707,13 @@ function extractBody (object, keepalive = false) { for (const [name, value] of object) { if (typeof value === 'string') { - const chunk = enc.encode(prefix + + const chunk = textEncoder.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))}"` + + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' @@ -12718,7 +12727,7 @@ function extractBody (object, keepalive = false) { } } - const chunk = enc.encode(`--${boundary}--`) + const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { @@ -13014,14 +13023,16 @@ function bodyMixinMethods (instance) { 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 }) + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = 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 += streamingDecoder.decode(chunk, { stream: true }) } - text += textDecoder.decode() + text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. @@ -13136,7 +13147,7 @@ function utf8DecodeBytes (buffer) { // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". - const output = new TextDecoder().decode(buffer) + const output = textDecoder.decode(buffer) // 4. Return output. return output @@ -13184,10 +13195,12 @@ module.exports = { const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ @@ -13199,6 +13212,8 @@ const badPorts = [ '10080' ] +const badPortsSet = new Set(badPorts) + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', @@ -13211,10 +13226,12 @@ const referrerPolicy = [ 'strict-origin-when-cross-origin', 'unsafe-url' ] +const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] @@ -13249,6 +13266,7 @@ const requestDuplex = [ // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', @@ -13264,6 +13282,7 @@ const subresource = [ 'xslt', '' ] +const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { @@ -13313,7 +13332,14 @@ module.exports = { nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } @@ -13969,6 +13995,7 @@ const { isBlobLike } = __nccwpck_require__(3640) const { webidl } = __nccwpck_require__(5989) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(8093) const { kEnumerableProperty } = __nccwpck_require__(5499) +const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { @@ -14242,7 +14269,7 @@ function processBlobParts (parts, options) { } // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(new TextEncoder().encode(s)) + bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) @@ -15240,11 +15267,11 @@ const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(8246) const assert = __nccwpck_require__(9491) const { safelyExtractBody } = __nccwpck_require__(2256) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException } = __nccwpck_require__(9602) const { kHeadersList } = __nccwpck_require__(5574) @@ -15256,6 +15283,7 @@ const { TransformStream } = __nccwpck_require__(5356) const { getGlobalDispatcher } = __nccwpck_require__(5377) const { webidl } = __nccwpck_require__(5989) const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -15315,7 +15343,7 @@ class Fetch extends EE { } // https://fetch.spec.whatwg.org/#fetch-method -async function fetch (input, init = {}) { +function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. @@ -15398,7 +15426,7 @@ async function fetch (input, init = {}) { const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { - return + return Promise.resolve() } // 2. If response’s aborted flag is set, then: @@ -15411,7 +15439,7 @@ async function fetch (input, init = {}) { // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) - return + return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError @@ -15420,7 +15448,7 @@ async function fetch (input, init = {}) { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) - return + return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, @@ -15703,7 +15731,7 @@ function fetching ({ } // 15. If request is a subresource request, then: - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { // TODO } @@ -15970,13 +15998,13 @@ async function mainFetch (fetchParams, recursive = false) { // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams -async function schemeFetch (fetchParams) { +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) + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. @@ -15992,7 +16020,7 @@ async function schemeFetch (fetchParams) { // and body is the empty byte sequence as a body. // Otherwise, return a network error. - return makeNetworkError('about scheme is not supported') + return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { @@ -16005,7 +16033,7 @@ async function schemeFetch (fetchParams) { // 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.') + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) @@ -16013,7 +16041,7 @@ async function schemeFetch (fetchParams) { // 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') + return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. @@ -16040,7 +16068,7 @@ async function schemeFetch (fetchParams) { response.body = body - return response + return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the @@ -16051,7 +16079,7 @@ async function schemeFetch (fetchParams) { // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { - return makeNetworkError('failed to fetch the data URL') + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. @@ -16060,28 +16088,28 @@ async function schemeFetch (fetchParams) { // 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({ + return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }) + })) } 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...') + return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) + return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { - return makeNetworkError('unknown scheme') + return Promise.resolve(makeNetworkError('unknown scheme')) } } } @@ -16100,7 +16128,7 @@ function finalizeResponse (fetchParams, response) { } // https://fetch.spec.whatwg.org/#fetch-finale -async function fetchFinale (fetchParams, response) { +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] ». @@ -16184,8 +16212,9 @@ async function fetchFinale (fetchParams, response) { } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. - await fullyReadBody(response.body, processBody, processBodyError) + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() } } @@ -16256,7 +16285,7 @@ async function httpFetch (fetchParams) { } // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(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. @@ -16293,7 +16322,7 @@ async function httpFetch (fetchParams) { } // https://fetch.spec.whatwg.org/#http-redirect-fetch -async function httpRedirectFetch (fetchParams, response) { +function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request @@ -16319,18 +16348,18 @@ async function httpRedirectFetch (fetchParams, response) { } } catch (err) { // 5. If locationURL is failure, then return a network error. - return makeNetworkError(err) + return Promise.resolve(makeNetworkError(err)) } // 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') + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { - return makeNetworkError('redirect count exceeded') + return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. @@ -16344,7 +16373,7 @@ async function httpRedirectFetch (fetchParams, response) { (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { - return makeNetworkError('cross origin not allowed for request mode "cors"') + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes @@ -16353,9 +16382,9 @@ async function httpRedirectFetch (fetchParams, response) { request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ) + )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, @@ -16365,7 +16394,7 @@ async function httpRedirectFetch (fetchParams, response) { request.body != null && request.body.source == null ) { - return makeNetworkError() + return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true @@ -16374,7 +16403,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEAD'].includes(request.method)) + !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. @@ -16658,7 +16687,7 @@ async function httpNetworkOrCacheFetch ( // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( - !safeMethods.includes(httpRequest.method) && + !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { @@ -17218,7 +17247,7 @@ async function httpNetworkFetch ( const willFollow = request.redirect === 'follow' && location && - redirectStatus.includes(status) + redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { @@ -17358,8 +17387,8 @@ const { makePolicyContainer } = __nccwpck_require__(3640) const { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -17664,7 +17693,7 @@ class Request { throw TypeError(`'${init.method}' is not a valid HTTP method.`) } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + if (forbiddenMethodsSet.has(method.toUpperCase())) { throw TypeError(`'${init.method}' HTTP method is unsupported.`) } @@ -17749,7 +17778,7 @@ class Request { 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)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) @@ -18311,7 +18340,7 @@ const { isomorphicEncode } = __nccwpck_require__(3640) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(9602) @@ -18325,6 +18354,7 @@ const assert = __nccwpck_require__(9491) const { types } = __nccwpck_require__(3837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { @@ -18354,7 +18384,7 @@ class Response { } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = new TextEncoder('utf-8').encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) @@ -18399,7 +18429,7 @@ class Response { } // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } @@ -18897,7 +18927,7 @@ module.exports = { "use strict"; -const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(9602) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(9602) const { getGlobalOrigin } = __nccwpck_require__(3913) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(5499) @@ -18926,7 +18956,7 @@ function responseURL (response) { // 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)) { + if (!redirectStatusSet.has(response.status)) { return null } @@ -18961,7 +18991,7 @@ function requestBadPort (request) { // 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)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } @@ -19103,7 +19133,7 @@ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 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)) { + if (referrerPolicyTokens.has(token)) { policy = token break } @@ -27156,14 +27186,20 @@ async function lintOdoc() { async function installOpamPackages() { - core.startGroup("Install opam packages"); - await (0,exec.exec)("opam", ["install", ".", "--deps-only", "--with-doc"]); - core.endGroup(); + await core.group("Install opam packages", async () => { + await (0,exec.exec)("opam", ["install", ".", "--deps-only", "--with-doc"]); + }); } async function installOdoc() { - core.startGroup("Install odoc"); - await (0,exec.exec)("opam", ["depext", "--install", "conf-m4", "dune", "odoc>=1.5.0"]); - core.endGroup(); + await core.group("Install odoc", async () => { + await (0,exec.exec)("opam", [ + "depext", + "--install", + "conf-m4", + "dune", + "odoc>=1.5.0", + ]); + }); } ;// CONCATENATED MODULE: ./src/index.ts diff --git a/lint-fmt/dist/index.js b/lint-fmt/dist/index.js index fc736667..f18c6593 100644 --- a/lint-fmt/dist/index.js +++ b/lint-fmt/dist/index.js @@ -11544,6 +11544,14 @@ class Request { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } } onConnect (abort) { @@ -12597,6 +12605,8 @@ let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { @@ -12620,7 +12630,7 @@ function extractBody (object, keepalive = false) { stream = new ReadableStream({ async pull (controller) { controller.enqueue( - typeof source === 'string' ? new TextEncoder().encode(source) : source + typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, @@ -12690,7 +12700,6 @@ function extractBody (object, keepalive = false) { // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. - const enc = new TextEncoder() const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 @@ -12698,13 +12707,13 @@ function extractBody (object, keepalive = false) { for (const [name, value] of object) { if (typeof value === 'string') { - const chunk = enc.encode(prefix + + const chunk = textEncoder.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))}"` + + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' @@ -12718,7 +12727,7 @@ function extractBody (object, keepalive = false) { } } - const chunk = enc.encode(`--${boundary}--`) + const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { @@ -13014,14 +13023,16 @@ function bodyMixinMethods (instance) { 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 }) + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = 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 += streamingDecoder.decode(chunk, { stream: true }) } - text += textDecoder.decode() + text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. @@ -13136,7 +13147,7 @@ function utf8DecodeBytes (buffer) { // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". - const output = new TextDecoder().decode(buffer) + const output = textDecoder.decode(buffer) // 4. Return output. return output @@ -13184,10 +13195,12 @@ module.exports = { const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ @@ -13199,6 +13212,8 @@ const badPorts = [ '10080' ] +const badPortsSet = new Set(badPorts) + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', @@ -13211,10 +13226,12 @@ const referrerPolicy = [ 'strict-origin-when-cross-origin', 'unsafe-url' ] +const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] @@ -13249,6 +13266,7 @@ const requestDuplex = [ // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', @@ -13264,6 +13282,7 @@ const subresource = [ 'xslt', '' ] +const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { @@ -13313,7 +13332,14 @@ module.exports = { nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } @@ -13969,6 +13995,7 @@ const { isBlobLike } = __nccwpck_require__(3640) const { webidl } = __nccwpck_require__(5989) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(8093) const { kEnumerableProperty } = __nccwpck_require__(5499) +const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { @@ -14242,7 +14269,7 @@ function processBlobParts (parts, options) { } // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(new TextEncoder().encode(s)) + bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) @@ -15240,11 +15267,11 @@ const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(8246) const assert = __nccwpck_require__(9491) const { safelyExtractBody } = __nccwpck_require__(2256) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException } = __nccwpck_require__(9602) const { kHeadersList } = __nccwpck_require__(5574) @@ -15256,6 +15283,7 @@ const { TransformStream } = __nccwpck_require__(5356) const { getGlobalDispatcher } = __nccwpck_require__(5377) const { webidl } = __nccwpck_require__(5989) const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -15315,7 +15343,7 @@ class Fetch extends EE { } // https://fetch.spec.whatwg.org/#fetch-method -async function fetch (input, init = {}) { +function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. @@ -15398,7 +15426,7 @@ async function fetch (input, init = {}) { const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { - return + return Promise.resolve() } // 2. If response’s aborted flag is set, then: @@ -15411,7 +15439,7 @@ async function fetch (input, init = {}) { // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) - return + return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError @@ -15420,7 +15448,7 @@ async function fetch (input, init = {}) { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) - return + return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, @@ -15703,7 +15731,7 @@ function fetching ({ } // 15. If request is a subresource request, then: - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { // TODO } @@ -15970,13 +15998,13 @@ async function mainFetch (fetchParams, recursive = false) { // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams -async function schemeFetch (fetchParams) { +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) + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. @@ -15992,7 +16020,7 @@ async function schemeFetch (fetchParams) { // and body is the empty byte sequence as a body. // Otherwise, return a network error. - return makeNetworkError('about scheme is not supported') + return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { @@ -16005,7 +16033,7 @@ async function schemeFetch (fetchParams) { // 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.') + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) @@ -16013,7 +16041,7 @@ async function schemeFetch (fetchParams) { // 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') + return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. @@ -16040,7 +16068,7 @@ async function schemeFetch (fetchParams) { response.body = body - return response + return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the @@ -16051,7 +16079,7 @@ async function schemeFetch (fetchParams) { // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { - return makeNetworkError('failed to fetch the data URL') + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. @@ -16060,28 +16088,28 @@ async function schemeFetch (fetchParams) { // 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({ + return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }) + })) } 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...') + return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) + return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { - return makeNetworkError('unknown scheme') + return Promise.resolve(makeNetworkError('unknown scheme')) } } } @@ -16100,7 +16128,7 @@ function finalizeResponse (fetchParams, response) { } // https://fetch.spec.whatwg.org/#fetch-finale -async function fetchFinale (fetchParams, response) { +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] ». @@ -16184,8 +16212,9 @@ async function fetchFinale (fetchParams, response) { } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. - await fullyReadBody(response.body, processBody, processBodyError) + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() } } @@ -16256,7 +16285,7 @@ async function httpFetch (fetchParams) { } // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(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. @@ -16293,7 +16322,7 @@ async function httpFetch (fetchParams) { } // https://fetch.spec.whatwg.org/#http-redirect-fetch -async function httpRedirectFetch (fetchParams, response) { +function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request @@ -16319,18 +16348,18 @@ async function httpRedirectFetch (fetchParams, response) { } } catch (err) { // 5. If locationURL is failure, then return a network error. - return makeNetworkError(err) + return Promise.resolve(makeNetworkError(err)) } // 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') + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { - return makeNetworkError('redirect count exceeded') + return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. @@ -16344,7 +16373,7 @@ async function httpRedirectFetch (fetchParams, response) { (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { - return makeNetworkError('cross origin not allowed for request mode "cors"') + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes @@ -16353,9 +16382,9 @@ async function httpRedirectFetch (fetchParams, response) { request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ) + )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, @@ -16365,7 +16394,7 @@ async function httpRedirectFetch (fetchParams, response) { request.body != null && request.body.source == null ) { - return makeNetworkError() + return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true @@ -16374,7 +16403,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEAD'].includes(request.method)) + !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. @@ -16658,7 +16687,7 @@ async function httpNetworkOrCacheFetch ( // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( - !safeMethods.includes(httpRequest.method) && + !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { @@ -17218,7 +17247,7 @@ async function httpNetworkFetch ( const willFollow = request.redirect === 'follow' && location && - redirectStatus.includes(status) + redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { @@ -17358,8 +17387,8 @@ const { makePolicyContainer } = __nccwpck_require__(3640) const { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -17664,7 +17693,7 @@ class Request { throw TypeError(`'${init.method}' is not a valid HTTP method.`) } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + if (forbiddenMethodsSet.has(method.toUpperCase())) { throw TypeError(`'${init.method}' HTTP method is unsupported.`) } @@ -17749,7 +17778,7 @@ class Request { 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)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) @@ -18311,7 +18340,7 @@ const { isomorphicEncode } = __nccwpck_require__(3640) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(9602) @@ -18325,6 +18354,7 @@ const assert = __nccwpck_require__(9491) const { types } = __nccwpck_require__(3837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { @@ -18354,7 +18384,7 @@ class Response { } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = new TextEncoder('utf-8').encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) @@ -18399,7 +18429,7 @@ class Response { } // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } @@ -18897,7 +18927,7 @@ module.exports = { "use strict"; -const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(9602) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(9602) const { getGlobalOrigin } = __nccwpck_require__(3913) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(5499) @@ -18926,7 +18956,7 @@ function responseURL (response) { // 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)) { + if (!redirectStatusSet.has(response.status)) { return null } @@ -18961,7 +18991,7 @@ function requestBadPort (request) { // 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)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } @@ -19103,7 +19133,7 @@ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 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)) { + if (referrerPolicyTokens.has(token)) { policy = token break } @@ -27186,9 +27216,9 @@ async function getOcamlformatVersion() { async function installOcamlformat(version) { - core.startGroup("Install ocamlformat"); - await (0,exec.exec)("opam", ["depext", "--install", `ocamlformat=${version}`]); - core.endGroup(); + await core.group("Install ocamlformat", async () => { + await (0,exec.exec)("opam", ["depext", "--install", `ocamlformat=${version}`]); + }); } ;// CONCATENATED MODULE: ./src/index.ts diff --git a/lint-opam/dist/index.js b/lint-opam/dist/index.js index 833d029a..e712d59c 100644 --- a/lint-opam/dist/index.js +++ b/lint-opam/dist/index.js @@ -11544,6 +11544,14 @@ class Request { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } } onConnect (abort) { @@ -12597,6 +12605,8 @@ let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { @@ -12620,7 +12630,7 @@ function extractBody (object, keepalive = false) { stream = new ReadableStream({ async pull (controller) { controller.enqueue( - typeof source === 'string' ? new TextEncoder().encode(source) : source + typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, @@ -12690,7 +12700,6 @@ function extractBody (object, keepalive = false) { // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. - const enc = new TextEncoder() const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 @@ -12698,13 +12707,13 @@ function extractBody (object, keepalive = false) { for (const [name, value] of object) { if (typeof value === 'string') { - const chunk = enc.encode(prefix + + const chunk = textEncoder.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))}"` + + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' @@ -12718,7 +12727,7 @@ function extractBody (object, keepalive = false) { } } - const chunk = enc.encode(`--${boundary}--`) + const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { @@ -13014,14 +13023,16 @@ function bodyMixinMethods (instance) { 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 }) + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = 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 += streamingDecoder.decode(chunk, { stream: true }) } - text += textDecoder.decode() + text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. @@ -13136,7 +13147,7 @@ function utf8DecodeBytes (buffer) { // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". - const output = new TextDecoder().decode(buffer) + const output = textDecoder.decode(buffer) // 4. Return output. return output @@ -13184,10 +13195,12 @@ module.exports = { const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ @@ -13199,6 +13212,8 @@ const badPorts = [ '10080' ] +const badPortsSet = new Set(badPorts) + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', @@ -13211,10 +13226,12 @@ const referrerPolicy = [ 'strict-origin-when-cross-origin', 'unsafe-url' ] +const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] @@ -13249,6 +13266,7 @@ const requestDuplex = [ // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', @@ -13264,6 +13282,7 @@ const subresource = [ 'xslt', '' ] +const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { @@ -13313,7 +13332,14 @@ module.exports = { nullBodyStatus, safeMethods, badPorts, - requestDuplex + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } @@ -13969,6 +13995,7 @@ const { isBlobLike } = __nccwpck_require__(3640) const { webidl } = __nccwpck_require__(5989) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(8093) const { kEnumerableProperty } = __nccwpck_require__(5499) +const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { @@ -14242,7 +14269,7 @@ function processBlobParts (parts, options) { } // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(new TextEncoder().encode(s)) + bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) @@ -15240,11 +15267,11 @@ const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(8246) const assert = __nccwpck_require__(9491) const { safelyExtractBody } = __nccwpck_require__(2256) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, - safeMethods, + safeMethodsSet, requestBodyHeader, - subresource, + subresourceSet, DOMException } = __nccwpck_require__(9602) const { kHeadersList } = __nccwpck_require__(5574) @@ -15256,6 +15283,7 @@ const { TransformStream } = __nccwpck_require__(5356) const { getGlobalDispatcher } = __nccwpck_require__(5377) const { webidl } = __nccwpck_require__(5989) const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -15315,7 +15343,7 @@ class Fetch extends EE { } // https://fetch.spec.whatwg.org/#fetch-method -async function fetch (input, init = {}) { +function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. @@ -15398,7 +15426,7 @@ async function fetch (input, init = {}) { const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { - return + return Promise.resolve() } // 2. If response’s aborted flag is set, then: @@ -15411,7 +15439,7 @@ async function fetch (input, init = {}) { // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) - return + return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError @@ -15420,7 +15448,7 @@ async function fetch (input, init = {}) { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) - return + return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, @@ -15703,7 +15731,7 @@ function fetching ({ } // 15. If request is a subresource request, then: - if (subresource.includes(request.destination)) { + if (subresourceSet.has(request.destination)) { // TODO } @@ -15970,13 +15998,13 @@ async function mainFetch (fetchParams, recursive = false) { // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams -async function schemeFetch (fetchParams) { +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) + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. @@ -15992,7 +16020,7 @@ async function schemeFetch (fetchParams) { // and body is the empty byte sequence as a body. // Otherwise, return a network error. - return makeNetworkError('about scheme is not supported') + return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { @@ -16005,7 +16033,7 @@ async function schemeFetch (fetchParams) { // 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.') + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) @@ -16013,7 +16041,7 @@ async function schemeFetch (fetchParams) { // 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') + return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. @@ -16040,7 +16068,7 @@ async function schemeFetch (fetchParams) { response.body = body - return response + return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the @@ -16051,7 +16079,7 @@ async function schemeFetch (fetchParams) { // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { - return makeNetworkError('failed to fetch the data URL') + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. @@ -16060,28 +16088,28 @@ async function schemeFetch (fetchParams) { // 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({ + return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] - }) + })) } 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...') + return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) + return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { - return makeNetworkError('unknown scheme') + return Promise.resolve(makeNetworkError('unknown scheme')) } } } @@ -16100,7 +16128,7 @@ function finalizeResponse (fetchParams, response) { } // https://fetch.spec.whatwg.org/#fetch-finale -async function fetchFinale (fetchParams, response) { +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] ». @@ -16184,8 +16212,9 @@ async function fetchFinale (fetchParams, response) { } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. - await fullyReadBody(response.body, processBody, processBodyError) + return fullyReadBody(response.body, processBody, processBodyError) } + return Promise.resolve() } } @@ -16256,7 +16285,7 @@ async function httpFetch (fetchParams) { } // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatus.includes(actualResponse.status)) { + if (redirectStatusSet.has(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. @@ -16293,7 +16322,7 @@ async function httpFetch (fetchParams) { } // https://fetch.spec.whatwg.org/#http-redirect-fetch -async function httpRedirectFetch (fetchParams, response) { +function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request @@ -16319,18 +16348,18 @@ async function httpRedirectFetch (fetchParams, response) { } } catch (err) { // 5. If locationURL is failure, then return a network error. - return makeNetworkError(err) + return Promise.resolve(makeNetworkError(err)) } // 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') + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { - return makeNetworkError('redirect count exceeded') + return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. @@ -16344,7 +16373,7 @@ async function httpRedirectFetch (fetchParams, response) { (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { - return makeNetworkError('cross origin not allowed for request mode "cors"') + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes @@ -16353,9 +16382,9 @@ async function httpRedirectFetch (fetchParams, response) { request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { - return makeNetworkError( + return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' - ) + )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, @@ -16365,7 +16394,7 @@ async function httpRedirectFetch (fetchParams, response) { request.body != null && request.body.source == null ) { - return makeNetworkError() + return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true @@ -16374,7 +16403,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEAD'].includes(request.method)) + !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. @@ -16658,7 +16687,7 @@ async function httpNetworkOrCacheFetch ( // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( - !safeMethods.includes(httpRequest.method) && + !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { @@ -17218,7 +17247,7 @@ async function httpNetworkFetch ( const willFollow = request.redirect === 'follow' && location && - redirectStatus.includes(status) + redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { @@ -17358,8 +17387,8 @@ const { makePolicyContainer } = __nccwpck_require__(3640) const { - forbiddenMethods, - corsSafeListedMethods, + forbiddenMethodsSet, + corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, @@ -17664,7 +17693,7 @@ class Request { throw TypeError(`'${init.method}' is not a valid HTTP method.`) } - if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + if (forbiddenMethodsSet.has(method.toUpperCase())) { throw TypeError(`'${init.method}' HTTP method is unsupported.`) } @@ -17749,7 +17778,7 @@ class Request { 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)) { + if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) @@ -18311,7 +18340,7 @@ const { isomorphicEncode } = __nccwpck_require__(3640) const { - redirectStatus, + redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(9602) @@ -18325,6 +18354,7 @@ const assert = __nccwpck_require__(9491) const { types } = __nccwpck_require__(3837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { @@ -18354,7 +18384,7 @@ class Response { } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = new TextEncoder('utf-8').encode( + const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) @@ -18399,7 +18429,7 @@ class Response { } // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatus.includes(status)) { + if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } @@ -18897,7 +18927,7 @@ module.exports = { "use strict"; -const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = __nccwpck_require__(9602) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(9602) const { getGlobalOrigin } = __nccwpck_require__(3913) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(5499) @@ -18926,7 +18956,7 @@ function responseURL (response) { // 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)) { + if (!redirectStatusSet.has(response.status)) { return null } @@ -18961,7 +18991,7 @@ function requestBadPort (request) { // 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)) { + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } @@ -19103,7 +19133,7 @@ function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // 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)) { + if (referrerPolicyTokens.has(token)) { policy = token break } @@ -27149,20 +27179,20 @@ async function opamDuneLint() { async function installOpamPackages() { - core.startGroup("Install opam packages"); - await (0,exec.exec)("opam", [ - "install", - ".", - "--deps-only", - "--with-test", - "--with-doc", - ]); - core.endGroup(); + await core.group("Install opam packages", async () => { + await (0,exec.exec)("opam", [ + "install", + ".", + "--deps-only", + "--with-test", + "--with-doc", + ]); + }); } async function installOpamDuneLint() { - core.startGroup("Install opam-dune-lint"); - await (0,exec.exec)("opam", ["depext", "--install", "opam-dune-lint"]); - core.endGroup(); + await core.group("Install opam-dune-lint", async () => { + await (0,exec.exec)("opam", ["depext", "--install", "opam-dune-lint"]); + }); } ;// CONCATENATED MODULE: ./src/index.ts diff --git a/packages/lint-doc/src/opam.ts b/packages/lint-doc/src/opam.ts index 15eef6de..63b9c447 100644 --- a/packages/lint-doc/src/opam.ts +++ b/packages/lint-doc/src/opam.ts @@ -2,13 +2,19 @@ import * as core from "@actions/core"; import { exec } from "@actions/exec"; export async function installOpamPackages() { - core.startGroup("Install opam packages"); - await exec("opam", ["install", ".", "--deps-only", "--with-doc"]); - core.endGroup(); + await core.group("Install opam packages", async () => { + await exec("opam", ["install", ".", "--deps-only", "--with-doc"]); + }); } export async function installOdoc() { - core.startGroup("Install odoc"); - await exec("opam", ["depext", "--install", "conf-m4", "dune", "odoc>=1.5.0"]); - core.endGroup(); + await core.group("Install odoc", async () => { + await exec("opam", [ + "depext", + "--install", + "conf-m4", + "dune", + "odoc>=1.5.0", + ]); + }); } diff --git a/packages/lint-fmt/src/opam.ts b/packages/lint-fmt/src/opam.ts index 91bca85f..4572ec21 100644 --- a/packages/lint-fmt/src/opam.ts +++ b/packages/lint-fmt/src/opam.ts @@ -2,7 +2,7 @@ import * as core from "@actions/core"; import { exec } from "@actions/exec"; export async function installOcamlformat(version: string) { - core.startGroup("Install ocamlformat"); - await exec("opam", ["depext", "--install", `ocamlformat=${version}`]); - core.endGroup(); + await core.group("Install ocamlformat", async () => { + await exec("opam", ["depext", "--install", `ocamlformat=${version}`]); + }); } diff --git a/packages/lint-opam/src/opam.ts b/packages/lint-opam/src/opam.ts index 9266334b..55725c1d 100644 --- a/packages/lint-opam/src/opam.ts +++ b/packages/lint-opam/src/opam.ts @@ -2,19 +2,19 @@ import * as core from "@actions/core"; import { exec } from "@actions/exec"; export async function installOpamPackages() { - core.startGroup("Install opam packages"); - await exec("opam", [ - "install", - ".", - "--deps-only", - "--with-test", - "--with-doc", - ]); - core.endGroup(); + await core.group("Install opam packages", async () => { + await exec("opam", [ + "install", + ".", + "--deps-only", + "--with-test", + "--with-doc", + ]); + }); } export async function installOpamDuneLint() { - core.startGroup("Install opam-dune-lint"); - await exec("opam", ["depext", "--install", "opam-dune-lint"]); - core.endGroup(); + await core.group("Install opam-dune-lint", async () => { + await exec("opam", ["depext", "--install", "opam-dune-lint"]); + }); } diff --git a/packages/setup-ocaml/src/cache.ts b/packages/setup-ocaml/src/cache.ts index 8e4bd3a1..28e9b0d7 100644 --- a/packages/setup-ocaml/src/cache.ts +++ b/packages/setup-ocaml/src/cache.ts @@ -220,75 +220,75 @@ async function saveCache(key: string, paths: string[]) { } export async function restoreCygwinCache() { - core.startGroup("Retrieve the Cygwin cache"); - const { key, restoreKeys } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await restoreCache(key, restoreKeys, paths); - core.endGroup(); + await core.group("Retrieve the Cygwin cache", async () => { + const { key, restoreKeys } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } export async function saveCygwinCache() { - core.startGroup("Save the Cygwin cache"); - const { key } = await composeCygwinCacheKeys(); - const paths = composeCygwinCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the Cygwin cache", async () => { + const { key } = await composeCygwinCacheKeys(); + const paths = composeCygwinCachePaths(); + await saveCache(key, paths); + }); } export async function restoreDuneCache() { - core.startGroup("Retrieve the dune cache"); - const { key, restoreKeys } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await restoreCache(key, restoreKeys, paths); - core.endGroup(); + await core.group("Retrieve the dune cache", async () => { + const { key, restoreKeys } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await restoreCache(key, restoreKeys, paths); + }); } export async function saveDuneCache() { - core.startGroup("Save the dune cache"); - const { key } = composeDuneCacheKeys(); - const paths = composeDuneCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the dune cache", async () => { + const { key } = composeDuneCacheKeys(); + const paths = composeDuneCachePaths(); + await saveCache(key, paths); + }); } export async function restoreOpamCache() { - core.startGroup("Retrieve the opam cache"); - const { key, restoreKeys } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - core.endGroup(); - return cacheKey; + return await core.group("Retrieve the opam cache", async () => { + const { key, restoreKeys } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } export async function saveOpamCache() { - core.startGroup("Save the opam cache"); - await exec("opam", [ - "clean", - "--all-switches", - "--download-cache", - "--logs", - "--repo-cache", - "--unused-repositories", - ]); - const { key } = await composeOpamCacheKeys(); - const paths = composeOpamCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the opam cache", async () => { + await exec("opam", [ + "clean", + "--all-switches", + "--download-cache", + "--logs", + "--repo-cache", + "--unused-repositories", + ]); + const { key } = await composeOpamCacheKeys(); + const paths = composeOpamCachePaths(); + await saveCache(key, paths); + }); } export async function restoreOpamDownloadCache() { - core.startGroup("Retrieve the opam download cache"); - const { key, restoreKeys } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - const cacheKey = await restoreCache(key, restoreKeys, paths); - core.endGroup(); - return cacheKey; + return await core.group("Retrieve the opam download cache", async () => { + const { key, restoreKeys } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + const cacheKey = await restoreCache(key, restoreKeys, paths); + return cacheKey; + }); } export async function saveOpamDownloadCache() { - core.startGroup("Save the opam download cache"); - const { key } = composeOpamDownloadCacheKeys(); - const paths = composeOpamDownloadCachePaths(); - await saveCache(key, paths); - core.endGroup(); + await core.group("Save the opam download cache", async () => { + const { key } = composeOpamDownloadCacheKeys(); + const paths = composeOpamDownloadCachePaths(); + await saveCache(key, paths); + }); } diff --git a/packages/setup-ocaml/src/depext.ts b/packages/setup-ocaml/src/depext.ts index 850c6bbd..094ae89d 100644 --- a/packages/setup-ocaml/src/depext.ts +++ b/packages/setup-ocaml/src/depext.ts @@ -7,26 +7,31 @@ import { OPAM_DEPEXT_FLAGS, Platform } from "./constants"; import { getPlatform } from "./system"; export async function installDepext(ocamlVersion: string) { - core.startGroup("Install depext"); - const platform = getPlatform(); - const depextCygwinports = - platform === Platform.Win32 ? ["depext-cygwinports"] : []; - await exec("opam", ["install", "opam-depext", ...depextCygwinports]); - if (platform === Platform.Win32) { - let base = ""; - if (ocamlVersion.includes("mingw64")) { - base = "x86_64-w64-mingw32"; - } else if (ocamlVersion.includes("mingw32")) { - base = "i686-w64-mingw32"; + await core.group("Install depext", async () => { + const platform = getPlatform(); + const depextCygwinports = + platform === Platform.Win32 ? ["depext-cygwinports"] : []; + await exec("opam", ["install", "opam-depext", ...depextCygwinports]); + if (platform === Platform.Win32) { + let base = ""; + if (ocamlVersion.includes("mingw64")) { + base = "x86_64-w64-mingw32"; + } else if (ocamlVersion.includes("mingw32")) { + base = "i686-w64-mingw32"; + } + core.addPath( + path.posix.join("/", "usr", base, "sys-root", "mingw", "bin"), + ); } - core.addPath(path.posix.join("/", "usr", base, "sys-root", "mingw", "bin")); - } - core.endGroup(); + }); } export async function installDepextPackages(fpaths: string[]) { - core.startGroup("Install system packages required by opam packages"); - const fnames = fpaths.map((fpath) => path.basename(fpath, ".opam")); - await exec("opam", ["depext", ...fnames, ...OPAM_DEPEXT_FLAGS]); - core.endGroup(); + await core.group( + "Install system packages required by opam packages", + async () => { + const fnames = fpaths.map((fpath) => path.basename(fpath, ".opam")); + await exec("opam", ["depext", ...fnames, ...OPAM_DEPEXT_FLAGS]); + }, + ); } diff --git a/packages/setup-ocaml/src/dune.ts b/packages/setup-ocaml/src/dune.ts index 987bc0b4..8fb28e9e 100644 --- a/packages/setup-ocaml/src/dune.ts +++ b/packages/setup-ocaml/src/dune.ts @@ -10,30 +10,33 @@ const { } = github.context; export async function installDune() { - core.startGroup("Install dune"); - await exec("opam", ["depext", "--install", "dune"]); - core.endGroup(); + await core.group("Install dune", async () => { + await exec("opam", ["depext", "--install", "dune"]); + }); } export async function trimDuneCache() { - core.startGroup("Remove oldest files from the dune cache to free space"); - const octokit = github.getOctokit(GITHUB_TOKEN); - const { - data: { total_count: totalCount }, - } = await octokit.rest.actions.listJobsForWorkflowRun({ - owner, - repo, - run_id, - }); - const cacheSize = Math.floor(5000 / totalCount); - await exec("opam", [ - "exec", - "--", - "dune", - "cache", - "trim", - "--size", - `${cacheSize}MB`, - ]); - core.endGroup(); + await core.group( + "Remove oldest files from the dune cache to free space", + async () => { + const octokit = github.getOctokit(GITHUB_TOKEN); + const { + data: { total_count: totalCount }, + } = await octokit.rest.actions.listJobsForWorkflowRun({ + owner, + repo, + run_id, + }); + const cacheSize = Math.floor(5000 / totalCount); + await exec("opam", [ + "exec", + "--", + "dune", + "cache", + "trim", + "--size", + `${cacheSize}MB`, + ]); + }, + ); } diff --git a/packages/setup-ocaml/src/installer.ts b/packages/setup-ocaml/src/installer.ts index e3f57fd1..8997762a 100644 --- a/packages/setup-ocaml/src/installer.ts +++ b/packages/setup-ocaml/src/installer.ts @@ -54,18 +54,18 @@ export async function installer() { core.exportVariable("OPAMROOT", opamRoot); } if (platform === Platform.Win32) { - core.startGroup("Change the file system behavior parameters"); - await exec("fsutil", ["behavior", "query", "SymlinkEvaluation"]); - // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-behavior - await exec("fsutil", [ - "behavior", - "set", - "symlinkEvaluation", - "R2L:1", - "R2R:1", - ]); - await exec("fsutil", ["behavior", "query", "SymlinkEvaluation"]); - core.endGroup(); + await core.group("Change the file system behavior parameters", async () => { + await exec("fsutil", ["behavior", "query", "SymlinkEvaluation"]); + // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil-behavior + await exec("fsutil", [ + "behavior", + "set", + "symlinkEvaluation", + "R2L:1", + "R2R:1", + ]); + await exec("fsutil", ["behavior", "query", "SymlinkEvaluation"]); + }); } if (platform === Platform.Win32) { core.exportVariable("HOME", process.env["USERPROFILE"]); diff --git a/packages/setup-ocaml/src/opam.ts b/packages/setup-ocaml/src/opam.ts index d42e7c15..fa51eff0 100644 --- a/packages/setup-ocaml/src/opam.ts +++ b/packages/setup-ocaml/src/opam.ts @@ -157,12 +157,12 @@ async function initializeOpamUnix() { } async function setupOpamUnix() { - core.startGroup("Install opam"); - await acquireOpamUnix(); - core.endGroup(); - core.startGroup("Initialise the opam state"); - await initializeOpamUnix(); - core.endGroup(); + await core.group("Install opam", async () => { + await acquireOpamUnix(); + }); + await core.group("Initialise the opam state", async () => { + await initializeOpamUnix(); + }); } async function setupCygwin() { @@ -252,25 +252,25 @@ async function initializeOpamWindows() { } async function setupOpamWindows() { - core.startGroup("Prepare the Cygwin environment"); - core.exportVariable("CYGWIN", "winsymlinks:native"); - core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); - core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); - core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); - core.addPath(CYGWIN_ROOT_WRAPPERBIN); - await setupCygwin(); - core.endGroup(); + await core.group("Prepare the Cygwin environment", async () => { + core.exportVariable("CYGWIN", "winsymlinks:native"); + core.exportVariable("CYGWIN_ROOT", CYGWIN_ROOT); + core.exportVariable("CYGWIN_ROOT_BIN", CYGWIN_ROOT_BIN); + core.exportVariable("CYGWIN_ROOT_WRAPPERBIN", CYGWIN_ROOT_WRAPPERBIN); + core.addPath(CYGWIN_ROOT_WRAPPERBIN); + await setupCygwin(); + }); await saveCygwinCache(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const originalPath = process.env["PATH"]!.split(path.delimiter); const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; process.env["PATH"] = patchedPath.join(path.delimiter); - core.startGroup("Install opam"); - await acquireOpamWindows(); - core.endGroup(); - core.startGroup("Initialise the opam state"); - await initializeOpamWindows(); - core.endGroup(); + await core.group("Install opam", async () => { + await acquireOpamWindows(); + }); + await core.group("Initialise the opam state", async () => { + await initializeOpamWindows(); + }); process.env["PATH"] = originalPath.join(path.delimiter); } @@ -284,46 +284,46 @@ export async function setupOpam() { } export async function installOcaml(ocamlCompiler: string) { - core.startGroup("Install OCaml"); - const platform = getPlatform(); - if (platform === Platform.Win32) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalPath = process.env["PATH"]!.split(path.delimiter); - const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; - process.env["PATH"] = patchedPath.join(path.delimiter); - await exec("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - process.env["PATH"] = originalPath.join(path.delimiter); - } else { - await exec("opam", [ - "switch", - "create", - ".", - "--no-install", - "--packages", - ocamlCompiler, - ]); - } - core.endGroup(); + await core.group("Install OCaml", async () => { + const platform = getPlatform(); + if (platform === Platform.Win32) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalPath = process.env["PATH"]!.split(path.delimiter); + const patchedPath = [CYGWIN_ROOT_BIN, ...originalPath]; + process.env["PATH"] = patchedPath.join(path.delimiter); + await exec("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + process.env["PATH"] = originalPath.join(path.delimiter); + } else { + await exec("opam", [ + "switch", + "create", + ".", + "--no-install", + "--packages", + ocamlCompiler, + ]); + } + }); } export async function pin(fpaths: string[]) { - core.startGroup("Pin local packages"); - const opam = await findOpam(); - for (const fpath of fpaths) { - const fname = path.basename(fpath, ".opam"); - const dname = path.dirname(fpath); - await exec(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { - cwd: dname, - }); - } - core.endGroup(); + await core.group("Pin local packages", async () => { + const opam = await findOpam(); + for (const fpath of fpaths) { + const fname = path.basename(fpath, ".opam"); + const dname = path.dirname(fpath); + await exec(opam, ["pin", "add", `${fname}.dev`, ".", "--no-action"], { + cwd: dname, + }); + } + }); } async function repositoryAdd(name: string, address: string) { @@ -339,42 +339,42 @@ async function repositoryAdd(name: string, address: string) { } export async function repositoryAddAll(repositories: [string, string][]) { - const platform = getPlatform(); - let restore_autocrlf; - core.startGroup("Initialise the opam repositories"); - // Works around the lack of https://github.com/ocaml/opam/pull/3882 when - // adding ocaml/opam-repository on Windows. Can be removed when the action - // switches to opam 2.2 - if (platform === Platform.Win32) { - const autocrlf = await getExecOutput( - "git", - ["config", "--global", "core.autocrlf"], - { ignoreReturnCode: true }, - ); - if (autocrlf.stdout.trim() !== "input") { - if (autocrlf.exitCode === 0) { - restore_autocrlf = autocrlf.stdout.trim(); - } else { - // eslint-disable-next-line unicorn/no-null - restore_autocrlf = null; // Unset the value at the end + await core.group("Initialise the opam repositories", async () => { + const platform = getPlatform(); + let restore_autocrlf; + // Works around the lack of https://github.com/ocaml/opam/pull/3882 when + // adding ocaml/opam-repository on Windows. Can be removed when the action + // switches to opam 2.2 + if (platform === Platform.Win32) { + const autocrlf = await getExecOutput( + "git", + ["config", "--global", "core.autocrlf"], + { ignoreReturnCode: true }, + ); + if (autocrlf.stdout.trim() !== "input") { + if (autocrlf.exitCode === 0) { + restore_autocrlf = autocrlf.stdout.trim(); + } else { + // eslint-disable-next-line unicorn/no-null + restore_autocrlf = null; // Unset the value at the end + } } + await exec("git", ["config", "--global", "core.autocrlf", "input"]); } - await exec("git", ["config", "--global", "core.autocrlf", "input"]); - } - for (const [name, address] of repositories) { - await repositoryAdd(name, address); - } - if (restore_autocrlf === null) { - await exec("git", ["config", "--global", "--unset", "core.autocrlf"]); - } else if (restore_autocrlf !== undefined) { - await exec("git", [ - "config", - "--global", - "core.autocrlf", - restore_autocrlf, - ]); - } - core.endGroup(); + for (const [name, address] of repositories) { + await repositoryAdd(name, address); + } + if (restore_autocrlf === null) { + await exec("git", ["config", "--global", "--unset", "core.autocrlf"]); + } else if (restore_autocrlf !== undefined) { + await exec("git", [ + "config", + "--global", + "core.autocrlf", + restore_autocrlf, + ]); + } + }); } async function repositoryRemove(name: string) { @@ -400,10 +400,10 @@ async function repositoryList() { } export async function repositoryRemoveAll() { - core.startGroup("Remove the opam repositories"); - const repositories = await repositoryList(); - for (const repository of repositories) { - await repositoryRemove(repository); - } - core.endGroup(); + await core.group("Remove the opam repositories", async () => { + const repositories = await repositoryList(); + for (const repository of repositories) { + await repositoryRemove(repository); + } + }); }