@halospv3/hce.shared-config 3.4.7 → 3.4.8-develop.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +19 -4
  2. package/mjs/CaseInsensitiveMap.mjs +27 -1
  3. package/mjs/CaseInsensitiveMap.mjs.map +1 -1
  4. package/mjs/commitlintConfig.mjs +13 -1
  5. package/mjs/commitlintConfig.mjs.map +1 -1
  6. package/mjs/debug.mjs +8 -1
  7. package/mjs/debug.mjs.map +1 -1
  8. package/mjs/dotnet/GithubNugetRegistryInfo.mjs +39 -1
  9. package/mjs/dotnet/GithubNugetRegistryInfo.mjs.map +1 -1
  10. package/mjs/dotnet/GitlabNugetRegistryInfo.mjs +81 -1
  11. package/mjs/dotnet/GitlabNugetRegistryInfo.mjs.map +1 -1
  12. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.mjs +42 -1
  13. package/mjs/dotnet/IsNextVersionAlreadyPublished.cli.mjs.map +1 -1
  14. package/mjs/dotnet/MSBuildProject.mjs +345 -2
  15. package/mjs/dotnet/MSBuildProject.mjs.map +1 -1
  16. package/mjs/dotnet/MSBuildProjectProperties.mjs +233 -1
  17. package/mjs/dotnet/MSBuildProjectProperties.mjs.map +1 -1
  18. package/mjs/dotnet/NugetProjectProperties.mjs +520 -1
  19. package/mjs/dotnet/NugetProjectProperties.mjs.map +1 -1
  20. package/mjs/dotnet/NugetRegistryInfo.mjs +599 -3
  21. package/mjs/dotnet/NugetRegistryInfo.mjs.map +1 -1
  22. package/mjs/dotnet/helpers.mjs +222 -1
  23. package/mjs/dotnet/helpers.mjs.map +1 -1
  24. package/mjs/dotnet/index.mjs +9 -1
  25. package/mjs/dotnet.mjs +9 -1
  26. package/mjs/eslintConfig.mjs +97 -1
  27. package/mjs/eslintConfig.mjs.map +1 -1
  28. package/mjs/index.mjs +2 -1
  29. package/mjs/insertPlugins.mjs +35 -1
  30. package/mjs/insertPlugins.mjs.map +1 -1
  31. package/mjs/semanticReleaseConfig.mjs +63 -1
  32. package/mjs/semanticReleaseConfig.mjs.map +1 -1
  33. package/mjs/semanticReleaseConfigDotnet.mjs +223 -6
  34. package/mjs/semanticReleaseConfigDotnet.mjs.map +1 -1
  35. package/mjs/setupGitPluginSpec.default.mjs +18 -2
  36. package/mjs/setupGitPluginSpec.default.mjs.map +1 -1
  37. package/mjs/setupGitPluginSpec.mjs +108 -1
  38. package/mjs/setupGitPluginSpec.mjs.map +1 -1
  39. package/mjs/utils/Exact.d.mts +10 -10
  40. package/mjs/utils/Exact.d.mts.map +1 -1
  41. package/mjs/utils/env.mjs +39 -1
  42. package/mjs/utils/env.mjs.map +1 -1
  43. package/mjs/utils/execAsync.mjs +54 -7
  44. package/mjs/utils/execAsync.mjs.map +1 -1
  45. package/mjs/utils/isError.mjs +17 -1
  46. package/mjs/utils/isError.mjs.map +1 -1
  47. package/mjs/utils/miscTypes.mjs +7 -1
  48. package/mjs/utils/miscTypes.mjs.map +1 -1
  49. package/mjs/utils/reflection/filterForGetters.mjs +25 -1
  50. package/mjs/utils/reflection/filterForGetters.mjs.map +1 -1
  51. package/mjs/utils/reflection/getOwnPropertyDescriptors.mjs +27 -1
  52. package/mjs/utils/reflection/getOwnPropertyDescriptors.mjs.map +1 -1
  53. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.mjs +34 -1
  54. package/mjs/utils/reflection/getOwnPropertyDescriptorsRecursively.mjs.map +1 -1
  55. package/mjs/utils/reflection/getPrototypeChainOf.mjs +39 -1
  56. package/mjs/utils/reflection/getPrototypeChainOf.mjs.map +1 -1
  57. package/mjs/utils/reflection/getPrototypeOf.mjs +12 -1
  58. package/mjs/utils/reflection/getPrototypeOf.mjs.map +1 -1
  59. package/mjs/utils/reflection/inheritance.mjs +10 -1
  60. package/mjs/utils/reflection/inheritance.mjs.map +1 -1
  61. package/mjs/utils/reflection/isConstructor.mjs +30 -1
  62. package/mjs/utils/reflection/isConstructor.mjs.map +1 -1
  63. package/mjs/utils/reflection/isGetterDescriptor.mjs +13 -1
  64. package/mjs/utils/reflection/isGetterDescriptor.mjs.map +1 -1
  65. package/mjs/utils/reflection/listOwnGetters.mjs +29 -1
  66. package/mjs/utils/reflection/listOwnGetters.mjs.map +1 -1
  67. package/mjs/utils/reflection.mjs +10 -1
  68. package/package.json +17 -43
  69. package/src/utils/Exact.d.ts +17 -0
  70. package/mjs/utils/Exact.mjs +0 -2
  71. package/mjs/utils/Exact.mjs.map +0 -1
  72. package/src/utils/Exact.ts +0 -49
@@ -1,5 +1,601 @@
1
- import{isError as e}from"../utils/isError.mjs";import{execAsync as t}from"../utils/execAsync.mjs";import{MSBuildEvaluationOutput as n,MSBuildProject as r,catchEBUSY as i}from"./MSBuildProject.mjs";import{getEnvVarValue as a}from"../utils/env.mjs";import{cwd as o,env as s}from"node:process";import{type as c}from"arktype";import*as l from"node:path";import{existsSync as u,writeFileSync as d}from"node:fs";import{writeFile as f}from"node:fs/promises";import{setTimeout as p}from"node:timers/promises";import{tmpdir as m}from"node:os";import{ok as h}from"node:assert/strict";import{config as g}from"@dotenvx/dotenvx";import{detectFile as _,detectFileSync as v}from"chardet";import y from"sanitize-filename";const b=l.join(m(),`HCE.Shared`,`.NET`,`Dummies`),x=`_OutputPackItems`;async function S(){if(s.GITHUB_OUTPUT===void 0||!u(s.GITHUB_OUTPUT)){let e=l.join(m(),`GITHUB_OUTPUT`);u(e)||await f(e,``),s.GITHUB_OUTPUT=e}let t=await _(s.GITHUB_OUTPUT),n=g({path:s.GITHUB_OUTPUT,override:!0,encoding:t??void 0,processEnv:{}});if(e(n.error))throw n.error;return n.parsed}function C(){if(s.GITHUB_OUTPUT===void 0||!u(s.GITHUB_OUTPUT)){let e=l.join(m(),`GITHUB_OUTPUT`);u(e)||d(e,``),s.GITHUB_OUTPUT=e}let e=v(s.GITHUB_OUTPUT),t=g({path:s.GITHUB_OUTPUT,override:!0,encoding:e??void 0,processEnv:{}});if(`error`in t)throw t.error;return t.parsed}function w(e){switch(!0){case e===void 0:return l.join(b,l.sep);case e instanceof r:return l.join(b,e.Properties.PackageId,l.sep);default:throw Error("The type of argument `project` must be `undefined` or `MSBuildProject`.")}}function T(e){let t=Object.freeze(e.map(e=>[e,a(e)]).filter(e=>e[1]!==void 0));if(t.length>0)return t}var E=class r{_canPushPackagesToSource=void 0;_project;_resolvedEnvVariable;_source;static DefaultTokenEnvVars=Object.freeze([`NUGET_TOKEN`]);static GetDirNameForSource(e){return y(e.replaceAll(/\/index.json$/g,``),{replacement:`_`})}constructor(e){let t=k.from(e);this._project=t.project;let n=T(t.tokenEnvVars);n&&(this._resolvedEnvVariable=n[0][0]),this._source=t.source}get project(){return this._project}get canPushPackagesToSource(){if(this._canPushPackagesToSource!==void 0)return this._canPushPackagesToSource;let e;if(this.resolvedEnvVariable!==void 0&&(e=D._GetTokenValue(this.resolvedEnvVariable)),e?.startsWith(`github_pat_`)){let e=`The value of the token in 'resolvedEnvVariable' ${String(this.resolvedEnvVariable)} begins with 'github_pat_', indicating it's a Fine-Grained token. At the time of writing, GitHub Fine-Grained tokens cannot push packages. If you believe this is statement is outdated, report the issue at https://github.com/halospv3/hce.shared/issues/new. For more information, see https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry.`,t=Error(e);return this._canPushPackagesToSource=Promise.reject(t)}return this._canPushPackagesToSource=this.PackDummyPackage({}).then(async()=>await this._PushDummyPackages({apiKey:e})).then(e=>(h(e),!0))}get resolvedEnvVariable(){return this._resolvedEnvVariable}get source(){return this._source}static _GetTokenValue(e){c.string.assert(e);let t=a(e);if(t===void 0)throw Error(`\
2
- The environment variable ${e} was specified \
1
+ import { isError } from "../utils/isError.mjs";
2
+ import { execAsync } from "../utils/execAsync.mjs";
3
+ import { MSBuildEvaluationOutput, MSBuildProject, catchEBUSY } from "./MSBuildProject.mjs";
4
+ import { getEnvVarValue } from "../utils/env.mjs";
5
+ import { cwd, env } from "node:process";
6
+ import { type } from "arktype";
7
+ import * as node_path from "node:path";
8
+ import { existsSync, writeFileSync } from "node:fs";
9
+ import { writeFile } from "node:fs/promises";
10
+ import { setTimeout } from "node:timers/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { ok } from "node:assert/strict";
13
+ import { config } from "@dotenvx/dotenvx";
14
+ import { detectFile, detectFileSync } from "chardet";
15
+ import sanitizeFileName from "sanitize-filename";
16
+ //#region src/dotnet/NugetRegistryInfo.ts
17
+ const tmpDirNamespace = node_path.join(tmpdir(), "HCE.Shared", ".NET", "Dummies");
18
+ const defaultNugetSource = "https://api.nuget.org/v3/index.json";
19
+ const key_OutputPackItems = "_OutputPackItems";
20
+ /**
21
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
22
+ * If the file doesn't exist, it is created.
23
+ * @returns If successful, a promised object with a parsed key.
24
+ */
25
+ async function getGithubOutput() {
26
+ if (env["GITHUB_OUTPUT"] === void 0 || !existsSync(env["GITHUB_OUTPUT"])) {
27
+ const githubOutputPath = node_path.join(tmpdir(), "GITHUB_OUTPUT");
28
+ if (!existsSync(githubOutputPath)) await writeFile(githubOutputPath, "");
29
+ env["GITHUB_OUTPUT"] = githubOutputPath;
30
+ }
31
+ const encoding = await detectFile(env["GITHUB_OUTPUT"]);
32
+ const envOutput = config({
33
+ path: env["GITHUB_OUTPUT"],
34
+ override: true,
35
+ encoding: encoding ?? void 0,
36
+ processEnv: {}
37
+ });
38
+ if (isError(envOutput.error)) throw envOutput.error;
39
+ return envOutput.parsed;
40
+ }
41
+ /**
42
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
43
+ * If the file doesn't exist, it is created.
44
+ * @returns An object with a parsed key if successful.
45
+ */
46
+ function getGithubOutputSync() {
47
+ if (env["GITHUB_OUTPUT"] === void 0 || !existsSync(env["GITHUB_OUTPUT"])) {
48
+ const githubOutputPath = node_path.join(tmpdir(), "GITHUB_OUTPUT");
49
+ if (!existsSync(githubOutputPath)) writeFileSync(githubOutputPath, "");
50
+ env["GITHUB_OUTPUT"] = githubOutputPath;
51
+ }
52
+ const encoding = detectFileSync(env["GITHUB_OUTPUT"]);
53
+ const envOutput = config({
54
+ path: env["GITHUB_OUTPUT"],
55
+ override: true,
56
+ encoding: encoding ?? void 0,
57
+ processEnv: {}
58
+ });
59
+ if ("error" in envOutput) throw envOutput.error;
60
+ return envOutput.parsed;
61
+ }
62
+ /**
63
+ * Get HCE.Shared's temporary directory for .NET projects' dummy packages.
64
+ * @param project The MSBuild project whose PackageId will be used to create a
65
+ * directory for its dummy packages.
66
+ * @returns a platform-specific path like
67
+ * `${tmpdir()}/HCE.Shared/.NET/Dummies/${project.Properties.PackageId}` if
68
+ * {@link project} is defined. Else `${tmpdir()}/HCE.Shared/.NET/Dummies`
69
+ */
70
+ function getDummiesDir(project) {
71
+ switch (true) {
72
+ case project === void 0: return node_path.join(tmpDirNamespace, node_path.sep);
73
+ case project instanceof MSBuildProject: return node_path.join(tmpDirNamespace, project.Properties.PackageId, node_path.sep);
74
+ default: throw new Error("The type of argument `project` must be `undefined` or `MSBuildProject`.");
75
+ }
76
+ }
77
+ /**
78
+ * Get the environment variables as key-value pairs.
79
+ * @param tokenEnvVars The name of the environment variables whose values are
80
+ * NuGet API keys.
81
+ * @returns an array of key-value pairs of the given environment variables and
82
+ * their values, filtered to only those whose values are not undefined.
83
+ * @throws {Error} when none of the provided environment variables are defined.
84
+ */
85
+ function _GetTokenEnvVariables(tokenEnvVars) {
86
+ const definedTokens = Object.freeze(tokenEnvVars.map((key) => [key, getEnvVarValue(key)]).filter((envVarTuple) => envVarTuple[1] !== void 0));
87
+ if (definedTokens.length > 0) return definedTokens;
88
+ }
89
+ var NugetRegistryInfo = class NugetRegistryInfo {
90
+ _canPushPackagesToSource = void 0;
91
+ _project;
92
+ _resolvedEnvVariable;
93
+ _source;
94
+ static DefaultTokenEnvVars = Object.freeze(["NUGET_TOKEN"]);
95
+ /**
96
+ * Convert a URL string to a filesystem folder name.
97
+ *
98
+ * Intended usage: modify the output path of `dotnet pack` based on the NuGet
99
+ * Source the package should be pushed to. This is extra work is usually
100
+ * unnecessary and you'd typically push the same file to multiple sources.
101
+ * This is for the edge-case scenario of creating multiple nupkgs and signing
102
+ * each one with a different certificate corresponding to a given NuGet
103
+ * Source. This is only useful if the Sources have different certificates
104
+ * registered for a given package/user/organization.
105
+ * @param source The URL of the NuGet Source
106
+ * @returns A string suitable for a local filesystem folder name, formatted as
107
+ * `${hostname}_${pathname.replace('/', '_')}`.
108
+ */
109
+ static GetDirNameForSource(source) {
110
+ return sanitizeFileName(source.replaceAll(/\/index.json$/g, ""), { replacement: "_" });
111
+ }
112
+ /**
113
+ * Creates an instance of NugetRegistryInfo.\
114
+ * This class enables the ability to push a given {@link project}'s
115
+ * package(s) to the {@link source} of a given NuGet Source's API endpoint with
116
+ * a user-defined API key. This API key, herein referred to as a "token", is
117
+ * derived from the {@link tokenEnvVars} array. This array is iterated through
118
+ * until one of the items is discovered to be an existing environment variable
119
+ * (or is defined in a file named '.env' in the current working directory for
120
+ * LOCAL TESTING ONLY! Do NOT `git add` your private keys!).
121
+ * \
122
+ * WARNING:
123
+ * - The token value is stored privately within this class, but it is plain text.
124
+ * - This private key may be copied to command line strings stored in Semantic
125
+ * Release's config object for later use by `@semantic-release/exec`.
126
+ * - Other EcmaScript modules can access the environment variable(s) and steal
127
+ * your key. Be aware of malicious dependencies!
128
+ * @param opts The input type of {@link NRIOpts.from}
129
+ * @param opts.project The project whose package(s) will be
130
+ * pushed.\
131
+ * - Its {@link NugetProjectProperties#PackageId} will be read.\
132
+ * - Its {@link NugetProjectProperties#PackageVersion} will be overridden via CLI args when creating a dummy package. The real package's
133
+ * `PackageVersion` will *not* be overridden.
134
+ * @param [opts.tokenEnvVars] The environment variables
135
+ * whose values are tokens with permission to push a package to the NuGet
136
+ * package registry. The array is iterated through until one token is found.
137
+ * If none of the environment variables are defined, this constructor will
138
+ * throw an {@link Error}.
139
+ * @param [opts.source] A NuGet package registry's API endpoint URL or name. Default: 'https://api.nuget.org/v3/index.json'
140
+ */
141
+ constructor(opts) {
142
+ const validOpts = NRIOpts.from(opts);
143
+ this._project = validOpts.project;
144
+ /**
145
+ * May throw! Assign key of the first key-value pair to
146
+ * {@link resolvedEnvVariable}
147
+ */
148
+ const tokenVars = _GetTokenEnvVariables(validOpts.tokenEnvVars);
149
+ if (tokenVars) this._resolvedEnvVariable = tokenVars[0][0];
150
+ this._source = validOpts.source;
151
+ }
152
+ get project() {
153
+ return this._project;
154
+ }
155
+ /**
156
+ * This is not useful without it being executed as part of a Semantic Release
157
+ * plugin. Deferring this to `@semantic-release/exec`'s prepareCmd is possible,
158
+ * but impractical. You'd need to configure prepareCmd to invoke something
159
+ * like `node customScriptFile.mjs`. It's not worth the hassle.
160
+ * @returns `true` if the token can be used to push nupkg to the given Nuget registry
161
+ * @throws {TypeError | Error | import('../utils/execAsync.js').ChildProcessSpawnException }
162
+ * - {@link Error} | {@link module:utils/execAsync:ChildProcessSpawnException ChildProcessSpawnException}
163
+ * - The token is invalid, of the wrong token type, or lacks permission to push packages
164
+ * - The URL does not exist or a connection could not be established
165
+ * - The command line string is malformed.
166
+ * @deprecated Call during the `verifyConditions` step of Semantic Release! Additionally, {@link GetIsNextVersionAlreadyPublishedCommand}'s return value should be assigned to `prepareCmd` to prevent package version collision errors.
167
+ */
168
+ get canPushPackagesToSource() {
169
+ if (this._canPushPackagesToSource !== void 0) return this._canPushPackagesToSource;
170
+ let tokenValue;
171
+ if (this.resolvedEnvVariable !== void 0) tokenValue = NRI._GetTokenValue(this.resolvedEnvVariable);
172
+ if (tokenValue?.startsWith("github_pat_")) {
173
+ const errMsg = `The value of the token in 'resolvedEnvVariable' ${String(this.resolvedEnvVariable)} begins with 'github_pat_', indicating it's a Fine-Grained token. At the time of writing, GitHub Fine-Grained tokens cannot push packages. If you believe this is statement is outdated, report the issue at https://github.com/halospv3/hce.shared/issues/new. For more information, see https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry.`;
174
+ const err = new Error(errMsg);
175
+ return this._canPushPackagesToSource = Promise.reject(err);
176
+ }
177
+ return this._canPushPackagesToSource = this.PackDummyPackage({}).then(async () => await this._PushDummyPackages({ apiKey: tokenValue })).then((execAsyncReturn) => {
178
+ ok(execAsyncReturn);
179
+ return true;
180
+ });
181
+ }
182
+ /**
183
+ * The first environment variable found to have a defined value. Set by
184
+ * {@link _GetTokenEnvVariables} in the constructor.
185
+ * @returns The first environment variable found to have a defined value.
186
+ */
187
+ get resolvedEnvVariable() {
188
+ return this._resolvedEnvVariable;
189
+ }
190
+ get source() {
191
+ return this._source;
192
+ }
193
+ /**
194
+ * Get the API token from {@link NugetRegistryInfo#resolvedEnvVariable}
195
+ * @param resolvedEnvVariable The name of the environment variable(s) whose
196
+ * value is a NuGet API key. Typically, the value of
197
+ * {@link NugetRegistryInfo#resolvedEnvVariable}.
198
+ * @returns The value of the first defined environment variable.
199
+ * @throws {Error} when none of the provided environment variables are defined.
200
+ */
201
+ static _GetTokenValue(resolvedEnvVariable) {
202
+ type.string.assert(resolvedEnvVariable);
203
+ const tokenValue = getEnvVarValue(resolvedEnvVariable);
204
+ if (tokenValue === void 0) throw new Error(`\
205
+ The environment variable ${resolvedEnvVariable} was specified \
3
206
  as the source of the token to push a NuGet package, \
4
- but the environment variable is empty or undefined.`);return t}static PackPackagesOptionsType=Object.freeze(c({"propertyOverrides?":c(`Record<string,string>`),"artifactsPath?":`string`,"configuration?":`"Release" | "Debug"`,"disableBuildServers?":`boolean`,"force?":`boolean`,"includeSource?":`boolean`,"includeSymbols?":`boolean`,"interactive?":`boolean`,"noBuild?":`boolean`,"noLogo?":`boolean`,"noRestore?":`boolean`,"output?":`string`,"runtime?":`string`,"serviceable?":`boolean`,"terminalLogger?":`"auto" | "on" | "off"`,"useCurrentRuntime?":`boolean`,"verbosity?":`"quiet" | "minimal" | "normal" | "detailed" | "diagnostic"`,"versionSuffix?":`string`,"-GetItem?":c.string.array().readonly().or(`string[]`)}));static PackDummyPackagesOptionsType=this.PackPackagesOptionsType.omit(`output`);GetPackCommand(e,t=!1,n=!1){let i=D.PackPackagesOptionsType.from(e);c.boolean.assert(t),c.boolean.assert(n),i.output??=l.join(o(),`publish`),t&&(i.output=l.join(i.output,r.GetDirNameForSource(this.source),l.sep)),n&&(i.output=l.join(i.output,this._project.Properties.PackageId,l.sep));let a=[`dotnet`,`pack`,`"${this._project.Properties.MSBuildProjectFullPath}"`];if(i.artifactsPath!==void 0&&a.push(`--artifactsPath`,`"${i.artifactsPath}"`),i.configuration!==void 0&&a.push(`--configuration`,i.configuration),i.disableBuildServers===!0&&a.push(`--disable-build-servers`),i.force===!0&&a.push(`--force`),i.includeSource===!0&&a.push(`--include-source`),i.includeSymbols===!0&&a.push(`--include-symbols`),i.interactive===!0&&a.push(`--interactive`),i.noBuild===!0&&a.push(`--no-build`),i.noLogo===!0&&a.push(`--nologo`),i.noRestore===!0&&a.push(`--no-restore`),i.runtime!==void 0&&a.push(`--runtime`,i.runtime),i.serviceable===!0&&a.push(`--serviceable`),i.terminalLogger!==void 0&&a.push(`--tl`,i.terminalLogger),i.useCurrentRuntime===!0&&a.push(`--use-current-runtime`),i.verbosity!==void 0&&a.push(`--verbosity`,i.verbosity),i.versionSuffix!==void 0&&a.push(`--version-suffix`,i.versionSuffix),i.propertyOverrides){let e=`-p:`+Object.entries(i.propertyOverrides).map(e=>`${e[0]}=${e[1]}`).join(`;`);a.push(`"${e}"`)}return i[`-GetItem`]&&i[`-GetItem`].length>0&&a.push(`-GetItem:${i[`-GetItem`].join(`,`)}`),a.push(`-o`,`"${i.output}"`),a.join(` `)}async _PackPackages(e,r=!1,a=!1){e[`-GetItem`]=[...e[`-GetItem`]??[],x];let o=this.GetPackCommand(e,r,a),s;for(;s===void 0;)s=await p(1e3,t(o,!0)).then(async e=>await e).catch(i);return new n(s.stdout).Items?.[x]?.filter(e=>e.Extension!==`.nuspec`).map(e=>e.FullPath)??[]}async PackDummyPackage(e){let r=this.GetPackCommand({...e,output:w(this._project),propertyOverrides:{...e.propertyOverrides,Version:`0.0.1-DUMMY`,UpdateVersionProperties:`false`},"-GetItem":[...e[`-GetItem`]??[],x]},!0),a;for(;a===void 0;)a=await p(1e3,t(r,!0)).then(async e=>await e).catch(i);return new n(a.stdout).Items?.[x]?.filter(e=>e.Extension!==`.nuspec`).map(e=>e.FullPath)??[]}static PushPackagesOptionsType=Object.freeze(c({root:`string`,"apiKey?":`string`,"configFile?":`string`,"disableBuffering?":`boolean`,"forceEnglishOutput?":`boolean`,"interactive?":`boolean`,"noServiceEndpoint?":`boolean`,"noSymbols?":`boolean`,"skipDuplicate?":`boolean`,"source?":`string`,"symbolApiKey?":`string`,"symbolSource?":`string`,"timeout?":`number`}));static PushDummyPackagesOptionsType=r.PushPackagesOptionsType.merge({skipDuplicate:`true = true`}).omit(`root`);GetPushCommand(e,t=!1,n=!1){let i=D.PushPackagesOptionsType.from(e);c.boolean.assert(t),c.boolean.assert(n),i.root=i.root===``?`${o()}/publish`:i.root,t&&(i.root=l.join(i.root,r.GetDirNameForSource(this.source),l.sep)),n&&(i.root=l.join(i.root,this._project.Properties.PackageId,l.sep));let a=[`dotnet`,`nuget`,`push`,`"${l.join(i.root,`*.nupkg`)}"`];return this.resolvedEnvVariable&&(i.apiKey??=D._GetTokenValue(this.resolvedEnvVariable)),i.apiKey&&i.apiKey!==``&&a.push(`--api-key`,i.apiKey),i.configFile&&a.push(`--configfile`,i.configFile),i.disableBuffering===!0&&a.push(`--disable-buffering`),i.forceEnglishOutput===!0&&a.push(`--force-english-output`),i.interactive===!0&&a.push(`--interactive`),i.noServiceEndpoint===!0&&a.push(`--no-service-endpoint`),i.noSymbols===!0&&a.push(`--no-symbols`),i.skipDuplicate===!0&&a.push(`--skip-duplicate`),i.source??=this.source,a.push(`--source`,i.source),i.symbolApiKey!==void 0&&a.push(`--symbol-api-key`,i.symbolApiKey),i.symbolSource!==void 0&&a.push(`--symbol-source`,i.symbolSource),i.timeout!==void 0&&a.push(`--timeout`,i.timeout.toString()),a.join(` `)}async _PushPackages(n,r=!1,i=!1){await t(this.GetPushCommand(n,r,i),!0).catch(t=>{let r=e(t)?t:Error(JSON.stringify(t));throw n.apiKey?j(r,n.apiKey):r})}GetPushDummyCommand(e){return this.GetPushCommand({...D.PushDummyPackagesOptionsType.from(e),root:w(this._project)},!0)}async _PushDummyPackages(n){return await t(this.GetPushDummyCommand(n),!0).catch(t=>{let r=e(t)?t:Error(String(t));throw n.apiKey?j(r,n.apiKey):r})}static _NugetSearchReturnTypes={ExactMatch:{v2:c({version:`2`,problems:`unknown[]`,searchResult:[{sourceName:`string`,packages:c({id:`string`,version:c.keywords.string.semver}).array()}]})}};static _ParseNugetSearchReturn=c(`string.json.parse`).to(this._NugetSearchReturnTypes.ExactMatch.v2);static async IsNextVersionAlreadyPublished(e,n,r){if(r===``)throw Error(`The value of nextVersion is empty`);return await t(`dotnet package search --format JSON --exact-match --source ${e} --prerelease ${n}`,!0).then(e=>e.stdout).then(e=>this._ParseNugetSearchReturn(e)).then(e=>e instanceof c.errors?e.throw():e).then(e=>e.searchResult).then(e=>e[0].packages).then(e=>e.find(e=>e.version===c(`string.semver`).from(r))).then(e=>e!==void 0)}GetIsNextVersionAlreadyPublishedCommand(){return C(),`node ${l.join(import.meta.dirname,`./IsNextVersionAlreadyPublished.cli.js`)} --packageId ${this._project.Properties.PackageId} --source ${this.source}`}};const D=E,O=c({project:c.instanceOf(r).or(c.instanceOf(r).readonly()),source:c.string,tokenEnvVars:c.string.array().readonly()}),k=O.merge({tokenEnvVars:O.get(`tokenEnvVars`).default(()=>E.DefaultTokenEnvVars),source:O.get(`source`).default(()=>`https://api.nuget.org/v3/index.json`)});function A(e,t){return e.replaceAll(t,`***`)}function j(e,t){return Object.assign(e,JSON.parse(A(JSON.stringify({...e,message:e.message,stack:e.stack}),t)))}export{k as NRIOpts,O as NRIOptsBase,E as NugetRegistryInfo,S as getGithubOutput,C as getGithubOutputSync};
207
+ but the environment variable is empty or undefined.`);
208
+ return tokenValue;
209
+ }
210
+ /**
211
+ * The type for options and arguments of `dotnet pack`. See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack.
212
+ *
213
+ * {@link NRI.PackPackagesOptionsType.t.propertyOverrides `propertyOverrides`}
214
+ * is a wrapper for MSBuild's `-property:<n>=<v>` properties override arg.
215
+ */
216
+ static PackPackagesOptionsType = Object.freeze(type({
217
+ "propertyOverrides?": type("Record<string,string>"),
218
+ "artifactsPath?": "string",
219
+ "configuration?": "\"Release\" | \"Debug\"",
220
+ "disableBuildServers?": "boolean",
221
+ "force?": "boolean",
222
+ "includeSource?": "boolean",
223
+ "includeSymbols?": "boolean",
224
+ "interactive?": "boolean",
225
+ "noBuild?": "boolean",
226
+ "noLogo?": "boolean",
227
+ "noRestore?": "boolean",
228
+ "output?": "string",
229
+ "runtime?": "string",
230
+ "serviceable?": "boolean",
231
+ "terminalLogger?": "\"auto\" | \"on\" | \"off\"",
232
+ "useCurrentRuntime?": "boolean",
233
+ "verbosity?": "\"quiet\" | \"minimal\" | \"normal\" | \"detailed\" | \"diagnostic\"",
234
+ "versionSuffix?": "string",
235
+ "-GetItem?": type.string.array().readonly().or("string[]")
236
+ }));
237
+ static PackDummyPackagesOptionsType = this.PackPackagesOptionsType.omit("output");
238
+ /**
239
+ * Get a `dotnet pack` command line string, outputting the package(s) to a
240
+ * path determined by this method's parameters.
241
+ * When pushing the package(s), you only need to supply the main .nupkg's path
242
+ * or its directory to the dotnet CLI—by default, it will also push the
243
+ * symbols package, if present.
244
+ * @param opts Options passed to
245
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument. The
246
+ * {@link PackPackagesOptionsType.t.output} path is modified according to the
247
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
248
+ * arguments.
249
+ * @param usePerSourceSubfolder If true, the path of the package output will
250
+ * include a subfolder named after the NuGet Source.
251
+ * @param usePerPackageIdSubfolder If true, the path of the package output
252
+ * will include a subfolder named after the NuGet package's ID.
253
+ * @returns `dotnet pack "${this.project.Properties.MSBuildProjectFullPath}"
254
+ * -o "${outDir}"` where outDir may be `${cwd()}/publish/${NugetRegistryInfo.GetNameForURL(this.source)}/${this._project.Properties.PackageId}`
255
+ */
256
+ GetPackCommand(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
257
+ const validOpts = NRI.PackPackagesOptionsType.from(opts);
258
+ type.boolean.assert(usePerSourceSubfolder);
259
+ type.boolean.assert(usePerPackageIdSubfolder);
260
+ validOpts.output ??= node_path.join(cwd(), "publish");
261
+ if (usePerSourceSubfolder) validOpts.output = node_path.join(validOpts.output, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
262
+ if (usePerPackageIdSubfolder) validOpts.output = node_path.join(validOpts.output, this._project.Properties.PackageId, node_path.sep);
263
+ const packCmdArr = [
264
+ "dotnet",
265
+ "pack",
266
+ `"${this._project.Properties.MSBuildProjectFullPath}"`
267
+ ];
268
+ if (validOpts.artifactsPath !== void 0) packCmdArr.push("--artifactsPath", `"${validOpts.artifactsPath}"`);
269
+ if (validOpts.configuration !== void 0) packCmdArr.push("--configuration", validOpts.configuration);
270
+ if (validOpts.disableBuildServers === true) packCmdArr.push("--disable-build-servers");
271
+ if (validOpts.force === true) packCmdArr.push("--force");
272
+ if (validOpts.includeSource === true) packCmdArr.push("--include-source");
273
+ if (validOpts.includeSymbols === true) packCmdArr.push("--include-symbols");
274
+ if (validOpts.interactive === true) packCmdArr.push("--interactive");
275
+ if (validOpts.noBuild === true) packCmdArr.push("--no-build");
276
+ if (validOpts.noLogo === true) packCmdArr.push("--nologo");
277
+ if (validOpts.noRestore === true) packCmdArr.push("--no-restore");
278
+ if (validOpts.runtime !== void 0) packCmdArr.push("--runtime", validOpts.runtime);
279
+ if (validOpts.serviceable === true) packCmdArr.push("--serviceable");
280
+ if (validOpts.terminalLogger !== void 0) packCmdArr.push("--tl", validOpts.terminalLogger);
281
+ if (validOpts.useCurrentRuntime === true) packCmdArr.push("--use-current-runtime");
282
+ if (validOpts.verbosity !== void 0) packCmdArr.push("--verbosity", validOpts.verbosity);
283
+ if (validOpts.versionSuffix !== void 0) packCmdArr.push("--version-suffix", validOpts.versionSuffix);
284
+ /**
285
+ * Haphazard. I need to override the Version and I'm not considering side
286
+ * effects of arbitrary overrides.
287
+ */
288
+ if (validOpts.propertyOverrides) {
289
+ /** convert propertyOverrides record to "-p:n0=v0;n1=v1;n2=v2" et cetera */
290
+ const assignments = "-p:" + Object.entries(validOpts.propertyOverrides).map((v) => `${v[0]}=${v[1]}`).join(";");
291
+ packCmdArr.push(`"${assignments}"`);
292
+ }
293
+ if (validOpts["-GetItem"] && validOpts["-GetItem"].length > 0) packCmdArr.push(`-GetItem:${validOpts["-GetItem"].join(",")}`);
294
+ packCmdArr.push("-o", `"${validOpts.output}"`);
295
+ return packCmdArr.join(" ");
296
+ }
297
+ /**
298
+ * !Not ready for use! Remove private modifier and commit as `feat(dotnet)` when ready for release!
299
+ * Blocking Issue: convert all dotnet-related functionality to a Semantic Release plugin!
300
+ * The current {@link _srcd SemanticReleaseConfigDotnet} leverages
301
+ * `@semantic-release/exec` to invoke dotnet commands. This is fine for
302
+ * relatively short command lines, but chaining commands with ' && ' results
303
+ * in quickly-growing complexity.
304
+ * NuGet packages should be created during the `prepare` step, but complex
305
+ * configuration of `dotnet pack` via command lines intended to be invoked by
306
+ * `@semantic-release/exec` is impractical.
307
+ * @param opts `dotnet pack` options. See `dotnet pack -h`,
308
+ * https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack, and
309
+ * {@link PackPackagesOptionsType}.
310
+ * {@link opts['-GetItem']} will _always_ have '_OutputPackItems'.
311
+ * @param [usePerSourceSubfolder] If `true`, modify the output path to
312
+ * include a subfolder bearing a path-safe encoding of the NuGet Source that
313
+ * will receive the nupkg.
314
+ * @param [usePerPackageIdSubfolder] If `true`, modify the output path
315
+ * to include a subfolder named after the the PackageId.
316
+ * @returns a string[] containing the full file paths of all new packages i.e.
317
+ * .nupkg, .symbols.nupkg, .snupkg
318
+ */
319
+ async _PackPackages(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
320
+ opts["-GetItem"] = [...opts["-GetItem"] ?? [], key_OutputPackItems];
321
+ const packCmd = this.GetPackCommand(opts, usePerSourceSubfolder, usePerPackageIdSubfolder);
322
+ let packOutput = void 0;
323
+ while (packOutput === void 0) packOutput = await setTimeout(1e3, execAsync(packCmd, true)).then(async (p) => await p).catch(catchEBUSY);
324
+ return new MSBuildEvaluationOutput(packOutput.stdout).Items?.[key_OutputPackItems]?.filter((item) => item.Extension !== ".nuspec").map((item) => item.FullPath) ?? [];
325
+ }
326
+ /**
327
+ * Create a dummy package for the current {@link project} by executing a
328
+ * command line like \``dotnet pack ${this.project.Properties.MSBuildProjectFullPath} -p:Version=0.0.1-DUMMY -output ${getDummiesDir(this._project)}/${GetNameForURL(this.source)}`\`
329
+ * @param opts Options passed to
330
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument.
331
+ * - The `output` field is ignored and overwritten. It is replaced with
332
+ * ${{@link getDummiesDir}({@link project})}/${{@link GetDirNameForSource}({@link source})}
333
+ * - The `output` path will be affixed with a folder named after this
334
+ * {@link NugetRegistryInfo#source}, but will not include a subfolder for the
335
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}.
336
+ * @returns the full paths of all nupkg, symbols.nupkg, and snupkg files
337
+ * created by the Pack target, as extracted from the dotnet process's STDOUT.
338
+ * If mixed with other nupkgs, filter for the {@link NugetProjectProperties#PackageId}
339
+ */
340
+ async PackDummyPackage(opts) {
341
+ const packCmd = this.GetPackCommand({
342
+ ...opts,
343
+ output: getDummiesDir(this._project),
344
+ propertyOverrides: {
345
+ ...opts.propertyOverrides,
346
+ Version: "0.0.1-DUMMY",
347
+ UpdateVersionProperties: "false"
348
+ },
349
+ "-GetItem": [...opts["-GetItem"] ?? [], key_OutputPackItems]
350
+ }, true);
351
+ let packOutput = void 0;
352
+ while (packOutput === void 0) packOutput = await setTimeout(1e3, execAsync(packCmd, true)).then(async (p) => await p).catch(catchEBUSY);
353
+ return new MSBuildEvaluationOutput(packOutput.stdout).Items?.[key_OutputPackItems]?.filter((item) => item.Extension !== ".nuspec").map((item) => item.FullPath) ?? [];
354
+ }
355
+ /**
356
+ * Also includes required argument 'ROOT': the directory in which packages
357
+ * should be present and ready to be pushed the default or specified Source.
358
+ * The ROOT may also include wildcards e.g. `*.nupkg`, `**\\*.nupkg`
359
+ * See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-push
360
+ *
361
+ * Specific to this API:
362
+ * If you want to use this API's default root value (\`${cwd()}/publish`), assign an empty string.
363
+ */
364
+ static PushPackagesOptionsType = Object.freeze(type({
365
+ root: "string",
366
+ "apiKey?": "string",
367
+ "configFile?": "string",
368
+ "disableBuffering?": "boolean",
369
+ "forceEnglishOutput?": "boolean",
370
+ "interactive?": "boolean",
371
+ "noServiceEndpoint?": "boolean",
372
+ "noSymbols?": "boolean",
373
+ "skipDuplicate?": "boolean",
374
+ "source?": "string",
375
+ "symbolApiKey?": "string",
376
+ "symbolSource?": "string",
377
+ "timeout?": "number"
378
+ }));
379
+ /**
380
+ * {@link NRI.PushPackagesOptionsType} sans {@link NRI.PushPackagesOptionsType.t.root}.
381
+ * The result of {@link getDummiesDir} is used, instead.
382
+ */
383
+ static PushDummyPackagesOptionsType = NugetRegistryInfo.PushPackagesOptionsType.merge({ skipDuplicate: "true = true" }).omit("root");
384
+ /**
385
+ * Create a `dotnet nuget push` command line from the given options and
386
+ * optional boolean parameters.
387
+ * @param opts See {@link PushPackagesOptionsType}
388
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
389
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
390
+ * wildcards in ROOT with this set to `true`!
391
+ * @param usePerPackageIdSubfolder If `true`, the
392
+ * {@link project}'s {@link NugetProjectProperties#PackageId}
393
+ * is appended to the ROOT as a subfolder. Do not use wildcards in
394
+ * ROOT with this set to `true`!
395
+ * @returns A `dotnet nuget push` command line formatted with the
396
+ * appropriate arguments.
397
+ */
398
+ GetPushCommand(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
399
+ const validOpts = NRI.PushPackagesOptionsType.from(opts);
400
+ type.boolean.assert(usePerSourceSubfolder);
401
+ type.boolean.assert(usePerPackageIdSubfolder);
402
+ validOpts.root = validOpts.root === "" ? `${cwd()}/publish` : validOpts.root;
403
+ if (usePerSourceSubfolder) validOpts.root = node_path.join(validOpts.root, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
404
+ if (usePerPackageIdSubfolder) validOpts.root = node_path.join(validOpts.root, this._project.Properties.PackageId, node_path.sep);
405
+ const packCmdArr = [
406
+ "dotnet",
407
+ "nuget",
408
+ "push",
409
+ `"${node_path.join(validOpts.root, "*.nupkg")}"`
410
+ ];
411
+ if (this.resolvedEnvVariable) validOpts.apiKey ??= NRI._GetTokenValue(this.resolvedEnvVariable);
412
+ /**
413
+ * If apiKey is an empty string, defer to the dotnet CLI's NuGet client
414
+ * ability to lookup API keys saved via `dotnet nuget add source` or NuGet config
415
+ * files.
416
+ */
417
+ if (validOpts.apiKey && validOpts.apiKey !== "") packCmdArr.push("--api-key", validOpts.apiKey);
418
+ if (validOpts.configFile) packCmdArr.push("--configfile", validOpts.configFile);
419
+ if (validOpts.disableBuffering === true) packCmdArr.push("--disable-buffering");
420
+ if (validOpts.forceEnglishOutput === true) packCmdArr.push("--force-english-output");
421
+ if (validOpts.interactive === true) packCmdArr.push("--interactive");
422
+ if (validOpts.noServiceEndpoint === true) packCmdArr.push("--no-service-endpoint");
423
+ if (validOpts.noSymbols === true) packCmdArr.push("--no-symbols");
424
+ if (validOpts.skipDuplicate === true) packCmdArr.push("--skip-duplicate");
425
+ validOpts.source ??= this.source;
426
+ packCmdArr.push("--source", validOpts.source);
427
+ if (validOpts.symbolApiKey !== void 0) packCmdArr.push("--symbol-api-key", validOpts.symbolApiKey);
428
+ if (validOpts.symbolSource !== void 0) packCmdArr.push("--symbol-source", validOpts.symbolSource);
429
+ if (validOpts.timeout !== void 0) packCmdArr.push("--timeout", validOpts.timeout.toString());
430
+ return packCmdArr.join(" ");
431
+ }
432
+ /**
433
+ * Immediately push packages. The input path may be modified according to the
434
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
435
+ * arguments.
436
+ * @param opts The `dotnet nuget push` command line options, including the
437
+ * ROOT argument, the directory containing local nuget packages ready to be
438
+ * pushed.
439
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
440
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
441
+ * wildcards in ROOT with this set to `true`!
442
+ * @param usePerPackageIdSubfolder If `true`, the current {@link project}'s
443
+ * PackageId is appended to the ROOT as a subfolder. Do not use wildcards in
444
+ * ROOT with this set to `true`!
445
+ */
446
+ async _PushPackages(opts, usePerSourceSubfolder = false, usePerPackageIdSubfolder = false) {
447
+ await execAsync(this.GetPushCommand(opts, usePerSourceSubfolder, usePerPackageIdSubfolder), true).catch((error) => {
448
+ const _error = isError(error) ? error : new Error(JSON.stringify(error));
449
+ throw opts.apiKey ? _censorTokenInError(_error, opts.apiKey) : _error;
450
+ });
451
+ }
452
+ /**
453
+ *
454
+ * Get a `dotnet nuget push` command for pushing one or more nupkg/snupkg
455
+ * files created by {@link GetPackCommand} or {@link _PackPackages}.\
456
+ * Like {@link PackDummyPackage}, the output/ROOT path will include a
457
+ * folder named after this NRI instance's {@link NugetRegistryInfo#source},
458
+ * but will not include a subfolder for the
459
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}
460
+ * @example
461
+ * ```ts
462
+ * const packAndPushDummyCmd = [
463
+ * nri.GetPackCommand(
464
+ * NugetRegistryInfo.PackPackagesOptionsType.from({ root: '' }),
465
+ * false,
466
+ * false,
467
+ * ),
468
+ * nri.GetPushDummyPackageCommand(pushOpts, false, false),
469
+ * ].join(' && ')
470
+ * ```
471
+ * @param opts options for `dotnet nuget push`. The following
472
+ * fields are overwritten:
473
+ * - root: getDummiesDir(this.project)
474
+ * - skipDuplicates: true
475
+ * @returns a `dotnet nuget push` command to push a dummy package
476
+ * (created by executing {@link PackDummyPackage}) to {@link source}
477
+ */
478
+ GetPushDummyCommand(opts) {
479
+ return this.GetPushCommand({
480
+ ...NRI.PushDummyPackagesOptionsType.from(opts),
481
+ root: getDummiesDir(this._project)
482
+ }, true);
483
+ }
484
+ /**
485
+ * Call {@link GetPushDummyCommand} and immediately execute it.
486
+ * @throws {Error} when the process exits with an error code indicating
487
+ * failure i.e. the command line is invalid, the process fails to start,
488
+ * the push fails, et cetera.
489
+ * @param opts the ROOT arg and options for `dotnet nuget push`. The following
490
+ * fields are overwritten:
491
+ * - root: getDummiesDir(this.project)
492
+ * - skipDuplicates: true
493
+ * @returns The return type of {@link execAsync} i.e. a {@link Promise} resolving to `{ stdout: string; stderr: string }`.
494
+ */
495
+ async _PushDummyPackages(opts) {
496
+ return await execAsync(this.GetPushDummyCommand(opts), true).catch((error) => {
497
+ const _error = isError(error) ? error : new Error(String(error));
498
+ throw opts.apiKey ? _censorTokenInError(_error, opts.apiKey) : _error;
499
+ });
500
+ }
501
+ static _NugetSearchReturnTypes = { ExactMatch: { v2: type({
502
+ version: "2",
503
+ problems: "unknown[]",
504
+ searchResult: [{
505
+ sourceName: "string",
506
+ packages: type({
507
+ id: "string",
508
+ version: type.keywords.string.semver
509
+ }).array()
510
+ }]
511
+ }) } };
512
+ static _ParseNugetSearchReturn = type("string.json.parse").to(this._NugetSearchReturnTypes.ExactMatch.v2);
513
+ /**
514
+ * !WARNING: this method requires the Nuget Source to be configured via `dotnet nuget add source` or `dotnet nuget update source`. `NUGET_TOKEN` works, but it may be vulnerable to supply chain attacks.\
515
+ * Call during the `prepare` step of a Semantic Release run.\
516
+ * Determine if the `nextVersion` generated during the `analyze` Semantic
517
+ * Release step was already published to the NuGet {@link source}.
518
+ * @param source The name or URI of the NuGet Source to search. If this API
519
+ * endpoint does not support searches, the operation will fail. If this API
520
+ * endpoint requires authentication (e.g. GitHub), it must be configured via
521
+ * `dotnet nuget add source` or `dotnet nuget update source` before calling
522
+ * this method.
523
+ * @param packageId The ID of the NuGet package to search for.
524
+ * @param nextVersion The nextVersion value generated by semantic-release's hidden ["Create Git tag" step](https://semantic-release.gitbook.io/semantic-release#:~:text=the%20last%20release.-,Create%20Git%20tag,-Create%20a%20Git).
525
+ * @returns A promised boolean.
526
+ * If the promise resolves to `true`, the semantic release run should be
527
+ * cancelled immediately.
528
+ * Otherwise, the release should proceed.
529
+ * @todo utilize in custom plugin inserted at the beginning of `prepare`
530
+ */
531
+ static async IsNextVersionAlreadyPublished(source, packageId, nextVersion) {
532
+ if (nextVersion === "") throw new Error("The value of nextVersion is empty");
533
+ return await execAsync(`dotnet package search --format JSON --exact-match --source ${source} --prerelease ${packageId}`, true).then((stdPair) => stdPair.stdout).then((json) => this._ParseNugetSearchReturn(json)).then((errsOrObj) => errsOrObj instanceof type.errors ? errsOrObj.throw() : errsOrObj).then((obj) => obj.searchResult).then((results) => results[0].packages).then((pkgs) => pkgs.find((p) => p.version === type("string.semver").from(nextVersion))).then((pkg) => pkg !== void 0);
534
+ }
535
+ /**
536
+ * !WARNING: GITHUB_OUTPUT must be the full path to an environment file.
537
+ * The plugin "semantic-release-output-variables" next-release-version
538
+ *
539
+ * !WARNING: NuGet Source API Key mus tbe configured via `dotnet nuget add source` or `dotnet nuget update source`.
540
+ * Some Sources (e.g. GitHub) require authentication for package searches.
541
+ *
542
+ * # Authenticating NuGet Package Searches
543
+ *
544
+ * ## GitHub NuGet Registry authentication
545
+ * - {@link https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry#authenticating-in-a-github-actions-workflow Authenticating in a GitHub Actions workflow}
546
+ * - {@link https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry#authenticating-with-a-personal-access-token Authenticating with a personal access token}.
547
+ * ## For GitLab NuGet Registry authentication, see
548
+ * - {@link https://docs.gitlab.com/ee/user/packages/nuget_repository/#add-a-source-with-the-net-cli Add a source with the .NET CLI}
549
+ * @returns a string containing a Node.JS command line invoking {@link ./IsNextVersionAlreadyPublished.cli.ts}
550
+ * @see {@link ./IsNextVersionAlreadyPublished.cli.ts}, {@link ./IsNextVersionAlreadyPublished.cli.js}
551
+ */
552
+ GetIsNextVersionAlreadyPublishedCommand() {
553
+ getGithubOutputSync();
554
+ return `node ${node_path.join(import.meta.dirname, "./IsNextVersionAlreadyPublished.cli.js")} --packageId ${this._project.Properties.PackageId} --source ${this.source}`;
555
+ }
556
+ };
557
+ const NRI = NugetRegistryInfo;
558
+ /**
559
+ * The base type for {@link NRIOpts} and related types. Extend this type while
560
+ * overriding member types via {@link NRIOptsBase.merge}
561
+ */
562
+ const NRIOptsBase = type({
563
+ project: type.instanceOf(MSBuildProject).or(type.instanceOf(MSBuildProject).readonly()),
564
+ source: type.string,
565
+ tokenEnvVars: type.string.array().readonly()
566
+ });
567
+ /**
568
+ * The type of the parameter for {@link NugetRegistryInfo}'s constructor.
569
+ */
570
+ const NRIOpts = NRIOptsBase.merge({
571
+ tokenEnvVars: NRIOptsBase.get("tokenEnvVars").default(() => NugetRegistryInfo.DefaultTokenEnvVars),
572
+ source: NRIOptsBase.get("source").default(() => defaultNugetSource)
573
+ });
574
+ /**
575
+ * Replace all occurrences of {@link token} in the {@link string} with '***'.
576
+ * @param string The string in which a {@link token} may be found.
577
+ * @param token The NuGet API token you definitely don't want to leak!
578
+ * @returns A modified copy of the {@link string} with all occurrences of the
579
+ * {@link token} replaced with '***'.
580
+ */
581
+ function _censorToken(string, token) {
582
+ return string.replaceAll(token, "***");
583
+ }
584
+ /**
585
+ * Censor all occurrences of an API {@link token} in an {@link error}.
586
+ * @param error A {@link ExecException} in which the NuGet API {@link token} may be found.
587
+ * @param token The value of the NuGet API token
588
+ * @returns A modified copy of the provided exception sans any occurrence of the
589
+ * NuGet API token.
590
+ */
591
+ function _censorTokenInError(error, token) {
592
+ return Object.assign(error, JSON.parse(_censorToken(JSON.stringify({
593
+ ...error,
594
+ message: error.message,
595
+ stack: error.stack
596
+ }), token)));
597
+ }
598
+ //#endregion
599
+ export { NRIOpts, NRIOptsBase, NugetRegistryInfo, getGithubOutput, getGithubOutputSync };
600
+
5
601
  //# sourceMappingURL=NugetRegistryInfo.mjs.map