@halospv3/hce.shared-config 2.6.4 → 3.0.0-develop.2

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 (152) hide show
  1. package/CHANGELOG.md +356 -101
  2. package/README.md +100 -87
  3. package/dotnet/.github/workflows/_unit_test.yml +6 -3
  4. package/dotnet/.github/workflows/ci.yml +2 -2
  5. package/dotnet/.github/workflows/dotnet-release.yml +31 -28
  6. package/dotnet/.github/workflows/sample-dotnet-build.yml +16 -11
  7. package/dotnet/ExecNupkgDeterministicator.README.md +20 -0
  8. package/dotnet/ExecNupkgDeterministicator.targets +173 -0
  9. package/dotnet/GitVersion.yml +3 -1
  10. package/dotnet/GitVersion6.0.yml +3 -1
  11. package/dotnet/HCE.Shared.sln +34 -0
  12. package/dotnet/HCE.Shared.targets +1 -0
  13. package/dotnet/PublishAll.targets +2 -0
  14. package/dotnet/SignAfterPack.targets +104 -0
  15. package/dotnet/samples/HCE.Shared.DeterministicNupkg/Dummy.cs +6 -0
  16. package/dotnet/samples/HCE.Shared.DeterministicNupkg/HCE.Shared.DeterministicNupkg.csproj +21 -0
  17. package/dotnet/samples/HCE.Shared.SignAfterPack/Class1.cs +6 -0
  18. package/dotnet/samples/HCE.Shared.SignAfterPack/HCE.Shared.SignAfterPack.csproj +21 -0
  19. package/dotnet/samples/HCE.Shared.SignAfterPack/sampleCert.samplepfx +0 -0
  20. package/dotnet/samples/README.md +7 -0
  21. package/package.json +72 -73
  22. package/src/CaseInsensitiveMap.ts +34 -0
  23. package/src/commitlintConfig.ts +17 -9
  24. package/src/debug.ts +3 -3
  25. package/src/dotnet/GithubNugetRegistryInfo.ts +60 -0
  26. package/src/dotnet/GitlabNugetRegistryInfo.ts +112 -0
  27. package/src/dotnet/IsNextVersionAlreadyPublished.cli.ts +44 -0
  28. package/src/dotnet/MSBuildProject.ts +557 -76
  29. package/src/dotnet/MSBuildProjectProperties.ts +280 -15
  30. package/src/dotnet/NugetProjectProperties.ts +608 -0
  31. package/src/dotnet/NugetRegistryInfo.ts +939 -0
  32. package/src/dotnet/helpers.ts +448 -0
  33. package/src/eslintConfig.ts +174 -71
  34. package/src/index.ts +1 -3
  35. package/src/semantic-release__commit-analyzer.d.ts +44 -38
  36. package/src/semantic-release__exec.d.ts +15 -0
  37. package/src/semantic-release__git.d.ts +85 -88
  38. package/src/semantic-release__github.d.ts +139 -139
  39. package/src/semanticReleaseConfig.ts +106 -47
  40. package/src/semanticReleaseConfigDotnet.ts +394 -104
  41. package/src/setupGitPluginSpec.ts +149 -57
  42. package/src/tsconfig.json +8 -8
  43. package/src/utils/Exact.ts +49 -0
  44. package/src/utils/GracefulRecursion.d.ts +12 -0
  45. package/src/utils/env.ts +44 -0
  46. package/src/utils/execAsync.ts +77 -0
  47. package/src/utils/miscTypes.ts +17 -0
  48. package/src/utils/reflection/FunctionLike.d.ts +17 -0
  49. package/src/utils/reflection/GetterDescriptor.d.ts +8 -0
  50. package/src/utils/reflection/InstancePropertyDescriptorMap.d.ts +32 -0
  51. package/src/utils/reflection/InstanceTypeOrSelfPropertyDescriptorMap.d.ts +20 -0
  52. package/src/utils/reflection/OwnGetterDescriptorMap.d.ts +17 -0
  53. package/src/utils/reflection/OwnKeyOf.d.ts +20 -0
  54. package/src/utils/reflection/OwnPropertyDescriptorMap.d.ts +82 -0
  55. package/src/utils/reflection/PropertyDescriptorMap.d.ts +15 -0
  56. package/src/utils/reflection/filterForGetters.ts +59 -0
  57. package/src/utils/reflection/getOwnPropertyDescriptors.ts +52 -0
  58. package/src/utils/reflection/getOwnPropertyDescriptorsRecursively.ts +127 -0
  59. package/src/utils/reflection/getPrototypeChainOf.ts +85 -0
  60. package/src/utils/reflection/getPrototypeOf.ts +12 -0
  61. package/src/utils/reflection/inheritance.ts +262 -0
  62. package/src/utils/reflection/isConstructor.ts +74 -0
  63. package/src/utils/reflection/isGetterDescriptor.ts +11 -0
  64. package/src/utils/reflection/listOwnGetters.ts +80 -0
  65. package/src/utils/reflection.ts +18 -0
  66. package/cjs/commitlintConfig-wrapper.mjs +0 -6
  67. package/cjs/commitlintConfig.cjs +0 -14
  68. package/cjs/commitlintConfig.cjs.map +0 -1
  69. package/cjs/commitlintConfig.d.ts +0 -4
  70. package/cjs/commitlintConfig.d.ts.map +0 -1
  71. package/cjs/debug.cjs +0 -13
  72. package/cjs/debug.cjs.map +0 -1
  73. package/cjs/debug.d.ts +0 -4
  74. package/cjs/debug.d.ts.map +0 -1
  75. package/cjs/dotnet/MSBuildProject.cjs +0 -84
  76. package/cjs/dotnet/MSBuildProject.cjs.map +0 -1
  77. package/cjs/dotnet/MSBuildProject.d.ts +0 -42
  78. package/cjs/dotnet/MSBuildProject.d.ts.map +0 -1
  79. package/cjs/dotnet/MSBuildProjectProperties.cjs +0 -22
  80. package/cjs/dotnet/MSBuildProjectProperties.cjs.map +0 -1
  81. package/cjs/dotnet/MSBuildProjectProperties.d.ts +0 -13
  82. package/cjs/dotnet/MSBuildProjectProperties.d.ts.map +0 -1
  83. package/cjs/dotnet/createDummyNupkg.cjs +0 -26
  84. package/cjs/dotnet/createDummyNupkg.cjs.map +0 -1
  85. package/cjs/dotnet/createDummyNupkg.d.ts +0 -2
  86. package/cjs/dotnet/createDummyNupkg.d.ts.map +0 -1
  87. package/cjs/dotnet/dotnetGHPR.cjs +0 -173
  88. package/cjs/dotnet/dotnetGHPR.cjs.map +0 -1
  89. package/cjs/dotnet/dotnetGHPR.d.ts +0 -37
  90. package/cjs/dotnet/dotnetGHPR.d.ts.map +0 -1
  91. package/cjs/dotnet/dotnetGLPR.cjs +0 -41
  92. package/cjs/dotnet/dotnetGLPR.cjs.map +0 -1
  93. package/cjs/dotnet/dotnetGLPR.d.ts +0 -13
  94. package/cjs/dotnet/dotnetGLPR.d.ts.map +0 -1
  95. package/cjs/dotnet/dotnetHelpers.cjs +0 -141
  96. package/cjs/dotnet/dotnetHelpers.cjs.map +0 -1
  97. package/cjs/dotnet/dotnetHelpers.d.ts +0 -26
  98. package/cjs/dotnet/dotnetHelpers.d.ts.map +0 -1
  99. package/cjs/dotnet-wrapper.mjs +0 -6
  100. package/cjs/dotnet.cjs +0 -15
  101. package/cjs/dotnet.cjs.map +0 -1
  102. package/cjs/dotnet.d.ts +0 -7
  103. package/cjs/dotnet.d.ts.map +0 -1
  104. package/cjs/envUtils-wrapper.mjs +0 -6
  105. package/cjs/envUtils.cjs +0 -37
  106. package/cjs/envUtils.cjs.map +0 -1
  107. package/cjs/envUtils.d.ts +0 -15
  108. package/cjs/envUtils.d.ts.map +0 -1
  109. package/cjs/eslintConfig-wrapper.mjs +0 -6
  110. package/cjs/eslintConfig.cjs +0 -52
  111. package/cjs/eslintConfig.cjs.map +0 -1
  112. package/cjs/eslintConfig.d.ts +0 -3
  113. package/cjs/eslintConfig.d.ts.map +0 -1
  114. package/cjs/findStaticConfig-wrapper.mjs +0 -6
  115. package/cjs/findStaticConfig.cjs +0 -34
  116. package/cjs/findStaticConfig.cjs.map +0 -1
  117. package/cjs/findStaticConfig.d.ts +0 -2
  118. package/cjs/findStaticConfig.d.ts.map +0 -1
  119. package/cjs/index-wrapper.mjs +0 -6
  120. package/cjs/index.cjs +0 -10
  121. package/cjs/index.cjs.map +0 -1
  122. package/cjs/index.d.ts +0 -5
  123. package/cjs/index.d.ts.map +0 -1
  124. package/cjs/semantic-release__commit-analyzer.d.cjs +0 -2
  125. package/cjs/semantic-release__commit-analyzer.d.cjs.map +0 -1
  126. package/cjs/semantic-release__git.d.cjs +0 -2
  127. package/cjs/semantic-release__git.d.cjs.map +0 -1
  128. package/cjs/semantic-release__github.d.cjs +0 -2
  129. package/cjs/semantic-release__github.d.cjs.map +0 -1
  130. package/cjs/semanticReleaseConfig-wrapper.mjs +0 -6
  131. package/cjs/semanticReleaseConfig.cjs +0 -33
  132. package/cjs/semanticReleaseConfig.cjs.map +0 -1
  133. package/cjs/semanticReleaseConfig.d.ts +0 -4
  134. package/cjs/semanticReleaseConfig.d.ts.map +0 -1
  135. package/cjs/semanticReleaseConfigDotnet-wrapper.mjs +0 -7
  136. package/cjs/semanticReleaseConfigDotnet.cjs +0 -112
  137. package/cjs/semanticReleaseConfigDotnet.cjs.map +0 -1
  138. package/cjs/semanticReleaseConfigDotnet.d.ts +0 -51
  139. package/cjs/semanticReleaseConfigDotnet.d.ts.map +0 -1
  140. package/cjs/setupGitPluginSpec-wrapper.mjs +0 -6
  141. package/cjs/setupGitPluginSpec.cjs +0 -67
  142. package/cjs/setupGitPluginSpec.cjs.map +0 -1
  143. package/cjs/setupGitPluginSpec.d.ts +0 -19
  144. package/cjs/setupGitPluginSpec.d.ts.map +0 -1
  145. package/src/dotnet/createDummyNupkg.ts +0 -30
  146. package/src/dotnet/dotnetGHPR.ts +0 -232
  147. package/src/dotnet/dotnetGLPR.ts +0 -46
  148. package/src/dotnet/dotnetHelpers.ts +0 -184
  149. package/src/dotnet.ts +0 -6
  150. package/src/envUtils.ts +0 -36
  151. package/src/findStaticConfig.ts +0 -31
  152. package/static/.releaserc.yml +0 -35
@@ -0,0 +1,939 @@
1
+ /* JSDoc Types */
2
+ /* eslint-disable @typescript-eslint/no-unused-vars */
3
+ import type { SemanticReleaseConfigDotnet } from '../semanticReleaseConfigDotnet.js';
4
+ import type { NugetProjectProperties } from './NugetProjectProperties.js';
5
+ /* eslint-enable @typescript-eslint/no-unused-vars */
6
+
7
+ import { type } from 'arktype';
8
+ import { detectFile, detectFileSync } from 'chardet';
9
+ import { config as configDotenv } from '@dotenvx/dotenvx';
10
+ import { ok } from 'node:assert/strict';
11
+ import type { ExecException } from 'node:child_process';
12
+ import { existsSync, writeFileSync } from 'node:fs';
13
+ import { writeFile } from 'node:fs/promises';
14
+ import { tmpdir } from 'node:os';
15
+ import node_path from 'node:path';
16
+ import { cwd, env } from 'node:process';
17
+ import { setTimeout } from 'node:timers/promises';
18
+ import { isNativeError } from 'node:util/types';
19
+ import sanitizeFileName from 'sanitize-filename';
20
+ import { getEnvVarValue } from '../utils/env.js';
21
+ import { execAsync } from '../utils/execAsync.js';
22
+ import { catchCsc2012, MSBuildEvaluationOutput, MSBuildProject } from './MSBuildProject.js';
23
+
24
+ type TmpDirNamespace_Unix = `${ReturnType<typeof tmpdir>}/HCE.Shared/.NET/Dummies`;
25
+ type TmpDirNamespace_Win = `${ReturnType<typeof tmpdir>}\\HCE.Shared\\.NET\\Dummies`;
26
+ const tmpDirNamespace = node_path.join(tmpdir(), 'HCE.Shared', '.NET', 'Dummies') as TmpDirNamespace_Unix | TmpDirNamespace_Win;
27
+ const defaultNugetSource = 'https://api.nuget.org/v3/index.json';
28
+ const key_OutputPackItems = '_OutputPackItems';
29
+ /**
30
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
31
+ * If the file doesn't exist, it is created.
32
+ * @returns If successful, a promised object with a parsed key.
33
+ */
34
+ export async function getGithubOutput(): Promise<ReturnType<typeof configDotenv>['parsed']> {
35
+ if (env['GITHUB_OUTPUT'] === undefined || !existsSync(env['GITHUB_OUTPUT'])) {
36
+ const githubOutputPath: string = node_path.join(tmpdir(), 'GITHUB_OUTPUT');
37
+ if (!existsSync(githubOutputPath))
38
+ await writeFile(githubOutputPath, '');
39
+ env['GITHUB_OUTPUT'] = githubOutputPath;
40
+ }
41
+
42
+ const encoding = await detectFile(env['GITHUB_OUTPUT']);
43
+ const envOutput = configDotenv({
44
+ path: env['GITHUB_OUTPUT'],
45
+ override: true,
46
+ encoding: encoding ?? undefined,
47
+ processEnv: {},
48
+ });
49
+
50
+ if (isNativeError(envOutput.error))
51
+ throw envOutput.error;
52
+ return envOutput.parsed;
53
+ }
54
+
55
+ /**
56
+ * Read the contents of $GITHUB_OUTPUT (if its value is a file path) or $TEMP/GITHUB_OUTPUT.
57
+ * If the file doesn't exist, it is created.
58
+ * @returns An object with a parsed key if successful.
59
+ */
60
+ export function getGithubOutputSync(): NonNullable<ReturnType<typeof configDotenv>['parsed']> {
61
+ if (env['GITHUB_OUTPUT'] === undefined || !existsSync(env['GITHUB_OUTPUT'])) {
62
+ const githubOutputPath: string = node_path.join(tmpdir(), 'GITHUB_OUTPUT');
63
+ if (!existsSync(githubOutputPath))
64
+ writeFileSync(githubOutputPath, '');
65
+ env['GITHUB_OUTPUT'] = githubOutputPath;
66
+ }
67
+
68
+ const encoding = detectFileSync(env['GITHUB_OUTPUT']);
69
+ const envOutput = configDotenv({
70
+ path: env['GITHUB_OUTPUT'],
71
+ override: true,
72
+ encoding: encoding ?? undefined,
73
+ processEnv: {},
74
+ }) as { error: Error }
75
+ | { parsed: NonNullable<ReturnType<typeof configDotenv>['parsed']> };
76
+
77
+ if ('error' in envOutput)
78
+ throw envOutput.error;
79
+ return envOutput.parsed;
80
+ }
81
+
82
+ type DummiesDir<T> = T extends undefined
83
+ ? `${TmpDirNamespace_Unix}/` | `${TmpDirNamespace_Win}\\`
84
+ : T extends MSBuildProject
85
+ ? `${TmpDirNamespace_Unix}/${T['Properties']['PackageId']}/` | `${TmpDirNamespace_Win}\\${T['Properties']['PackageId']}\\`
86
+ : never;
87
+
88
+ function getDummiesDir<T extends MSBuildProject | undefined = undefined>(project?: T): DummiesDir<T>;
89
+ function getDummiesDir<T extends MSBuildProject>(project: T): DummiesDir<T>;
90
+ /**
91
+ * Get HCE.Shared's temporary directory for .NET projects' dummy packages.
92
+ * @param project The MSBuild project whose PackageId will be used to create a
93
+ * directory for its dummy packages.
94
+ * @returns a platform-specific path like
95
+ * `${tmpdir()}/HCE.Shared/.NET/Dummies/${project.Properties.PackageId}` if
96
+ * {@link project} is defined. Else `${tmpdir()}/HCE.Shared/.NET/Dummies`
97
+ */
98
+ function getDummiesDir<T extends MSBuildProject | undefined = undefined>(project?: T): DummiesDir<typeof project> {
99
+ switch (true) {
100
+ case project === undefined: {
101
+ return node_path.join(tmpDirNamespace, node_path.sep) as
102
+ DummiesDir<typeof project> satisfies
103
+ ReturnType<typeof getDummiesDir>;
104
+ }
105
+ case project instanceof MSBuildProject: {
106
+ return node_path.join(tmpDirNamespace, project.Properties.PackageId, node_path.sep) as
107
+ DummiesDir<typeof project> satisfies
108
+ ReturnType<typeof getDummiesDir<MSBuildProject>>;
109
+ }
110
+ default: {
111
+ throw new Error('The type of argument `project` must be `undefined` or `MSBuildProject`.');
112
+ }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Get the environment variables as key-value pairs.
118
+ * @param tokenEnvVars The name of the environment variables whose values are
119
+ * NuGet API keys.
120
+ * @returns an array of key-value pairs of the given environment variables and
121
+ * their values, filtered to only those whose values are not undefined.
122
+ * @throws {Error} when none of the provided environment variables are defined.
123
+ */
124
+ function _GetTokenEnvVariables(tokenEnvVars: readonly string[]): undefined | [readonly [string, string], ...readonly [string, string][]] {
125
+ const definedTokens = Object.freeze(
126
+ tokenEnvVars
127
+ .map((key: string) => [key, getEnvVarValue(key)] as const)
128
+ .filter((envVarTuple: readonly [string, string | undefined]): envVarTuple is [string, string] =>
129
+ envVarTuple[1] !== undefined,
130
+ ),
131
+ );
132
+
133
+ if (definedTokens.length > 0)
134
+ return definedTokens as [readonly [string, string], ...readonly [string, string][]];
135
+ return undefined;
136
+ }
137
+
138
+ export class NugetRegistryInfo {
139
+ private _canPushPackagesToSource: Promise<true> | undefined = undefined;
140
+ private readonly _project: MSBuildProject;
141
+ private readonly _resolvedEnvVariable: string | undefined;
142
+ private readonly _source: string;
143
+
144
+ public static readonly DefaultTokenEnvVars: readonly ['NUGET_TOKEN']
145
+ = Object.freeze(['NUGET_TOKEN'] as const);
146
+
147
+ /**
148
+ * Convert a URL string to a filesystem folder name.
149
+ *
150
+ * Intended usage: modify the output path of `dotnet pack` based on the NuGet
151
+ * Source the package should be pushed to. This is extra work is usually
152
+ * unnecessary and you'd typically push the same file to multiple sources.
153
+ * This is for the edge-case scenario of creating multiple nupkgs and signing
154
+ * each one with a different certificate corresponding to a given NuGet
155
+ * Source. This is only useful if the Sources have different certificates
156
+ * registered for a given package/user/organization.
157
+ * @param source The URL of the NuGet Source
158
+ * @returns A string suitable for a local filesystem folder name, formatted as
159
+ * `${hostname}_${pathname.replace('/', '_')}`.
160
+ */
161
+ static GetDirNameForSource(source: string): string {
162
+ return sanitizeFileName(
163
+ source.replaceAll(/\/index.json$/g, ''),
164
+ { replacement: '_' },
165
+ );
166
+ }
167
+
168
+ /**
169
+ * Creates an instance of NugetRegistryInfo.\
170
+ * This class enables the ability to push a given {@link project}'s
171
+ * package(s) to the {@link source} of a given NuGet Source's API endpoint with
172
+ * a user-defined API key. This API key, herein referred to as a "token", is
173
+ * derived from the {@link tokenEnvVars} array. This array is iterated through
174
+ * until one of the items is discovered to be an existing environment variable
175
+ * (or is defined in a file named '.env' in the current working directory for
176
+ * LOCAL TESTING ONLY! Do NOT `git add` your private keys!).
177
+ * \
178
+ * WARNING:
179
+ * - The token value is stored privately within this class, but it is plain text.
180
+ * - This private key may be copied to command line strings stored in Semantic
181
+ * Release's config object for later use by `@semantic-release/exec`.
182
+ * - Other EcmaScript modules can access the environment variable(s) and steal
183
+ * your key. Be aware of malicious dependencies!
184
+ * @param opts The input type of {@link NRIOpts.from}
185
+ * @param opts.project The project whose package(s) will be
186
+ * pushed.\
187
+ * - Its {@link NugetProjectProperties#PackageId} will be read.\
188
+ * - Its {@link NugetProjectProperties#PackageVersion} will be overridden via CLI args when creating a dummy package. The real package's
189
+ * `PackageVersion` will *not* be overridden.
190
+ * @param [opts.tokenEnvVars] The environment variables
191
+ * whose values are tokens with permission to push a package to the NuGet
192
+ * package registry. The array is iterated through until one token is found.
193
+ * If none of the environment variables are defined, this constructor will
194
+ * throw an {@link Error}.
195
+ * @param [opts.source] A NuGet package registry's API endpoint URL or name. Default: 'https://api.nuget.org/v3/index.json'
196
+ */
197
+ constructor(opts: typeof NRIOpts['inferIn']) {
198
+ // note: you can reassign `opts` only when typeof `inferOut` is assignable
199
+ // to typeof `inferIn`.
200
+ const validOpts = NRIOpts.from(opts);
201
+ this._project = validOpts.project;
202
+ /**
203
+ * May throw! Assign key of the first key-value pair to
204
+ * {@link resolvedEnvVariable}
205
+ */
206
+ const tokenVars = _GetTokenEnvVariables(validOpts.tokenEnvVars);
207
+ if (tokenVars)
208
+ this._resolvedEnvVariable = tokenVars[0][0];
209
+ this._source = validOpts.source;
210
+ }
211
+
212
+ public get project(): MSBuildProject {
213
+ return this._project;
214
+ }
215
+
216
+ /**
217
+ * This is not useful without it being executed as part of a Semantic Release
218
+ * plugin. Deferring this to @semantic-release/exec's prepareCmd is possible,
219
+ * but impractical. You'd need to configure prepareCmd to invoke something
220
+ * like `node customScriptFile.mjs`. It's not worth the hassle.
221
+ * @returns `true` if the token can be used to push nupkg to the given Nuget registry
222
+ * @throws {TypeError | Error | import('../utils/execAsync.js').ChildProcessSpawnException }
223
+ * - {@link Error} | {@link module:utils/execAsync:ChildProcessSpawnException ChildProcessSpawnException}
224
+ * - The token is invalid, of the wrong token type, or lacks permission to push packages
225
+ * - The URL does not exist or a connection could not be established
226
+ * - The command line string is malformed.
227
+ * @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.
228
+ */
229
+ public get canPushPackagesToSource(): Promise<true> {
230
+ if (this._canPushPackagesToSource !== undefined)
231
+ return this._canPushPackagesToSource;
232
+
233
+ let tokenValue: string | undefined;
234
+ if (this.resolvedEnvVariable !== undefined)
235
+ tokenValue = NRI._GetTokenValue(this.resolvedEnvVariable);
236
+
237
+ if (tokenValue?.startsWith('github_pat_')) {
238
+ 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.`;
239
+ const err = new Error(errMsg);
240
+ return this._canPushPackagesToSource = Promise.reject(err);
241
+ }
242
+
243
+ return this._canPushPackagesToSource = this.PackDummyPackage({})
244
+ .then(async () => await this._PushDummyPackages({
245
+ apiKey: tokenValue,
246
+ }))
247
+ .then<true>((execAsyncReturn) => {
248
+ ok(execAsyncReturn);
249
+ return true as const;
250
+ });
251
+ }
252
+
253
+ /**
254
+ * The first environment variable found to have a defined value. Set by
255
+ * {@link _GetTokenEnvVariables} in the constructor.
256
+ * @returns The first environment variable found to have a defined value.
257
+ */
258
+ get resolvedEnvVariable(): string | undefined {
259
+ return this._resolvedEnvVariable;
260
+ }
261
+
262
+ get source(): string {
263
+ return this._source;
264
+ }
265
+
266
+ /**
267
+ * Get the API token from {@link NugetRegistryInfo#resolvedEnvVariable}
268
+ * @param resolvedEnvVariable The name of the environment variable(s) whose
269
+ * value is a NuGet API key. Typically, the value of
270
+ * {@link NugetRegistryInfo#resolvedEnvVariable}.
271
+ * @returns The value of the first defined environment variable.
272
+ * @throws {Error} when none of the provided environment variables are defined.
273
+ */
274
+ private static _GetTokenValue(resolvedEnvVariable: string): string {
275
+ type.string.assert(resolvedEnvVariable);
276
+
277
+ const tokenValue = getEnvVarValue(resolvedEnvVariable);
278
+ if (tokenValue === undefined) {
279
+ throw new Error(`\
280
+ The environment variable ${resolvedEnvVariable} was specified \
281
+ as the source of the token to push a NuGet package, \
282
+ but the environment variable is empty or undefined.`);
283
+ }
284
+ return tokenValue;
285
+ }
286
+
287
+ // #region Pack
288
+
289
+ /**
290
+ * The type for options and arguments of `dotnet pack`. See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack.
291
+ *
292
+ * {@link NRI.PackPackagesOptionsType.t.propertyOverrides `propertyOverrides`}
293
+ * is a wrapper for MSBuild's `-property:<n>=<v>` properties override arg.
294
+ */
295
+ static readonly PackPackagesOptionsType = Object.freeze(
296
+ type({
297
+ /**
298
+ * a custom arg for handling MSBuild's `-property:<n>=<v>` argument for overriding MSBuild properties.
299
+ */
300
+ 'propertyOverrides?': type('Record<string,string>'),
301
+ 'artifactsPath?': 'string',
302
+ 'configuration?': '"Release" | "Debug"',
303
+ 'disableBuildServers?': 'boolean',
304
+ 'force?': 'boolean',
305
+ 'includeSource?': 'boolean',
306
+ 'includeSymbols?': 'boolean',
307
+ 'interactive?': 'boolean',
308
+ 'noBuild?': 'boolean',
309
+ 'noLogo?': 'boolean',
310
+ 'noRestore?': 'boolean',
311
+ 'output?': 'string',
312
+ 'runtime?': 'string',
313
+ 'serviceable?': 'boolean',
314
+ 'terminalLogger?': '"auto" | "on" | "off"',
315
+ 'useCurrentRuntime?': 'boolean',
316
+ 'verbosity?': '"quiet" | "minimal" | "normal" | "detailed" | "diagnostic"',
317
+ 'versionSuffix?': 'string',
318
+ /**
319
+ * MSBuild evaluation option. Added to get the output Nupkgs' file paths.
320
+ * @todo consider adding -GetProperty, -GetTarget
321
+ */
322
+ '-GetItem?': type.string.array().readonly().or('string[]'),
323
+ }),
324
+ );
325
+
326
+ public static readonly PackDummyPackagesOptionsType
327
+ = this.PackPackagesOptionsType.omit('output');
328
+
329
+ /**
330
+ * Get a `dotnet pack` command line string, outputting the package(s) to a
331
+ * path determined by this method's parameters.
332
+ * When pushing the package(s), you only need to supply the main .nupkg's path
333
+ * or its directory to the dotnet CLI—by default, it will also push the
334
+ * symbols package, if present.
335
+ * @param opts Options passed to
336
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument. The
337
+ * {@link PackPackagesOptionsType.t.output} path is modified according to the
338
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
339
+ * arguments.
340
+ * @param usePerSourceSubfolder If true, the path of the package output will
341
+ * include a subfolder named after the NuGet Source.
342
+ * @param usePerPackageIdSubfolder If true, the path of the package output
343
+ * will include a subfolder named after the NuGet package's ID.
344
+ * @returns `dotnet pack "${this.project.Properties.MSBuildProjectFullPath}"
345
+ * -o "${outDir}"` where outDir may be `${cwd()}/publish/${NugetRegistryInfo.GetNameForURL(this.source)}/${this._project.Properties.PackageId}`
346
+ */
347
+ GetPackCommand(
348
+ opts: typeof NRI.PackPackagesOptionsType.inferIn,
349
+ usePerSourceSubfolder = false,
350
+ usePerPackageIdSubfolder = false,
351
+ ): string {
352
+ const validOpts = NRI.PackPackagesOptionsType.from(opts);
353
+ type.boolean.assert(usePerSourceSubfolder);
354
+ type.boolean.assert(usePerPackageIdSubfolder);
355
+
356
+ validOpts.output ??= node_path.join(cwd(), 'publish');
357
+ if (usePerSourceSubfolder)
358
+ validOpts.output = node_path.join(validOpts.output, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
359
+ if (usePerPackageIdSubfolder)
360
+ validOpts.output = node_path.join(validOpts.output, this._project.Properties.PackageId, node_path.sep);
361
+
362
+ const packCmdArr: string[] = [
363
+ 'dotnet',
364
+ 'pack',
365
+ `"${this._project.Properties.MSBuildProjectFullPath}"`,
366
+ ];
367
+ if (validOpts.artifactsPath !== undefined)
368
+ packCmdArr.push('--artifactsPath', `"${validOpts.artifactsPath}"`);
369
+ if (validOpts.configuration !== undefined)
370
+ packCmdArr.push('--configuration', validOpts.configuration);
371
+ if (validOpts.disableBuildServers === true)
372
+ packCmdArr.push('--disable-build-servers');
373
+ if (validOpts.force === true) packCmdArr.push('--force');
374
+ if (validOpts.includeSource === true) packCmdArr.push('--include-source');
375
+ if (validOpts.includeSymbols === true) packCmdArr.push('--include-symbols');
376
+ if (validOpts.interactive === true) packCmdArr.push('--interactive');
377
+ if (validOpts.noBuild === true) packCmdArr.push('--no-build');
378
+ if (validOpts.noLogo === true) packCmdArr.push('--nologo');
379
+ if (validOpts.noRestore === true) packCmdArr.push('--no-restore');
380
+ if (validOpts.runtime !== undefined)
381
+ packCmdArr.push('--runtime', validOpts.runtime);
382
+ if (validOpts.serviceable === true) packCmdArr.push('--serviceable');
383
+ if (validOpts.terminalLogger !== undefined)
384
+ packCmdArr.push('--tl', validOpts.terminalLogger);
385
+ if (validOpts.useCurrentRuntime === true)
386
+ packCmdArr.push('--use-current-runtime');
387
+ if (validOpts.verbosity !== undefined)
388
+ packCmdArr.push('--verbosity', validOpts.verbosity);
389
+ if (validOpts.versionSuffix !== undefined)
390
+ packCmdArr.push('--version-suffix', validOpts.versionSuffix);
391
+ /**
392
+ * Haphazard. I need to override the Version and I'm not considering side
393
+ * effects of arbitrary overrides.
394
+ */
395
+ if (validOpts.propertyOverrides) {
396
+ /** convert propertyOverrides record to "-p:n0=v0;n1=v1;n2=v2" et cetera */
397
+ const assignments: string = '-p:' + Object.entries(validOpts.propertyOverrides)
398
+ .map(v => `${v[0]}=${v[1]}`).join(';');
399
+ packCmdArr.push(`"${assignments}"`);
400
+ }
401
+ if (validOpts['-GetItem'] && validOpts['-GetItem'].length > 0) {
402
+ // -GetItem:_OutputPackItems,MyCustomItem
403
+ packCmdArr.push(`-GetItem:${validOpts['-GetItem'].join(',')}`);
404
+ }
405
+ // MSBuild parses everything after -o as the path.
406
+ packCmdArr.push('-o', `"${validOpts.output}"`);
407
+
408
+ return packCmdArr.join(' ');
409
+ }
410
+
411
+ /**
412
+ * !Not ready for use! Remove private modifier and commit as `feat(dotnet)` when ready for release!
413
+ * Blocking Issue: convert all dotnet-related functionality to a Semantic Release plugin!
414
+ * The current {@link SemanticReleaseConfigDotnet} leverages
415
+ * `@semantic-release/exec` to invoke dotnet commands. This is fine for
416
+ * relatively short command lines, but chaining commands with ' && ' results
417
+ * in quickly-growing complexity.
418
+ * NuGet packages should be created during the `prepare` step, but complex
419
+ * configuration of `dotnet pack` via command lines intended to be invoked by
420
+ * `@semantic-release/exec` is impractical.
421
+ * @param opts `dotnet pack` options. See `dotnet pack -h`,
422
+ * https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-pack, and
423
+ * {@link PackPackagesOptionsType}.
424
+ * {@link opts['-GetItem']} will _always_ have '_OutputPackItems'.
425
+ * @param [usePerSourceSubfolder] If `true`, modify the output path to
426
+ * include a subfolder bearing a path-safe encoding of the NuGet Source that
427
+ * will receive the nupkg.
428
+ * @param [usePerPackageIdSubfolder] If `true`, modify the output path
429
+ * to include a subfolder named after the the PackageId.
430
+ * @returns a string[] containing the full file paths of all new packages i.e.
431
+ * .nupkg, .symbols.nupkg, .snupkg
432
+ */
433
+ // @ts-expect-error Todo: publicize to dismiss this "unused" error.
434
+ private async _PackPackages(
435
+ opts: typeof NRI.PackPackagesOptionsType.inferIn,
436
+ usePerSourceSubfolder = false,
437
+ usePerPackageIdSubfolder = false,
438
+ ): Promise<string[]> {
439
+ opts['-GetItem'] = [...opts['-GetItem'] ?? [], key_OutputPackItems];
440
+
441
+ const packCmd = this.GetPackCommand(
442
+ opts,
443
+ usePerSourceSubfolder,
444
+ usePerPackageIdSubfolder,
445
+ );
446
+ let packOutput: undefined | { stdout: string; stderr: string } = undefined;
447
+ while (packOutput === undefined) {
448
+ packOutput = await setTimeout(
449
+ 1000,
450
+ execAsync(packCmd, true),
451
+ )
452
+ .then(async p => await p)
453
+ .catch<undefined>(catchCsc2012);
454
+ }
455
+ // may include .snupkg
456
+ const nupkgFullPaths: string[] | undefined = new MSBuildEvaluationOutput(packOutput.stdout)
457
+ .Items
458
+ ?.[key_OutputPackItems]
459
+ ?.filter(item => item.Extension !== '.nuspec')
460
+ .map(item => item.FullPath);
461
+ return nupkgFullPaths ?? [];
462
+ }
463
+
464
+ /**
465
+ * Create a dummy package for the current {@link project} by executing a
466
+ * command line like \``dotnet pack ${this.project.Properties.MSBuildProjectFullPath} -p:Version=0.0.1-DUMMY -output ${getDummiesDir(this._project)}/${GetNameForURL(this.source)}`\`
467
+ * @param opts Options passed to
468
+ * `dotnet pack`, excluding the required `<PROJECT | SOLUTION>` argument.
469
+ * - The `output` field is ignored and overwritten. It is replaced with
470
+ * ${{@link getDummiesDir}({@link project})}/${{@link GetDirNameForSource}({@link source})}
471
+ * - The `output` path will be affixed with a folder named after this
472
+ * {@link NugetRegistryInfo#source}, but will not include a subfolder for the
473
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}.
474
+ * @returns the full paths of all nupkg, symbols.nupkg, and snupkg files
475
+ * created by the Pack target, as extracted from the dotnet process's STDOUT.
476
+ * If mixed with other nupkgs, filter for the {@link NugetProjectProperties#PackageId}
477
+ */
478
+ public async PackDummyPackage(
479
+ opts: typeof NRI.PackDummyPackagesOptionsType.inferIn,
480
+ ): Promise<string[]> {
481
+ const packCmd: string = this.GetPackCommand(
482
+ {
483
+ ...opts,
484
+ output: getDummiesDir(this._project),
485
+ propertyOverrides: { ...opts.propertyOverrides, Version: '0.0.1-DUMMY' },
486
+ '-GetItem': [...opts['-GetItem'] ?? [], key_OutputPackItems],
487
+ },
488
+ true,
489
+ );
490
+
491
+ let packOutput: undefined | { stdout: string; stderr: string } = undefined;
492
+ while (packOutput === undefined) {
493
+ packOutput = await setTimeout(
494
+ 1000,
495
+ execAsync(packCmd, true),
496
+ )
497
+ .then(async p => await p)
498
+ .catch<undefined>(catchCsc2012);
499
+ }
500
+ // may include .snupkg
501
+ const nupkgFullPaths: string[] | undefined = new MSBuildEvaluationOutput(packOutput.stdout)
502
+ .Items
503
+ ?.['outputPackItems']
504
+ ?.filter(item => item.Extension !== '.nuspec')
505
+ .map(item => item.FullPath);
506
+ return nupkgFullPaths ?? [];
507
+ }
508
+
509
+ // #endregion Pack
510
+ // #region Push
511
+
512
+ /**
513
+ * Also includes required argument 'ROOT': the directory in which packages
514
+ * should be present and ready to be pushed the default or specified Source.
515
+ * The ROOT may also include wildcards e.g. `*.nupkg`, `**\\*.nupkg`
516
+ * See https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-push
517
+ *
518
+ * Specific to this API:
519
+ * If you want to use this API's default root value (\`${cwd()}/publish`), assign an empty string.
520
+ */
521
+ static readonly PushPackagesOptionsType = Object.freeze(
522
+ type({
523
+ /** If an empty string is passed, this property is overridden to `./publish` */
524
+ root: 'string',
525
+ /** The API key for the server. NOTE: if `undefined` or an empty string, the `dotnet nuget` client will lookup credentials set via `dotnet nuget {add|update} source`. */
526
+ 'apiKey?': 'string',
527
+ /** The NuGet configuration file (nuget.config) to use. If specified, only the settings from this file will be used. If not specified, the hierarchy of configuration files from the current directory will be used. For more information, see {@link https://learn.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior Common NuGet Configurations}. */
528
+ 'configFile?': 'string',
529
+ /** Disables buffering when pushing to an HTTP(S) server to reduce memory usage. */
530
+ 'disableBuffering?': 'boolean',
531
+ /** Forces the application to run using an invariant, English-based culture. */
532
+ 'forceEnglishOutput?': 'boolean',
533
+ /** Allows the command to stop and wait for user input or action. For example, to complete authentication. Available since .NET Core 3.0 SDK. */
534
+ 'interactive?': 'boolean',
535
+ /** Doesn't append "api/v2/package" to the source URL. */
536
+ 'noServiceEndpoint?': 'boolean',
537
+ 'noSymbols?': 'boolean',
538
+ /** When pushing multiple packages to an HTTP(S) server, treats any 409 Conflict response as a warning so that other pushes can continue. */
539
+ 'skipDuplicate?': 'boolean',
540
+ /**
541
+ * Specifies the server URL. NuGet identifies a UNC or local folder source and simply copies the file there instead of pushing it using HTTP.
542
+ *
543
+ * ### Important
544
+ * > Starting with NuGet 3.4.2, this is a mandatory parameter unless the NuGet config file specifies a `DefaultPushSource` value. For more information, see {@link https://learn.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior Configuring NuGet behavior}.
545
+ */
546
+ 'source?': 'string',
547
+ /** The API key for the symbol server. NOTE: if `undefined`, the `dotnet nuget` client will lookup credentials set via `dotnet nuget {add|update} source`.` */
548
+ 'symbolApiKey?': 'string',
549
+ /** Specifies the symbol server URL. */
550
+ 'symbolSource?': 'string',
551
+ /** Specifies the timeout for pushing to a server in seconds. Defaults to 300 seconds (5 minutes). Specifying 0 applies the default value. */
552
+ 'timeout?': 'number',
553
+ }),
554
+ );
555
+
556
+ /**
557
+ * {@link NRI.PushPackagesOptionsType} sans {@link NRI.PushPackagesOptionsType.t.root}.
558
+ * The result of {@link getDummiesDir} is used, instead.
559
+ */
560
+ public static readonly PushDummyPackagesOptionsType
561
+ = NugetRegistryInfo.PushPackagesOptionsType.merge({
562
+ skipDuplicate: 'true = true',
563
+ }).omit('root');
564
+
565
+ /**
566
+ * Create a `dotnet nuget push` command line from the given options and
567
+ * optional boolean parameters.
568
+ * @param opts See {@link PushPackagesOptionsType}
569
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
570
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
571
+ * wildcards in ROOT with this set to `true`!
572
+ * @param usePerPackageIdSubfolder If `true`, the
573
+ * {@link project}'s {@link NugetProjectProperties#PackageId}
574
+ * is appended to the ROOT as a subfolder. Do not use wildcards in
575
+ * ROOT with this set to `true`!
576
+ * @returns A `dotnet nuget push` command line formatted with the
577
+ * appropriate arguments.
578
+ */
579
+ GetPushCommand(
580
+ opts: typeof NRI.PushPackagesOptionsType.inferIn,
581
+ usePerSourceSubfolder = false,
582
+ usePerPackageIdSubfolder = false,
583
+ ): string {
584
+ const validOpts = NRI.PushPackagesOptionsType.from(opts);
585
+ type.boolean.assert(usePerSourceSubfolder);
586
+ type.boolean.assert(usePerPackageIdSubfolder);
587
+
588
+ validOpts.root = validOpts.root === '' ? `${cwd()}/publish` : validOpts.root;
589
+ if (usePerSourceSubfolder)
590
+ validOpts.root = node_path.join(validOpts.root, NugetRegistryInfo.GetDirNameForSource(this.source), node_path.sep);
591
+ if (usePerPackageIdSubfolder)
592
+ validOpts.root = node_path.join(validOpts.root, this._project.Properties.PackageId, node_path.sep);
593
+
594
+ const packCmdArr: string[] = [
595
+ 'dotnet',
596
+ 'nuget',
597
+ 'push',
598
+ `"${node_path.join(validOpts.root, '*.nupkg')}"`,
599
+ ];
600
+
601
+ if (this.resolvedEnvVariable)
602
+ validOpts.apiKey ??= NRI._GetTokenValue(this.resolvedEnvVariable);
603
+ /**
604
+ * If apiKey is an empty string, defer to the dotnet CLI's NuGet client
605
+ * ability to lookup API keys saved via `dotnet nuget add source` or NuGet config
606
+ * files.
607
+ */
608
+ if (validOpts.apiKey && validOpts.apiKey !== '')
609
+ packCmdArr.push('--api-key', validOpts.apiKey);
610
+ if (validOpts.configFile)
611
+ packCmdArr.push('--configfile', validOpts.configFile);
612
+ if (validOpts.disableBuffering === true)
613
+ packCmdArr.push('--disable-buffering');
614
+ if (validOpts.forceEnglishOutput === true)
615
+ packCmdArr.push('--force-english-output');
616
+ if (validOpts.interactive === true)
617
+ packCmdArr.push('--interactive');
618
+ if (validOpts.noServiceEndpoint === true)
619
+ packCmdArr.push('--no-service-endpoint');
620
+ if (validOpts.noSymbols === true)
621
+ packCmdArr.push('--no-symbols');
622
+ if (validOpts.skipDuplicate === true)
623
+ packCmdArr.push('--skip-duplicate');
624
+ validOpts.source ??= this.source;
625
+ packCmdArr.push('--source', validOpts.source);
626
+ if (validOpts.symbolApiKey !== undefined)
627
+ packCmdArr.push('--symbol-api-key', validOpts.symbolApiKey);
628
+ if (validOpts.symbolSource !== undefined)
629
+ packCmdArr.push('--symbol-source', validOpts.symbolSource);
630
+ if (validOpts.timeout !== undefined)
631
+ packCmdArr.push('--timeout', validOpts.timeout.toString());
632
+
633
+ return packCmdArr.join(' ');
634
+ }
635
+
636
+ /**
637
+ * Immediately push packages. The input path may be modified according to the
638
+ * {@link usePerSourceSubfolder} and {@link usePerPackageIdSubfolder}
639
+ * arguments.
640
+ * @param opts The `dotnet nuget push` command line options, including the
641
+ * ROOT argument, the directory containing local nuget packages ready to be
642
+ * pushed.
643
+ * @param usePerSourceSubfolder If `true`, the NuGet Source name or URL is formatted
644
+ * to a folder name and appended to the ROOT as a subfolder. Do not use
645
+ * wildcards in ROOT with this set to `true`!
646
+ * @param usePerPackageIdSubfolder If `true`, the current {@link project}'s
647
+ * PackageId is appended to the ROOT as a subfolder. Do not use wildcards in
648
+ * ROOT with this set to `true`!
649
+ */
650
+ // @ts-expect-error Todo: publicize to dismiss this "unused" error.
651
+ private async _PushPackages(
652
+ opts: typeof NRI.PushPackagesOptionsType.inferIn,
653
+ usePerSourceSubfolder = false,
654
+ usePerPackageIdSubfolder = false,
655
+ ) {
656
+ // const pushOutput =
657
+ await execAsync(
658
+ this.GetPushCommand(
659
+ opts,
660
+ usePerSourceSubfolder,
661
+ usePerPackageIdSubfolder,
662
+ ),
663
+ true,
664
+ ).catch((error: unknown) => {
665
+ const _error: Error = isNativeError(error) ? error : new Error(JSON.stringify(error));
666
+ throw opts.apiKey
667
+ ? _censorTokenInError(_error, opts.apiKey)
668
+ : _error;
669
+ });
670
+ }
671
+
672
+ /**
673
+ *
674
+ * Get a `dotnet nuget push` command for pushing one or more nupkg/snupkg
675
+ * files created by {@link GetPackCommand} or {@link _PackPackages}.\
676
+ * Like {@link PackDummyPackage}, the output/ROOT path will include a
677
+ * folder named after this NRI instance's {@link NugetRegistryInfo#source},
678
+ * but will not include a subfolder for the
679
+ * {@link NugetRegistryInfo#project NugetRegistryInfo.project}.{@link MSBuildProject#Properties Properties}.{@link MSBuildProject#Properties#PackageId PackageId}
680
+ * @example
681
+ * ```ts
682
+ * const packAndPushDummyCmd = [
683
+ * nri.GetPackCommand(
684
+ * NugetRegistryInfo.PackPackagesOptionsType.from({ root: '' }),
685
+ * false,
686
+ * false,
687
+ * ),
688
+ * nri.GetPushDummyPackageCommand(pushOpts, false, false),
689
+ * ].join(' && ')
690
+ * ```
691
+ * @param opts options for `dotnet nuget push`. The following
692
+ * fields are overwritten:
693
+ * - root: getDummiesDir(this.project)
694
+ * - skipDuplicates: true
695
+ * @returns a `dotnet nuget push` command to push a dummy package
696
+ * (created by executing {@link PackDummyPackage}) to {@link source}
697
+ */
698
+ GetPushDummyCommand(
699
+ opts: typeof NRI.PushDummyPackagesOptionsType.inferIn,
700
+ ): string {
701
+ return this.GetPushCommand(
702
+ {
703
+ ...NRI.PushDummyPackagesOptionsType.from(opts),
704
+ root: getDummiesDir(this._project),
705
+ },
706
+ true,
707
+ );
708
+ }
709
+
710
+ /**
711
+ * Call {@link GetPushDummyCommand} and immediately execute it.
712
+ * @throws {Error} when the process exits with an error code indicating
713
+ * failure i.e. the command line is invalid, the process fails to start,
714
+ * the push fails, et cetera.
715
+ * @param opts the ROOT arg and options for `dotnet nuget push`. The following
716
+ * fields are overwritten:
717
+ * - root: getDummiesDir(this.project)
718
+ * - skipDuplicates: true
719
+ * @returns The return type of {@link execAsync} i.e. a {@link Promise} resolving to `{ stdout: string; stderr: string }`.
720
+ */
721
+ private async _PushDummyPackages(
722
+ opts: typeof NRI.PushDummyPackagesOptionsType.inferIn,
723
+ ): ReturnType<typeof execAsync> {
724
+ const pushCmd: string = this.GetPushDummyCommand(opts);
725
+ return await execAsync(pushCmd, true)
726
+ .catch((error: unknown) => {
727
+ const _error: Error = isNativeError(error) ? error : new Error(String(error));
728
+ throw opts.apiKey
729
+ ? _censorTokenInError(_error, opts.apiKey)
730
+ : _error;
731
+ });
732
+ }
733
+
734
+ // #endregion Push
735
+
736
+ // if non-exact-match is needed, learn how to make a parameter-driven type.
737
+ private static readonly _NugetSearchReturnTypes = {
738
+ ExactMatch: {
739
+ v2: type({
740
+ version: '2',
741
+ problems: 'unknown[]',
742
+ searchResult: [
743
+ {
744
+ sourceName: 'string',
745
+ packages: type({
746
+ id: 'string',
747
+ version: type.keywords.string.semver,
748
+ }).array(),
749
+ },
750
+ ],
751
+ }),
752
+ },
753
+ };
754
+
755
+ private static readonly _ParseNugetSearchReturn = type(
756
+ 'string.json.parse',
757
+ ).to(this._NugetSearchReturnTypes.ExactMatch.v2);
758
+
759
+ /**
760
+ * !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.\
761
+ * Call during the `prepare` step of a Semantic Release run.\
762
+ * Determine if the `nextVersion` generated during the `analyze` Semantic
763
+ * Release step was already published to the NuGet {@link source}.
764
+ * @param source The name or URI of the NuGet Source to search. If this API
765
+ * endpoint does not support searches, the operation will fail. If this API
766
+ * endpoint requires authentication (e.g. GitHub), it must be configured via
767
+ * `dotnet nuget add source` or `dotnet nuget update source` before calling
768
+ * this method.
769
+ * @param packageId The ID of the NuGet package to search for.
770
+ * @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).
771
+ * @returns A promised boolean.
772
+ * If the promise resolves to `true`, the semantic release run should be
773
+ * cancelled immediately.
774
+ * Otherwise, the release should proceed.
775
+ * @todo utilize in custom plugin inserted at the beginning of `prepare`
776
+ */
777
+ static async IsNextVersionAlreadyPublished(
778
+ source: string,
779
+ packageId: string,
780
+ nextVersion: string,
781
+ ): Promise<boolean> {
782
+ if (nextVersion === '')
783
+ throw new Error('The value of nextVersion is empty');
784
+ return await execAsync(
785
+ `dotnet package search --format JSON --exact-match --source ${source} --prerelease ${packageId}`,
786
+ true,
787
+ )
788
+ .then(stdPair => stdPair.stdout)
789
+ .then(json => this._ParseNugetSearchReturn(json))
790
+ .then(errsOrObj => errsOrObj instanceof type.errors ? errsOrObj.throw() : errsOrObj)
791
+ .then(obj => obj.searchResult)
792
+ .then(results => results[0].packages)
793
+ .then(pkgs =>
794
+ pkgs.find(p => p.version === type('string.semver').from(nextVersion)),
795
+ )
796
+ .then(pkg => pkg !== undefined);
797
+ }
798
+
799
+ /**
800
+ * !WARNING: GITHUB_OUTPUT must be the full path to an environment file.
801
+ * The plugin "semantic-release-output-variables" next-release-version
802
+ *
803
+ * !WARNING: NuGet Source API Key mus tbe configured via `dotnet nuget add source` or `dotnet nuget update source`.
804
+ * Some Sources (e.g. GitHub) require authentication for package searches.
805
+ *
806
+ * # Authenticating NuGet Package Searches
807
+ *
808
+ * ## GitHub NuGet Registry authentication
809
+ * - {@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}
810
+ * - {@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}.
811
+ * ## For GitLab NuGet Registry authentication, see
812
+ * - {@link https://docs.gitlab.com/ee/user/packages/nuget_repository/#add-a-source-with-the-net-cli Add a source with the .NET CLI}
813
+ * @returns a string containing a Node.JS command line invoking {@link ./IsNextVersionAlreadyPublished.cli.ts}
814
+ * @see {@link ./IsNextVersionAlreadyPublished.cli.ts}, {@link ./IsNextVersionAlreadyPublished.cli.js}
815
+ */
816
+ GetIsNextVersionAlreadyPublishedCommand(): string {
817
+ // if GITHUB_OUTPUT unset or its file does not exist, create it. ''
818
+ getGithubOutputSync();
819
+ // The script will run
820
+ return `node ${node_path.join(import.meta.dirname, './IsNextVersionAlreadyPublished.cli.js')} --packageId ${this._project.Properties.PackageId} --source ${this.source}`;
821
+ }
822
+
823
+ /*
824
+ * Copy https://github.com/joelharkes/nuget-push when we split off our dotnet
825
+ * modules to a semantic-release plugin.
826
+ */
827
+
828
+ /*
829
+ * If you want a deterministic nupkg, do so with a custom MSBuild target with
830
+ * AfterTargets="Pack" to restore and execute the dotnet tool "Kuinox.NupkgDeterministicator" .
831
+ */
832
+ }
833
+
834
+ // shorthand/alias for NugetRegistryInfo
835
+ const NRI = NugetRegistryInfo;
836
+
837
+ /**
838
+ * The base type for {@link NRIOpts} and related types. Extend this type while
839
+ * overriding member types via {@link NRIOptsBase.merge}
840
+ */
841
+ export const NRIOptsBase = type({
842
+ /**
843
+ * The environment variables whose values are tokens with permission to push a
844
+ * package to the NuGet package registry. The array is iterated through until
845
+ * one token is found. If none of the environment variables are defined,
846
+ * {@link NugetRegistryInfo}'s constructor will throw an {@link Error}.
847
+ */
848
+ project: type
849
+ .instanceOf(MSBuildProject)
850
+ .or(type.instanceOf(MSBuildProject).readonly()),
851
+ /**
852
+ * A NuGet package registry's API endpoint URL -OR- the name assigned via the
853
+ * client e.g. `dotnet nuget add source --name ${source} ${source's URL}`
854
+ */
855
+ source: type.string,
856
+ /**
857
+ * WARNING: If possible, set credentials via `dotnet nuget {add|update}
858
+ * source` as recommended by Microsoft! This is more secure than exposing
859
+ * credentials to the Node.JS runtime and all its loaded modules.
860
+ *
861
+ * The environment variables whose values are tokens with permission to push a
862
+ * package to the NuGet package registry.The array is iterated through until
863
+ * one token is found.If none of the environment variables are defined,
864
+ * {@link NugetRegistryInfo}'s constructor will throw an {@link Error}.
865
+ *
866
+ * If none of these are defined in the `.env` or process environment variables (.vault.env is impractical in CI), the `--api-key/-k` argument is excluded from `dotnet nuget push` commands.
867
+ * Instead, the NuGet client relies on credentials configured for the
868
+ * given NuGet source. If the NuGet client does not find credentials saved for the
869
+ * NuGet {@link NRIOptsBase.t.source source} and they are required, the command will fail.
870
+ *
871
+ * Use the `dotnet` CLI to configure credentials for existing NuGet sources
872
+ * ({@link https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-update-source `dotnet nuget update source`})
873
+ * -OR- configure credentials for non-default NuGet sources
874
+ * ({@link https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-add-source `dotnet nuget add source`}).\
875
+ * Alternatively, use the `nuget.exe` CLI to add/update sources. See
876
+ * {@link https://learn.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-sources `nuget sources` (NuGet CLI)}.
877
+ *
878
+ * The credentials will be validated during the `verifyConditions` step of Semantic Release.
879
+ */
880
+ tokenEnvVars: type.string.array().readonly(),
881
+ });
882
+
883
+ /**
884
+ * The type of the parameter for {@link NugetRegistryInfo}'s constructor.
885
+ */
886
+ export const NRIOpts = NRIOptsBase.merge({
887
+ /**
888
+ * Defaults to {@link NugetRegistryInfo.DefaultTokenEnvVars}
889
+ * @see {@link NRIOptsBase.t.tokenEnvVars}
890
+ */
891
+ tokenEnvVars: NRIOptsBase.get('tokenEnvVars').default(
892
+ () => NugetRegistryInfo.DefaultTokenEnvVars,
893
+ ),
894
+ /**
895
+ * A NuGet package registry's API endpoint URL -OR- the name assigned to it
896
+ * via your NuGet client.
897
+ * @default 'https://api.nuget.org/v3/index.json' (name: 'nuget.org')
898
+ * @see {@link NRIOptsBase.t.source}
899
+ */
900
+ source: NRIOptsBase.get('source').default(() => defaultNugetSource),
901
+ });
902
+
903
+ // #region token censorship
904
+
905
+ /**
906
+ * Replace all occurrences of {@link token} in the {@link string} with '***'.
907
+ * @param string The string in which a {@link token} may be found.
908
+ * @param token The NuGet API token you definitely don't want to leak!
909
+ * @returns A modified copy of the {@link string} with all occurrences of the
910
+ * {@link token} replaced with '***'.
911
+ */
912
+ function _censorToken(string: string, token: string): string {
913
+ return string.replaceAll(token, '***');
914
+ }
915
+
916
+ /**
917
+ * Censor all occurrences of an API {@link token} in an {@link error}.
918
+ * @param error A {@link ExecException} in which the NuGet API {@link token} may be found.
919
+ * @param token The value of the NuGet API token
920
+ * @returns A modified copy of the provided exception sans any occurrence of the
921
+ * NuGet API token.
922
+ */
923
+ function _censorTokenInError(error: ExecException, token: string): ExecException {
924
+ return Object.assign(
925
+ error,
926
+ JSON.parse(
927
+ _censorToken(
928
+ JSON.stringify({
929
+ ...error,
930
+ message: error.message,
931
+ stack: error.stack,
932
+ }),
933
+ token,
934
+ ),
935
+ ) as ExecException,
936
+ );
937
+ }
938
+
939
+ // #endregion token censorship