diff --git a/.github/workflows/test-upgrade-deps.yml b/.github/workflows/test-upgrade-deps.yml index ea6e152..1243856 100644 --- a/.github/workflows/test-upgrade-deps.yml +++ b/.github/workflows/test-upgrade-deps.yml @@ -18,7 +18,7 @@ jobs: - name: test uses: ./actions/upgrade-deps with: - token: test + token: ${{ github.token }} dry-run: true repo: tdesign-vue owner: Tencent @@ -37,7 +37,7 @@ jobs: - name: test uses: ./actions/upgrade-deps with: - token: test + token: ${{ github.token }} dry-run: true repo: tdesign-vue-next owner: Tencent @@ -47,6 +47,44 @@ jobs: @tdesign/site-components @tdesign/theme-generator + tdesign-icons-vue-next: + name: tdesign-icons-vue-next + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: 22 + + - name: test + uses: ./actions/upgrade-deps + with: + token: ${{ github.token }} + dry-run: true + repo: tdesign-vue-next + owner: Tencent + package-manager: pnpm + deps: tdesign-icons-vue-next + + tdesign: + name: tdesign + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + + - name: test + uses: ./actions/upgrade-deps + with: + token: ${{ github.token }} + dry-run: true + repo: tdesign + owner: Tencent + package-manager: pnpm + deps: tdesign-icons-view + # tdesign-flutter: # name: tdesign-flutter # runs-on: ubuntu-latest diff --git a/actions/upgrade-deps/action.yml b/actions/upgrade-deps/action.yml index e1ae380..b50b2b9 100644 --- a/actions/upgrade-deps/action.yml +++ b/actions/upgrade-deps/action.yml @@ -1,5 +1,5 @@ name: Upgrade Dependencies -description: Upgrade dependencies to specified versions +description: Upgrade dependencies to their latest versions inputs: token: @@ -20,14 +20,14 @@ inputs: required: false default: npm deps: - description: Dependencies to upgrade in format "package1@version1 package2@version2" + description: Package names to upgrade, separated by spaces or newlines required: true target-dir: description: Target directory to upgrade dependencies required: false default: '' title: - description: "Custom PR title (optional, defaults to 'chore(deps): upgrade ...')" + description: "Custom PR title (optional, defaults to 'chore: upgrade ...')" required: false default: '' diff --git a/actions/upgrade-deps/dist/index.mjs b/actions/upgrade-deps/dist/index.mjs index f208490..588caeb 100644 --- a/actions/upgrade-deps/dist/index.mjs +++ b/actions/upgrade-deps/dist/index.mjs @@ -8,7 +8,9 @@ import * as events from "events"; import { StringDecoder } from "string_decoder"; import * as child from "child_process"; import { setTimeout as setTimeout$1 } from "timers"; +import { readFile, realpath, writeFile } from "node:fs/promises"; import * as path from "node:path"; +import { env } from "node:process"; //#region \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; @@ -413,7 +415,7 @@ var require_symbols$4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { })); //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/core/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => { +var require_errors$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const kUndiciError = Symbol.for("undici.error.UND_ERR"); var UndiciError = class extends Error { constructor(message) { @@ -988,7 +990,7 @@ var require_util$7 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const nodeUtil$3 = __require("node:util"); const { stringify } = __require("node:querystring"); const { EventEmitter: EE$2 } = __require("node:events"); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const { headerNameLowerCasedRecord } = require_constants$4(); const { tree } = require_tree(); const [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v) => Number(v)); @@ -1530,7 +1532,7 @@ var require_diagnostics = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/core/request.js var require_request$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { InvalidArgumentError, NotSupportedError } = require_errors(); + const { InvalidArgumentError, NotSupportedError } = require_errors$1(); const assert$25 = __require("node:assert"); const { isValidHTTPToken, isValidHeaderValue, isStream, destroy, isBuffer, isFormDataLike, isIterable, isBlobLike, buildURL, validateHandler, getServerName, normalizedMethodRecords } = require_util$7(); const { channels } = require_diagnostics(); @@ -1793,7 +1795,7 @@ var require_dispatcher = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/dispatcher/dispatcher-base.js var require_dispatcher_base = /* @__PURE__ */ __commonJSMin(((exports, module) => { const Dispatcher = require_dispatcher(); - const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = require_errors(); + const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = require_errors$1(); const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require_symbols$4(); const kOnDestroyed = Symbol("onDestroyed"); const kOnClosed = Symbol("onClosed"); @@ -2247,7 +2249,7 @@ var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => { const net$1 = __require("node:net"); const assert$24 = __require("node:assert"); const util = require_util$7(); - const { InvalidArgumentError, ConnectTimeoutError } = require_errors(); + const { InvalidArgumentError, ConnectTimeoutError } = require_errors$1(); const timers = require_timers(); function noop() {} let tls; @@ -5156,7 +5158,7 @@ var require_client_h1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const util = require_util$7(); const { channels } = require_diagnostics(); const timers = require_timers(); - const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = require_errors(); + const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = require_errors$1(); const { kUrl, kReset, kClient, kParser, kBlocking, kRunning, kPending, kSize, kWriting, kQueue, kNoRef, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kSocket, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kMaxRequests, kCounter, kMaxResponseSize, kOnError, kResume, kHTTPContext } = require_symbols$4(); const constants = require_constants$3(); const EMPTY_BUF = Buffer.alloc(0); @@ -5929,7 +5931,7 @@ var require_client_h2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$18 = __require("node:assert"); const { pipeline: pipeline$2 } = __require("node:stream"); const util = require_util$7(); - const { RequestContentLengthMismatchError, RequestAbortedError, SocketError, InformationalError } = require_errors(); + const { RequestContentLengthMismatchError, RequestAbortedError, SocketError, InformationalError } = require_errors$1(); const { kUrl, kReset, kClient, kRunning, kPending, kQueue, kPendingIdx, kRunningIdx, kError, kSocket, kStrictContentLength, kOnError, kMaxConcurrentStreams, kHTTP2Session, kResume, kSize, kHTTPContext } = require_symbols$4(); const kOpenStreams = Symbol("open streams"); let extractBody; @@ -6315,7 +6317,7 @@ var require_redirect_handler = /* @__PURE__ */ __commonJSMin(((exports, module) const util = require_util$7(); const { kBodyUsed } = require_symbols$4(); const assert$17 = __require("node:assert"); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const EE$1 = __require("node:events"); const redirectableStatusCodes = [ 300, @@ -6465,7 +6467,7 @@ var require_client = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { channels } = require_diagnostics(); const Request = require_request$1(); const DispatcherBase = require_dispatcher_base(); - const { InvalidArgumentError, InformationalError, ClientDestroyedError } = require_errors(); + const { InvalidArgumentError, InformationalError, ClientDestroyedError } = require_errors$1(); const buildConnector = require_connect(); const { kUrl, kServerName, kClient, kBusy, kConnect, kResuming, kRunning, kPending, kSize, kQueue, kConnected, kConnecting, kNeedDrain, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector, kMaxRedirections, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, kInterceptors, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, kResume } = require_symbols$4(); const connectH1 = require_client_h1(); @@ -7009,7 +7011,7 @@ var require_pool_base = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { PoolBase, kClients, kNeedDrain, kAddClient, kGetDispatcher } = require_pool_base(); const Client = require_client(); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const util = require_util$7(); const { kUrl, kInterceptors } = require_symbols$4(); const buildConnector = require_connect(); @@ -7068,7 +7070,7 @@ var require_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/dispatcher/balanced-pool.js var require_balanced_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = require_errors(); + const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = require_errors$1(); const { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } = require_pool_base(); const Pool = require_pool(); const { kUrl, kInterceptors } = require_symbols$4(); @@ -7179,7 +7181,7 @@ var require_balanced_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/dispatcher/agent.js var require_agent = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols$4(); const DispatcherBase = require_dispatcher_base(); const Pool = require_pool(); @@ -7264,7 +7266,7 @@ var require_proxy_agent = /* @__PURE__ */ __commonJSMin(((exports, module) => { const Agent = require_agent(); const Pool = require_pool(); const DispatcherBase = require_dispatcher_base(); - const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors(); + const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors$1(); const buildConnector = require_connect(); const Client = require_client(); const kAgent = Symbol("proxy agent"); @@ -7559,7 +7561,7 @@ var require_env_http_proxy_agent = /* @__PURE__ */ __commonJSMin(((exports, modu var require_retry_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$15 = __require("node:assert"); const { kRetryHandlerDefaultRetry } = require_symbols$4(); - const { RequestRetryError } = require_errors(); + const { RequestRetryError } = require_errors$1(); const { isDisturbed, parseHeaders, parseRangeHeader, wrapRequestBody } = require_util$7(); function calculateRetryAfterHeader(retryAfter) { const current = Date.now(); @@ -7813,7 +7815,7 @@ var require_retry_agent = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_readable = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$14 = __require("node:assert"); const { Readable: Readable$2 } = __require("node:stream"); - const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors(); + const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors$1(); const util = require_util$7(); const { ReadableStreamFrom } = require_util$7(); const kConsume = Symbol("kConsume"); @@ -8040,7 +8042,7 @@ var require_readable = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/api/util.js var require_util$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$13 = __require("node:assert"); - const { ResponseStatusCodeError } = require_errors(); + const { ResponseStatusCodeError } = require_errors$1(); const { chunksDecode } = require_readable(); const CHUNK_LIMIT = 128 * 1024; async function getResolveErrorBodyCallback({ callback, body, contentType, statusCode, statusMessage, headers }) { @@ -8094,7 +8096,7 @@ var require_util$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_api_request = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$12 = __require("node:assert"); const { Readable } = require_readable(); - const { InvalidArgumentError, RequestAbortedError } = require_errors(); + const { InvalidArgumentError, RequestAbortedError } = require_errors$1(); const util = require_util$7(); const { getResolveErrorBodyCallback } = require_util$5(); const { AsyncResource: AsyncResource$4 } = __require("node:async_hooks"); @@ -8245,7 +8247,7 @@ var require_api_request = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/api/abort-signal.js var require_abort_signal = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { addAbortListener } = require_util$7(); - const { RequestAbortedError } = require_errors(); + const { RequestAbortedError } = require_errors$1(); const kListener = Symbol("kListener"); const kSignal = Symbol("kSignal"); function abort(self) { @@ -8285,7 +8287,7 @@ var require_abort_signal = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_api_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$11 = __require("node:assert"); const { finished: finished$1, PassThrough: PassThrough$1 } = __require("node:stream"); - const { InvalidArgumentError, InvalidReturnValueError } = require_errors(); + const { InvalidArgumentError, InvalidReturnValueError } = require_errors$1(); const util = require_util$7(); const { getResolveErrorBodyCallback } = require_util$5(); const { AsyncResource: AsyncResource$3 } = __require("node:async_hooks"); @@ -8429,7 +8431,7 @@ var require_api_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/api/api-pipeline.js var require_api_pipeline = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { Readable: Readable$1, Duplex, PassThrough } = __require("node:stream"); - const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = require_errors(); + const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = require_errors$1(); const util = require_util$7(); const { AsyncResource: AsyncResource$2 } = __require("node:async_hooks"); const { addSignal, removeSignal } = require_abort_signal(); @@ -8596,7 +8598,7 @@ var require_api_pipeline = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/api/api-upgrade.js var require_api_upgrade = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { InvalidArgumentError, SocketError } = require_errors(); + const { InvalidArgumentError, SocketError } = require_errors$1(); const { AsyncResource: AsyncResource$1 } = __require("node:async_hooks"); const util = require_util$7(); const { addSignal, removeSignal } = require_abort_signal(); @@ -8677,7 +8679,7 @@ var require_api_upgrade = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_api_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => { const assert$8 = __require("node:assert"); const { AsyncResource } = __require("node:async_hooks"); - const { InvalidArgumentError, SocketError } = require_errors(); + const { InvalidArgumentError, SocketError } = require_errors$1(); const util = require_util$7(); const { addSignal, removeSignal } = require_abort_signal(); var ConnectHandler = class extends AsyncResource { @@ -8762,7 +8764,7 @@ var require_api = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#endregion //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/mock/mock-errors.js var require_mock_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { UndiciError } = require_errors(); + const { UndiciError } = require_errors$1(); const kMockNotMatchedError = Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED"); module.exports = { MockNotMatchedError: class MockNotMatchedError extends UndiciError { constructor(message) { @@ -9048,7 +9050,7 @@ var require_mock_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { var require_mock_interceptor = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { getResponseData, buildKey, addMockDispatch } = require_mock_utils(); const { kDispatches, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch } = require_mock_symbols(); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const { buildURL } = require_util$7(); /** * Defines the scope API for an interceptor reply @@ -9192,7 +9194,7 @@ var require_mock_client = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = require_mock_symbols(); const { MockInterceptor } = require_mock_interceptor(); const Symbols = require_symbols$4(); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); /** * MockClient provides an API that extends the Client to influence the mockDispatches. */ @@ -9235,7 +9237,7 @@ var require_mock_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = require_mock_symbols(); const { MockInterceptor } = require_mock_interceptor(); const Symbols = require_symbols$4(); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); /** * MockPool provides an API that extends the Pool to influence the mockDispatches. */ @@ -9345,7 +9347,7 @@ var require_mock_agent = /* @__PURE__ */ __commonJSMin(((exports, module) => { const MockClient = require_mock_client(); const MockPool = require_mock_pool(); const { matchValue, buildMockOptions } = require_mock_utils(); - const { InvalidArgumentError, UndiciError } = require_errors(); + const { InvalidArgumentError, UndiciError } = require_errors$1(); const Dispatcher = require_dispatcher(); const Pluralizer = require_pluralizer(); const PendingInterceptorsFormatter = require_pending_interceptors_formatter(); @@ -9443,7 +9445,7 @@ ${pendingInterceptorsFormatter.format(pending)} //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/global.js var require_global = /* @__PURE__ */ __commonJSMin(((exports, module) => { const globalDispatcher = Symbol.for("undici.globalDispatcher.1"); - const { InvalidArgumentError } = require_errors(); + const { InvalidArgumentError } = require_errors$1(); const Agent = require_agent(); if (getGlobalDispatcher() === void 0) setGlobalDispatcher(new Agent()); function setGlobalDispatcher(agent) { @@ -9538,7 +9540,7 @@ var require_retry = /* @__PURE__ */ __commonJSMin(((exports, module) => { //#region ../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/lib/interceptor/dump.js var require_dump = /* @__PURE__ */ __commonJSMin(((exports, module) => { const util = require_util$7(); - const { InvalidArgumentError, RequestAbortedError } = require_errors(); + const { InvalidArgumentError, RequestAbortedError } = require_errors$1(); const DecoratorHandler = require_decorator_handler(); var DumpHandler = class extends DecoratorHandler { #maxSize = 1024 * 1024; @@ -9607,7 +9609,7 @@ var require_dns = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { isIP } = __require("node:net"); const { lookup } = __require("node:dns"); const DecoratorHandler = require_decorator_handler(); - const { InvalidArgumentError, InformationalError } = require_errors(); + const { InvalidArgumentError, InformationalError } = require_errors$1(); const maxInt = Math.pow(2, 31) - 1; var DNSInstance = class { #maxTTL = 0; @@ -12069,7 +12071,7 @@ var require_util$4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const { serializeAMimeType, parseMIMEType } = require_data_url(); const { types: types$1 } = __require("node:util"); const { StringDecoder: StringDecoder$1 } = __require("string_decoder"); - const { btoa } = __require("node:buffer"); + const { btoa: btoa$1 } = __require("node:buffer"); /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, @@ -12165,8 +12167,8 @@ var require_util$4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { if (parsed !== "failure") dataURL += serializeAMimeType(parsed); dataURL += ";base64,"; const decoder = new StringDecoder$1("latin1"); - for (const chunk of bytes) dataURL += btoa(decoder.write(chunk)); - dataURL += btoa(decoder.end()); + for (const chunk of bytes) dataURL += btoa$1(decoder.write(chunk)); + dataURL += btoa$1(decoder.end()); return dataURL; } case "Text": { @@ -15505,7 +15507,7 @@ var require_undici = /* @__PURE__ */ __commonJSMin(((exports, module) => { const ProxyAgent = require_proxy_agent(); const EnvHttpProxyAgent = require_env_http_proxy_agent(); const RetryAgent = require_retry_agent(); - const errors = require_errors(); + const errors = require_errors$1(); const util = require_util$7(); const { InvalidArgumentError } = errors; const api = require_api(); @@ -15691,7 +15693,7 @@ var __awaiter$7 = function(thisArg, _arguments, P, generator) { step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -const { access, appendFile, writeFile } = promises; +const { access, appendFile, writeFile: writeFile$1 } = promises; const SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; var Summary = class { constructor() { @@ -15742,7 +15744,7 @@ var Summary = class { return __awaiter$7(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); - yield (overwrite ? writeFile : appendFile)(filePath, this._buffer, { encoding: "utf8" }); + yield (overwrite ? writeFile$1 : appendFile)(filePath, this._buffer, { encoding: "utf8" }); return this.emptyBuffer(); }); } @@ -16672,6 +16674,14 @@ function error(message, properties = {}) { issueCommand("error", toCommandProperties(properties), message instanceof Error ? message.toString() : message); } /** +* Adds a warning issue +* @param message warning issue message. Errors will be converted to string via toString() +* @param properties optional properties to add to the annotation. +*/ +function warning(message, properties = {}) { + issueCommand("warning", toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** * Writes info to log with console.log. * @param message info message */ @@ -17708,7 +17718,7 @@ function expand(template, context) { if (template === "/") return template; else return template.replace(/\/$/, ""); } -function parse(options) { +function parse$2(options) { let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); @@ -17745,7 +17755,7 @@ function parse(options) { }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null); } function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); + return parse$2(merge(defaults, route, options)); } function withDefaults$2(oldDefaults, newDefaults) { const DEFAULTS2 = merge(oldDefaults, newDefaults); @@ -17754,7 +17764,7 @@ function withDefaults$2(oldDefaults, newDefaults) { DEFAULTS: DEFAULTS2, defaults: withDefaults$2.bind(null, DEFAULTS2), merge: merge.bind(null, DEFAULTS2), - parse + parse: parse$2 }); } var endpoint = withDefaults$2(null, DEFAULTS); @@ -20057,83 +20067,8405 @@ var GithubHelper = class { } }; //#endregion -//#region main.ts -const PACKAGE_MANAGER_COMMANDS = { - pnpm: { - cmd: "pnpm", - args: [ - "up", - "-r", - "--latest" - ] - }, - yarn: { - cmd: "yarn", - args: ["upgrade", "--latest"] +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js +/** +* Creates a JSON scanner on the given text. +* If ignoreTrivia is set, whitespaces or comments are ignored. +*/ +function createScanner(text, ignoreTrivia = false) { + const len = text.length; + let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0; + function scanHexDigits(count, exact) { + let digits = 0; + let value = 0; + while (digits < count || !exact) { + let ch = text.charCodeAt(pos); + if (ch >= 48 && ch <= 57) value = value * 16 + ch - 48; + else if (ch >= 65 && ch <= 70) value = value * 16 + ch - 65 + 10; + else if (ch >= 97 && ch <= 102) value = value * 16 + ch - 97 + 10; + else break; + pos++; + digits++; + } + if (digits < count) value = -1; + return value; + } + function setPosition(newPosition) { + pos = newPosition; + value = ""; + tokenOffset = 0; + token = 16; + scanError = 0; + } + function scanNumber() { + let start = pos; + if (text.charCodeAt(pos) === 48) pos++; + else { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++; + } + if (pos < text.length && text.charCodeAt(pos) === 46) { + pos++; + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++; + } else { + scanError = 3; + return text.substring(start, pos); + } + } + let end = pos; + if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) { + pos++; + if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++; + if (pos < text.length && isDigit(text.charCodeAt(pos))) { + pos++; + while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++; + end = pos; + } else scanError = 3; + } + return text.substring(start, end); + } + function scanString() { + let result = "", start = pos; + while (true) { + if (pos >= len) { + result += text.substring(start, pos); + scanError = 2; + break; + } + const ch = text.charCodeAt(pos); + if (ch === 34) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92) { + result += text.substring(start, pos); + pos++; + if (pos >= len) { + scanError = 2; + break; + } + switch (text.charCodeAt(pos++)) { + case 34: + result += "\""; + break; + case 92: + result += "\\"; + break; + case 47: + result += "/"; + break; + case 98: + result += "\b"; + break; + case 102: + result += "\f"; + break; + case 110: + result += "\n"; + break; + case 114: + result += "\r"; + break; + case 116: + result += " "; + break; + case 117: + const ch3 = scanHexDigits(4, true); + if (ch3 >= 0) result += String.fromCharCode(ch3); + else scanError = 4; + break; + default: scanError = 5; + } + start = pos; + continue; + } + if (ch >= 0 && ch <= 31) if (isLineBreak(ch)) { + result += text.substring(start, pos); + scanError = 2; + break; + } else scanError = 6; + pos++; + } + return result; + } + function scanNext() { + value = ""; + scanError = 0; + tokenOffset = pos; + lineStartOffset = lineNumber; + prevTokenLineStartOffset = tokenLineStartOffset; + if (pos >= len) { + tokenOffset = len; + return token = 17; + } + let code = text.charCodeAt(pos); + if (isWhiteSpace(code)) { + do { + pos++; + value += String.fromCharCode(code); + code = text.charCodeAt(pos); + } while (isWhiteSpace(code)); + return token = 15; + } + if (isLineBreak(code)) { + pos++; + value += String.fromCharCode(code); + if (code === 13 && text.charCodeAt(pos) === 10) { + pos++; + value += "\n"; + } + lineNumber++; + tokenLineStartOffset = pos; + return token = 14; + } + switch (code) { + case 123: + pos++; + return token = 1; + case 125: + pos++; + return token = 2; + case 91: + pos++; + return token = 3; + case 93: + pos++; + return token = 4; + case 58: + pos++; + return token = 6; + case 44: + pos++; + return token = 5; + case 34: + pos++; + value = scanString(); + return token = 10; + case 47: + const start = pos - 1; + if (text.charCodeAt(pos + 1) === 47) { + pos += 2; + while (pos < len) { + if (isLineBreak(text.charCodeAt(pos))) break; + pos++; + } + value = text.substring(start, pos); + return token = 12; + } + if (text.charCodeAt(pos + 1) === 42) { + pos += 2; + const safeLength = len - 1; + let commentClosed = false; + while (pos < safeLength) { + const ch = text.charCodeAt(pos); + if (ch === 42 && text.charCodeAt(pos + 1) === 47) { + pos += 2; + commentClosed = true; + break; + } + pos++; + if (isLineBreak(ch)) { + if (ch === 13 && text.charCodeAt(pos) === 10) pos++; + lineNumber++; + tokenLineStartOffset = pos; + } + } + if (!commentClosed) { + pos++; + scanError = 1; + } + value = text.substring(start, pos); + return token = 13; + } + value += String.fromCharCode(code); + pos++; + return token = 16; + case 45: + value += String.fromCharCode(code); + pos++; + if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16; + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + value += scanNumber(); + return token = 11; + default: + while (pos < len && isUnknownContentCharacter(code)) { + pos++; + code = text.charCodeAt(pos); + } + if (tokenOffset !== pos) { + value = text.substring(tokenOffset, pos); + switch (value) { + case "true": return token = 8; + case "false": return token = 9; + case "null": return token = 7; + } + return token = 16; + } + value += String.fromCharCode(code); + pos++; + return token = 16; + } + } + function isUnknownContentCharacter(code) { + if (isWhiteSpace(code) || isLineBreak(code)) return false; + switch (code) { + case 125: + case 93: + case 123: + case 91: + case 34: + case 58: + case 44: + case 47: return false; + } + return true; + } + function scanNextNonTrivia() { + let result; + do + result = scanNext(); + while (result >= 12 && result <= 15); + return result; + } + return { + setPosition, + getPosition: () => pos, + scan: ignoreTrivia ? scanNextNonTrivia : scanNext, + getToken: () => token, + getTokenValue: () => value, + getTokenOffset: () => tokenOffset, + getTokenLength: () => pos - tokenOffset, + getTokenStartLine: () => lineStartOffset, + getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, + getTokenError: () => scanError + }; +} +function isWhiteSpace(ch) { + return ch === 32 || ch === 9; +} +function isLineBreak(ch) { + return ch === 10 || ch === 13; +} +function isDigit(ch) { + return ch >= 48 && ch <= 57; +} +var CharacterCodes; +(function(CharacterCodes) { + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; +})(CharacterCodes || (CharacterCodes = {})); +//#endregion +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +const cachedSpaces = new Array(20).fill(0).map((_, index) => { + return " ".repeat(index); +}); +const maxCachedValues = 200; +const cachedBreakLinesWithSpaces = { + " ": { + "\n": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\n" + " ".repeat(index); + }), + "\r": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\r" + " ".repeat(index); + }), + "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\r\n" + " ".repeat(index); + }) }, - npm: { - cmd: "npm", - args: ["install"] + " ": { + "\n": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\n" + " ".repeat(index); + }), + "\r": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\r" + " ".repeat(index); + }), + "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => { + return "\r\n" + " ".repeat(index); + }) } }; -function slugify(value) { - return value.replace(/@/g, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, ""); +const supportedEols = [ + "\n", + "\r", + "\r\n" +]; +//#endregion +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js +function format(documentText, range, options) { + let initialIndentLevel; + let formatText; + let formatTextStart; + let rangeStart; + let rangeEnd; + if (range) { + rangeStart = range.offset; + rangeEnd = rangeStart + range.length; + formatTextStart = rangeStart; + while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) formatTextStart--; + let endOffset = rangeEnd; + while (endOffset < documentText.length && !isEOL(documentText, endOffset)) endOffset++; + formatText = documentText.substring(formatTextStart, endOffset); + initialIndentLevel = computeIndentLevel(formatText, options); + } else { + formatText = documentText; + initialIndentLevel = 0; + formatTextStart = 0; + rangeStart = 0; + rangeEnd = documentText.length; + } + const eol = getEOL(options, documentText); + const eolFastPathSupported = supportedEols.includes(eol); + let numberLineBreaks = 0; + let indentLevel = 0; + let indentValue; + if (options.insertSpaces) indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4); + else indentValue = " "; + const indentType = indentValue === " " ? " " : " "; + let scanner = createScanner(formatText, false); + let hasError = false; + function newLinesAndIndent() { + if (numberLineBreaks > 1) return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); + const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); + if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) return eol + repeat(indentValue, initialIndentLevel + indentLevel); + if (amountOfSpaces <= 0) return eol; + return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; + } + function scanNext() { + let token = scanner.scan(); + numberLineBreaks = 0; + while (token === 15 || token === 14) { + if (token === 14 && options.keepLines) numberLineBreaks += 1; + else if (token === 14) numberLineBreaks = 1; + token = scanner.scan(); + } + hasError = token === 16 || scanner.getTokenError() !== 0; + return token; + } + const editOperations = []; + function addEdit(text, startOffset, endOffset) { + if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({ + offset: startOffset, + length: endOffset - startOffset, + content: text + }); + } + let firstToken = scanNext(); + if (options.keepLines && numberLineBreaks > 0) addEdit(repeat(eol, numberLineBreaks), 0, 0); + if (firstToken !== 17) { + let firstTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel), formatTextStart, firstTokenStart); + } + while (firstToken !== 17) { + let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + let secondToken = scanNext(); + let replaceContent = ""; + let needsLineBreak = false; + while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) { + let commentTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart); + firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; + needsLineBreak = secondToken === 12; + replaceContent = needsLineBreak ? newLinesAndIndent() : ""; + secondToken = scanNext(); + } + if (secondToken === 2) { + if (firstToken !== 1) indentLevel--; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent(); + else if (options.keepLines) replaceContent = cachedSpaces[1]; + } else if (secondToken === 4) { + if (firstToken !== 3) indentLevel--; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent(); + else if (options.keepLines) replaceContent = cachedSpaces[1]; + } else { + switch (firstToken) { + case 3: + case 1: + indentLevel++; + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent(); + else replaceContent = cachedSpaces[1]; + break; + case 5: + if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent(); + else replaceContent = cachedSpaces[1]; + break; + case 12: + replaceContent = newLinesAndIndent(); + break; + case 13: + if (numberLineBreaks > 0) replaceContent = newLinesAndIndent(); + else if (!needsLineBreak) replaceContent = cachedSpaces[1]; + break; + case 6: + if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent(); + else if (!needsLineBreak) replaceContent = cachedSpaces[1]; + break; + case 10: + if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent(); + else if (secondToken === 6 && !needsLineBreak) replaceContent = ""; + break; + case 7: + case 8: + case 9: + case 11: + case 2: + case 4: + if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent(); + else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = cachedSpaces[1]; + else if (secondToken !== 5 && secondToken !== 17) hasError = true; + break; + case 16: + hasError = true; + break; + } + if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent(); + } + if (secondToken === 17) if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent(); + else replaceContent = options.insertFinalNewline ? eol : ""; + const secondTokenStart = scanner.getTokenOffset() + formatTextStart; + addEdit(replaceContent, firstTokenEnd, secondTokenStart); + firstToken = secondToken; + } + return editOperations; } -function getBranchName(deps) { - return `chore/deps/upgrade-${deps.map((d) => `${slugify(d.name)}-${slugify(d.version)}`).join("-")}`; +function repeat(s, count) { + let result = ""; + for (let i = 0; i < count; i++) result += s; + return result; } -function getPrTitle(deps) { - return `chore: upgrade ${deps.map((d) => `${d.name} to ${d.version}`).join(", ")}`; +function computeIndentLevel(content, options) { + let i = 0; + let nChars = 0; + const tabSize = options.tabSize || 4; + while (i < content.length) { + let ch = content.charAt(i); + if (ch === cachedSpaces[1]) nChars++; + else if (ch === " ") nChars += tabSize; + else break; + i++; + } + return Math.floor(nChars / tabSize); } -function getRepoPath(repo, targetDir) { - const base = `./${repo}`; - return targetDir ? path.join(base, targetDir) : base; +function getEOL(options, text) { + for (let i = 0; i < text.length; i++) { + const ch = text.charAt(i); + if (ch === "\r") { + if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n"; + return "\r"; + } else if (ch === "\n") return "\n"; + } + return options && options.eol || "\n"; } -function parseDependencyName(spec) { - const value = spec.trim(); - if (!value) throw new Error("Empty dependency name"); - if ((value.startsWith("@") ? value.indexOf("@", value.indexOf("/") + 1) : value.lastIndexOf("@")) > 0) throw new Error(`Dependency versions are not supported: ${spec}. Please pass package names only.`); - return value; +function isEOL(text, offset) { + return "\r\n".indexOf(text.charAt(offset)) !== -1; } -function parseDependencyInputs(inputs) { - const deps = inputs.flatMap((input) => input.split(/\s+/)).map((item) => item.trim()).filter(Boolean).map(parseDependencyName); - if (!deps.length) throw new Error("Missing deps input"); - return deps; +//#endregion +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js +var ParseOptions; +(function(ParseOptions) { + ParseOptions.DEFAULT = { allowTrailingComma: false }; +})(ParseOptions || (ParseOptions = {})); +/** +* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. +* Therefore always check the errors list to find out if the input was valid. +*/ +function parse$1(text, errors = [], options = ParseOptions.DEFAULT) { + let currentProperty = null; + let currentParent = []; + const previousParents = []; + function onValue(value) { + if (Array.isArray(currentParent)) currentParent.push(value); + else if (currentProperty !== null) currentParent[currentProperty] = value; + } + visit(text, { + onObjectBegin: () => { + const object = {}; + onValue(object); + previousParents.push(currentParent); + currentParent = object; + currentProperty = null; + }, + onObjectProperty: (name) => { + currentProperty = name; + }, + onObjectEnd: () => { + currentParent = previousParents.pop(); + }, + onArrayBegin: () => { + const array = []; + onValue(array); + previousParents.push(currentParent); + currentParent = array; + currentProperty = null; + }, + onArrayEnd: () => { + currentParent = previousParents.pop(); + }, + onLiteralValue: onValue, + onError: (error, offset, length) => { + errors.push({ + error, + offset, + length + }); + } + }, options); + return currentParent[0]; } -function validatePackageManager(packageManager) { - if (packageManager in PACKAGE_MANAGER_COMMANDS) return packageManager; - throw new Error(`Unsupported package-manager "${packageManager}". Supported values: npm, yarn, pnpm.`); +/** +* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. +*/ +function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { + let currentParent = { + type: "array", + offset: -1, + length: -1, + children: [], + parent: void 0 + }; + function ensurePropertyComplete(endOffset) { + if (currentParent.type === "property") { + currentParent.length = endOffset - currentParent.offset; + currentParent = currentParent.parent; + } + } + function onValue(valueNode) { + currentParent.children.push(valueNode); + return valueNode; + } + visit(text, { + onObjectBegin: (offset) => { + currentParent = onValue({ + type: "object", + offset, + length: -1, + parent: currentParent, + children: [] + }); + }, + onObjectProperty: (name, offset, length) => { + currentParent = onValue({ + type: "property", + offset, + length: -1, + parent: currentParent, + children: [] + }); + currentParent.children.push({ + type: "string", + value: name, + offset, + length, + parent: currentParent + }); + }, + onObjectEnd: (offset, length) => { + ensurePropertyComplete(offset + length); + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onArrayBegin: (offset, length) => { + currentParent = onValue({ + type: "array", + offset, + length: -1, + parent: currentParent, + children: [] + }); + }, + onArrayEnd: (offset, length) => { + currentParent.length = offset + length - currentParent.offset; + currentParent = currentParent.parent; + ensurePropertyComplete(offset + length); + }, + onLiteralValue: (value, offset, length) => { + onValue({ + type: getNodeType(value), + offset, + length, + parent: currentParent, + value + }); + ensurePropertyComplete(offset + length); + }, + onSeparator: (sep, offset, length) => { + if (currentParent.type === "property") { + if (sep === ":") currentParent.colonOffset = offset; + else if (sep === ",") ensurePropertyComplete(offset); + } + }, + onError: (error, offset, length) => { + errors.push({ + error, + offset, + length + }); + } + }, options); + const result = currentParent.children[0]; + if (result) delete result.parent; + return result; } -async function fetchPackageVersion(pkg) { - try { - const response = await fetch(`https://registry.npmjs.org/${pkg}/latest`); - if (!response.ok) throw new Error(`status code: ${response.status}`); - const { version } = await response.json(); - if (!version) throw new Error("no version found"); - info(`Latest version of ${pkg} is ${version}`); - return { - name: pkg, - version - }; - } catch (error) { - throw new Error(`Failed to get ${pkg} info from npm registry: ${error instanceof Error ? error.message : String(error)}`); +/** +* Finds the node at the given path in a JSON DOM. +*/ +function findNodeAtLocation(root, path) { + if (!root) return; + let node = root; + for (let segment of path) if (typeof segment === "string") { + if (node.type !== "object" || !Array.isArray(node.children)) return; + let found = false; + for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { + node = propertyNode.children[1]; + found = true; + break; + } + if (!found) return; + } else { + const index = segment; + if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return; + node = node.children[index]; } + return node; } -async function resolveDependencyInfos(deps) { - return Promise.all(deps.map(fetchPackageVersion)); +/** +* Parses the given text and invokes the visitor functions for each object, array and literal reached. +*/ +function visit(text, visitor, options = ParseOptions.DEFAULT) { + const _scanner = createScanner(text, false); + const _jsonPath = []; + let suppressedCallbacks = 0; + function toNoArgVisit(visitFunction) { + return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toOneArgVisit(visitFunction) { + return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; + } + function toOneArgVisitWithPath(visitFunction) { + return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; + } + function toBeginVisit(visitFunction) { + return visitFunction ? () => { + if (suppressedCallbacks > 0) suppressedCallbacks++; + else if (visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) === false) suppressedCallbacks = 1; + } : () => true; + } + function toEndVisit(visitFunction) { + return visitFunction ? () => { + if (suppressedCallbacks > 0) suppressedCallbacks--; + if (suppressedCallbacks === 0) visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); + } : () => true; + } + const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); + const disallowComments = options && options.disallowComments; + const allowTrailingComma = options && options.allowTrailingComma; + function scanNext() { + while (true) { + const token = _scanner.scan(); + switch (_scanner.getTokenError()) { + case 4: + handleError(14); + break; + case 5: + handleError(15); + break; + case 3: + handleError(13); + break; + case 1: + if (!disallowComments) handleError(11); + break; + case 2: + handleError(12); + break; + case 6: + handleError(16); + break; + } + switch (token) { + case 12: + case 13: + if (disallowComments) handleError(10); + else onComment(); + break; + case 16: + handleError(1); + break; + case 15: + case 14: break; + default: return token; + } + } + } + function handleError(error, skipUntilAfter = [], skipUntil = []) { + onError(error); + if (skipUntilAfter.length + skipUntil.length > 0) { + let token = _scanner.getToken(); + while (token !== 17) { + if (skipUntilAfter.indexOf(token) !== -1) { + scanNext(); + break; + } else if (skipUntil.indexOf(token) !== -1) break; + token = scanNext(); + } + } + } + function parseString(isValue) { + const value = _scanner.getTokenValue(); + if (isValue) onLiteralValue(value); + else { + onObjectProperty(value); + _jsonPath.push(value); + } + scanNext(); + return true; + } + function parseLiteral() { + switch (_scanner.getToken()) { + case 11: + const tokenValue = _scanner.getTokenValue(); + let value = Number(tokenValue); + if (isNaN(value)) { + handleError(2); + value = 0; + } + onLiteralValue(value); + break; + case 7: + onLiteralValue(null); + break; + case 8: + onLiteralValue(true); + break; + case 9: + onLiteralValue(false); + break; + default: return false; + } + scanNext(); + return true; + } + function parseProperty() { + if (_scanner.getToken() !== 10) { + handleError(3, [], [2, 5]); + return false; + } + parseString(false); + if (_scanner.getToken() === 6) { + onSeparator(":"); + scanNext(); + if (!parseValue()) handleError(4, [], [2, 5]); + } else handleError(5, [], [2, 5]); + _jsonPath.pop(); + return true; + } + function parseObject() { + onObjectBegin(); + scanNext(); + let needsComma = false; + while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) { + if (_scanner.getToken() === 5) { + if (!needsComma) handleError(4, [], []); + onSeparator(","); + scanNext(); + if (_scanner.getToken() === 2 && allowTrailingComma) break; + } else if (needsComma) handleError(6, [], []); + if (!parseProperty()) handleError(4, [], [2, 5]); + needsComma = true; + } + onObjectEnd(); + if (_scanner.getToken() !== 2) handleError(7, [2], []); + else scanNext(); + return true; + } + function parseArray() { + onArrayBegin(); + scanNext(); + let isFirstElement = true; + let needsComma = false; + while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) { + if (_scanner.getToken() === 5) { + if (!needsComma) handleError(4, [], []); + onSeparator(","); + scanNext(); + if (_scanner.getToken() === 4 && allowTrailingComma) break; + } else if (needsComma) handleError(6, [], []); + if (isFirstElement) { + _jsonPath.push(0); + isFirstElement = false; + } else _jsonPath[_jsonPath.length - 1]++; + if (!parseValue()) handleError(4, [], [4, 5]); + needsComma = true; + } + onArrayEnd(); + if (!isFirstElement) _jsonPath.pop(); + if (_scanner.getToken() !== 4) handleError(8, [4], []); + else scanNext(); + return true; + } + function parseValue() { + switch (_scanner.getToken()) { + case 3: return parseArray(); + case 1: return parseObject(); + case 10: return parseString(true); + default: return parseLiteral(); + } + } + scanNext(); + if (_scanner.getToken() === 17) { + if (options.allowEmptyContent) return true; + handleError(4, [], []); + return false; + } + if (!parseValue()) { + handleError(4, [], []); + return false; + } + if (_scanner.getToken() !== 17) handleError(9, [], []); + return true; } -async function updatePackageDependencies(packageManager, deps, repo, targetDir) { - const repoPath = getRepoPath(repo, targetDir); - const { cmd, args } = PACKAGE_MANAGER_COMMANDS[packageManager]; - await exec(cmd, [...args, ...deps], { cwd: repoPath }); +function getNodeType(value) { + switch (typeof value) { + case "boolean": return "boolean"; + case "number": return "number"; + case "string": return "string"; + case "object": + if (!value) return "null"; + else if (Array.isArray(value)) return "array"; + return "object"; + default: return "null"; + } } -async function createDepsPr(title, branchName, baseBranch, context) { - await new GithubHelper({ - owner: context.owner, - repo: context.repo, - token: context.token, - dryRun: context.dryRun - }).createPR(title, branchName, title, baseBranch); +//#endregion +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js +function setProperty(text, originalPath, value, options) { + const path = originalPath.slice(); + const root = parseTree(text, []); + let parent = void 0; + let lastSegment = void 0; + while (path.length > 0) { + lastSegment = path.pop(); + parent = findNodeAtLocation(root, path); + if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value }; + else value = [value]; + else break; + } + if (!parent) { + if (value === void 0) throw new Error("Can not delete in empty document"); + return withFormatting(text, { + offset: root ? root.offset : 0, + length: root ? root.length : 0, + content: JSON.stringify(value) + }, options); + } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) { + const existing = findNodeAtLocation(parent, [lastSegment]); + if (existing !== void 0) if (value === void 0) { + if (!existing.parent) throw new Error("Malformed AST"); + const propertyIndex = parent.children.indexOf(existing.parent); + let removeBegin; + let removeEnd = existing.parent.offset + existing.parent.length; + if (propertyIndex > 0) { + let previous = parent.children[propertyIndex - 1]; + removeBegin = previous.offset + previous.length; + } else { + removeBegin = parent.offset + 1; + if (parent.children.length > 1) removeEnd = parent.children[1].offset; + } + return withFormatting(text, { + offset: removeBegin, + length: removeEnd - removeBegin, + content: "" + }, options); + } else return withFormatting(text, { + offset: existing.offset, + length: existing.length, + content: JSON.stringify(value) + }, options); + else { + if (value === void 0) return []; + const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; + const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length; + let edit; + if (index > 0) { + let previous = parent.children[index - 1]; + edit = { + offset: previous.offset + previous.length, + length: 0, + content: "," + newProperty + }; + } else if (parent.children.length === 0) edit = { + offset: parent.offset + 1, + length: 0, + content: newProperty + }; + else edit = { + offset: parent.offset + 1, + length: 0, + content: newProperty + "," + }; + return withFormatting(text, edit, options); + } + } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) { + const insertIndex = lastSegment; + if (insertIndex === -1) { + const newProperty = `${JSON.stringify(value)}`; + let edit; + if (parent.children.length === 0) edit = { + offset: parent.offset + 1, + length: 0, + content: newProperty + }; + else { + const previous = parent.children[parent.children.length - 1]; + edit = { + offset: previous.offset + previous.length, + length: 0, + content: "," + newProperty + }; + } + return withFormatting(text, edit, options); + } else if (value === void 0 && parent.children.length >= 0) { + const removalIndex = lastSegment; + const toRemove = parent.children[removalIndex]; + let edit; + if (parent.children.length === 1) edit = { + offset: parent.offset + 1, + length: parent.length - 2, + content: "" + }; + else if (parent.children.length - 1 === removalIndex) { + let previous = parent.children[removalIndex - 1]; + let offset = previous.offset + previous.length; + edit = { + offset, + length: parent.offset + parent.length - 2 - offset, + content: "" + }; + } else edit = { + offset: toRemove.offset, + length: parent.children[removalIndex + 1].offset - toRemove.offset, + content: "" + }; + return withFormatting(text, edit, options); + } else if (value !== void 0) { + let edit; + const newProperty = `${JSON.stringify(value)}`; + if (!options.isArrayInsertion && parent.children.length > lastSegment) { + const toModify = parent.children[lastSegment]; + edit = { + offset: toModify.offset, + length: toModify.length, + content: newProperty + }; + } else if (parent.children.length === 0 || lastSegment === 0) edit = { + offset: parent.offset + 1, + length: 0, + content: parent.children.length === 0 ? newProperty : newProperty + "," + }; + else { + const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; + const previous = parent.children[index - 1]; + edit = { + offset: previous.offset + previous.length, + length: 0, + content: "," + newProperty + }; + } + return withFormatting(text, edit, options); + } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`); + } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`); +} +function withFormatting(text, edit, options) { + if (!options.formattingOptions) return [edit]; + let newText = applyEdit(text, edit); + let begin = edit.offset; + let end = edit.offset + edit.content.length; + if (edit.length === 0 || edit.content.length === 0) { + while (begin > 0 && !isEOL(newText, begin - 1)) begin--; + while (end < newText.length && !isEOL(newText, end)) end++; + } + const edits = format(newText, { + offset: begin, + length: end - begin + }, { + ...options.formattingOptions, + keepLines: false + }); + for (let i = edits.length - 1; i >= 0; i--) { + const edit = edits[i]; + newText = applyEdit(newText, edit); + begin = Math.min(begin, edit.offset); + end = Math.max(end, edit.offset + edit.length); + end += edit.content.length - edit.length; + } + const editLength = text.length - (newText.length - end) - begin; + return [{ + offset: begin, + length: editLength, + content: newText.substring(begin, end) + }]; +} +function applyEdit(text, edit) { + return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); +} +//#endregion +//#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js +var ScanError; +(function(ScanError) { + ScanError[ScanError["None"] = 0] = "None"; + ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; + ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; + ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; + ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; + ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; + ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; +})(ScanError || (ScanError = {})); +var SyntaxKind; +(function(SyntaxKind) { + SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; + SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; + SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; + SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; + SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; + SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; + SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; + SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; + SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; +})(SyntaxKind || (SyntaxKind = {})); +/** +* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. +* Therefore, always check the errors list to find out if the input was valid. +*/ +const parse = parse$1; +var ParseErrorCode; +(function(ParseErrorCode) { + ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; + ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; + ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; + ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; + ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; + ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; + ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; + ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; + ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; + ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; + ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; + ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; + ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; + ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; +})(ParseErrorCode || (ParseErrorCode = {})); +/** +* Computes the edit operations needed to modify a value in the JSON document. +* +* @param documentText The input text +* @param path The path of the value to change. The path represents either to the document root, a property or an array item. +* If the path points to an non-existing property or item, it will be created. +* @param value The new value for the specified property or item. If the value is undefined, +* the property or item will be removed. +* @param options Options +* @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. +* To apply the edit operations to the input, use {@linkcode applyEdits}. +*/ +function modify(text, path, value, options) { + return setProperty(text, path, value, options); +} +/** +* Applies edits to an input string. +* @param text The input text +* @param edits Edit operations following the format described in {@linkcode EditResult}. +* @returns The text with the applied edits. +* @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. +*/ +function applyEdits(text, edits) { + let sortedEdits = edits.slice(0).sort((a, b) => { + const diff = a.offset - b.offset; + if (diff === 0) return a.length - b.length; + return diff; + }); + let lastModifiedOffset = text.length; + for (let i = sortedEdits.length - 1; i >= 0; i--) { + let e = sortedEdits[i]; + if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e); + else throw new Error("Overlapping edit"); + lastModifiedOffset = e.offset; + } + return text; +} +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js +var require_identity = /* @__PURE__ */ __commonJSMin(((exports) => { + const ALIAS = Symbol.for("yaml.alias"); + const DOC = Symbol.for("yaml.document"); + const MAP = Symbol.for("yaml.map"); + const PAIR = Symbol.for("yaml.pair"); + const SCALAR = Symbol.for("yaml.scalar"); + const SEQ = Symbol.for("yaml.seq"); + const NODE_TYPE = Symbol.for("yaml.node.type"); + const isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + const isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + const isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + const isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + const isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + const isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + function isCollection(node) { + if (node && typeof node === "object") switch (node[NODE_TYPE]) { + case MAP: + case SEQ: return true; + } + return false; + } + function isNode(node) { + if (node && typeof node === "object") switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: return true; + } + return false; + } + const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + exports.ALIAS = ALIAS; + exports.DOC = DOC; + exports.MAP = MAP; + exports.NODE_TYPE = NODE_TYPE; + exports.PAIR = PAIR; + exports.SCALAR = SCALAR; + exports.SEQ = SEQ; + exports.hasAnchor = hasAnchor; + exports.isAlias = isAlias; + exports.isCollection = isCollection; + exports.isDocument = isDocument; + exports.isMap = isMap; + exports.isNode = isNode; + exports.isPair = isPair; + exports.isScalar = isScalar; + exports.isSeq = isSeq; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js +var require_visit = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + const BREAK = Symbol("break visit"); + const SKIP = Symbol("skip children"); + const REMOVE = Symbol("remove node"); + /** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ + function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + if (visit_(null, node.contents, visitor_, Object.freeze([node])) === REMOVE) node.contents = null; + } else visit_(null, node, visitor_, Object.freeze([])); + } + /** Terminate visit traversal completely */ + visit.BREAK = BREAK; + /** Do not visit the children of the current node */ + visit.SKIP = SKIP; + /** Remove the current node */ + visit.REMOVE = REMOVE; + function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) return BREAK; + else if (ck === REMOVE) node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) return BREAK; + else if (cv === REMOVE) node.value = null; + } + } + return ctrl; + } + /** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ + async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + if (await visitAsync_(null, node.contents, visitor_, Object.freeze([node])) === REMOVE) node.contents = null; + } else await visitAsync_(null, node, visitor_, Object.freeze([])); + } + /** Terminate visit traversal completely */ + visitAsync.BREAK = BREAK; + /** Do not visit the children of the current node */ + visitAsync.SKIP = SKIP; + /** Remove the current node */ + visitAsync.REMOVE = REMOVE; + async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) return BREAK; + else if (ck === REMOVE) node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) return BREAK; + else if (cv === REMOVE) node.value = null; + } + } + return ctrl; + } + function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + return visitor; + } + function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") return visitor(key, node, path); + if (identity.isMap(node)) return visitor.Map?.(key, node, path); + if (identity.isSeq(node)) return visitor.Seq?.(key, node, path); + if (identity.isPair(node)) return visitor.Pair?.(key, node, path); + if (identity.isScalar(node)) return visitor.Scalar?.(key, node, path); + if (identity.isAlias(node)) return visitor.Alias?.(key, node, path); + } + function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (identity.isCollection(parent)) parent.items[key] = node; + else if (identity.isPair(parent)) if (key === "key") parent.key = node; + else parent.value = node; + else if (identity.isDocument(parent)) parent.contents = node; + else { + const pt = identity.isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } + } + exports.visit = visit; + exports.visitAsync = visitAsync; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js +var require_directives = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var visit = require_visit(); + const escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + var Directives = class Directives { + constructor(yaml, tags) { + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + this.docStart = null; + /** The doc-end marker `...`. */ + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.1" + }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + if (handle === "!") return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) if (tag.startsWith(prefix)) return handle + escapeTagName(tag.substring(prefix.length)); + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { + const tags = {}; + visit.visit(doc.contents, (_key, node) => { + if (identity.isNode(node) && node.tag) tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } + }; + Directives.defaultYaml = { + explicit: false, + version: "1.2" + }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + exports.Directives = Directives; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js +var require_anchors = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var visit = require_visit(); + /** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ + function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const msg = `Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`; + throw new Error(msg); + } + return true; + } + function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit.visit(root, { Value(_key, node) { + if (node.anchor) anchors.add(node.anchor); + } }); + return anchors; + } + /** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ + function findNewAnchor(prefix, exclude) { + for (let i = 1;; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) return name; + } + } + function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) ref.node.anchor = ref.anchor; + else { + const error = /* @__PURE__ */ new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; + } + exports.anchorIsValid = anchorIsValid; + exports.anchorNames = anchorNames; + exports.createNodeAnchors = createNodeAnchors; + exports.findNewAnchor = findNewAnchor; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js +var require_applyReviver = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ + function applyReviver(reviver, obj, key, val) { + if (val && typeof val === "object") if (Array.isArray(val)) for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) delete val[i]; + else if (v1 !== v0) val[i] = v1; + } + else if (val instanceof Map) for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) val.delete(k); + else if (v1 !== v0) val.set(k, v1); + } + else if (val instanceof Set) for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + else for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) delete val[k]; + else if (v1 !== v0) val[k] = v1; + } + return reviver.call(obj, key, val); + } + exports.applyReviver = applyReviver; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js +var require_toJS = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + /** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ + function toJS(value, arg, ctx) { + if (Array.isArray(value)) return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !identity.hasAnchor(value)) return value.toJSON(arg, ctx); + const data = { + aliasCount: 0, + count: 1, + res: void 0 + }; + ctx.anchors.set(value, data); + ctx.onCreate = (res) => { + data.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !ctx?.keep) return Number(value); + return value; + } + exports.toJS = toJS; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js +var require_Node = /* @__PURE__ */ __commonJSMin(((exports) => { + var applyReviver = require_applyReviver(); + var identity = require_identity(); + var toJS = require_toJS(); + var NodeBase = class { + constructor(type) { + Object.defineProperty(this, identity.NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!identity.isDocument(doc)) throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this, "", ctx); + if (typeof onAnchor === "function") for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + }; + exports.NodeBase = NodeBase; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js +var require_Alias = /* @__PURE__ */ __commonJSMin(((exports) => { + var anchors = require_anchors(); + var visit = require_visit(); + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + var Alias = class extends Node.NodeBase { + constructor(source) { + super(identity.ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { set() { + throw new Error("Alias nodes cannot have tags"); + } }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) nodes = ctx.aliasResolveCache; + else { + nodes = []; + visit.visit(doc, { Node: (_key, node) => { + if (identity.isAlias(node) || identity.hasAnchor(node)) nodes.push(node); + } }); + if (ctx) ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) break; + if (node.anchor === this.source) found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + toJS.toJS(source, null, ctx); + data = anchors.get(source); + } + /* istanbul ignore if */ + if (data?.res === void 0) throw new ReferenceError("This should not happen: Alias anchor was not resolved?"); + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack"); + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) return `${src} `; + } + return src; + } + }; + function getAliasCount(doc, node, anchors) { + if (identity.isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (identity.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) count = c; + } + return count; + } else if (identity.isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; + } + exports.Alias = Alias; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js +var require_Scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + const isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; + var Scalar = class extends Node.NodeBase { + constructor(value) { + super(identity.SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + exports.Scalar = Scalar; + exports.isScalarValue = isScalarValue; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js +var require_createNode = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var Scalar = require_Scalar(); + const defaultTagPrefix = "tag:yaml.org,2002:"; + function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value) && !t.format); + } + function createNode(value, tagName, ctx) { + if (identity.isDocument(value)) value = value.contents; + if (identity.isNode(value)) return value; + if (identity.isPair(value)) { + const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) value = value.valueOf(); + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias.Alias(ref.anchor); + } else { + ref = { + anchor: null, + node: null + }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") value = value.toJSON(); + if (!value || typeof value !== "object") { + const node = new Scalar.Scalar(value); + if (ref) ref.node = node; + return node; + } + tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); + if (tagName) node.tag = tagName; + else if (!tagObj.default) node.tag = tagObj.tag; + if (ref) ref.node = node; + return node; + } + exports.createNode = createNode; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js +var require_Collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var identity = require_identity(); + var Node = require_Node(); + function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else v = /* @__PURE__ */ new Map([[k, v]]); + } + return createNode.createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema, + sourceObjects: /* @__PURE__ */ new Map() + }); + } + const isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + var Collection = class extends Node.NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, "schema", { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) copy.schema = schema; + copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (identity.isCollection(node)) node.addIn(rest, value); + else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) return this.delete(key); + const node = this.get(key, true); + if (identity.isCollection(node)) return node.deleteIn(rest); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; + else return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!identity.isPair(node)) return false; + const n = node.value; + return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) return this.has(key); + const node = this.get(key, true); + return identity.isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) this.set(key, value); + else { + const node = this.get(key, true); + if (identity.isCollection(node)) node.setIn(rest, value); + else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + }; + exports.Collection = Collection; + exports.collectionFromPath = collectionFromPath; + exports.isEmptyPath = isEmptyPath; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js +var require_stringifyComment = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ + const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); + function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; + } + const lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; + exports.indentComment = indentComment; + exports.lineComment = lineComment; + exports.stringifyComment = stringifyComment; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js +var require_foldFlowLines = /* @__PURE__ */ __commonJSMin(((exports) => { + const FOLD_FLOW = "flow"; + const FOLD_BLOCK = "block"; + const FOLD_QUOTED = "quoted"; + /** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ + function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) return text; + if (lineWidth < minContentWidth) minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0); + else end = lineWidth - indentAtStart; + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) end = i + endStep; + } + for (let ch; ch = text[i += 1];) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") split = i; + } + if (i >= end) if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else overflow = true; + } + prev = ch; + } + if (overflow && onOverflow) onOverflow(); + if (folds.length === 0) return text; + if (onFold) onFold(); + let res = text.slice(0, folds[0]); + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) res = `\n${indent}${text.slice(0, end)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + return res; + } + /** + * Presumes `i + 1` is at the start of a line + * @returns index of last newline in more-indented block + */ + function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") if (i < start + indent) ch = text[++i]; + else { + do + ch = text[++i]; + while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + return end; + } + exports.FOLD_BLOCK = FOLD_BLOCK; + exports.FOLD_FLOW = FOLD_FLOW; + exports.FOLD_QUOTED = FOLD_QUOTED; + exports.foldFlowLines = foldFlowLines; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyString.js +var require_stringifyString = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var foldFlowLines = require_foldFlowLines(); + const getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) return false; + for (let i = 0, start = 0; i < strLen; ++i) if (str[i] === "\n") { + if (i - start > limit) return true; + start = i + 1; + if (strLen - start <= limit) return false; + } + return true; + } + function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: if (code.substr(0, 2) === "00") str += "\\x" + code.substr(2); + else str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === "\"" || json.length < minMultiLineLength) i += 1; + else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== "\"") { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") str += "\\"; + i += 1; + start = i + 1; + } + break; + default: i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); + } + function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) qs = doubleQuotedString; + else { + const hasDouble = value.includes("\""); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) qs = singleQuotedString; + else if (hasSingle && !hasDouble) qs = doubleQuotedString; + else qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); + } + let blockEndNewlines; + try { + blockEndNewlines = /* @__PURE__ */ new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) chomp = "-"; + else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) onChompKeep(); + } else chomp = ""; + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") startWithSpace = true; + else if (ch === "\n") startNlPos = startEnd; + else break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + let header = (startWithSpace ? indent ? "2" : "1" : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) foldOptions.onOverflow = () => { + literalFallback = true; + }; + const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) return `>${header}\n${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header}\n${indent}${start}${value}${end}`; + } + function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) return quotedString(value, ctx); + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) return blockString(item, ctx, onComment, onChompKeep); + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) return quotedString(value, ctx); + } + const str = value.replace(/\n+/g, `$&\n${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) type = Scalar.Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.Scalar.BLOCK_FOLDED: + case Scalar.Scalar.BLOCK_LITERAL: return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.Scalar.QUOTE_DOUBLE: return doubleQuotedString(ss.value, ctx); + case Scalar.Scalar.QUOTE_SINGLE: return singleQuotedString(ss.value, ctx); + case Scalar.Scalar.PLAIN: return plainString(ss, ctx, onComment, onChompKeep); + default: return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) throw new Error(`Unsupported default string type ${t}`); + } + return res; + } + exports.stringifyString = stringifyString; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringify.js +var require_stringify = /* @__PURE__ */ __commonJSMin(((exports) => { + var anchors = require_anchors(); + var identity = require_identity(); + var stringifyComment = require_stringifyComment(); + var stringifyString = require_stringifyString(); + function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment.stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; + } + function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (identity.isScalar(item)) { + obj = item.value; + let match = tags.filter((t) => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; + } + function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { + if (!doc.directives) return ""; + const props = []; + const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; + if (anchor && anchors.anchorIsValid(anchor)) { + anchors$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) props.push(doc.directives.tagString(tag)); + return props.join(" "); + } + function stringify(item, ctx, onComment, onChompKeep) { + if (identity.isPair(item)) return item.toString(ctx, onComment, onChompKeep); + if (identity.isAlias(item)) { + if (ctx.doc.directives) return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) throw new TypeError(`Cannot stringify circular structure without alias nodes`); + else { + if (ctx.resolvedAliases) ctx.resolvedAliases.add(item); + else ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) return str; + return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; + } + exports.createStringifyContext = createStringifyContext; + exports.stringify = stringify; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyPair.js +var require_stringifyPair = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = identity.isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) throw new Error("With simple keys, key nodes cannot have comments"); + if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") throw new Error("With simple keys, collection cannot be used as a key value"); + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + if (keyCommentDone) keyComment = null; + if (explicitKey) { + if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str}\n${indent}:`; + } else { + str = `${str}:`; + if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity.isScalar(value)) ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) ctx.indent = ctx.indent.substring(2); + let valueCommentDone = false; + const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) ws = "\n\n"; + } else ws += `\n${ctx.indent}`; + } else if (!explicitKey && identity.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") sp0 = valueStr.indexOf(" ", sp0 + 1); + if (sp0 === -1 || nl0 < sp0) hasPropsLine = true; + } + if (!hasPropsLine) ws = `\n${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") ws = ""; + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) onComment(); + } else if (valueComment && !valueCommentDone) str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); + else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + exports.stringifyPair = stringifyPair; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/log.js +var require_log = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process$2 = __require("process"); + function debug(logLevel, ...messages) { + if (logLevel === "debug") console.log(...messages); + } + function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") if (typeof node_process$2.emitWarning === "function") node_process$2.emitWarning(warning); + else console.warn(warning); + } + exports.debug = debug; + exports.warn = warn; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/merge.js +var require_merge = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + const MERGE_KEY = "<<"; + const merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { addToJSMap: addMergeToJSMap }), + stringify: () => MERGE_KEY + }; + const isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default); + function addMergeToJSMap(ctx, map, value) { + const source = resolveAliasValue(ctx, value); + if (identity.isSeq(source)) for (const it of source.items) mergeValue(ctx, map, it); + else if (Array.isArray(source)) for (const it of source) mergeValue(ctx, map, it); + else mergeValue(ctx, map, source); + } + function mergeValue(ctx, map, value) { + const source = resolveAliasValue(ctx, value); + if (!identity.isMap(source)) throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) if (map instanceof Map) { + if (!map.has(key)) map.set(key, value); + } else if (map instanceof Set) map.add(key); + else if (!Object.prototype.hasOwnProperty.call(map, key)) Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + return map; + } + function resolveAliasValue(ctx, value) { + return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; + } + exports.addMergeToJSMap = addMergeToJSMap; + exports.isMergeKey = isMergeKey; + exports.merge = merge; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/addPairToJSMap.js +var require_addPairToJSMap = /* @__PURE__ */ __commonJSMin(((exports) => { + var log = require_log(); + var merge = require_merge(); + var stringify = require_stringify(); + var identity = require_identity(); + var toJS = require_toJS(); + function addPairToJSMap(ctx, map, { key, value }) { + if (identity.isNode(key) && key.addToJSMap) key.addToJSMap(ctx, map, value); + else if (merge.isMergeKey(ctx, key)) merge.addMergeToJSMap(ctx, map, value); + else { + const jsKey = toJS.toJS(key, "", ctx); + if (map instanceof Map) map.set(jsKey, toJS.toJS(value, jsKey, ctx)); + else if (map instanceof Set) map.add(jsKey); + else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS.toJS(value, stringKey, ctx); + if (stringKey in map) Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else map[stringKey] = jsValue; + } + } + return map; + } + function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) return ""; + if (typeof jsKey !== "object") return String(jsKey); + if (identity.isNode(key) && ctx?.doc) { + const strCtx = stringify.createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) jsonStr = jsonStr.substring(0, 36) + "...\""; + log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); + } + exports.addPairToJSMap = addPairToJSMap; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Pair.js +var require_Pair = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var stringifyPair = require_stringifyPair(); + var addPairToJSMap = require_addPairToJSMap(); + var identity = require_identity(); + function createPair(key, value, ctx) { + return new Pair(createNode.createNode(key, void 0, ctx), createNode.createNode(value, void 0, ctx)); + } + var Pair = class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (identity.isNode(key)) key = key.clone(schema); + if (identity.isNode(value)) value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap.addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + }; + exports.Pair = Pair; + exports.createPair = createPair; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyCollection.js +var require_stringifyCollection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyCollection(collection, ctx, options) { + return (ctx.inFlow ?? collection.flow ? stringifyFlowCollection : stringifyBlockCollection)(collection, ctx, options); + } + function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + type: null + }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (!chompKeep && item.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str = stringify.stringify(item, itemCtx, () => comment = null, () => chompKeep = true); + if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + if (chompKeep && comment) chompKeep = false; + lines.push(blockItemPrefix + str); + } + let str; + if (lines.length === 0) str = flowChars.start + flowChars.end; + else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? `\n${indent}${line}` : "\n"; + } + } + if (comment) { + str += "\n" + stringifyComment.indentComment(commentString(comment), indent); + if (onComment) onComment(); + } else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (item.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) reqNewline = true; + } + const iv = identity.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) comment = iv.comment; + if (iv.commentBefore) reqNewline = true; + } else if (item.value == null && ik?.comment) comment = ik.comment; + } + if (comment) reqNewline = true; + let str = stringify.stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); + if (i < items.length - 1) str += ","; + else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); + if (reqNewline) str += ","; + } + if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) return start + end; + else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) str += line ? `\n${indentStep}${indent}${line}` : "\n"; + return `${str}\n${indent}${end}`; + } else return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } + function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = stringifyComment.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } + } + exports.stringifyCollection = stringifyCollection; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLMap.js +var require_YAMLMap = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyCollection = require_stringifyCollection(); + var addPairToJSMap = require_addPairToJSMap(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + function findPair(items, key) { + const k = identity.isScalar(key) ? key.value : key; + for (const it of items) if (identity.isPair(it)) { + if (it.key === key || it.key === k) return it; + if (identity.isScalar(it.key) && it.key.value === k) return it; + } + } + var YAMLMap = class extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema) { + super(identity.MAP, schema); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === "function") value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) return; + if (value !== void 0 || keepUndefined) map.items.push(Pair.createPair(key, value, ctx)); + }; + if (obj instanceof Map) for (const [key, value] of obj) add(key, value); + else if (obj && typeof obj === "object") for (const key of Object.keys(obj)) add(key, obj[key]); + if (typeof schema.sortMapEntries === "function") map.items.sort(schema.sortMapEntries); + return map; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (identity.isPair(pair)) _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) _pair = new Pair.Pair(pair, pair?.value); + else _pair = new Pair.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) throw new Error(`Key ${_pair.key} already set`); + if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) prev.value.value = _pair.value; + else prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) this.items.push(_pair); + else this.items.splice(i, 0, _pair); + } else this.items.push(_pair); + } + delete(key) { + const it = findPair(this.items, key); + if (!it) return false; + return this.items.splice(this.items.indexOf(it), 1).length > 0; + } + get(key, keepScalar) { + const node = findPair(this.items, key)?.value; + return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair.Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) ctx.onCreate(map); + for (const item of this.items) addPairToJSMap.addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + for (const item of this.items) if (!identity.isPair(item)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + if (!ctx.allNullValues && this.hasAllNullValues(false)) ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { + start: "{", + end: "}" + }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + }; + exports.YAMLMap = YAMLMap; + exports.findPair = findPair; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/map.js +var require_map = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var YAMLMap = require_YAMLMap(); + exports.map = { + collection: "map", + default: true, + nodeClass: YAMLMap.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map, onError) { + if (!identity.isMap(map)) onError("Expected a mapping for this tag"); + return map; + }, + createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) + }; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLSeq.js +var require_YAMLSeq = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var stringifyCollection = require_stringifyCollection(); + var Collection = require_Collection(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var toJS = require_toJS(); + var YAMLSeq = class extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema) { + super(identity.SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") return false; + return this.items.splice(idx, 1).length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") return void 0; + const it = this.items[idx]; + return !keepScalar && identity.isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity.isScalar(prev) && Scalar.isScalarValue(value)) prev.value = value; + else this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) ctx.onCreate(seq); + let i = 0; + for (const item of this.items) seq.push(toJS.toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { + start: "[", + end: "]" + }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode.createNode(it, void 0, ctx)); + } + } + return seq; + } + }; + function asItemIndex(key) { + let idx = identity.isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; + } + exports.YAMLSeq = YAMLSeq; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/seq.js +var require_seq = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var YAMLSeq = require_YAMLSeq(); + exports.seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq, onError) { + if (!identity.isSeq(seq)) onError("Expected a sequence for this tag"); + return seq; + }, + createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) + }; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/string.js +var require_string = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyString = require_stringifyString(); + exports.string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); + } + }; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/null.js +var require_null = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + const nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar.Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + exports.nullTag = nullTag; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/bool.js +var require_bool$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + const boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + if (value === (source[0] === "t" || source[0] === "T")) return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + exports.boolTag = boolTag; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js +var require_stringifyNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) n += "0"; + } + return n; + } + exports.stringifyNumber = stringifyNumber; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/float.js +var require_float$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + const floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + const floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + exports.float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/int.js +var require_int$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + const intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + const intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); + return stringifyNumber.stringifyNumber(node); + } + const intOct = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: (node) => intStringify(node, 8, "0o") + }; + const int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + const intHex = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intHex = intHex; + exports.intOct = intOct; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/schema.js +var require_schema$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var bool = require_bool$1(); + var float = require_float$1(); + var int = require_int$1(); + exports.schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.boolTag, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float + ]; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/json/schema.js +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var map = require_map(); + var seq = require_seq(); + function intIdentify(value) { + return typeof value === "bigint" || Number.isInteger(value); + } + const stringifyJSON = ({ value }) => JSON.stringify(value); + const jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } + ]; + exports.schema = [map.map, seq.seq].concat(jsonScalars, { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } + }); +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/binary.js +var require_binary = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_buffer = __require("buffer"); + var Scalar = require_Scalar(); + var stringifyString = require_stringifyString(); + exports.binary = { + identify: (value) => value instanceof Uint8Array, + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof node_buffer.Buffer === "function") return node_buffer.Buffer.from(src, "base64"); + else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) return ""; + const buf = value; + let str; + if (typeof node_buffer.Buffer === "function") str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); + else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) s += String.fromCharCode(buf[i]); + str = btoa(s); + } else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + type ?? (type = Scalar.Scalar.BLOCK_LITERAL); + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) lines[i] = str.substr(o, lineWidth); + str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString.stringifyString({ + comment, + type, + value: str + }, ctx, onComment, onChompKeep); + } + }; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +var require_pairs = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLSeq = require_YAMLSeq(); + function resolvePairs(seq, onError) { + if (identity.isSeq(seq)) for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (identity.isPair(item)) continue; + else if (identity.isMap(item)) { + if (item.items.length > 1) onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); + if (item.commentBefore) pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}\n${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment}\n${cn.comment}` : item.comment; + } + item = pair; + } + seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); + } + else onError("Expected a sequence for this tag"); + return seq; + } + function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs = new YAMLSeq.YAMLSeq(schema); + pairs.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable) { + if (typeof replacer === "function") it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) if (it.length === 2) { + key = it[0]; + value = it[1]; + } else throw new TypeError(`Expected [key, value] tuple: ${it}`); + else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } else key = it; + pairs.items.push(Pair.createPair(key, value, ctx)); + } + return pairs; + } + const pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + exports.createPairs = createPairs; + exports.pairs = pairs; + exports.resolvePairs = resolvePairs; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js +var require_omap = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var toJS = require_toJS(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var pairs = require_pairs(); + var YAMLOMap = class YAMLOMap extends YAMLSeq.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) return super.toJSON(_); + const map = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (identity.isPair(pair)) { + key = toJS.toJS(pair.key, "", ctx); + value = toJS.toJS(pair.value, key, ctx); + } else key = toJS.toJS(pair, "", ctx); + if (map.has(key)) throw new Error("Ordered maps must not include duplicate keys"); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs$1 = pairs.createPairs(schema, iterable, ctx); + const omap = new this(); + omap.items = pairs$1.items; + return omap; + } + }; + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + const omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq, onError) { + const pairs$1 = pairs.resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs$1.items) if (identity.isScalar(key)) if (seenKeys.includes(key.value)) onError(`Ordered maps must not include duplicate keys: ${key.value}`); + else seenKeys.push(key.value); + return Object.assign(new YAMLOMap(), pairs$1); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) + }; + exports.YAMLOMap = YAMLOMap; + exports.omap = omap; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js +var require_bool = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + function boolStringify({ value, source }, ctx) { + if (source && (value ? trueTag : falseTag).test.test(source)) return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + const trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar.Scalar(true), + stringify: boolStringify + }; + const falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar.Scalar(false), + stringify: boolStringify + }; + exports.falseTag = falseTag; + exports.trueTag = trueTag; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js +var require_float = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + const floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + const floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + exports.float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js +var require_int = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + const intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n = BigInt(str); + return sign === "-" ? BigInt(-1) * n : n; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; + } + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber.stringifyNumber(node); + } + const intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") + }; + const intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") + }; + const int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + const intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intBin = intBin; + exports.intHex = intHex; + exports.intOct = intOct; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js +var require_set = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSet = class YAMLSet extends YAMLMap.YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (identity.isPair(key)) pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) pair = new Pair.Pair(key.key, null); + else pair = new Pair.Pair(key, null); + if (!YAMLMap.findPair(this.items, pair.key)) this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = YAMLMap.findPair(this.items, key); + return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap.findPair(this.items, key); + if (prev && !value) this.items.splice(this.items.indexOf(prev), 1); + else if (!prev && value) this.items.push(new Pair.Pair(key)); + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + if (this.hasAllNullValues(true)) return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else throw new Error("Set items must all have null values"); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) for (let value of iterable) { + if (typeof replacer === "function") value = replacer.call(iterable, value, value); + set.items.push(Pair.createPair(value, null, ctx)); + } + return set; + } + }; + YAMLSet.tag = "tag:yaml.org,2002:set"; + const set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (identity.isMap(map)) if (map.hasAllNullValues(true)) return Object.assign(new YAMLSet(), map); + else onError("Set items must all have null values"); + else onError("Expected a mapping for this tag"); + return map; + } + }; + exports.YAMLSet = YAMLSet; + exports.set = set; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +var require_timestamp = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + /** Internal types handle bigint as number, because TS can't figure it out. */ + function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res, p) => res * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; + } + /** + * hhhh:mm:ss.sss + * + * Internal types handle bigint as number, because TS can't figure it out. + */ + function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === "bigint") num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) return stringifyNumber.stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) parts.unshift(0); + else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + } + const intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal + }; + const floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal + }; + const timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + exports.floatTime = floatTime; + exports.intTime = intTime; + exports.timestamp = timestamp; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js +var require_schema = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var binary = require_binary(); + var bool = require_bool(); + var float = require_float(); + var int = require_int(); + var merge = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var set = require_set(); + var timestamp = require_timestamp(); + exports.schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.trueTag, + bool.falseTag, + int.intBin, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float, + binary.binary, + merge.merge, + omap.omap, + pairs.pairs, + set.set, + timestamp.intTime, + timestamp.floatTime, + timestamp.timestamp + ]; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js +var require_tags = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var bool = require_bool$1(); + var float = require_float$1(); + var int = require_int$1(); + var schema = require_schema$2(); + var schema$1 = require_schema$1(); + var binary = require_binary(); + var merge = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var schema$2 = require_schema(); + var set = require_set(); + var timestamp = require_timestamp(); + const schemas = /* @__PURE__ */ new Map([ + ["core", schema.schema], + ["failsafe", [ + map.map, + seq.seq, + string.string + ]], + ["json", schema$1.schema], + ["yaml11", schema$2.schema], + ["yaml-1.1", schema$2.schema] + ]); + const tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int.int, + intHex: int.intHex, + intOct: int.intOct, + intTime: timestamp.intTime, + map: map.map, + merge: merge.merge, + null: _null.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq.seq, + set: set.set, + timestamp: timestamp.timestamp + }; + const coreKnownTags = { + "tag:yaml.org,2002:binary": binary.binary, + "tag:yaml.org,2002:merge": merge.merge, + "tag:yaml.org,2002:omap": omap.omap, + "tag:yaml.org,2002:pairs": pairs.pairs, + "tag:yaml.org,2002:set": set.set, + "tag:yaml.org,2002:timestamp": timestamp.timestamp + }; + function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice(); + let tags = schemaTags; + if (!tags) if (Array.isArray(customTags)) tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + if (Array.isArray(customTags)) for (const tag of customTags) tags = tags.concat(tag); + else if (typeof customTags === "function") tags = customTags(tags.slice()); + if (addMergeTag) tags = tags.concat(merge.merge); + return tags.reduce((tags, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags.includes(tagObj)) tags.push(tagObj); + return tags; + }, []); + } + exports.coreKnownTags = coreKnownTags; + exports.getTags = getTags; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js +var require_Schema = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var map = require_map(); + var seq = require_seq(); + var string = require_string(); + var tags = require_tags(); + const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + exports.Schema = class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; + this.name = typeof schema === "string" && schema || "core"; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity.MAP, { value: map.map }); + Object.defineProperty(this, identity.SCALAR, { value: string.string }); + Object.defineProperty(this, identity.SEQ, { value: seq.seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } + }; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js +var require_stringifyDocument = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) hasDirectives = true; + } + if (hasDirectives) lines.push("---"); + const ctx = stringify.createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (identity.isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) body += stringifyComment.lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") lines[lines.length - 1] = `--- ${body}`; + else lines.push(body); + } else lines.push(stringify.stringify(doc.contents, ctx)); + if (doc.directives?.docEnd) if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(stringifyComment.indentComment(cs, "")); + } else lines.push(`... ${cs}`); + } else lines.push("..."); + else { + let dc = doc.comment; + if (dc && chompKeep) dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") lines.push(""); + lines.push(stringifyComment.indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; + } + exports.stringifyDocument = stringifyDocument; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/Document.js +var require_Document = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var toJS = require_toJS(); + var Schema = require_Schema(); + var stringifyDocument = require_stringifyDocument(); + var anchors = require_anchors(); + var applyReviver = require_applyReviver(); + var createNode = require_createNode(); + var directives = require_directives(); + var Document = class Document { + constructor(value, replacer, options) { + /** A comment before this Document */ + this.commentBefore = null; + /** A comment immediately after this Document */ + this.comment = null; + /** Errors encountered during parsing. */ + this.errors = []; + /** Warnings encountered during parsing. */ + this.warnings = []; + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) _replacer = replacer; + else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) version = this.directives.yaml.version; + } else this.directives = new directives.Directives({ version }); + this.setSchema(version, options); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { [identity.NODE_TYPE]: { value: identity.DOC } }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + } + return new Alias.Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a"); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity.isCollection(node)) node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair.Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (Collection.isEmptyPath(path)) { + if (this.contents == null) return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (Collection.isEmptyPath(path)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; + return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return identity.isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (Collection.isEmptyPath(path)) return this.contents !== void 0; + return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) this.contents = Collection.collectionFromPath(this.schema, [key], value); + else if (assertCollection(this.contents)) this.contents.set(key, value); + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (Collection.isEmptyPath(path)) this.contents = value; + else if (this.contents == null) this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); + else if (assertCollection(this.contents)) this.contents.setIn(path, value); + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) this.directives.yaml.version = "1.1"; + else this.directives = new directives.Directives({ version: "1.1" }); + opt = { + resolveKnownTags: false, + schema: "yaml-1.1" + }; + break; + case "1.2": + case "next": + if (this.directives) this.directives.yaml.version = version; + else this.directives = new directives.Directives({ version }); + opt = { + resolveKnownTags: true, + schema: "core" + }; + break; + case null: + if (this.directives) delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) this.schema = options.schema; + else if (opt) this.schema = new Schema.Schema(Object.assign(opt, options)); + else throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ + json: true, + jsonArg, + mapAsMap: false, + onAnchor + }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument.stringifyDocument(this, options); + } + }; + function assertCollection(contents) { + if (identity.isCollection(contents)) return true; + throw new Error("Expected a YAML collection as document contents"); + } + exports.Document = Document; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + }; + var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + }; + var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + }; + const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) prev = prev.substring(0, 79) + "…\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) count = Math.max(1, Math.min(end.col - col, 80 - ci)); + const pointer = " ".repeat(ci) + "^".repeat(count); + error.message += `:\n\n${lineStr}\n${pointer}\n`; + } + }; + exports.YAMLError = YAMLError; + exports.YAMLParseError = YAMLParseError; + exports.YAMLWarning = YAMLWarning; + exports.prettifyError = prettifyError; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-props.js +var require_resolve_props = /* @__PURE__ */ __commonJSMin(((exports) => { + function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) tab = token; + hasSpace = true; + break; + case "comment": { + if (!hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) comment = cb; + else comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) comment += token.source; + else if (!found || indicator !== "seq-item-ind") spaceBefore = true; + } else commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": + if (tag) onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case indicator: + if (anchor || tag) onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": if (flow) { + if (comma) onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; + } + exports.resolveProps = resolveProps; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-contains-newline.js +var require_util_contains_newline = /* @__PURE__ */ __commonJSMin(((exports) => { + function containsNewline(key) { + if (!key) return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) return true; + if (key.end) { + for (const st of key.end) if (st.type === "newline") return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) if (st.type === "newline") return true; + if (it.sep) { + for (const st of it.sep) if (st.type === "newline") return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) return true; + } + return false; + default: return true; + } + } + exports.containsNewline = containsNewline; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-flow-indent-check.js +var require_util_flow_indent_check = /* @__PURE__ */ __commonJSMin(((exports) => { + var utilContainsNewline = require_util_contains_newline(); + function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) onError(end, "BAD_INDENT", "Flow end indicator should be more indented than parent", true); + } + } + exports.flowIndentCheck = flowIndentCheck; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-map-includes.js +var require_util_map_includes = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); + } + exports.mapIncludes = mapIncludes; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-map.js +var require_resolve_block_map = /* @__PURE__ */ __commonJSMin(((exports) => { + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + var utilMapIncludes = require_util_map_includes(); + const startColMsg = "All mapping items must start at the same column"; + function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const map = new ((tag?.nodeClass) ?? YAMLMap.YAMLMap)(ctx.schema); + if (ctx.atRoot) ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps.resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) if (map.comment) map.comment += "\n" + keyProps.comment; + else map.comment = keyProps.comment; + continue; + } + if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } else if (keyProps.found?.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps.resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + map.items.push(pair); + } else { + if (implicitKey) onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; + else keyNode.comment = valueProps.comment; + const pair = new Pair.Pair(keyNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map.range = [ + bm.offset, + offset, + commentEnd ?? offset + ]; + return map; + } + exports.resolveBlockMap = resolveBlockMap; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-seq.js +var require_resolve_block_seq = /* @__PURE__ */ __commonJSMin(((exports) => { + var YAMLSeq = require_YAMLSeq(); + var resolveProps = require_resolve_props(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const seq = new ((tag?.nodeClass) ?? YAMLSeq.YAMLSeq)(ctx.schema); + if (ctx.atRoot) ctx.atRoot = false; + if (ctx.atKey) ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps.resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) if (props.anchor || props.tag || value) if (value?.type === "block-seq") onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + else { + commentEnd = props.end; + if (props.comment) seq.comment = props.comment; + continue; + } + const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [ + bs.offset, + offset, + commentEnd ?? offset + ]; + return seq; + } + exports.resolveBlockSeq = resolveBlockSeq; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-end.js +var require_resolve_end = /* @__PURE__ */ __commonJSMin(((exports) => { + function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) comment = cb; + else comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) sep += source; + hasSpace = true; + break; + default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { + comment, + offset + }; + } + exports.resolveEnd = resolveEnd; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-collection.js +var require_resolve_flow_collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilMapIncludes = require_util_map_includes(); + const blockMsg = "Block collections are not allowed within flow collections"; + const isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === "{"; + const fcName = isMap ? "flow map" : "flow sequence"; + const coll = new ((tag?.nodeClass) ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq))(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) ctx.atRoot = false; + if (ctx.atKey) ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps.resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) if (coll.comment) coll.comment += "\n" + props.comment; + else coll.comment = props.comment; + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + } + if (i === 0) { + if (props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) switch (st.type) { + case "comma": + case "space": break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: break loop; + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity.isPair(prev)) prev = prev.value ?? prev.key; + if (prev.comment) prev.comment += "\n" + prevItemComment; + else prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps.resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) for (const st of sep) { + if (st === valueProps.found) break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) if ("source" in value && value.source?.[0] === ":") onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; + else keyNode.comment = valueProps.comment; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map.items.push(pair); + } else { + const map = new YAMLMap.YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map.range = [ + keyNode.range[0], + endRange[1], + endRange[2] + ]; + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) if (coll.comment) coll.comment += "\n" + end.comment; + else coll.comment = end.comment; + coll.range = [ + fc.offset, + cePos, + end.offset + ]; + } else coll.range = [ + fc.offset, + cePos, + cePos + ]; + return coll; + } + exports.resolveFlowCollection = resolveFlowCollection; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-collection.js +var require_compose_collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveBlockMap = require_resolve_block_map(); + var resolveBlockSeq = require_resolve_block_seq(); + var resolveFlowCollection = require_resolve_flow_collection(); + function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) coll.tag = tagName; + return coll; + } + function composeCollection(CN, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) onError(lastProp, "MISSING_CHAR", "Missing newline after block sequence props"); + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") return resolveCollection(CN, ctx, token, onError, tagName); + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + else onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = identity.isNode(res) ? res : new Scalar.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) node.format = tag.format; + return node; + } + exports.composeCollection = composeCollection; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-scalar.js +var require_resolve_block_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) return { + value: "", + type: null, + comment: "", + range: [ + start, + start, + start + ] + }; + const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") chompStart = i; + else break; + } + if (chompStart === 0) { + const value = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end = start + header.length; + if (scalar.source) end += scalar.source.length; + return { + value, + type, + comment: header.comment, + range: [ + start, + end, + end + ] + }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) trimIndent = indent.length; + } else { + if (indent.length < trimIndent) onError(offset + indent.length, "MISSING_CHAR", "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"); + if (header.indent === 0) trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) onError(offset, "BAD_INDENT", "Block scalar values in collections must be indented"); + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines.length - 1; i >= chompStart; --i) if (lines[i][0].length > trimIndent) chompStart = i + 1; + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) value += lines[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) content = content.slice(0, -1); + /* istanbul ignore if already caught in lexer */ + if (content && indent.length < trimIndent) { + const message = `Block scalar lines must not be less indented than their ${header.indent ? "explicit indentation indicator" : "first line"}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") sep = "\n"; + else if (!prevMoreIndented && sep === "\n") sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") if (sep === "\n") value += "\n"; + else sep = "\n"; + else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": break; + case "+": + for (let i = chompStart; i < lines.length; ++i) value += "\n" + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") value += "\n"; + break; + default: value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { + value, + type, + comment: header.comment, + range: [ + start, + end, + end + ] + }; + } + function parseBlockScalarHeader({ offset, props }, strict, onError) { + /* istanbul ignore if should not happen */ + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) chomp = ch; + else { + const n = Number(ch); + if (!indent && n) indent = n; + else if (error === -1) error = offset + i; + } + } + if (error !== -1) onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": hasSpace = true; + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + onError(token, "UNEXPECTED_TOKEN", `Unexpected token in block scalar header: ${token.type}`); + const ts = token.source; + if (ts && typeof ts === "string") length += ts.length; + } + } + } + return { + mode, + indent, + chomp, + comment, + length + }; + } + /** @returns Array of lines split up as `[indent, content]` */ + function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const lines = [m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]]; + for (let i = 1; i < split.length; i += 2) lines.push([split[i], split[i + 1]]); + return lines; + } + exports.resolveBlockScalar = resolveBlockScalar; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-scalar.js +var require_resolve_flow_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var resolveEnd = require_resolve_end(); + function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [ + offset, + offset + source.length, + offset + source.length + ] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [ + offset, + valueEnd, + re.offset + ] + }; + } + function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": + badChar = `block scalar indicator ${source[0]}`; + break; + case "@": + case "`": + badChar = `reserved character ${source[0]}`; + break; + } + if (badChar) onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); + } + function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + } + function foldLines(source) { + /** + * The negative lookbehind here and in the `re` RegExp is to + * prevent causing a polynomial search time in certain cases. + * + * The try-catch is for Safari, which doesn't support this yet: + * https://caniuse.com/js-regexp-lookbehind + */ + let first, line; + try { + first = /* @__PURE__ */ new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else res += ch; + } + if (source[source.length - 1] !== "\"" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing \"quote"); + return res; + } + /** + * Fold a single newline into a space, multiple newlines to N - 1 newlines. + * Presumes `source[offset] === '\n'` + */ + function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") break; + if (ch === "\n") fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) fold = " "; + return { + fold, + offset + }; + } + const escapeCodes = { + "0": "\0", + a: "\x07", + b: "\b", + e: "\x1B", + f: "\f", + n: "\n", + r: "\r", + t: " ", + v: "\v", + N: "…", + _: "\xA0", + L: "\u2028", + P: "\u2029", + " ": " ", + "\"": "\"", + "/": "/", + "\\": "\\", + " ": " " + }; + function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const code = cc.length === length && /^[0-9a-fA-F]+$/.test(cc) ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + } + exports.resolveFlowScalar = resolveFlowScalar; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-scalar.js +var require_compose_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) tag = ctx.schema[identity.SCALAR]; + else if (tagName) tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") tag = findScalarTagByTest(ctx, value, token, onError); + else tag = ctx.schema[identity.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar.Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) scalar.type = type; + if (tagName) scalar.tag = tagName; + if (tag.format) scalar.format = tag.format; + if (comment) scalar.comment = comment; + return scalar; + } + function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === "!") return schema[identity.SCALAR]; + const matchWithTest = []; + for (const tag of schema.tags) if (!tag.collection && tag.tag === tagName) if (tag.default && tag.test) matchWithTest.push(tag); + else return tag; + for (const tag of matchWithTest) if (tag.test?.test(value)) return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + schema.tags.push(Object.assign({}, kt, { + default: false, + test: void 0 + })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema[identity.SCALAR]; + } + function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { + const tag = schema.tags.find((tag) => (tag.default === true || atKey && tag.default === "key") && tag.test?.test(value)) || schema[identity.SCALAR]; + if (schema.compat) { + const compat = schema.compat.find((tag) => tag.default && tag.test?.test(value)) ?? schema[identity.SCALAR]; + if (tag.tag !== compat.tag) onError(token, "TAG_RESOLVE_FAILED", `Value may be parsed as either ${directives.tagString(tag.tag)} or ${directives.tagString(compat.tag)}`, true); + } + return tag; + } + exports.composeScalar = composeScalar; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-empty-scalar-position.js +var require_util_empty_scalar_position = /* @__PURE__ */ __commonJSMin(((exports) => { + function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; + } + exports.emptyScalarPosition = emptyScalarPosition; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-node.js +var require_compose_node = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var composeCollection = require_compose_collection(); + var composeScalar = require_compose_scalar(); + var resolveEnd = require_resolve_end(); + var utilEmptyScalarPosition = require_util_empty_scalar_position(); + const CN = { + composeNode, + composeEmptyNode + }; + function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection.composeCollection(CN, ctx, token, props, onError); + if (anchor) node.anchor = anchor.source.substring(1); + } catch (error) { + onError(token, "RESOURCE_EXHAUSTION", error instanceof Error ? error.message : String(error)); + } + break; + default: + onError(token, "UNEXPECTED_TOKEN", token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`); + isSrcToken = false; + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) onError(tag ?? token, "NON_STRING_KEY", "With stringKeys, all keys must be strings"); + if (spaceBefore) node.spaceBefore = true; + if (comment) if (token.type === "scalar" && token.source === "") node.comment = comment; + else node.commentBefore = comment; + if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token; + return node; + } + function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; + } + function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias.Alias(source.substring(1)); + if (alias.source === "") onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [ + offset, + valueEnd, + re.offset + ]; + if (re.comment) alias.comment = re.comment; + return alias; + } + exports.composeEmptyNode = composeEmptyNode; + exports.composeNode = composeNode; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-doc.js +var require_compose_doc = /* @__PURE__ */ __commonJSMin(((exports) => { + var Document = require_Document(); + var composeNode = require_compose_node(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document.Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); + if (re.comment) doc.comment = re.comment; + doc.range = [ + offset, + contentEnd, + re.offset + ]; + return doc; + } + exports.composeDoc = composeDoc; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/composer.js +var require_composer = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process$1 = __require("process"); + var directives = require_directives(); + var Document = require_Document(); + var errors = require_errors(); + var identity = require_identity(); + var composeDoc = require_compose_doc(); + var resolveEnd = require_resolve_end(); + function getErrorPos(src) { + if (typeof src === "number") return [src, src + 1]; + if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; + } + function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") i += 1; + atComment = false; + break; + default: + if (!atComment) afterEmptyLine = true; + atComment = false; + } + } + return { + comment, + afterEmptyLine + }; + } + /** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ + var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) this.warnings.push(new errors.YAMLWarning(pos, code, message)); + else this.errors.push(new errors.YAMLParseError(pos, code, message)); + }; + this.directives = new directives.Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment; + else if (afterEmptyLine || doc.directives.docStart || !dc) doc.commentBefore = comment; + else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity.isPair(it)) it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment}\n${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + if (node_process$1.env.LOG_STREAM) console.dir(token, { depth: null }); + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) this.errors.push(error); + else this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", "Unexpected doc-end without preceding document")); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document.Document(void 0, opts); + if (this.atDirectives) this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [ + 0, + endOffset, + endOffset + ]; + this.decorate(doc, false); + yield doc; + } + } + }; + exports.Composer = Composer; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js +var require_cst_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + var errors = require_errors(); + var stringifyString = require_stringifyString(); + function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) onError(offset, code, message); + else throw new errors.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case "block-scalar": return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; + } + /** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ + function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString.stringifyString({ + type, + value + }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { + blockQuote: true, + lineWidth: -1 + } + }); + const end = context.end ?? [{ + type: "newline", + offset: -1, + indent, + source: "\n" + }]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [{ + type: "block-scalar-header", + offset, + indent, + source: head + }]; + if (!addEndtoBlockProps(props, end)) props.push({ + type: "newline", + offset: -1, + indent, + source: "\n" + }); + return { + type: "block-scalar", + offset, + indent, + props, + source: body + }; + } + case "\"": return { + type: "double-quoted-scalar", + offset, + indent, + source, + end + }; + case "'": return { + type: "single-quoted-scalar", + offset, + indent, + source, + end + }; + default: return { + type: "scalar", + offset, + indent, + source, + end + }; + } + } + /** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ + function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") indent += 2; + if (!type) switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: type = "PLAIN"; + } + const source = stringifyString.stringifyString({ + type, + value + }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { + blockQuote: true, + lineWidth: -1 + } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case "\"": + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: setFlowScalarValue(token, source, "scalar"); + } + } + function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [{ + type: "block-scalar-header", + offset, + indent, + source: head + }]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) props.push({ + type: "newline", + offset: -1, + indent, + source: "\n" + }); + for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; + Object.assign(token, { + type: "block-scalar", + indent, + props, + source: body + }); + } + } + /** @returns `true` if last token is a newline */ + function addEndtoBlockProps(props, end) { + if (end) for (const st of end) switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; + } + function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") oa -= token.props[0].source.length; + for (const tok of end) tok.offset += oa; + delete token.props; + Object.assign(token, { + type, + source, + end + }); + break; + } + case "block-map": + case "block-seq": { + const nl = { + type: "newline", + offset: token.offset + source.length, + indent: token.indent, + source: "\n" + }; + delete token.items; + Object.assign(token, { + type, + source, + end: [nl] + }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; + Object.assign(token, { + type, + indent, + source, + end + }); + } + } + } + exports.createScalarToken = createScalarToken; + exports.resolveAsScalar = resolveAsScalar; + exports.setScalarValue = setScalarValue; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js +var require_cst_stringify = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ + const stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) res += stringifyItem(item); + for (const st of token.end) res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) for (const st of token.end) res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) for (const st of token.end) res += st.source; + return res; + } + } + } + function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) res += st.source; + if (key) res += stringifyToken(key); + if (sep) for (const st of sep) res += st.source; + if (value) res += stringifyToken(value); + return res; + } + exports.stringify = stringify; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js +var require_cst_visit = /* @__PURE__ */ __commonJSMin(((exports) => { + const BREAK = Symbol("break visit"); + const SKIP = Symbol("skip children"); + const REMOVE = Symbol("remove item"); + /** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ + function visit(cst, visitor) { + if ("type" in cst && cst.type === "document") cst = { + start: cst.start, + value: cst.value + }; + _visit(Object.freeze([]), cst, visitor); + } + /** Terminate visit traversal completely */ + visit.BREAK = BREAK; + /** Do not visit the children of the current item */ + visit.SKIP = SKIP; + /** Remove the current item */ + visit.REMOVE = REMOVE; + /** Find the item at `path` from `cst` as the root */ + visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) item = tok.items[index]; + else return void 0; + } + return item; + }; + /** + * Get the immediate parent collection of the item at `path` from `cst` as the root. + * + * Throws an error if the collection is not found, which should never happen if the item itself exists. + */ + visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) return coll; + throw new Error("Parent collection not found"); + }; + function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; + } + exports.visit = visit; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js +var require_cst = /* @__PURE__ */ __commonJSMin(((exports) => { + var cstScalar = require_cst_scalar(); + var cstStringify = require_cst_stringify(); + var cstVisit = require_cst_visit(); + /** The byte order mark */ + const BOM = ""; + /** Start of doc-mode */ + const DOCUMENT = ""; + /** Unexpected end of flow-mode */ + const FLOW_END = ""; + /** Next token is a scalar value */ + const SCALAR = ""; + /** @returns `true` if `token` is a flow or block collection */ + const isCollection = (token) => !!token && "items" in token; + /** @returns `true` if `token` is a flow or block scalar; not an alias */ + const isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + /* istanbul ignore next */ + /** Get a printable representation of a lexer token */ + function prettyToken(token) { + switch (token) { + case BOM: return ""; + case DOCUMENT: return ""; + case FLOW_END: return ""; + case SCALAR: return ""; + default: return JSON.stringify(token); + } + } + /** Identify the type of a lexer token. May return `null` for unknown tokens. */ + function tokenType(source) { + switch (source) { + case BOM: return "byte-order-mark"; + case DOCUMENT: return "doc-mode"; + case FLOW_END: return "flow-error-end"; + case SCALAR: return "scalar"; + case "---": return "doc-start"; + case "...": return "doc-end"; + case "": + case "\n": + case "\r\n": return "newline"; + case "-": return "seq-item-ind"; + case "?": return "explicit-key-ind"; + case ":": return "map-value-ind"; + case "{": return "flow-map-start"; + case "}": return "flow-map-end"; + case "[": return "flow-seq-start"; + case "]": return "flow-seq-end"; + case ",": return "comma"; + } + switch (source[0]) { + case " ": + case " ": return "space"; + case "#": return "comment"; + case "%": return "directive-line"; + case "*": return "alias"; + case "&": return "anchor"; + case "!": return "tag"; + case "'": return "single-quoted-scalar"; + case "\"": return "double-quoted-scalar"; + case "|": + case ">": return "block-scalar-header"; + } + return null; + } + exports.createScalarToken = cstScalar.createScalarToken; + exports.resolveAsScalar = cstScalar.resolveAsScalar; + exports.setScalarValue = cstScalar.setScalarValue; + exports.stringify = cstStringify.stringify; + exports.visit = cstVisit.visit; + exports.BOM = BOM; + exports.DOCUMENT = DOCUMENT; + exports.FLOW_END = FLOW_END; + exports.SCALAR = SCALAR; + exports.isCollection = isCollection; + exports.isScalar = isScalar; + exports.prettyToken = prettyToken; + exports.tokenType = tokenType; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js +var require_lexer = /* @__PURE__ */ __commonJSMin(((exports) => { + var cst = require_cst(); + function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": return true; + default: return false; + } + } + const hexDigits = /* @__PURE__ */ new Set("0123456789ABCDEFabcdef"); + const tagChars = /* @__PURE__ */ new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + const flowIndicatorChars = /* @__PURE__ */ new Set(",[]{}"); + const invalidAnchorChars = /* @__PURE__ */ new Set(" ,[]{}\n\r "); + const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + /** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ + var Lexer = class { + constructor() { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + this.atEnd = false; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + this.blockScalarIndent = -1; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + this.blockScalarKeep = false; + /** Current input */ + this.buffer = ""; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + this.flowKey = false; + /** Count of surrounding flow collection levels. */ + this.flowLevel = 0; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + this.indentNext = 0; + /** Indentation level of the current line. */ + this.indentValue = 0; + /** Position of the next \n character. */ + this.lineEndPos = null; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + this.next = null; + /** A pointer to `buffer`; the current position of the lexer. */ + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") return true; + if (ch === "\r") return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": return yield* this.parseStream(); + case "line-start": return yield* this.parseLineStart(); + case "block-start": return yield* this.parseBlockStart(); + case "doc": return yield* this.parseDocument(); + case "flow": return yield* this.parseFlowCollection(); + case "quoted-scalar": return yield* this.parseQuotedScalar(); + case "block-scalar": return yield* this.parseBlockScalar(); + case "plain-scalar": return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) return this.setNext("stream"); + if (line[0] === cst.BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else cs = line.indexOf("#", cs + 1); + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") dirEnd -= 1; + else break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield cst.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": yield* this.pushCount(line.length - n); + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case "\"": + case "'": return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else sp = 0; + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + if (!(indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"))) { + this.flowLevel = 0; + yield cst.FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case "\"": + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") while (end !== -1 && this.buffer[end + 1] === "'") end = this.buffer.indexOf("'", end + 2); + else while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") n += 1; + if (n % 2 === 0) break; + end = this.buffer.indexOf("\"", end + 1); + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + if (end === -1) { + if (!this.atEnd) return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i = this.pos; ch = this.buffer[i]; ++i) switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i; + indent = 0; + break; + case "\r": { + const next = this.buffer[i + 1]; + if (!next && !this.atEnd) return this.setNext("block-scalar"); + if (next === "\n") break; + } + default: break loop; + } + if (!ch && !this.atEnd) return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) this.indentNext = indent; + else this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) do { + let i = nl - 1; + let ch = this.buffer[i]; + if (ch === "\r") ch = this.buffer[--i]; + const lastChar = i; + while (ch === " ") ch = this.buffer[--i]; + if (ch === "\n" && i >= this.pos && i + 1 + indent > lastChar) nl = i; + else break; + } while (true); + yield cst.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else end = i; + if (next === "#" || inFlow && flowIndicatorChars.has(next)) break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) break; + end = i; + } + if (!ch && !this.atEnd) return this.setNext("plain-scalar"); + yield cst.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + case "?": + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) this.indentNext = this.indentValue + 1; + else if (this.flowKey) this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) if (tagChars.has(ch)) ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) ch = this.buffer[i += 3]; + else break; + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") return yield* this.pushCount(2); + else return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do + ch = this.buffer[++i]; + while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } + }; + exports.Lexer = Lexer; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js +var require_line_counter = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ + var LineCounter = class { + constructor() { + this.lineStarts = []; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + this.addNewLine = (offset) => this.lineStarts.push(offset); + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) low = mid + 1; + else high = mid; + } + if (this.lineStarts[low] === offset) return { + line: low + 1, + col: 1 + }; + if (low === 0) return { + line: 0, + col: offset + }; + const start = this.lineStarts[low - 1]; + return { + line: low, + col: offset - start + 1 + }; + }; + } + }; + exports.LineCounter = LineCounter; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js +var require_parser = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process = __require("process"); + var cst = require_cst(); + var lexer = require_lexer(); + function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) if (list[i].type === type) return true; + return false; + } + function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) switch (list[i].type) { + case "space": + case "comment": + case "newline": break; + default: return i; + } + return -1; + } + function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": return true; + default: return false; + } + } + function getPrevProps(parent) { + switch (parent.type) { + case "document": return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: return []; + } + } + /** Note: May modify input array */ + function getFirstKeyStartProps(prev) { + if (prev.length === 0) return []; + let i = prev.length; + loop: while (--i >= 0) switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": break loop; + } + while (prev[++i]?.type === "space"); + return prev.splice(i, prev.length); + } + function arrayPushArray(target, source) { + if (source.length < 1e5) Array.prototype.push.apply(target, source); + else for (let i = 0; i < source.length; ++i) target.push(source[i]); + } + function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) if (it.value.end) arrayPushArray(it.value.end, it.sep); + else it.value.end = it.sep; + else arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } + /** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ + var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + /** If true, space and sequence indicators count as indentation */ + this.atNewLine = true; + /** If true, next token is a scalar value */ + this.atScalar = false; + /** Current indentation level */ + this.indent = 0; + /** Current offset since the start of parsing */ + this.offset = 0; + /** On the same line with a block map key */ + this.onKeyLine = false; + /** Top indicates the node that's currently being built */ + this.stack = []; + /** The source of the current token, set in parse() */ + this.source = ""; + /** The type of the current token, set in parse() */ + this.type = ""; + this.lexer = new lexer.Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) yield* this.next(lexeme); + if (!incomplete) yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) console.log("|", cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ + type: "error", + offset: this.offset, + message, + source + }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": return; + default: this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) yield* this.pop(); + } + get sourceToken() { + return { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) return yield* this.stream(); + switch (top.type) { + case "document": return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return yield* this.scalar(top); + case "block-scalar": return yield* this.blockScalar(top); + case "block-map": return yield* this.blockMap(top); + case "block-seq": return yield* this.blockSequence(top); + case "flow-collection": return yield* this.flowCollection(top); + case "doc-end": return yield* this.documentEnd(top); + } + /* istanbul ignore next should not happen */ + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + /* istanbul ignore if should not happen */ + if (!token) yield { + type: "error", + offset: this.offset, + source: "", + message: "Tried to pop an empty stack" + }; + else if (this.stack.length === 0) yield token; + else { + const top = this.peek(1); + if (token.type === "block-scalar") token.indent = "indent" in top ? top.indent : 0; + else if (token.type === "flow-collection" && top.type === "document") token.indent = 0; + if (token.type === "flow-collection") fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ + start: [], + key: token, + sep: [] + }); + this.onKeyLine = true; + return; + } else if (it.sep) it.value = token; + else { + Object.assign(it, { + key: token, + sep: [] + }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) top.items.push({ + start: [], + value: token + }); + else it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) top.items.push({ + start: [], + key: token, + sep: [] + }); + else if (it.sep) it.value = token; + else Object.assign(it, { + key: token, + sep: [] + }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") top.end = last.start; + else top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { + type: "directive", + offset: this.offset, + source: this.source + }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else doc.start.push(this.sourceToken); + return; + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) this.stack.push(bv); + else yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const start = getFirstKeyStartProps(getPrevProps(this.peek(2))); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else sep = [this.sourceToken]; + const map = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ + start, + key: scalar, + sep + }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + if ((Array.isArray(end) ? end[end.length - 1] : void 0)?.type === "comment") end?.push(this.sourceToken); + else map.items.push({ start: [this.sourceToken] }); + } else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) map.items.push({ start: [this.sourceToken] }); + else if (it.sep) it.sep.push(this.sourceToken); + else { + if (this.atIndentedComment(it.start, map.indent)) { + const end = map.items[map.items.length - 2]?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": break; + case "comment": + if (st.indent > map.indent) nl.length = 0; + break; + default: nl.length = 0; + } + } + if (nl.length >= 2) start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ + start, + explicitKey: true + }); + } else this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start: [this.sourceToken], + explicitKey: true + }] + }); + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) if (!it.sep) if (includesToken(it.start, "newline")) Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + else { + const start = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }); + } + else if (it.value) map.items.push({ + start: [], + key: null, + sep: [this.sourceToken] + }); + else if (includesToken(it.sep, "map-value-ind")) this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }); + else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key, + sep + }] + }); + } else if (start.length > 0) it.sep = it.sep.concat(start, this.sourceToken); + else it.sep.push(this.sourceToken); + else if (!it.sep) Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + else if (it.value || atNextItem) map.items.push({ + start, + key: null, + sep: [this.sourceToken] + }); + else if (includesToken(it.sep, "map-value-ind")) this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start: [], + key: null, + sep: [this.sourceToken] + }] + }); + else it.sep.push(this.sourceToken); + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ + start, + key: fs, + sep: [] + }); + this.onKeyLine = true; + } else if (it.sep) this.stack.push(fs); + else { + Object.assign(it, { + key: fs, + sep: [] + }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) map.items.push({ start }); + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + if ((Array.isArray(end) ? end[end.length - 1] : void 0)?.type === "comment") end?.push(this.sourceToken); + else seq.items.push({ start: [this.sourceToken] }); + } else it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const end = seq.items[seq.items.length - 2]?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq.indent) break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq.indent) break; + if (it.value || includesToken(it.start, "seq-item-ind")) seq.items.push({ start: [this.sourceToken] }); + else it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) fc.items.push({ start: [this.sourceToken] }); + else it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) fc.items.push({ + start: [], + key: null, + sep: [this.sourceToken] + }); + else if (it.sep) it.sep.push(this.sourceToken); + else Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) fc.items.push({ + start: [], + key: fs, + sep: [] + }); + else if (it.sep) this.stack.push(fs); + else Object.assign(it, { + key: fs, + sep: [] + }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + /* istanbul ignore else should not happen */ + if (bv) this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const start = getFirstKeyStartProps(getPrevProps(parent)); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ + start, + key: fc, + sep + }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else yield* this.lineEnd(fc); + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return this.flowScalar(this.type); + case "block-scalar-header": return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const start = getFirstKeyStartProps(getPrevProps(parent)); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + explicitKey: true + }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const start = getFirstKeyStartProps(getPrevProps(parent)); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") return false; + if (this.indent <= indent) return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) docEnd.end.push(this.sourceToken); + else docEnd.end = [this.sourceToken]; + if (this.type === "newline") yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": this.onKeyLine = false; + default: + if (token.end) token.end.push(this.sourceToken); + else token.end = [this.sourceToken]; + if (this.type === "newline") yield* this.pop(); + } + } + }; + exports.Parser = Parser; +})); +//#endregion +//#region ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js +var require_public_api = /* @__PURE__ */ __commonJSMin(((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var errors = require_errors(); + var log = require_log(); + var identity = require_identity(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + return { + lineCounter: options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null, + prettyErrors + }; + } + /** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ + function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + const docs = Array.from(composer$1.compose(parser$1.parse(source))); + if (prettyErrors && lineCounter) for (const doc of docs) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + if (docs.length > 0) return docs; + return Object.assign([], { empty: true }, composer$1.streamInfo()); + } + /** Parse an input string into a single YAML.Document */ + function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + let doc = null; + for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) if (!doc) doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + return doc; + } + function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") _reviver = reviver; + else if (options === void 0 && reviver && typeof reviver === "object") options = reviver; + const doc = parseDocument(src, options); + if (!doc) return null; + doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) if (doc.options.logLevel !== "silent") throw doc.errors[0]; + else doc.errors = []; + return doc.toJS(Object.assign({ reviver: _reviver }, options)); + } + function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) _replacer = replacer; + else if (options === void 0 && replacer) options = replacer; + if (typeof options === "string") options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) return void 0; + } + if (identity.isDocument(value) && !_replacer) return value.toString(options); + return new Document.Document(value, _replacer, options).toString(options); + } + exports.parse = parse; + exports.parseAllDocuments = parseAllDocuments; + exports.parseDocument = parseDocument; + exports.stringify = stringify; +})); +//#endregion +//#region main.ts +var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var Schema = require_Schema(); + var errors = require_errors(); + var Alias = require_Alias(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + require_cst(); + var lexer = require_lexer(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + var publicApi = require_public_api(); + var visit = require_visit(); + exports.Composer = composer.Composer; + exports.Document = Document.Document; + exports.Schema = Schema.Schema; + exports.YAMLError = errors.YAMLError; + exports.YAMLParseError = errors.YAMLParseError; + exports.YAMLWarning = errors.YAMLWarning; + exports.Alias = Alias.Alias; + exports.isAlias = identity.isAlias; + exports.isCollection = identity.isCollection; + exports.isDocument = identity.isDocument; + exports.isMap = identity.isMap; + exports.isNode = identity.isNode; + exports.isPair = identity.isPair; + exports.isScalar = identity.isScalar; + exports.isSeq = identity.isSeq; + exports.Pair = Pair.Pair; + exports.Scalar = Scalar.Scalar; + exports.YAMLMap = YAMLMap.YAMLMap; + exports.YAMLSeq = YAMLSeq.YAMLSeq; + exports.Lexer = lexer.Lexer; + exports.LineCounter = lineCounter.LineCounter; + exports.Parser = parser.Parser; + exports.parse = publicApi.parse; + exports.parseAllDocuments = publicApi.parseAllDocuments; + exports.parseDocument = publicApi.parseDocument; + exports.stringify = publicApi.stringify; + exports.visit = visit.visit; + exports.visitAsync = visit.visitAsync; +})))(); +const PACKAGE_MANAGER_COMMANDS = { + pnpm: { + cmd: "pnpm", + args: [ + "up", + "-r", + "--latest" + ] + }, + yarn: { + cmd: "yarn", + args: ["upgrade", "--latest"] + }, + npm: { + cmd: "npm", + args: ["install"] + } +}; +const PR_TEMPLATE_PATHS = [ + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/pull_request_template.md", + "PULL_REQUEST_TEMPLATE.md", + "pull_request_template.md", + "docs/PULL_REQUEST_TEMPLATE.md", + "docs/pull_request_template.md" +]; +const COMPONENT_REPOSITORIES = /* @__PURE__ */ new Set([ + "tdesign-flutter", + "tdesign-miniprogram", + "tdesign-mobile-react", + "tdesign-mobile-vue", + "tdesign-react", + "tdesign-vue", + "tdesign-vue-next" +]); +const SNAPSHOT_UPDATE_SCRIPTS = { + "tdesign-mobile-react": "test:update", + "tdesign-mobile-vue": "test:update", + "tdesign-react": "test:update", + "tdesign-vue": "test:update", + "tdesign-vue-next": "test:vue:update" +}; +const NO_CHANGELOG_DEPENDENCIES = /* @__PURE__ */ new Set(["@tdesign/site-components", "@tdesign/theme-generator"]); +const NO_CHANGELOG_CHECKBOX = "- [x] 本条 PR 不需要纳入 Changelog"; +const CHANGELOG_TARGET_SECTIONS = { + "tdesign-miniprogram": ["tdesign-miniprogram", "@tdesign/uniapp"], + "tdesign-react": ["tdesign-react"], + "tdesign-vue-next": ["tdesign-vue-next"] +}; +const DEPENDENCY_FIELDS = ["dependencies", "devDependencies"]; +const SEMVER_PATTERN = /^([~^]?)((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*)?(?:\+[0-9a-z-]+(?:\.[0-9a-z-]+)*)?)$/i; +function slugify(value) { + return value.replace(/@/g, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, ""); +} +function getBranchName(deps) { + return `chore/deps/upgrade-${deps.map((d) => `${slugify(d.name)}-${slugify(d.version)}`).join("-")}`; +} +function getPrTitle(deps) { + return `chore: upgrade ${deps.map((d) => `${d.name} to ${d.version}`).join(", ")}`; +} +function getRepoPath(repo, targetDir) { + const base = `./${repo}`; + return targetDir ? path.join(base, targetDir) : base; +} +function parseDependencyName(spec) { + const value = spec.trim(); + if (!value) throw new Error("Empty dependency name"); + if ((value.startsWith("@") ? value.indexOf("@", value.indexOf("/") + 1) : value.lastIndexOf("@")) > 0) throw new Error(`Dependency versions are not supported: ${spec}. Please pass package names only.`); + return value; +} +function parseDependencyInputs(inputs) { + const deps = inputs.flatMap((input) => input.split(/\s+/)).map((item) => item.trim()).filter(Boolean).map(parseDependencyName); + if (!deps.length) throw new Error("Missing deps input"); + return deps; +} +function validatePackageManager(packageManager) { + if (packageManager in PACKAGE_MANAGER_COMMANDS) return packageManager; + throw new Error(`Unsupported package-manager "${packageManager}". Supported values: npm, yarn, pnpm.`); +} +function updateVersionSpecifier(specifier, version, location) { + const match = specifier.match(SEMVER_PATTERN); + if (!match) throw new Error(`Unsupported version specifier "${specifier}" for ${location}. Supported formats: ^1.2.3, ~1.2.3, or 1.2.3.`); + const targetVersion = version.match(SEMVER_PATTERN); + if (!targetVersion || targetVersion[1]) throw new Error(`Invalid target version "${version}" for ${location}`); + return `${match[1]}${targetVersion[2]}`; +} +function formatYamlScalar(source, value) { + if (source.startsWith("'")) return `'${value}'`; + if (source.startsWith("\"")) return JSON.stringify(value); + return value; +} +function updatePnpmCatalogs(content, deps) { + const document = (0, import_dist.parseDocument)(content); + if (document.errors.length) throw new Error(`Failed to parse pnpm-workspace.yaml: ${document.errors[0].message}`); + const depVersions = new Map(deps.map((dep) => [dep.name, dep.version])); + const catalogDependencies = /* @__PURE__ */ new Set(); + const edits = []; + const updateCatalog = (catalog, location) => { + if (catalog == null) return; + if (!(0, import_dist.isMap)(catalog)) throw new Error(`Invalid pnpm catalog at ${location}: expected a mapping`); + for (const pair of catalog.items) { + if (!(0, import_dist.isScalar)(pair.key) || typeof pair.key.value !== "string") continue; + const name = pair.key.value; + const version = depVersions.get(name); + if (!version) continue; + if (!(0, import_dist.isScalar)(pair.value) || typeof pair.value.value !== "string" || !pair.value.range) throw new Error(`Unsupported catalog value for ${location}.${name}: expected a version string`); + const specifier = pair.value.value; + const nextSpecifier = updateVersionSpecifier(specifier, version, `${location}.${name}`); + const [start, end] = pair.value.range; + edits.push({ + end, + start, + value: formatYamlScalar(content.slice(start, end), nextSpecifier) + }); + catalogDependencies.add(name); + } + }; + updateCatalog(document.get("catalog", true), "catalog"); + const namedCatalogs = document.get("catalogs", true); + if (namedCatalogs != null) { + if (!(0, import_dist.isMap)(namedCatalogs)) throw new Error("Invalid pnpm catalogs: expected a mapping"); + for (const pair of namedCatalogs.items) { + if (!(0, import_dist.isScalar)(pair.key) || typeof pair.key.value !== "string") continue; + updateCatalog(pair.value, `catalogs.${pair.key.value}`); + } + } + const updatedContent = edits.sort((a, b) => b.start - a.start).reduce((result, edit) => `${result.slice(0, edit.start)}${edit.value}${result.slice(edit.end)}`, content); + return { + catalogDependencies: [...catalogDependencies], + content: updatedContent + }; +} +function updatePackageManifestVersions(content, deps, manifestPath = "package.json", dependencyFields = DEPENDENCY_FIELDS) { + const errors = []; + const manifest = parse(content, errors, { allowTrailingComma: true }); + if (errors.length || !manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw new Error(`Failed to parse ${manifestPath}`); + let updatedContent = content; + let updated = false; + for (const field of dependencyFields) { + const dependencies = manifest[field]; + if (!dependencies || typeof dependencies !== "object" || Array.isArray(dependencies)) continue; + for (const dep of deps) { + const specifier = dependencies[dep.name]; + if (specifier === void 0) continue; + if (typeof specifier !== "string") throw new Error(`Unsupported version specifier for ${manifestPath}#${field}.${dep.name}: expected a string`); + if (specifier.startsWith("catalog:")) continue; + const nextSpecifier = updateVersionSpecifier(specifier, dep.version, `${manifestPath}#${field}.${dep.name}`); + if (nextSpecifier === specifier) continue; + updatedContent = applyEdits(updatedContent, modify(updatedContent, [field, dep.name], nextSpecifier, {})); + updated = true; + } + } + return { + content: updatedContent, + updated + }; +} +function parseGithubRepository(repositoryUrl) { + if (!repositoryUrl) return void 0; + const normalizedUrl = repositoryUrl.replace(/^git\+/, "").replace(/^git@github\.com:/, "https://github.com/").replace(/^ssh:\/\/git@github\.com\//, "https://github.com/").replace(/^git:\/\/github\.com\//, "https://github.com/"); + try { + const url = new URL(normalizedUrl); + if (url.hostname !== "github.com") return void 0; + const [owner, repoName] = url.pathname.replace(/^\//, "").split("/"); + const repo = repoName?.replace(/\.git$/, ""); + return owner && repo ? { + owner, + repo + } : void 0; + } catch { + return; + } +} +async function fetchPackageVersion(pkg) { + try { + const response = await fetch(`https://registry.npmjs.org/${pkg}/latest`); + if (!response.ok) throw new Error(`status code: ${response.status}`); + const { version, repository } = await response.json(); + if (!version) throw new Error("no version found"); + info(`Latest version of ${pkg} is ${version}`); + const repositoryUrl = typeof repository === "string" ? repository : repository?.url; + const repositoryDirectory = typeof repository === "object" ? repository?.directory : void 0; + return { + name: pkg, + version, + ...repositoryUrl ? { repositoryUrl } : {}, + ...repositoryDirectory ? { repositoryDirectory } : {} + }; + } catch (error) { + throw new Error(`Failed to get ${pkg} info from npm registry: ${error instanceof Error ? error.message : String(error)}`); + } +} +async function resolveDependencyInfos(deps) { + return Promise.all(deps.map(fetchPackageVersion)); +} +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function extractVersionChangelog(content, version) { + const lines = content.split("\n"); + const versionPattern = new RegExp(`(?:^|[^0-9a-z])v?${escapeRegExp(version)}(?=$|[^0-9a-z])`, "i"); + const startIndex = lines.findIndex((line) => { + const headingText = getMarkdownHeading(line)?.replace(/\]\([^)]*\)/g, "]"); + return headingText !== void 0 && versionPattern.test(headingText); + }); + if (startIndex === -1) return void 0; + const headingLevel = lines[startIndex].match(/^#+/)?.[0].length; + if (!headingLevel) return void 0; + const endIndex = lines.findIndex((line, index) => index > startIndex && (line.match(/^#{1,6}(?=[ \t])/)?.[0].length ?? 7) <= headingLevel); + return lines.slice(startIndex, endIndex === -1 ? void 0 : endIndex).join("\n").trim(); +} +async function fetchDependencyRelease(dep, token) { + const repository = parseGithubRepository(dep.repositoryUrl); + if (!repository) { + warning(`No GitHub repository found for ${dep.name}; skipping changelog`); + return; + } + const headers = { + "Accept": "application/vnd.github.raw+json", + "X-GitHub-Api-Version": "2022-11-28" + }; + if (token && token !== "test") headers.Authorization = `Bearer ${token}`; + try { + const changelogPath = [...dep.repositoryDirectory?.split("/").filter(Boolean) ?? [], "CHANGELOG.md"].map((segment) => encodeURIComponent(segment)).join("/"); + const response = await fetch(`https://api.github.com/repos/${repository.owner}/${repository.repo}/contents/${changelogPath}`, { headers }); + if (response.status === 404) { + warning(`No CHANGELOG.md found for ${dep.name}`); + return; + } + if (!response.ok) throw new Error(`status code: ${response.status}`); + const body = extractVersionChangelog(await response.text(), dep.version); + if (!body) { + warning(`No ${dep.version} entry found in CHANGELOG.md for ${dep.name}`); + return; + } + const url = `https://github.com/${repository.owner}/${repository.repo}/blob/HEAD/${changelogPath}`; + info(`Changelog found for ${dep.name}@${dep.version}: ${url}`); + return { + body, + tag: `${dep.name}@${dep.version}`, + url + }; + } catch (error) { + warning(`Failed to get CHANGELOG.md for ${dep.name}@${dep.version}: ${error instanceof Error ? error.message : String(error)}`); + return; + } +} +async function resolveDependencyReleases(deps, token) { + return Promise.all(deps.map(async (dep) => ({ + ...dep, + release: await fetchDependencyRelease(dep, token) + }))); +} +function isPathWithin(root, candidate) { + const relativePath = path.relative(root, candidate); + return relativePath === "" || !path.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`); +} +async function findPnpmWorkspaceFile(startDir, cloneRoot) { + const root = await realpath(path.resolve(cloneRoot)); + let current = await realpath(path.resolve(startDir)); + if (!isPathWithin(root, current)) throw new Error(`Target directory ${startDir} is outside clone root ${cloneRoot}`); + while (true) { + const workspaceFile = path.join(current, "pnpm-workspace.yaml"); + try { + await readFile(workspaceFile, "utf8"); + if (!isPathWithin(root, await realpath(workspaceFile))) throw new Error(`pnpm workspace file is outside clone root: ${workspaceFile}`); + return workspaceFile; + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + if (current === root) return void 0; + current = path.dirname(current); + } +} +async function listPnpmWorkspacePackagePaths(workspaceDir) { + const { stdout } = await getExecOutput("pnpm", [ + "-r", + "list", + "--depth", + "-1", + "--json" + ], { + cwd: workspaceDir, + silent: true + }); + let packages; + try { + packages = JSON.parse(stdout); + if (!Array.isArray(packages)) throw new TypeError("expected an array"); + } catch (error) { + throw new Error(`Failed to read pnpm workspace packages: ${error instanceof Error ? error.message : String(error)}`); + } + const root = await realpath(path.resolve(workspaceDir)); + const packagePaths = /* @__PURE__ */ new Set([root]); + for (const pkg of packages) { + if (!pkg.path) continue; + const packagePath = await realpath(path.resolve(root, pkg.path)); + if (!isPathWithin(root, packagePath)) throw new Error(`pnpm returned a package path outside the workspace: ${pkg.path}`); + packagePaths.add(packagePath); + } + return [...packagePaths]; +} +function getPnpmUpdateCommands(deps, catalogDependencies, targetPath, workspaceDir) { + const catalogNames = new Set(catalogDependencies); + const nonCatalogDependencies = deps.filter((dep) => !catalogNames.has(dep.name)); + const commands = []; + if (nonCatalogDependencies.length) commands.push({ + args: [ + "-r", + "up", + "--latest", + ...nonCatalogDependencies.map((dep) => dep.name) + ], + cwd: targetPath + }); + if (catalogDependencies.length) commands.push({ + args: ["install"], + cwd: workspaceDir + }); + return commands; +} +function getSnapshotUpdateCommand(packageManager, deps, targetRepo, repoPath) { + if (!deps.some((dep) => /^tdesign-icons(?:-|$)/.test(dep.name))) return void 0; + const script = SNAPSHOT_UPDATE_SCRIPTS[targetRepo]; + if (!script) return void 0; + return { + args: packageManager === "npm" ? ["run", script] : [script], + cwd: repoPath + }; +} +async function preparePnpmCatalogUpdates(workspaceFile, deps) { + const workspaceContent = await readFile(workspaceFile, "utf8"); + const catalogResult = updatePnpmCatalogs(workspaceContent, deps); + if (!catalogResult.catalogDependencies.length) return { + catalogDependencies: [], + updates: [] + }; + const catalogNames = new Set(catalogResult.catalogDependencies); + const catalogDeps = deps.filter((dep) => catalogNames.has(dep.name)); + const workspaceDir = path.dirname(workspaceFile); + const packagePaths = await listPnpmWorkspacePackagePaths(workspaceDir); + const updates = (await Promise.all(packagePaths.map(async (packagePath) => { + const manifestPath = path.join(packagePath, "package.json"); + let content; + let resolvedManifestPath; + try { + resolvedManifestPath = await realpath(manifestPath); + if (!isPathWithin(workspaceDir, resolvedManifestPath)) throw new Error(`Package manifest is outside the workspace: ${manifestPath}`); + content = await readFile(resolvedManifestPath, "utf8"); + } catch (error) { + if (error.code === "ENOENT") return void 0; + throw error; + } + const result = updatePackageManifestVersions(content, catalogDeps, resolvedManifestPath); + return result.updated ? { + content: result.content, + filePath: resolvedManifestPath + } : void 0; + }))).filter((update) => update !== void 0); + if (catalogResult.content !== workspaceContent) updates.unshift({ + content: catalogResult.content, + filePath: workspaceFile + }); + return { + catalogDependencies: catalogResult.catalogDependencies, + updates + }; +} +async function printPnpmLockfileDiff(workspaceDir) { + startGroup("pnpm-lock.yaml diff"); + await exec("git", [ + "diff", + "--", + "pnpm-lock.yaml" + ], { cwd: workspaceDir }); + endGroup(); +} +async function updatePnpmDependencies(deps, repo, targetDir) { + const cloneRoot = getRepoPath(repo, ""); + const targetPath = getRepoPath(repo, targetDir); + const workspaceFile = await findPnpmWorkspaceFile(targetPath, cloneRoot); + if (!workspaceFile) { + await exec("pnpm", [ + "-r", + "up", + "--latest", + ...deps.map((dep) => dep.name) + ], { cwd: targetPath }); + await printPnpmLockfileDiff(targetPath); + return; + } + const { catalogDependencies, updates } = await preparePnpmCatalogUpdates(workspaceFile, deps); + await Promise.all(updates.map((update) => writeFile(update.filePath, update.content, "utf8"))); + const commands = getPnpmUpdateCommands(deps, catalogDependencies, targetPath, path.dirname(workspaceFile)); + for (const command of commands) { + const env$1 = command.args[0] === "install" ? Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== void 0)) : void 0; + await exec("pnpm", command.args, { + cwd: command.cwd, + ...env$1 ? { env: { + ...env$1, + CI: "false" + } } : {} + }); + } + await printPnpmLockfileDiff(path.dirname(workspaceFile)); +} +async function updatePackageDependencies(packageManager, deps, repo, targetDir) { + if (packageManager === "pnpm") await updatePnpmDependencies(deps, repo, targetDir); + else { + const repoPath = getRepoPath(repo, targetDir); + const { cmd, args } = PACKAGE_MANAGER_COMMANDS[packageManager]; + await exec(cmd, [...args, ...deps.map((dep) => dep.name)], { cwd: repoPath }); + } + const snapshotCommand = getSnapshotUpdateCommand(packageManager, deps, repo, getRepoPath(repo, "")); + if (snapshotCommand) await exec(packageManager, snapshotCommand.args, { cwd: snapshotCommand.cwd }); +} +async function readPullRequestTemplate(repoPath) { + for (const templatePath of PR_TEMPLATE_PATHS) try { + return await readFile(path.join(repoPath, templatePath), "utf8"); + } catch (error) { + if (error.code !== "ENOENT") throw error; + } +} +function getMarkdownHeading(line) { + const prefix = line.match(/^#{1,6}[ \t]+/); + return prefix ? line.slice(prefix[0].length).trim() : void 0; +} +function insertAfterHeading(body, heading, content) { + const lines = body.split("\n"); + const headingIndex = lines.findIndex((line) => { + const value = getMarkdownHeading(line); + return value !== void 0 && (typeof heading === "string" ? value === heading : heading.test(value)); + }); + if (headingIndex === -1) return { + body, + inserted: false + }; + lines.splice(headingIndex + 1, 0, "", content); + return { + body: lines.join("\n"), + inserted: true + }; +} +function formatReleaseBody(body) { + return body.trim().replace(/^(#{1,6})(?=\s)/gm, (heading) => "#".repeat(Math.min(6, heading.length + 3))); +} +function getDependencySummary(deps) { + return [ + "自动升级以下依赖:", + "", + ...deps.map((dep) => `- \`${dep.name}\` 升级至 \`${dep.version}\``) + ].join("\n"); +} +function getReleaseNotesMarkdown(deps) { + return deps.map((dep) => { + const npmUrl = `https://www.npmjs.com/package/${dep.name}/v/${dep.version}`; + if (!dep.release) return `#### [\`${dep.name}@${dep.version}\`](${npmUrl})\n\n未在仓库的 CHANGELOG.md 中找到对应版本日志。`; + return `#### [\`${dep.name}@${dep.version}\`](${dep.release.url})\n\n${formatReleaseBody(dep.release.body)}`; + }).join("\n\n"); +} +function getChangelogType(heading) { + const value = heading.toLowerCase(); + if (/breaking changes?|破坏性/.test(value)) return "feat!"; + if (/bug fixes?|fixes|修复/.test(value)) return "fix"; + if (/features?|新特性|新增功能/.test(value)) return "feat"; + if (/performance|性能/.test(value)) return "perf"; + if (/documentation|\bdocs?\b|文档/.test(value)) return "docs"; + if (/refactor|重构/.test(value)) return "refactor"; + if (/tests?|测试/.test(value)) return "test"; + if (/\bci\b|持续集成/.test(value)) return "ci"; + if (/build|构建/.test(value)) return "build"; + if (/styles?|代码风格/.test(value)) return "style"; + if (/others?|其他/.test(value)) return "chore"; +} +function parseReleaseChangelog(body) { + const entries = []; + const parents = []; + let currentType; + for (const line of body.split("\n")) { + const heading = getMarkdownHeading(line); + if (heading !== void 0) { + currentType = getChangelogType(heading); + parents.length = 0; + continue; + } + const bulletPrefix = line.match(/^([ \t]*)[-*+][ \t]+/); + if (!bulletPrefix || !currentType) continue; + const indent = bulletPrefix[1].replace(/\t/g, " ").length; + const text = line.slice(bulletPrefix[0].length).trim(); + if (!text) continue; + while (parents.length && parents[parents.length - 1].indent >= indent) parents.pop(); + if (text.endsWith(":")) { + parents.push({ + indent, + text: text.slice(0, -1) + }); + continue; + } + const parentText = parents.map((parent) => parent.text).join(": "); + entries.push({ + text: parentText ? `${parentText}: ${text}` : text, + type: currentType + }); + } + return entries; +} +function formatChangelogType(type, scoped) { + const breaking = type.endsWith("!"); + return `${breaking ? type.slice(0, -1) : type}${scoped ? "(Icon)" : ""}${breaking ? "!" : ""}`; +} +function getChangelogMarkdown(deps, targetRepo) { + const scoped = COMPONENT_REPOSITORIES.has(targetRepo); + return deps.filter((dep) => !NO_CHANGELOG_DEPENDENCIES.has(dep.name)).flatMap((dep) => { + const entries = dep.release ? parseReleaseChangelog(dep.release.body) : []; + if (!entries.length) return [`- ${formatChangelogType("chore", scoped)}: upgrade ${dep.name} to ${dep.version}`]; + return entries.map((entry) => `- ${formatChangelogType(entry.type, scoped)}: ${entry.text}`); + }).join("\n"); +} +function buildNoChangelogPullRequestBody(template) { + if (!template) return NO_CHANGELOG_CHECKBOX; + const body = template.trim(); + const updatedBody = body.replace(/^- \[ \] 本条 PR 不需要纳入 Changelog\r?$/m, NO_CHANGELOG_CHECKBOX); + return updatedBody === body ? `${body}\n\n${NO_CHANGELOG_CHECKBOX}` : updatedBody; +} +function fillTDesignCheckboxes(template) { + const checkedLabels = [ + "其他", + "文档已补充或无须补充", + "代码演示已提供或无须提供", + "TypeScript 定义已补充或无须补充", + "Changelog 已提供或无须提供" + ]; + return template.replace(/^- \[ \] (.+)$/gm, (line, label) => checkedLabels.includes(label.trim()) ? line.replace("[ ]", "[x]") : line).replace(/^- fix\(组件名称\): 处理问题或特性描述 \.\.\.$/gm, ""); +} +function insertChangelog(body, targetRepo, changelog) { + const targetSections = CHANGELOG_TARGET_SECTIONS[targetRepo] ?? []; + let result = body; + let inserted = false; + for (const section of targetSections) { + const sectionResult = insertAfterHeading(result, section, changelog); + result = sectionResult.body; + inserted ||= sectionResult.inserted; + } + if (inserted) return { + body: result, + inserted + }; + return insertAfterHeading(result, /更新日志|changelog|release notes/i, changelog); +} +function buildPullRequestBody(template, deps, targetRepo) { + if (deps.length && deps.every((dep) => NO_CHANGELOG_DEPENDENCIES.has(dep.name))) return buildNoChangelogPullRequestBody(template); + const background = `${getDependencySummary(deps)}\n\n${getReleaseNotesMarkdown(deps)}`; + const changelog = getChangelogMarkdown(deps, targetRepo); + if (!template) return `## 依赖升级\n\n${background}\n\n## 版本日志\n\n${changelog}`; + let body = fillTDesignCheckboxes(template.trim()); + body = insertAfterHeading(body, /相关 Issue|related issues?/i, "无").body; + const backgroundResult = insertAfterHeading(body, /需求背景|解决方案|background|summary|description/i, background); + body = backgroundResult.body; + const changelogResult = insertChangelog(body, targetRepo, changelog); + body = changelogResult.body; + const fallbackSections = [!backgroundResult.inserted ? `## 依赖升级\n\n${background}` : "", !changelogResult.inserted ? `## 版本日志\n\n${changelog}` : ""].filter(Boolean); + return fallbackSections.length ? `${fallbackSections.join("\n\n")}\n\n${body}` : body; } async function updateDependencies(context) { const packageManager = validatePackageManager(getInput("package-manager") || "npm"); @@ -20146,7 +28478,7 @@ async function updateDependencies(context) { info(`deps: ${JSON.stringify(deps)}`); info(`target-dir: ${targetDir || "default (repo root)"}`); if (customTitle) info(`custom-title: ${customTitle}`); - const depInfos = await resolveDependencyInfos(deps); + let depInfos = await resolveDependencyInfos(deps); info(`depInfos: ${JSON.stringify(depInfos)}`); if (packageManager !== "npm") await exec("corepack", ["enable"]); const gitHelper = new GitHelper({ @@ -20157,9 +28489,11 @@ async function updateDependencies(context) { }); const baseBranch = await gitHelper.clone(); await gitHelper.initSubmodule(); + const pullRequestTemplate = await readPullRequestTemplate(getRepoPath(context.repo, "")); + depInfos = await resolveDependencyReleases(depInfos, context.token); const branchName = getBranchName(depInfos); await gitHelper.createBranch(branchName); - await updatePackageDependencies(packageManager, deps, context.repo, targetDir); + await updatePackageDependencies(packageManager, depInfos, context.repo, targetDir); if (!await gitHelper.isNeedCommit()) { info("No changes to commit"); return; @@ -20168,9 +28502,15 @@ async function updateDependencies(context) { await gitHelper.printDiff(); endGroup(); const title = customTitle || getPrTitle(depInfos); + const body = buildPullRequestBody(pullRequestTemplate, depInfos, context.repo); await gitHelper.commit(title); await gitHelper.push(branchName); - await createDepsPr(title, branchName, baseBranch, context); + await new GithubHelper({ + owner: context.owner, + repo: context.repo, + token: context.token, + dryRun: context.dryRun + }).createPR(title, branchName, body, baseBranch); } async function main() { const repo = getInput("repo") || context.repo.repo; @@ -20185,8 +28525,7 @@ async function main() { repo, owner, token, - dryRun, - trigger: context.eventName + dryRun }); } //#endregion diff --git a/actions/upgrade-deps/main.test.ts b/actions/upgrade-deps/main.test.ts index d9b44d8..a706898 100644 --- a/actions/upgrade-deps/main.test.ts +++ b/actions/upgrade-deps/main.test.ts @@ -1,12 +1,26 @@ +import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as path from 'node:path' import * as exec from '@actions/exec' import { beforeEach, describe, expect, it, vi } from 'vitest' import { + buildPullRequestBody, + extractVersionChangelog, + fetchDependencyRelease, fetchPackageVersion, + findPnpmWorkspaceFile, getBranchName, + getChangelogMarkdown, + getPnpmUpdateCommands, getPrTitle, + getSnapshotUpdateCommand, parseDependencyInputs, + parseGithubRepository, resolveDependencyInfos, updatePackageDependencies, + updatePackageManifestVersions, + updatePnpmCatalogs, + updateVersionSpecifier, validatePackageManager, } from './main' @@ -19,6 +33,7 @@ vi.mock('@actions/core', () => ({ info: vi.fn(), setFailed: vi.fn(), startGroup: vi.fn(), + warning: vi.fn(), })) vi.mock('@actions/exec', () => ({ @@ -83,6 +98,24 @@ describe('升级依赖', () => { expect(fetch).toHaveBeenCalledWith('https://registry.npmjs.org/@tdesign/site-components/latest') }) + it('从 npm 元数据保留依赖仓库地址', async () => { + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ + version: '0.5.7', + repository: { + directory: 'packages/view', + type: 'git', + url: 'git+https://github.com/Tencent/tdesign-icons.git', + }, + }), { status: 200 })) + + await expect(fetchPackageVersion('tdesign-icons-view')).resolves.toEqual({ + name: 'tdesign-icons-view', + repositoryDirectory: 'packages/view', + version: '0.5.7', + repositoryUrl: 'git+https://github.com/Tencent/tdesign-icons.git', + }) + }) + it('npm registry 查询失败时中止流程', async () => { vi.mocked(fetch).mockResolvedValueOnce(new Response('', { status: 404 })) @@ -92,11 +125,496 @@ describe('升级依赖', () => { }) it('按包管理器执行升级命令', async () => { - await updatePackageDependencies('npm', ['vite'], 'tdesign-vue-next', '') + await updatePackageDependencies('npm', [{ name: 'vite', version: '7.0.0' }], 'tdesign-vue-next', '') expect(exec.exec).toHaveBeenLastCalledWith('npm', ['install', 'vite'], { cwd: './tdesign-vue-next' }) + }) + + it('icons 依赖升级后执行快照更新命令', async () => { + await updatePackageDependencies('npm', [{ name: 'tdesign-icons-vue-next', version: '0.4.6' }], 'tdesign-vue-next', '') + expect(exec.exec).toHaveBeenLastCalledWith('npm', ['run', 'test:vue:update'], { cwd: './tdesign-vue-next' }) + }) + + it('从 target-dir 查找最近的 pnpm workspace 且不越出 clone', async () => { + const tempDir = await mkdtemp(path.join(tmpdir(), 'upgrade-deps-')) + const cloneRoot = path.join(tempDir, 'repo') + const nestedWorkspace = path.join(cloneRoot, 'packages', 'nested') + const targetDir = path.join(nestedWorkspace, 'apps', 'site') + const outsideDir = path.join(tempDir, 'outside') + + try { + await mkdir(targetDir, { recursive: true }) + await mkdir(outsideDir, { recursive: true }) + await writeFile(path.join(cloneRoot, 'pnpm-workspace.yaml'), 'packages: []\n') + await writeFile(path.join(nestedWorkspace, 'pnpm-workspace.yaml'), 'packages: []\n') + + await expect(findPnpmWorkspaceFile(targetDir, cloneRoot)).resolves.toBe( + path.join(await realpath(nestedWorkspace), 'pnpm-workspace.yaml'), + ) + + await rm(path.join(nestedWorkspace, 'pnpm-workspace.yaml')) + await symlink(path.relative(nestedWorkspace, path.join(cloneRoot, 'pnpm-workspace.yaml')), path.join(nestedWorkspace, 'pnpm-workspace.yaml')) + await expect(findPnpmWorkspaceFile(targetDir, cloneRoot)).resolves.toBe( + path.join(await realpath(nestedWorkspace), 'pnpm-workspace.yaml'), + ) + + const outsideLink = path.join(cloneRoot, 'outside-link') + await symlink(outsideDir, outsideLink) + await expect(findPnpmWorkspaceFile(outsideLink, cloneRoot)).rejects.toThrow('outside clone root') + } + finally { + await rm(tempDir, { force: true, recursive: true }) + } + }) + + it('更新默认和命名 catalog 中的全部匹配项', () => { + const content = `packages: + - packages/* + +catalog: + vite: ^6.0.0 # keep comment + '@tdesign/site-components': '~0.18.0' + +catalogs: + build: + vite: "6.1.0" + eslint: ^9.0.0 + legacy: + vite: 5.4.0 +` + const result = updatePnpmCatalogs(content, [ + { name: 'vite', version: '7.0.0' }, + { name: '@tdesign/site-components', version: '0.19.1' }, + ]) + + expect(result.catalogDependencies).toEqual(['vite', '@tdesign/site-components']) + expect(result.content).toContain('vite: ^7.0.0 # keep comment') + expect(result.content).toContain(`'@tdesign/site-components': '~0.19.1'`) + expect(result.content).toContain('vite: "7.0.0"') + expect(result.content).toContain('vite: 7.0.0') + expect(result.content).toContain('eslint: ^9.0.0') + }) + + it('只更新 JSONC 中的 dependencies 和 devDependencies', () => { + const content = `{ + // catalog and direct declarations can coexist + "dependencies": { + "vite": "catalog:build" + }, + "devDependencies": { + "vite": "^6.0.0", + }, + "peerDependencies": { + "vite": "~6.0.0" + } +} +` + const result = updatePackageManifestVersions(content, [{ name: 'vite', version: '7.0.0' }]) + + expect(result.updated).toBe(true) + expect(result.content).toContain('// catalog and direct declarations can coexist') + expect(result.content).toContain('"vite": "catalog:build"') + expect(result.content).toContain('"vite": "^7.0.0"') + expect(result.content).toContain('"vite": "~6.0.0"') + }) + + it('复杂 catalog 或直接版本声明会中止更新', () => { + expect(() => updatePnpmCatalogs('catalog:\n vite: ">=6 <8"\n', [ + { name: 'vite', version: '7.0.0' }, + ])).toThrow('Unsupported version specifier ">=6 <8" for catalog.vite') + + expect(() => updatePackageManifestVersions(`{ + "dependencies": { + "vite": "workspace:^6.0.0" + } +}`, [{ name: 'vite', version: '7.0.0' }])).toThrow('Unsupported version specifier "workspace:^6.0.0"') + + expect(() => updateVersionSpecifier('=6.0.0', '7.0.0', 'catalog.vite')).toThrow('Unsupported version specifier "=6.0.0"') + expect(() => updateVersionSpecifier('^01.2.3', '7.0.0', 'catalog.vite')).toThrow('Unsupported version specifier "^01.2.3"') + expect(() => updateVersionSpecifier('^1.2.3-alpha..1', '7.0.0', 'catalog.vite')).toThrow('Unsupported version specifier "^1.2.3-alpha..1"') + }) + + it('catalog 依赖手动更新后只对其他依赖执行 up 并安装 workspace', () => { + expect(getPnpmUpdateCommands([ + { name: 'vite', version: '7.0.0' }, + { name: 'eslint', version: '10.0.0' }, + ], ['vite'], 'repo/packages/site', '/repo')).toEqual([ + { + args: ['-r', 'up', '--latest', 'eslint'], + cwd: 'repo/packages/site', + }, + { + args: ['install'], + cwd: '/repo', + }, + ]) + }) + + it('升级 icons 依赖后更新对应仓库快照', () => { + expect(getSnapshotUpdateCommand('pnpm', [{ name: 'tdesign-icons-vue-next', version: '0.4.6' }], 'tdesign-vue-next', './tdesign-vue-next')).toEqual({ + args: ['test:vue:update'], + cwd: './tdesign-vue-next', + }) + expect(getSnapshotUpdateCommand('npm', [{ name: 'tdesign-icons-react', version: '0.6.6' }], 'tdesign-react', './tdesign-react')).toEqual({ + args: ['run', 'test:update'], + cwd: './tdesign-react', + }) + expect(getSnapshotUpdateCommand('pnpm', [{ name: 'vite', version: '7.0.0' }], 'tdesign-vue-next', './tdesign-vue-next')).toBeUndefined() + expect(getSnapshotUpdateCommand('pnpm', [{ name: 'tdesign-icons-view', version: '0.5.7' }], 'tdesign', './tdesign')).toBeUndefined() + }) + + it('解析 npm 常见的 GitHub 仓库地址', () => { + expect(parseGithubRepository('git+https://github.com/Tencent/tdesign-icons.git')).toEqual({ + owner: 'Tencent', + repo: 'tdesign-icons', + }) + expect(parseGithubRepository('git@github.com:Tencent/tdesign-icons.git')).toEqual({ + owner: 'Tencent', + repo: 'tdesign-icons', + }) + expect(parseGithubRepository('https://gitlab.com/Tencent/tdesign-icons.git')).toBeUndefined() + }) + + it('从依赖包目录的 CHANGELOG.md 提取目标版本', async () => { + vi.mocked(fetch).mockResolvedValueOnce(new Response(`# tdesign-icons-view + +## 🌈 0.5.7 + +### Bug Fixes + +- Fix missing icons + +## 🌈 0.5.6 + +### Features + +- Previous change`, { status: 200 })) + + await expect(fetchDependencyRelease({ + name: 'tdesign-icons-view', + repositoryDirectory: 'packages/view', + version: '0.5.7', + repositoryUrl: 'git+https://github.com/Tencent/tdesign-icons.git', + }, 'test')).resolves.toEqual({ + body: '## 🌈 0.5.7\n\n### Bug Fixes\n\n- Fix missing icons', + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/blob/HEAD/packages/view/CHANGELOG.md', + }) + + expect(fetch).toHaveBeenCalledWith( + 'https://api.github.com/repos/Tencent/tdesign-icons/contents/packages/view/CHANGELOG.md', + { + headers: { + 'Accept': 'application/vnd.github.raw+json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + }, + ) + }) + + it('未在 CHANGELOG.md 找到目标版本时不返回其他版本日志', async () => { + vi.mocked(fetch).mockResolvedValueOnce(new Response('## 6.0.0\n\n### Features\n\n- Previous change', { status: 200 })) + + await expect(fetchDependencyRelease({ + name: 'vite', + version: '7.0.0', + repositoryUrl: 'https://github.com/vitejs/vite.git', + }, 'test')).resolves.toBeUndefined() + + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('按标题层级截取版本日志', () => { + expect(extractVersionChangelog(`# Changelog + +## [1.2.2](https://example.com/compare/v1.2.1...v1.2.3) + +- Previous change + +## [v1.2.3](https://example.com/v1.2.3) + +### Bug Fixes + +- Fix issue + +## 1.2.2 + +- Previous change`, '1.2.3')).toBe(`## [v1.2.3](https://example.com/v1.2.3) + +### Bug Fixes + +- Fix issue`) + }) + + it('根据 TDesign PR 模板填入升级摘要和版本日志', () => { + const template = `### 🤔 这个 PR 的性质是? + +- [ ] 日常 bug 修复 +- [ ] 其他 + +### 🔗 相关 Issue + + + +### 💡 需求背景和解决方案 + + + +### 📝 更新日志 + +- fix(组件名称): 处理问题或特性描述 ... + +- [ ] 本条 PR 不需要纳入 Changelog + +### ☑️ 请求合并前的自查清单 + +- [ ] 文档已补充或无须补充 +- [ ] 代码演示已提供或无须提供 +- [ ] TypeScript 定义已补充或无须补充 +- [ ] Changelog 已提供或无须提供` + const body = buildPullRequestBody(template, [{ + name: 'tdesign-icons-view', + version: '0.5.7', + release: { + body: '## 🌈 0.5.7 `2026-07-15`\n\n### 🐞 Bug Fixes\n\n- 修复 fullscreen、logo-wecom-filled、no-result-filled、tree-list、wifi-no-filled 5 个图标搜索缺失 @liweijie0812 ([#264](https://github.com/Tencent/tdesign-icons/pull/264))', + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/releases/tag/tdesign-icons-view%400.5.7', + }, + }], 'tdesign') + + expect(body).toContain('### 💡 需求背景和解决方案\n\n自动升级以下依赖:') + expect(body).toContain('### 🔗 相关 Issue\n\n无') + expect(body).toContain('- `tdesign-icons-view` 升级至 `0.5.7`') + expect(body).toContain('#### [`tdesign-icons-view@0.5.7`]') + expect(body).toContain('##### 🌈 0.5.7 `2026-07-15`\n\n###### 🐞 Bug Fixes') + expect(body).toContain('### 📝 更新日志\n\n- fix: 修复 fullscreen、logo-wecom-filled、no-result-filled、tree-list、wifi-no-filled 5 个图标搜索缺失 @liweijie0812 ([#264](https://github.com/Tencent/tdesign-icons/pull/264))') + expect(body).not.toContain('fix(组件名称)') + expect(body).toContain('- [x] 其他') + expect(body).toContain('- [ ] 本条 PR 不需要纳入 Changelog') + expect(body).toContain('- [x] Changelog 已提供或无须提供') + }) + + it('仅升级无需 Changelog 的依赖时只勾选对应选项', () => { + const template = `### 🤔 这个 PR 的性质是? + +- [ ] 其他 + +### 🔗 相关 Issue + + + +### 💡 需求背景和解决方案 + + + +### 📝 更新日志 + +- [ ] 本条 PR 不需要纳入 Changelog + +#### tdesign-vue-next + + +### ☑️ 请求合并前的自查清单 + +- [ ] 文档已补充或无须补充 +- [ ] Changelog 已提供或无须提供` + const body = buildPullRequestBody(template, [ + { name: '@tdesign/site-components', version: '0.19.1' }, + { name: '@tdesign/theme-generator', version: '1.2.5' }, + ], 'tdesign-vue-next') + + expect(body).toBe(template.replace( + '- [ ] 本条 PR 不需要纳入 Changelog', + '- [x] 本条 PR 不需要纳入 Changelog', + )) + expect(body).not.toContain('自动升级以下依赖') + expect(body).not.toContain('\n无\n') + expect(body).toContain('- [ ] 其他') + expect(body).toContain('- [ ] Changelog 已提供或无须提供') + }) + + it.each([ + '@tdesign/site-components', + '@tdesign/theme-generator', + ])('单独升级 %s 时无需 Changelog', (name) => { + expect(buildPullRequestBody( + '- [ ] 本条 PR 不需要纳入 Changelog', + [{ name, version: '1.0.0' }], + 'tdesign-vue-next', + )).toBe('- [x] 本条 PR 不需要纳入 Changelog') + }) + + it('无需 Changelog 的依赖在没有模板时生成最小正文', () => { + expect(buildPullRequestBody(undefined, [ + { name: '@tdesign/site-components', version: '0.19.1' }, + ], 'tdesign-vue-next')).toBe('- [x] 本条 PR 不需要纳入 Changelog') + }) + + it('混合升级时背景保留全部依赖但 Changelog 忽略特殊依赖', () => { + const template = `### 💡 需求背景和解决方案 + +### 📝 更新日志 + +- [ ] 本条 PR 不需要纳入 Changelog + +#### tdesign-vue-next +` + const body = buildPullRequestBody(template, [{ + name: '@tdesign/site-components', + version: '0.19.1', + release: { + body: '## 0.19.1\n\n### Features\n\n- Update site navigation', + tag: '@tdesign/site-components@0.19.1', + url: 'https://github.com/Tencent/tdesign/releases/tag/site-components', + }, + }, { + name: 'tdesign-icons-view', + version: '0.5.7', + release: { + body: '## 0.5.7\n\n### Bug Fixes\n\n- Fix missing icons', + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/releases/tag/tdesign-icons-view%400.5.7', + }, + }], 'tdesign-vue-next') + + expect(body).toContain('- `@tdesign/site-components` 升级至 `0.19.1`') + expect(body).toContain('Update site navigation') + expect(body).toContain('#### tdesign-vue-next\n\n- fix(Icon): Fix missing icons') + expect(body).not.toContain('feat(Icon): Update site navigation') + expect(body).toContain('- [ ] 本条 PR 不需要纳入 Changelog') + }) + + it('将 release 分类转换成 Conventional Changelog', () => { + const changelog = getChangelogMarkdown([{ + name: 'tdesign-icons-view', + version: '0.5.7', + release: { + body: `## 0.5.7 + +### Breaking Changes +- Remove legacy icon + +### Features +- Add new icon + +### Bug Fixes +- \`Icon\`: + - Fix missing icon + +### Performance +- Reduce bundle size + +### Documentation +- Update icon docs + +### Refactor +- Simplify loader + +### Others +- Update tooling`, + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/releases/tag/tdesign-icons-view%400.5.7', + }, + }], 'tdesign-vue-next') + + expect(changelog).toBe(`- feat(Icon)!: Remove legacy icon +- feat(Icon): Add new icon +- fix(Icon): \`Icon\`: Fix missing icon +- perf(Icon): Reduce bundle size +- docs(Icon): Update icon docs +- refactor(Icon): Simplify loader +- chore(Icon): Update tooling`) + }) + + it('组件仓库将日志写入目标主包区块', () => { + const template = `### 💡 需求背景和解决方案 + +### 📝 更新日志 + +#### tdesign-vue-next + + +#### @tdesign-vue-next/chat +` + const body = buildPullRequestBody(template, [{ + name: 'tdesign-icons-view', + version: '0.5.7', + release: { + body: '## 0.5.7\n\n### Bug Fixes\n\n- Fix missing icons', + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/releases/tag/tdesign-icons-view%400.5.7', + }, + }], 'tdesign-vue-next') + + expect(body).toContain('#### tdesign-vue-next\n\n- fix(Icon): Fix missing icons\n') + expect(body).not.toContain('#### @tdesign-vue-next/chat\n\n- fix(Icon)') + }) + + it('小程序仓库同时写入主包和 uniapp 区块', () => { + const template = `### 💡 需求背景和解决方案 + +### 📝 更新日志 + +#### tdesign-miniprogram + + +#### @tdesign/uniapp + + +#### @tdesign/uniapp-chat +` + const body = buildPullRequestBody(template, [{ + name: 'tdesign-icons-view', + version: '0.5.7', + release: { + body: '## 0.5.7\n\n### Features\n\n- Add new icon', + tag: 'tdesign-icons-view@0.5.7', + url: 'https://github.com/Tencent/tdesign-icons/releases/tag/tdesign-icons-view%400.5.7', + }, + }], 'tdesign-miniprogram') + + expect(body.match(/- feat\(Icon\): Add new icon/g)).toHaveLength(2) + expect(body).toContain('#### tdesign-miniprogram\n\n- feat(Icon): Add new icon') + expect(body).toContain('#### @tdesign/uniapp\n\n- feat(Icon): Add new icon') + expect(body).not.toContain('#### @tdesign/uniapp-chat\n\n- feat(Icon)') + }) + + it('release 缺失时根据目标仓库生成 chore 日志', () => { + const deps = [{ name: 'vite', version: '7.0.0' }] + expect(getChangelogMarkdown(deps, 'tdesign-mobile-vue')).toBe('- chore(Icon): upgrade vite to 7.0.0') + expect(getChangelogMarkdown(deps, 'tdesign')).toBe('- chore: upgrade vite to 7.0.0') + }) + + it.each([ + 'tdesign-flutter', + 'tdesign-miniprogram', + 'tdesign-mobile-react', + 'tdesign-mobile-vue', + 'tdesign-react', + 'tdesign-vue', + 'tdesign-vue-next', + ])('%s 使用 Icon scope', (repo) => { + expect(getChangelogMarkdown([{ + name: 'vite', + version: '7.0.0', + release: { + body: '## 7.0.0\n\n### Bug Fixes\n\n- Fix issue', + tag: 'v7.0.0', + url: 'https://github.com/vitejs/vite/releases/tag/v7.0.0', + }, + }], repo)).toBe('- fix(Icon): Fix issue') + }) + + it('模板没有已知区块时在模板前添加升级内容', () => { + const body = buildPullRequestBody('## Checklist\n\n- [ ] Reviewed', [{ + name: 'vite', + version: '7.0.0', + }], 'unknown-repo') - await updatePackageDependencies('pnpm', ['@tdesign/site-components'], 'tdesign-vue-next', 'site') - expect(exec.exec).toHaveBeenLastCalledWith('pnpm', ['up', '--latest', '@tdesign/site-components'], { cwd: 'tdesign-vue-next/site' }) + expect(body).toMatch(/^## 依赖升级/) + expect(body).toContain('## 版本日志') + expect(body).toContain('未在仓库的 CHANGELOG.md 中找到对应版本日志。') + expect(body).toContain('- chore: upgrade vite to 7.0.0') + expect(body).toContain('## Checklist\n\n- [ ] Reviewed') }) it('生成分支名和默认 PR 标题', () => { diff --git a/actions/upgrade-deps/main.ts b/actions/upgrade-deps/main.ts index d2abed1..9ebee62 100644 --- a/actions/upgrade-deps/main.ts +++ b/actions/upgrade-deps/main.ts @@ -1,20 +1,58 @@ +import type { ParseError } from 'jsonc-parser' +import { readFile, realpath, writeFile } from 'node:fs/promises' import * as path from 'node:path' +import { env as processEnv } from 'node:process' import * as core from '@actions/core' import * as exec from '@actions/exec' import * as github from '@actions/github' import { GitHelper, GithubHelper } from '@workflows/utils' +import { applyEdits, modify, parse as parseJson } from 'jsonc-parser' +import { isMap, isScalar, parseDocument } from 'yaml' interface TriggerContext { repo: string owner: string token: string dryRun: boolean - trigger: string } export interface DependencyInfo { name: string + repositoryDirectory?: string version: string + repositoryUrl?: string + release?: DependencyRelease +} + +export interface DependencyRelease { + body: string + tag: string + url: string +} + +export interface GithubRepository { + owner: string + repo: string +} + +export interface CatalogUpdateResult { + catalogDependencies: string[] + content: string +} + +export interface PackageManifestUpdateResult { + content: string + updated: boolean +} + +export interface PnpmUpdateCommand { + args: string[] + cwd: string +} + +interface FileUpdate { + content: string + filePath: string } const PACKAGE_MANAGER_COMMANDS = { @@ -23,8 +61,57 @@ const PACKAGE_MANAGER_COMMANDS = { npm: { cmd: 'npm', args: ['install'] }, } as const +const PR_TEMPLATE_PATHS = [ + '.github/PULL_REQUEST_TEMPLATE.md', + '.github/pull_request_template.md', + 'PULL_REQUEST_TEMPLATE.md', + 'pull_request_template.md', + 'docs/PULL_REQUEST_TEMPLATE.md', + 'docs/pull_request_template.md', +] + +const COMPONENT_REPOSITORIES = new Set([ + 'tdesign-flutter', + 'tdesign-miniprogram', + 'tdesign-mobile-react', + 'tdesign-mobile-vue', + 'tdesign-react', + 'tdesign-vue', + 'tdesign-vue-next', +]) + +const SNAPSHOT_UPDATE_SCRIPTS: Record = { + 'tdesign-mobile-react': 'test:update', + 'tdesign-mobile-vue': 'test:update', + 'tdesign-react': 'test:update', + 'tdesign-vue': 'test:update', + 'tdesign-vue-next': 'test:vue:update', +} + +const NO_CHANGELOG_DEPENDENCIES = new Set([ + '@tdesign/site-components', + '@tdesign/theme-generator', +]) + +const NO_CHANGELOG_CHECKBOX = '- [x] 本条 PR 不需要纳入 Changelog' + +const CHANGELOG_TARGET_SECTIONS: Record = { + 'tdesign-miniprogram': ['tdesign-miniprogram', '@tdesign/uniapp'], + 'tdesign-react': ['tdesign-react'], + 'tdesign-vue-next': ['tdesign-vue-next'], +} + type PackageManager = keyof typeof PACKAGE_MANAGER_COMMANDS +const DEPENDENCY_FIELDS = [ + 'dependencies', + 'devDependencies', +] as const + +type DependencyField = typeof DEPENDENCY_FIELDS[number] + +const SEMVER_PATTERN = /^([~^]?)((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*)?(?:\+[0-9a-z-]+(?:\.[0-9a-z-]+)*)?)$/i + function slugify(value: string): string { return value.replace(/@/g, '').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') } @@ -79,18 +166,172 @@ export function validatePackageManager(packageManager: string): PackageManager { throw new Error(`Unsupported package-manager "${packageManager}". Supported values: npm, yarn, pnpm.`) } +export function updateVersionSpecifier(specifier: string, version: string, location: string): string { + const match = specifier.match(SEMVER_PATTERN) + if (!match) { + throw new Error(`Unsupported version specifier "${specifier}" for ${location}. Supported formats: ^1.2.3, ~1.2.3, or 1.2.3.`) + } + const targetVersion = version.match(SEMVER_PATTERN) + if (!targetVersion || targetVersion[1]) + throw new Error(`Invalid target version "${version}" for ${location}`) + return `${match[1]}${targetVersion[2]}` +} + +function formatYamlScalar(source: string, value: string): string { + if (source.startsWith('\'')) + return `'${value}'` + if (source.startsWith('"')) + return JSON.stringify(value) + return value +} + +export function updatePnpmCatalogs(content: string, deps: DependencyInfo[]): CatalogUpdateResult { + const document = parseDocument(content) + if (document.errors.length) { + throw new Error(`Failed to parse pnpm-workspace.yaml: ${document.errors[0].message}`) + } + + const depVersions = new Map(deps.map(dep => [dep.name, dep.version])) + const catalogDependencies = new Set() + const edits: Array<{ end: number, start: number, value: string }> = [] + + const updateCatalog = (catalog: unknown, location: string): void => { + if (catalog == null) + return + if (!isMap(catalog)) + throw new Error(`Invalid pnpm catalog at ${location}: expected a mapping`) + + for (const pair of catalog.items) { + if (!isScalar(pair.key) || typeof pair.key.value !== 'string') + continue + + const name = pair.key.value + const version = depVersions.get(name) + if (!version) + continue + if (!isScalar(pair.value) || typeof pair.value.value !== 'string' || !pair.value.range) { + throw new Error(`Unsupported catalog value for ${location}.${name}: expected a version string`) + } + + const specifier = pair.value.value + const nextSpecifier = updateVersionSpecifier(specifier, version, `${location}.${name}`) + const [start, end] = pair.value.range + edits.push({ + end, + start, + value: formatYamlScalar(content.slice(start, end), nextSpecifier), + }) + catalogDependencies.add(name) + } + } + + updateCatalog(document.get('catalog', true), 'catalog') + const namedCatalogs = document.get('catalogs', true) + if (namedCatalogs != null) { + if (!isMap(namedCatalogs)) + throw new Error('Invalid pnpm catalogs: expected a mapping') + for (const pair of namedCatalogs.items) { + if (!isScalar(pair.key) || typeof pair.key.value !== 'string') + continue + updateCatalog(pair.value, `catalogs.${pair.key.value}`) + } + } + + const updatedContent = edits + .sort((a, b) => b.start - a.start) + .reduce((result, edit) => `${result.slice(0, edit.start)}${edit.value}${result.slice(edit.end)}`, content) + + return { + catalogDependencies: [...catalogDependencies], + content: updatedContent, + } +} + +export function updatePackageManifestVersions( + content: string, + deps: DependencyInfo[], + manifestPath = 'package.json', + dependencyFields: readonly DependencyField[] = DEPENDENCY_FIELDS, +): PackageManifestUpdateResult { + const errors: ParseError[] = [] + const manifest = parseJson(content, errors, { allowTrailingComma: true }) as Record | undefined + if (errors.length || !manifest || typeof manifest !== 'object' || Array.isArray(manifest)) { + throw new Error(`Failed to parse ${manifestPath}`) + } + + let updatedContent = content + let updated = false + for (const field of dependencyFields) { + const dependencies = manifest[field] + if (!dependencies || typeof dependencies !== 'object' || Array.isArray(dependencies)) + continue + + for (const dep of deps) { + const specifier = (dependencies as Record)[dep.name] + if (specifier === undefined) + continue + if (typeof specifier !== 'string') + throw new Error(`Unsupported version specifier for ${manifestPath}#${field}.${dep.name}: expected a string`) + if (specifier.startsWith('catalog:')) + continue + + const nextSpecifier = updateVersionSpecifier(specifier, dep.version, `${manifestPath}#${field}.${dep.name}`) + if (nextSpecifier === specifier) + continue + updatedContent = applyEdits(updatedContent, modify(updatedContent, [field, dep.name], nextSpecifier, {})) + updated = true + } + } + + return { content: updatedContent, updated } +} + +export function parseGithubRepository(repositoryUrl?: string): GithubRepository | undefined { + if (!repositoryUrl) + return undefined + + const normalizedUrl = repositoryUrl + .replace(/^git\+/, '') + .replace(/^git@github\.com:/, 'https://github.com/') + .replace(/^ssh:\/\/git@github\.com\//, 'https://github.com/') + .replace(/^git:\/\/github\.com\//, 'https://github.com/') + + try { + const url = new URL(normalizedUrl) + if (url.hostname !== 'github.com') + return undefined + + const [owner, repoName] = url.pathname.replace(/^\//, '').split('/') + const repo = repoName?.replace(/\.git$/, '') + return owner && repo ? { owner, repo } : undefined + } + catch { + return undefined + } +} + export async function fetchPackageVersion(pkg: string): Promise { try { const response = await fetch(`https://registry.npmjs.org/${pkg}/latest`) if (!response.ok) { throw new Error(`status code: ${response.status}`) } - const { version } = await response.json() as { version?: string } + const { version, repository } = await response.json() as { + repository?: string | { directory?: string, url?: string } + version?: string + } if (!version) { throw new Error('no version found') } core.info(`Latest version of ${pkg} is ${version}`) - return { name: pkg, version } + const repositoryUrl = typeof repository === 'string' ? repository : repository?.url + const repositoryDirectory = typeof repository === 'object' ? repository?.directory : undefined + return { + name: pkg, + version, + ...(repositoryUrl ? { repositoryUrl } : {}), + ...(repositoryDirectory ? { repositoryDirectory } : {}), + } } catch (error) { throw new Error(`Failed to get ${pkg} info from npm registry: ${error instanceof Error ? error.message : String(error)}`) @@ -101,25 +342,494 @@ export async function resolveDependencyInfos(deps: string[]): Promise { - const repoPath = getRepoPath(repo, targetDir) - const { cmd, args } = PACKAGE_MANAGER_COMMANDS[packageManager] - await exec.exec(cmd, [...args, ...deps], { cwd: repoPath }) +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } -async function createDepsPr( - title: string, - branchName: string, - baseBranch: string, - context: TriggerContext, -): Promise { - const githubHelper = new GithubHelper({ - owner: context.owner, - repo: context.repo, - token: context.token, - dryRun: context.dryRun, +export function extractVersionChangelog(content: string, version: string): string | undefined { + const lines = content.split('\n') + const versionPattern = new RegExp(`(?:^|[^0-9a-z])v?${escapeRegExp(version)}(?=$|[^0-9a-z])`, 'i') + + const startIndex = lines.findIndex((line) => { + const heading = getMarkdownHeading(line) + const headingText = heading?.replace(/\]\([^)]*\)/g, ']') + return headingText !== undefined && versionPattern.test(headingText) }) - await githubHelper.createPR(title, branchName, title, baseBranch) + if (startIndex === -1) + return undefined + + const headingLevel = lines[startIndex].match(/^#+/)?.[0].length + if (!headingLevel) + return undefined + + const endIndex = lines.findIndex((line, index) => ( + index > startIndex && (line.match(/^#{1,6}(?=[ \t])/)?.[0].length ?? 7) <= headingLevel + )) + return lines.slice(startIndex, endIndex === -1 ? undefined : endIndex).join('\n').trim() +} + +export async function fetchDependencyRelease(dep: DependencyInfo, token: string): Promise { + const repository = parseGithubRepository(dep.repositoryUrl) + if (!repository) { + core.warning(`No GitHub repository found for ${dep.name}; skipping changelog`) + return undefined + } + + const headers: Record = { + 'Accept': 'application/vnd.github.raw+json', + 'X-GitHub-Api-Version': '2022-11-28', + } + if (token && token !== 'test') { + headers.Authorization = `Bearer ${token}` + } + + try { + const changelogPath = [...(dep.repositoryDirectory?.split('/').filter(Boolean) ?? []), 'CHANGELOG.md'] + .map(segment => encodeURIComponent(segment)) + .join('/') + const response = await fetch( + `https://api.github.com/repos/${repository.owner}/${repository.repo}/contents/${changelogPath}`, + { headers }, + ) + if (response.status === 404) { + core.warning(`No CHANGELOG.md found for ${dep.name}`) + return undefined + } + if (!response.ok) + throw new Error(`status code: ${response.status}`) + + const body = extractVersionChangelog(await response.text(), dep.version) + if (!body) { + core.warning(`No ${dep.version} entry found in CHANGELOG.md for ${dep.name}`) + return undefined + } + + const url = `https://github.com/${repository.owner}/${repository.repo}/blob/HEAD/${changelogPath}` + core.info(`Changelog found for ${dep.name}@${dep.version}: ${url}`) + return { + body, + tag: `${dep.name}@${dep.version}`, + url, + } + } + catch (error) { + core.warning(`Failed to get CHANGELOG.md for ${dep.name}@${dep.version}: ${error instanceof Error ? error.message : String(error)}`) + return undefined + } +} + +export async function resolveDependencyReleases(deps: DependencyInfo[], token: string): Promise { + return Promise.all(deps.map(async dep => ({ + ...dep, + release: await fetchDependencyRelease(dep, token), + }))) +} + +function isPathWithin(root: string, candidate: string): boolean { + const relativePath = path.relative(root, candidate) + return relativePath === '' || (!path.isAbsolute(relativePath) && relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`)) +} + +export async function findPnpmWorkspaceFile(startDir: string, cloneRoot: string): Promise { + const root = await realpath(path.resolve(cloneRoot)) + let current = await realpath(path.resolve(startDir)) + if (!isPathWithin(root, current)) + throw new Error(`Target directory ${startDir} is outside clone root ${cloneRoot}`) + + while (true) { + const workspaceFile = path.join(current, 'pnpm-workspace.yaml') + try { + await readFile(workspaceFile, 'utf8') + const resolvedWorkspaceFile = await realpath(workspaceFile) + if (!isPathWithin(root, resolvedWorkspaceFile)) + throw new Error(`pnpm workspace file is outside clone root: ${workspaceFile}`) + return workspaceFile + } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') + throw error + } + + if (current === root) + return undefined + current = path.dirname(current) + } +} + +export async function listPnpmWorkspacePackagePaths(workspaceDir: string): Promise { + const { stdout } = await exec.getExecOutput( + 'pnpm', + ['-r', 'list', '--depth', '-1', '--json'], + { cwd: workspaceDir, silent: true }, + ) + + let packages: Array<{ path?: string }> + try { + packages = JSON.parse(stdout) as Array<{ path?: string }> + if (!Array.isArray(packages)) + throw new TypeError('expected an array') + } + catch (error) { + throw new Error(`Failed to read pnpm workspace packages: ${error instanceof Error ? error.message : String(error)}`) + } + + const root = await realpath(path.resolve(workspaceDir)) + const packagePaths = new Set([root]) + for (const pkg of packages) { + if (!pkg.path) + continue + const packagePath = await realpath(path.resolve(root, pkg.path)) + if (!isPathWithin(root, packagePath)) + throw new Error(`pnpm returned a package path outside the workspace: ${pkg.path}`) + packagePaths.add(packagePath) + } + return [...packagePaths] +} + +export function getPnpmUpdateCommands( + deps: DependencyInfo[], + catalogDependencies: string[], + targetPath: string, + workspaceDir: string, +): PnpmUpdateCommand[] { + const catalogNames = new Set(catalogDependencies) + const nonCatalogDependencies = deps.filter(dep => !catalogNames.has(dep.name)) + const commands: PnpmUpdateCommand[] = [] + + if (nonCatalogDependencies.length) { + commands.push({ + args: ['-r', 'up', '--latest', ...nonCatalogDependencies.map(dep => dep.name)], + cwd: targetPath, + }) + } + if (catalogDependencies.length) + commands.push({ args: ['install'], cwd: workspaceDir }) + + return commands +} + +export function getSnapshotUpdateCommand( + packageManager: PackageManager, + deps: DependencyInfo[], + targetRepo: string, + repoPath: string, +): PnpmUpdateCommand | undefined { + if (!deps.some(dep => /^tdesign-icons(?:-|$)/.test(dep.name))) + return undefined + + const script = SNAPSHOT_UPDATE_SCRIPTS[targetRepo] + if (!script) + return undefined + + const args = packageManager === 'npm' ? ['run', script] : [script] + return { args, cwd: repoPath } +} + +async function preparePnpmCatalogUpdates( + workspaceFile: string, + deps: DependencyInfo[], +): Promise<{ catalogDependencies: string[], updates: FileUpdate[] }> { + const workspaceContent = await readFile(workspaceFile, 'utf8') + const catalogResult = updatePnpmCatalogs(workspaceContent, deps) + if (!catalogResult.catalogDependencies.length) + return { catalogDependencies: [], updates: [] } + + const catalogNames = new Set(catalogResult.catalogDependencies) + const catalogDeps = deps.filter(dep => catalogNames.has(dep.name)) + const workspaceDir = path.dirname(workspaceFile) + const packagePaths = await listPnpmWorkspacePackagePaths(workspaceDir) + const manifestUpdates = await Promise.all(packagePaths.map(async (packagePath): Promise => { + const manifestPath = path.join(packagePath, 'package.json') + let content: string + let resolvedManifestPath: string + try { + resolvedManifestPath = await realpath(manifestPath) + if (!isPathWithin(workspaceDir, resolvedManifestPath)) + throw new Error(`Package manifest is outside the workspace: ${manifestPath}`) + content = await readFile(resolvedManifestPath, 'utf8') + } + catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + return undefined + throw error + } + + const result = updatePackageManifestVersions(content, catalogDeps, resolvedManifestPath) + return result.updated ? { content: result.content, filePath: resolvedManifestPath } : undefined + })) + + const updates = manifestUpdates.filter((update): update is FileUpdate => update !== undefined) + if (catalogResult.content !== workspaceContent) { + updates.unshift({ content: catalogResult.content, filePath: workspaceFile }) + } + return { catalogDependencies: catalogResult.catalogDependencies, updates } +} + +async function printPnpmLockfileDiff(workspaceDir: string): Promise { + core.startGroup('pnpm-lock.yaml diff') + await exec.exec('git', ['diff', '--', 'pnpm-lock.yaml'], { cwd: workspaceDir }) + core.endGroup() +} + +async function updatePnpmDependencies(deps: DependencyInfo[], repo: string, targetDir: string): Promise { + const cloneRoot = getRepoPath(repo, '') + const targetPath = getRepoPath(repo, targetDir) + const workspaceFile = await findPnpmWorkspaceFile(targetPath, cloneRoot) + if (!workspaceFile) { + await exec.exec('pnpm', ['-r', 'up', '--latest', ...deps.map(dep => dep.name)], { cwd: targetPath }) + await printPnpmLockfileDiff(targetPath) + return + } + + const { catalogDependencies, updates } = await preparePnpmCatalogUpdates(workspaceFile, deps) + await Promise.all(updates.map(update => writeFile(update.filePath, update.content, 'utf8'))) + + const commands = getPnpmUpdateCommands(deps, catalogDependencies, targetPath, path.dirname(workspaceFile)) + for (const command of commands) { + const env = command.args[0] === 'install' + ? Object.fromEntries(Object.entries(processEnv).filter((entry): entry is [string, string] => entry[1] !== undefined)) + : undefined + await exec.exec('pnpm', command.args, { + cwd: command.cwd, + ...(env ? { env: { ...env, CI: 'false' } } : {}), + }) + } + await printPnpmLockfileDiff(path.dirname(workspaceFile)) +} + +export async function updatePackageDependencies(packageManager: PackageManager, deps: DependencyInfo[], repo: string, targetDir: string): Promise { + if (packageManager === 'pnpm') { + await updatePnpmDependencies(deps, repo, targetDir) + } + else { + const repoPath = getRepoPath(repo, targetDir) + const { cmd, args } = PACKAGE_MANAGER_COMMANDS[packageManager] + await exec.exec(cmd, [...args, ...deps.map(dep => dep.name)], { cwd: repoPath }) + } + + const snapshotCommand = getSnapshotUpdateCommand(packageManager, deps, repo, getRepoPath(repo, '')) + if (snapshotCommand) + await exec.exec(packageManager, snapshotCommand.args, { cwd: snapshotCommand.cwd }) +} + +export async function readPullRequestTemplate(repoPath: string): Promise { + for (const templatePath of PR_TEMPLATE_PATHS) { + try { + return await readFile(path.join(repoPath, templatePath), 'utf8') + } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') + throw error + } + } + return undefined +} + +function getMarkdownHeading(line: string): string | undefined { + const prefix = line.match(/^#{1,6}[ \t]+/) + return prefix ? line.slice(prefix[0].length).trim() : undefined +} + +function insertAfterHeading(body: string, heading: RegExp | string, content: string): { body: string, inserted: boolean } { + const lines = body.split('\n') + const headingIndex = lines.findIndex((line) => { + const value = getMarkdownHeading(line) + return value !== undefined && (typeof heading === 'string' ? value === heading : heading.test(value)) + }) + if (headingIndex === -1) + return { body, inserted: false } + + lines.splice(headingIndex + 1, 0, '', content) + return { body: lines.join('\n'), inserted: true } +} + +function formatReleaseBody(body: string): string { + return body + .trim() + .replace(/^(#{1,6})(?=\s)/gm, heading => '#'.repeat(Math.min(6, heading.length + 3))) +} + +export function getDependencySummary(deps: DependencyInfo[]): string { + return [ + '自动升级以下依赖:', + '', + ...deps.map(dep => `- \`${dep.name}\` 升级至 \`${dep.version}\``), + ].join('\n') +} + +export function getReleaseNotesMarkdown(deps: DependencyInfo[]): string { + return deps.map((dep) => { + const npmUrl = `https://www.npmjs.com/package/${dep.name}/v/${dep.version}` + if (!dep.release) { + return `#### [\`${dep.name}@${dep.version}\`](${npmUrl})\n\n未在仓库的 CHANGELOG.md 中找到对应版本日志。` + } + + return `#### [\`${dep.name}@${dep.version}\`](${dep.release.url})\n\n${formatReleaseBody(dep.release.body)}` + }).join('\n\n') +} + +type ChangelogType = 'build' | 'chore' | 'ci' | 'docs' | 'feat' | 'feat!' | 'fix' | 'perf' | 'refactor' | 'style' | 'test' + +interface ChangelogEntry { + text: string + type: ChangelogType +} + +function getChangelogType(heading: string): ChangelogType | undefined { + const value = heading.toLowerCase() + if (/breaking changes?|破坏性/.test(value)) + return 'feat!' + if (/bug fixes?|fixes|修复/.test(value)) + return 'fix' + if (/features?|新特性|新增功能/.test(value)) + return 'feat' + if (/performance|性能/.test(value)) + return 'perf' + if (/documentation|\bdocs?\b|文档/.test(value)) + return 'docs' + if (/refactor|重构/.test(value)) + return 'refactor' + if (/tests?|测试/.test(value)) + return 'test' + if (/\bci\b|持续集成/.test(value)) + return 'ci' + if (/build|构建/.test(value)) + return 'build' + if (/styles?|代码风格/.test(value)) + return 'style' + if (/others?|其他/.test(value)) + return 'chore' + return undefined +} + +export function parseReleaseChangelog(body: string): ChangelogEntry[] { + const entries: ChangelogEntry[] = [] + const parents: Array<{ indent: number, text: string }> = [] + let currentType: ChangelogType | undefined + + for (const line of body.split('\n')) { + const heading = getMarkdownHeading(line) + if (heading !== undefined) { + currentType = getChangelogType(heading) + parents.length = 0 + continue + } + + const bulletPrefix = line.match(/^([ \t]*)[-*+][ \t]+/) + if (!bulletPrefix || !currentType) + continue + + const indent = bulletPrefix[1].replace(/\t/g, ' ').length + const text = line.slice(bulletPrefix[0].length).trim() + if (!text) + continue + + while (parents.length && parents[parents.length - 1].indent >= indent) { + parents.pop() + } + + if (text.endsWith(':')) { + parents.push({ indent, text: text.slice(0, -1) }) + continue + } + + const parentText = parents.map(parent => parent.text).join(': ') + entries.push({ + text: parentText ? `${parentText}: ${text}` : text, + type: currentType, + }) + } + + return entries +} + +function formatChangelogType(type: ChangelogType, scoped: boolean): string { + const breaking = type.endsWith('!') + const baseType = breaking ? type.slice(0, -1) : type + return `${baseType}${scoped ? '(Icon)' : ''}${breaking ? '!' : ''}` +} + +export function getChangelogMarkdown(deps: DependencyInfo[], targetRepo: string): string { + const scoped = COMPONENT_REPOSITORIES.has(targetRepo) + return deps.filter(dep => !NO_CHANGELOG_DEPENDENCIES.has(dep.name)).flatMap((dep) => { + const entries = dep.release ? parseReleaseChangelog(dep.release.body) : [] + if (!entries.length) { + return [`- ${formatChangelogType('chore', scoped)}: upgrade ${dep.name} to ${dep.version}`] + } + return entries.map(entry => `- ${formatChangelogType(entry.type, scoped)}: ${entry.text}`) + }).join('\n') +} + +function buildNoChangelogPullRequestBody(template: string | undefined): string { + if (!template) + return NO_CHANGELOG_CHECKBOX + + const body = template.trim() + const updatedBody = body.replace( + /^- \[ \] 本条 PR 不需要纳入 Changelog\r?$/m, + NO_CHANGELOG_CHECKBOX, + ) + return updatedBody === body ? `${body}\n\n${NO_CHANGELOG_CHECKBOX}` : updatedBody +} + +function fillTDesignCheckboxes(template: string): string { + const checkedLabels = [ + '其他', + '文档已补充或无须补充', + '代码演示已提供或无须提供', + 'TypeScript 定义已补充或无须补充', + 'Changelog 已提供或无须提供', + ] + + return template + .replace(/^- \[ \] (.+)$/gm, (line, label: string) => ( + checkedLabels.includes(label.trim()) ? line.replace('[ ]', '[x]') : line + )) + .replace(/^- fix\(组件名称\): 处理问题或特性描述 \.\.\.$/gm, '') +} + +function insertChangelog(body: string, targetRepo: string, changelog: string): { body: string, inserted: boolean } { + const targetSections = CHANGELOG_TARGET_SECTIONS[targetRepo] ?? [] + let result = body + let inserted = false + for (const section of targetSections) { + const sectionResult = insertAfterHeading(result, section, changelog) + result = sectionResult.body + inserted ||= sectionResult.inserted + } + + if (inserted) + return { body: result, inserted } + return insertAfterHeading(result, /更新日志|changelog|release notes/i, changelog) +} + +export function buildPullRequestBody(template: string | undefined, deps: DependencyInfo[], targetRepo: string): string { + if (deps.length && deps.every(dep => NO_CHANGELOG_DEPENDENCIES.has(dep.name))) { + return buildNoChangelogPullRequestBody(template) + } + + const summary = getDependencySummary(deps) + const releaseNotes = getReleaseNotesMarkdown(deps) + const background = `${summary}\n\n${releaseNotes}` + const changelog = getChangelogMarkdown(deps, targetRepo) + if (!template) { + return `## 依赖升级\n\n${background}\n\n## 版本日志\n\n${changelog}` + } + + let body = fillTDesignCheckboxes(template.trim()) + const issueResult = insertAfterHeading(body, /相关 Issue|related issues?/i, '无') + body = issueResult.body + const backgroundResult = insertAfterHeading(body, /需求背景|解决方案|background|summary|description/i, background) + body = backgroundResult.body + const changelogResult = insertChangelog(body, targetRepo, changelog) + body = changelogResult.body + + const fallbackSections = [ + !backgroundResult.inserted ? `## 依赖升级\n\n${background}` : '', + !changelogResult.inserted ? `## 版本日志\n\n${changelog}` : '', + ].filter(Boolean) + + return fallbackSections.length ? `${fallbackSections.join('\n\n')}\n\n${body}` : body } export async function updateDependencies(context: TriggerContext): Promise { @@ -134,7 +844,7 @@ export async function updateDependencies(context: TriggerContext): Promise core.info(`custom-title: ${customTitle}`) } - const depInfos = await resolveDependencyInfos(deps) + let depInfos = await resolveDependencyInfos(deps) core.info(`depInfos: ${JSON.stringify(depInfos)}`) if (packageManager !== 'npm') { @@ -150,10 +860,12 @@ export async function updateDependencies(context: TriggerContext): Promise const baseBranch = await gitHelper.clone() await gitHelper.initSubmodule() + const pullRequestTemplate = await readPullRequestTemplate(getRepoPath(context.repo, '')) + depInfos = await resolveDependencyReleases(depInfos, context.token) const branchName = getBranchName(depInfos) await gitHelper.createBranch(branchName) - await updatePackageDependencies(packageManager, deps, context.repo, targetDir) + await updatePackageDependencies(packageManager, depInfos, context.repo, targetDir) if (!(await gitHelper.isNeedCommit())) { core.info('No changes to commit') @@ -165,9 +877,16 @@ export async function updateDependencies(context: TriggerContext): Promise core.endGroup() const title = customTitle || getPrTitle(depInfos) + const body = buildPullRequestBody(pullRequestTemplate, depInfos, context.repo) await gitHelper.commit(title) await gitHelper.push(branchName) - await createDepsPr(title, branchName, baseBranch, context) + const githubHelper = new GithubHelper({ + owner: context.owner, + repo: context.repo, + token: context.token, + dryRun: context.dryRun, + }) + await githubHelper.createPR(title, branchName, body, baseBranch) } export async function main(): Promise { @@ -186,6 +905,5 @@ export async function main(): Promise { owner, token, dryRun, - trigger: github.context.eventName, }) } diff --git a/actions/upgrade-deps/package.json b/actions/upgrade-deps/package.json index fe31ba1..14a3ad4 100644 --- a/actions/upgrade-deps/package.json +++ b/actions/upgrade-deps/package.json @@ -10,7 +10,9 @@ "@actions/core": "catalog:", "@actions/exec": "catalog:", "@actions/github": "catalog:", - "@workflows/utils": "workspace:*" + "@workflows/utils": "workspace:*", + "jsonc-parser": "catalog:", + "yaml": "catalog:" }, "devDependencies": { "@octokit/plugin-rest-endpoint-methods": "catalog:", diff --git a/actions/upgrade-deps/tsdown.config.ts b/actions/upgrade-deps/tsdown.config.ts index a29b31d..4d6f20c 100644 --- a/actions/upgrade-deps/tsdown.config.ts +++ b/actions/upgrade-deps/tsdown.config.ts @@ -3,12 +3,19 @@ import { defineConfig } from 'tsdown' export default defineConfig({ entry: ['index.ts'], shims: true, + inputOptions: { + resolve: { + mainFields: ['module', 'main'], + }, + }, deps: { alwaysBundle: [ '@actions/core', '@actions/exec', '@actions/github', '@workflows/utils', + 'jsonc-parser', + 'yaml', ], onlyBundle: [ '@actions/core', @@ -26,9 +33,11 @@ export default defineConfig({ '@octokit/request-error', 'before-after-hook', 'fast-content-type-parse', + 'jsonc-parser', 'tunnel', 'undici', 'universal-user-agent', + 'yaml', ], }, }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 426ec55..6671746 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -30,12 +30,18 @@ catalogs: eslint: specifier: ^10.7.0 version: 10.7.0 + jsonc-parser: + specifier: ^3.3.1 + version: 3.3.1 tsdown: specifier: ^0.22.5 version: 0.22.5 vitest: specifier: ^4.1.10 version: 4.1.10 + yaml: + specifier: ^2.9.0 + version: 2.9.0 importers: @@ -138,6 +144,12 @@ importers: '@workflows/utils': specifier: workspace:* version: link:../../packages/utils + jsonc-parser: + specifier: 'catalog:' + version: 3.3.1 + yaml: + specifier: 'catalog:' + version: 2.9.0 devDependencies: '@octokit/plugin-rest-endpoint-methods': specifier: 'catalog:' @@ -1651,6 +1663,9 @@ packages: resolution: {integrity: sha512-75EA7EWZExL/j+MDKQrRbdzcRI2HOkRlmUw8fZJc1ioqFEOvBsq7Rt+A6yCxOt9w/TYNpkt52gC6nm/g5tFIng==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} + jsonc-parser@3.3.1: + resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + katex@0.16.45: resolution: {integrity: sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==} hasBin: true @@ -2349,11 +2364,6 @@ packages: resolution: {integrity: sha512-h0uDm97wvT2bokfwwTmY6kJ1hp6YDFL0nRHwNKz8s/VD1FH/vvZjAKoMUE+un0eaYBSG7/c6h+lJTP+31tjgTw==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} - yaml@2.8.2: - resolution: {integrity: sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==} - engines: {node: '>= 14.6'} - hasBin: true - yaml@2.9.0: resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} engines: {node: '>= 14.6'} @@ -3792,6 +3802,8 @@ snapshots: eslint-visitor-keys: 5.0.1 semver: 7.8.5 + jsonc-parser@3.3.1: {} + katex@0.16.45: dependencies: commander: 8.3.0 @@ -4615,9 +4627,7 @@ snapshots: yaml-eslint-parser@2.0.0: dependencies: eslint-visitor-keys: 5.0.1 - yaml: 2.8.2 - - yaml@2.8.2: {} + yaml: 2.9.0 yaml@2.9.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a78bf75..ec70bdc 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,5 +18,7 @@ catalog: '@types/node': ^24.13.3 '@typescript/native-preview': 7.0.0-dev.20260707.2 eslint: ^10.7.0 + jsonc-parser: ^3.3.1 tsdown: ^0.22.5 vitest: ^4.1.10 + yaml: ^2.9.0