@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
@@ -1,83 +1,564 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { type } from 'arktype';
2
+ import { warn } from 'node:console';
3
+ import { type Dirent } from 'node:fs';
4
+ import { readdir, realpath, stat } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { setTimeout } from 'node:timers/promises';
7
+ import { isNativeError } from 'node:util/types';
8
+ import { CaseInsensitiveMap } from '../CaseInsensitiveMap.js';
9
+ import { execAsync } from '../utils/execAsync.js';
2
10
  import { MSBuildProjectProperties } from './MSBuildProjectProperties.js';
11
+ import {
12
+ NPPGetterNames,
13
+ NugetProjectProperties,
14
+ } from './NugetProjectProperties.js';
3
15
 
4
16
  /**
5
- * All pre-defined properties of {@link MSBuildProjectProperties} except FullPath
17
+ * See [MSBuild well-known item metadata](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-well-known-item-metadata).
18
+ * Additional string-type properties may be present (e.g. `{ SubType: "designer" }`).
6
19
  */
7
- export const MSBuildProjectPreDefinedProperties = Object.keys(
8
- new MSBuildProjectProperties('', false),
9
- ).filter((p) => p !== 'FullPath');
10
- /** @todo Experimental and may be removed in a later release.
11
- * A cache for your evaluated MSBuild Projects.
12
- */
13
- export const MSBuildEvaluatedProjects: MSBuildProject[] = [];
20
+ const interface_ItemMetadataBuiltIn = type({
21
+ '[string]': 'string',
22
+ /** @example "c:\\source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\ConsoleApp1.dll" */
23
+ Identity: 'string',
24
+ /** @example "Designer" */
25
+ 'SubType?': 'string',
26
+ /** @example ".NETCoreApp" */
27
+ 'TargetFrameworkIdentifier?': 'string',
28
+ 'TargetPlatformMoniker?': 'string',
29
+ /** @example "c:\\source\\repos\\ConsoleApp1\\ConsoleApp1\\obj\\Debug\\net6.0\\ConsoleApp1.csproj.CopyComplete" */
30
+ 'CopyUpToDateMarker?': 'string',
31
+ 'TargetPlatformIdentifier?': 'string',
32
+ /** @example "6.0" */
33
+ 'TargetFrameworkVersion?': 'string',
34
+ /** @example "c:\\source\\repos\\ConsoleApp1\\ConsoleApp1\\obj\\Debug\\net6.0\\ref\\ConsoleApp1.dll" */
35
+ 'ReferenceAssembly?': 'string',
36
+ /** @example "c:\\source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\ConsoleApp1.dll" */
37
+ FullPath: 'string',
38
+ /** @example "c:\\" */
39
+ RootDir: 'string',
40
+ /** @example "ConsoleApp1" */
41
+ Filename: 'string',
42
+ /** @example ".dll" */
43
+ Extension: 'string',
44
+ /** @example "c:\\source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\" */
45
+ RelativeDir: 'string',
46
+ /** @example "source\\repos\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0\\" */
47
+ Directory: 'string',
48
+ RecursiveDir: 'string',
49
+ /** @example "2023-11-30 13:38:06.5084339" */
50
+ ModifiedTime: 'string',
51
+ /** @example "2023-11-30 13:38:06.9308716" */
52
+ CreatedTime: 'string',
53
+ /** @example "2023-11-30 13:38:06.9318732" */
54
+ AccessedTime: 'string',
55
+ /** @example "C:\\Program Files\\Microsoft Visual Studio\\2022\\Preview\\MSBuild\\Current\\Bin\\amd64\\Microsoft.Common.CurrentVersion.targets" */
56
+ DefiningProjectFullPath: 'string',
57
+ /** @example "C:\\Program Files\\Microsoft Visual Studio\\2022\\Preview\\MSBuild\\Current\\Bin\\amd64\\" */
58
+ DefiningProjectDirectory: 'string',
59
+ /** @example "Microsoft.Common.CurrentVersion" */
60
+ DefiningProjectName: 'string',
61
+ /** @example ".targets" */
62
+ DefiningProjectExtension: 'string',
63
+ });
64
+
65
+ const targetSuccess = type({
66
+ Result: '\'Success\'',
67
+ Items: interface_ItemMetadataBuiltIn.array(),
68
+ });
69
+
70
+ const targetFailure = type({
71
+ Result: '\'Failure\'',
72
+ Items: 'never[]',
73
+ });
74
+
75
+ const msbuildEvaluationOutput = type({
76
+ 'Properties?': type({ '[string]': 'string' }),
77
+ 'Items?': type({ '[string]': interface_ItemMetadataBuiltIn.array() }),
78
+ 'TargetResults?': type({ '[string]': targetSuccess.or(targetFailure) }),
79
+ });
80
+
81
+ export class MSBuildEvaluationOutput {
82
+ /**
83
+ * @param rawMSBuildEvaluation The output of a CLI MSBuild project evaluation.
84
+ * May be the UTF-8 string-encoded JSON or the object decoded from that JSON.
85
+ */
86
+ constructor(rawMSBuildEvaluation: Parameters<typeof JSON.parse>[0] | Parameters<typeof msbuildEvaluationOutput.from>[0]) {
87
+ /** `.assert` instead of `.from` to allow `unknown` JSON.parse return type */
88
+ const knownObject = msbuildEvaluationOutput.assert(typeof rawMSBuildEvaluation === 'string' ? JSON.parse(rawMSBuildEvaluation) : rawMSBuildEvaluation);
89
+
90
+ this.Properties = knownObject.Properties;
91
+ this.Items = knownObject.Items;
92
+ this.TargetResults = knownObject.TargetResults;
93
+ }
94
+
95
+ /**
96
+ * The specified properties and their values as evaluated by MSBuild Core.
97
+ * `-getProperty:{propertyName,...}`
98
+ */
99
+ Properties?: typeof msbuildEvaluationOutput.infer.Properties;
100
+ /**
101
+ * The specified items and their values and associated metadata as evaluated
102
+ * by MSBuild Core.
103
+ * `-getItem:{itemName,...}`
104
+ */
105
+ Items?: typeof msbuildEvaluationOutput.infer.Items;
106
+ /**
107
+ * The specified Targets and their output values as evaluated by MSBuild
108
+ * Core.
109
+ * `-getTargetResult:{targetName,...}`
110
+ */
111
+ TargetResults?: typeof msbuildEvaluationOutput.infer.TargetResults;
112
+ }
113
+
114
+ export const EvaluationOptions = Object.freeze(
115
+ type({
116
+ /**
117
+ * The project file's full path.
118
+ */
119
+ FullName: 'string',
120
+ /**
121
+ * User-defined Properties and their values.
122
+ * { Configuration: "Release" } will cause the MSBuild to first set the
123
+ * Configuration property to Release before evaluating the project
124
+ * or the project's Target(s).
125
+ * ```txt
126
+ * -property:<n>=<v> Set or override these project-level properties. <n> is
127
+ * the property name, and <v> is the property value. Use a
128
+ * semicolon or a comma to separate multiple properties, or
129
+ * specify each property separately. (Short form: -p)
130
+ * Example:
131
+ * -property:WarningLevel=2;OutDir=bin\Debug\
132
+ * ```
133
+ */
134
+ Property: type({ '[string]': 'string' })
135
+ .as<{ -readonly [P in keyof MSBuildProjectProperties]: MSBuildProjectProperties[P] }>()
136
+ .partial(),
137
+ /**
138
+ * The MSBuild Targets to run for evaluation. ["Pack"] is recommended.
139
+ * Property values may be changed by Targets such as those provided by
140
+ * dependencies.
141
+ *
142
+ * ```txt
143
+ * -target:<targets> Build these targets in this project. Use a semicolon or a
144
+ * comma to separate multiple targets, or specify each
145
+ * target separately. (Short form: -t)
146
+ * Example:
147
+ * -target:Resources;Compile
148
+ * ```
149
+ * @default []
150
+ */
151
+ Targets: type.string.array().readonly().or('string[]'),
152
+ /**
153
+ * MSBuild Items to evaluate. `["Compile"]` will result in the MSBuild output
154
+ * including {@link MSBuild}
155
+ */
156
+ GetItem: type.string.array().readonly().or('string[]'),
157
+ GetProperty: type.string.array().readonly().or('string[]'),
158
+ GetTargetResult: type.string.array().readonly().or('string[]'),
159
+ }),
160
+ );
14
161
 
15
162
  export class MSBuildProject {
16
- Properties: MSBuildProjectProperties;
17
-
18
- /**
19
- *
20
- * @param fullPath The full path of the .NET MSBuild project file.
21
- * @param customProperties MSBuild properties to evaluate in addition to those pre-defined in {@link MSBuildProjectProperties}
22
- */
23
- constructor(fullPath: string, customProperties?: string[]) {
24
- // super();
25
- this.Properties = MSBuildProject.evaluateProperties(fullPath, customProperties ?? []);
26
- }
27
-
28
- /**
29
- *
30
- * `dotnet msbuild src -getProperty:TargetFramework -getProperty:TargetFrameworks -getProperty:RuntimeIdentifiers -getProperty:IsTrimmable`
31
- *
32
- * ...produces...
33
- *
34
- * ```json
35
- * {
36
- * "Properties": {
37
- * "TargetFramework": "net6.0",
38
- * "TargetFrameworks": "",
39
- * "RuntimeIdentifiers": "win7-x64;win7-x86;win-arm64;linux-x64;linux-arm64",
40
- * "IsTrimmable": "true",
41
- * }
42
- * }
43
- * ```
44
- *
45
- * ...which can can be parsed like...
46
- * ```js
47
- * var ridArray = JSON.parse(out).Properties.RuntimeIdentifiers.split(';');
48
- * ```
49
- */
50
- static evaluateProperties(fullPath: string, properties: string[]): MSBuildProjectProperties {
51
- const evaluatedProps: MSBuildProjectProperties = new MSBuildProjectProperties(fullPath);
52
-
53
- // if a default prop isn't in properties, add it
54
- const defaultProps = MSBuildProjectPreDefinedProperties;
55
- for (const defaultProp of defaultProps) {
56
- if (!properties.includes(defaultProp)) properties.push(defaultProp);
57
- }
58
- const getPropArgs: string[] = properties.map((propName) => `-getProperty:${propName}`);
59
- // should return a single value OR string-encoded JSON object with 'Properties' object-type property.
60
- const out = execFileSync('dotnet', ['msbuild', evaluatedProps.FullPath, ...getPropArgs], {
61
- encoding: 'utf8',
62
- stdio: 'pipe',
63
- }).trim();
64
- if (out.startsWith('MSBUILD : error'))
65
- throw new Error(out);
66
-
67
- let props: Record<string, string>;
68
- if (out.startsWith('{')) {
69
- const obj = JSON.parse(out) as object;
70
- if ("Properties" in obj && typeof obj.Properties === 'object' && obj.Properties !== null)
71
- props = obj.Properties as Record<string, string>;
72
- else throw new Error('When evaluating properties with MSBuild, "Properties" could not be found in the deserialized JSON object...\n' + JSON.stringify(obj))
73
- }
74
- else {
75
- props = { [properties[0]]: out.trim() }
76
- }
77
-
78
- return {
79
- ...evaluatedProps,
80
- ...props,
81
- };
82
- }
163
+ /**
164
+ * Properties for multi-targeting `dotnet publish` outputs.
165
+ * These are included in {@link NPPGetterNames.InstanceGettersRecursive}.
166
+ */
167
+ public static readonly MatrixProperties: readonly string[] = Object.freeze([
168
+ 'TargetFramework',
169
+ 'TargetFrameworks',
170
+ 'RuntimeIdentifier',
171
+ 'RuntimeIdentifiers',
172
+ ]);
173
+
174
+ /**
175
+ * Creates an instance of MSBuildProject.
176
+ * @param opts The order-independent arguments for this constructor.
177
+ * Properties may be added or moved around in this definition without
178
+ * breaking compatibility.
179
+ * @param opts.fullPath The full path of the MSBuild project's file. This
180
+ * should have a '.csproj', '.fsproj', or '.vbproj' file extension.
181
+ * @param opts.projTargets A list of MSBuild Targets supported by the project.
182
+ * @param opts.evaluation The output of an MSBuild project evaluation. This
183
+ * comprises MSBuild Properties, Items, and Target results.
184
+ */
185
+ public constructor(opts: {
186
+ fullPath: string;
187
+ projTargets: string[];
188
+ evaluation: MSBuildEvaluationOutput;
189
+ }) {
190
+ this.Items = opts.evaluation.Items ?? {};
191
+ this.Properties = new NugetProjectProperties(
192
+ opts.fullPath,
193
+ new CaseInsensitiveMap<string, string>(
194
+ Object.entries(opts.evaluation.Properties ?? {}),
195
+ ),
196
+ );
197
+ this.Targets = opts.projTargets;
198
+ this.TargetResults
199
+ = opts.evaluation.TargetResults === undefined
200
+ ? []
201
+ : [opts.evaluation.TargetResults];
202
+ }
203
+
204
+ readonly Items: Readonly<Required<MSBuildEvaluationOutput>['Items']>;
205
+ readonly Properties: Readonly<NugetProjectProperties>;
206
+ readonly Targets: readonly string[];
207
+ /**
208
+ * Allows appending subsequent target results.
209
+ */
210
+ readonly TargetResults: Required<MSBuildEvaluationOutput>['TargetResults'][];
211
+
212
+ /**
213
+ * @param projectPath The full path of the project file or its directory. A
214
+ * relative path may be passed, but will resolve relative to the current
215
+ * working directory.
216
+ * @param includeNonPublic Include conventionally internal/private MSBuild
217
+ * targets in the result.
218
+ * @returns A string array of the project's MSBuild targets.
219
+ * @todo consider 'file' of -targets[:file]
220
+ * Prints a list of available targets without executing the
221
+ * actual build process. By default the output is written to
222
+ * the console window. If the path to an output file
223
+ * is provided that will be used instead.
224
+ * (Short form: -ts)
225
+ * Example:
226
+ * -ts:out.txt
227
+ */
228
+ static async GetTargets(
229
+ projectPath: string,
230
+ includeNonPublic = false,
231
+ ): Promise<string[]> {
232
+ return execAsync(`dotnet msbuild ${projectPath} -targets`, true)
233
+ .then((v) => {
234
+ const targets = v.stdout
235
+ .split('\n')
236
+ .filter((v, index) => v !== '' && index !== 0)
237
+ .map(v => v.replace('\r', ''))
238
+ .sort((a, b) => a.localeCompare(b));
239
+ return includeNonPublic
240
+ ? targets
241
+ : targets.filter(v => !v.startsWith('_'));
242
+ });
243
+ }
244
+
245
+ /**
246
+ * Evaluate {@link Items}, {@link Properties}, and {@link TargetResults},
247
+ * returning them as an instance of {@link MSBuildProject}.\
248
+ * Note: MSBuild will probably fail if Restore is skipped and another
249
+ * target is specified. If you choose Pack, you must do ['Restore', 'Pack'].
250
+ * @param options The result of {@link EvaluationOptions.from}.
251
+ * @returns A promised {@link MSBuildProject} instance.
252
+ * @throws if the exec command fails -OR- the JSON parse fails -OR-
253
+ * MSBuildProject's constructor fails.
254
+ * @see {@link PackableProjectsToMSBuildProjects} for most use-cases.
255
+ */
256
+ public static async Evaluate(
257
+ options: typeof EvaluationOptions.inferOut,
258
+ ): Promise<MSBuildProject> {
259
+ if (
260
+ options.GetProperty.length === 0
261
+ && options.GetItem.length === 0
262
+ && options.GetTargetResult.length === 0
263
+ ) {
264
+ throw new Error(
265
+ 'No MSBuild Property, Item, or TargetResult queries were provided.',
266
+ );
267
+ }
268
+ // reminder: args containing spaces and semi-colons MUST be quote-enclosed!
269
+ options.FullName = MSBuildProjectProperties.GetFullPath(options.FullName);
270
+ const _pairs = Object.entries(options.Property).filter(p => typeof p[1] === 'string');
271
+ const property
272
+ = _pairs.length === 0
273
+ ? ''
274
+ : `-p:"${_pairs.map(pair => pair[0] + '=' + pair[1]).join(';')}"`;
275
+ const target
276
+ = options.Targets.length === 0
277
+ ? ''
278
+ : `"-t:${options.Targets.join(';')}"`;
279
+ const getItem
280
+ = options.GetItem.length === 0
281
+ ? ''
282
+ : `-getItem:"${options.GetItem.join(',')}"`;
283
+ const getProperty
284
+ = options.GetProperty.length === 0
285
+ ? ''
286
+ : `-getProperty:"${options.GetProperty.join(',')}"`;
287
+ const getTargetResult
288
+ = options.GetTargetResult.length === 0
289
+ ? ''
290
+ : `-getTargetResult:"${options.GetTargetResult.join(',')}"`;
291
+ const cmdLine = [
292
+ 'dotnet',
293
+ 'msbuild',
294
+ `"${options.FullName}"`,
295
+ '-restore',
296
+ property,
297
+ target,
298
+ getItem,
299
+ getProperty,
300
+ getTargetResult,
301
+ ]
302
+ .filter(v => v !== '')
303
+ .join(' ');
304
+ let stdio: Awaited<ReturnType<typeof execAsync>> | undefined = undefined;
305
+ // may throw
306
+ while (stdio === undefined) {
307
+ stdio = await setTimeout(
308
+ 1000,
309
+ execAsync(cmdLine, true),
310
+ )
311
+ .then(async p => await p)
312
+ .catch<undefined>(catchCsc2012);
313
+ }
314
+
315
+ // todo: consider -getResultOutputFile:file
316
+ // Redirect output from get* into a file.
317
+ //
318
+ // Example:
319
+ // -getProperty:Bar -getResultOutputFile:Biz.txt
320
+ // This writes the value of property Bar into Biz.txt.
321
+
322
+ /**
323
+ * The following issues have triggered this code path:
324
+ * - BaseIntermediateOutputPath must use Unix path separators ('/') on all
325
+ * platforms. Even Windows. Otherwise, MSBuild/dotnet will error-exit with
326
+ * "The BaseIntermediateOutputPath must end with a trailing slash".
327
+ */
328
+ if (stdio.stdout.startsWith('MSBuild version')) {
329
+ warn(stdio.stdout);
330
+ throw new Error(
331
+ 'dotnet msbuild was expected to output JSON, but output its version header instead.',
332
+ );
333
+ }
334
+
335
+ let rawOutput = undefined;
336
+ if (stdio.stdout.startsWith('{')) {
337
+ /** stdout is JSON string */
338
+ rawOutput = stdio.stdout;
339
+ }
340
+ else if (options.GetProperty.length > 0 && options.GetProperty[0] !== undefined) {
341
+ rawOutput = {
342
+ Properties: {
343
+ [options.GetProperty[0]]: String(JSON.parse(stdio.stdout)),
344
+ },
345
+ };
346
+ }
347
+ else {
348
+ throw new Error('Dotnet/MSBuild evaluation output is not a string nor JSON object or array.');
349
+ }
350
+
351
+ const evaluation = new MSBuildEvaluationOutput(rawOutput);
352
+
353
+ return new MSBuildProject({
354
+ fullPath: options.FullName,
355
+ projTargets: await MSBuildProject.GetTargets(options.FullName),
356
+ evaluation,
357
+ });
358
+ }
359
+
360
+ /**
361
+ * Evaluate multiple project paths with some default Evaluate options.
362
+ * @async
363
+ * @param projectsToPackAndPush An array of MSBuild projects' full file
364
+ * paths. If a path is a directory, files in that directory are filtered for
365
+ * `.csproj`, `.fsproj`, and `.vbproj` project files.
366
+ * See https://github.com/dotnet/sdk/blob/497f334b2862bdf98b30c00ede2fd259ea5f624d/src/Cli/dotnet/Commands/New/MSBuildEvaluation/MSBuildEvaluationResult.cs#L19-L32.\
367
+ * @returns A promised array of {@link MSBuildProject} instances.
368
+ * All known MSBuild and NuGet properties are evaluated.
369
+ * If applicable, a project's "Pack" target is evaluated.
370
+ */
371
+ public static async PackableProjectsToMSBuildProjects(
372
+ projectsToPackAndPush: string[],
373
+ ): Promise<Promise<MSBuildProject>[]> {
374
+ const dirEntriesPromise = toDirEntries(typeof projectsToPackAndPush === 'string' ? [projectsToPackAndPush] : projectsToPackAndPush);
375
+ const projectPromises: Promise<MSBuildProject>[] = await dirEntriesPromise
376
+ .then(
377
+ (direntArray: Dirent[]) =>
378
+ direntArray.map(element => convertDirentToMSBuildProject(element)),
379
+ );
380
+ return projectPromises;
381
+
382
+ /**
383
+ * Map an array of filesystem paths to {@link Dirent} instances representing project files.
384
+ * @param projectsToPackAndPush An array of MSBuild projects' full file
385
+ * paths. If a path is a directory, files in that directory are filtered for
386
+ * `.csproj`, `.fsproj`, and `.vbproj` project files. See
387
+ * https://github.com/dotnet/sdk/blob/497f334b2862bdf98b30c00ede2fd259ea5f624d/src/Cli/dotnet/Commands/New/MSBuildEvaluation/MSBuildEvaluationResult.cs#L19-L32.\
388
+ * @returns An promised array of Dirent instances for discovered project files.
389
+ */
390
+ async function toDirEntries(
391
+ projectsToPackAndPush: string[],
392
+ ): Promise<Dirent[]> {
393
+ const dirEntries: (Dirent | Dirent[])[] = await Promise.all(
394
+ projectsToPackAndPush.map(async (proj) => {
395
+ proj = await realpath(makeAbsolute(proj));
396
+ const stats = await stat(proj);
397
+ let entries: Dirent[];
398
+
399
+ if (stats.isFile()) {
400
+ entries = await readdir(path.dirname(proj), { withFileTypes: true });
401
+ const dirent: Dirent | undefined = entries.find(v =>
402
+ path.join(
403
+ // condition required for compatibility. `.path` was deprecated, but `.parentPath` is not available in our node minversion
404
+ v.path as string | undefined ?? (v as unknown as Omit<typeof v, 'path'> & { parentPath: string }).parentPath,
405
+ v.name,
406
+ ) === proj,
407
+ );
408
+ if (dirent)
409
+ return dirent;
410
+ else
411
+ throw new Error(
412
+ `file "${proj}" not found. It may have been moved or deleted.`,
413
+ );
414
+ }
415
+ if (!stats.isDirectory())
416
+ throw new Error(`"${proj}" is not a file or directory`);
417
+
418
+ entries = await readdir(proj, { withFileTypes: true });
419
+ return entries.filter(v =>
420
+ v.isFile()
421
+ && (v.name.endsWith('.csproj') || v.name.endsWith('.fsproj') || v.name.endsWith('.vbproj')),
422
+ );
423
+ }),
424
+ );
425
+
426
+ return dirEntries.flat();
427
+ }
428
+
429
+ /**
430
+ * Map a {@link Dirent} instance to an {@link MSBuildProject} instance.
431
+ * @param dirent A {@link Dirent} instance. This instance should be an MSBuild project file.
432
+ * @returns An instance of {@link MSBuildProject} evaluated with the `Pack` target result, if applicable. Evaluated properties will be those whose names are returned by {@link NPPGetterNames.InstanceGettersRecursive}.
433
+ */
434
+ async function convertDirentToMSBuildProject(dirent: Dirent): Promise<MSBuildProject> {
435
+ const fullPath = path.join(
436
+ // condition required for compatibility. `.path` was deprecated, but `.parentPath` is not available in our node minversion
437
+ dirent.path as string | undefined ?? (dirent as unknown as Omit<typeof dirent, 'path'> & { parentPath: string }).parentPath,
438
+ dirent.name,
439
+ );
440
+ const projTargets: Promise<string[]> = MSBuildProject.GetTargets(fullPath);
441
+ const evalTargets = await projTargets.then(v =>
442
+ v.includes('Pack') ? ['Pack'] : [],
443
+ );
444
+ // this might be too long for a command line. What was it on Windows?
445
+ // 2^15 (32,768) character limit for command lines?
446
+ const getProperties = NPPGetterNames.InstanceGettersRecursive;
447
+
448
+ return await MSBuildProject.Evaluate(
449
+ EvaluationOptions.from({
450
+ FullName: fullPath,
451
+ GetItem: [],
452
+ GetProperty: getProperties,
453
+ GetTargetResult: [],
454
+ Property: {},
455
+ Targets: evalTargets,
456
+ }),
457
+ );
458
+ }
459
+ }
460
+
461
+ public static fromJSON(json: string): MSBuildProject {
462
+ const parsed = T_PseudoMSBPInstance.assert(JSON.parse(json));
463
+
464
+ type.true.assert(
465
+ Reflect.setPrototypeOf(parsed, MSBuildProject.prototype),
466
+ );
467
+ type.true.assert(
468
+ Reflect.setPrototypeOf(parsed.Properties, NugetProjectProperties.prototype),
469
+ );
470
+ parsed.Properties = T_NPP.assert(parsed.Properties);
471
+ return T_MSBuildProject.assert(parsed);
472
+ }
473
+ }
474
+
475
+ const T_MSBuildProject = type.instanceOf(MSBuildProject);
476
+ const T_NPP = type.instanceOf(NugetProjectProperties);
477
+ const T_PseudoMSBPInstance = type({
478
+ Items: type({
479
+ '[string]': type({
480
+ '[string]': 'string',
481
+ Identity: 'string',
482
+ FullPath: 'string',
483
+ RootDir: 'string',
484
+ Filename: 'string',
485
+ Extension: 'string',
486
+ RelativeDir: 'string',
487
+ Directory: 'string',
488
+ RecursiveDir: 'string',
489
+ ModifiedTime: 'string',
490
+ CreatedTime: 'string',
491
+ AccessedTime: 'string',
492
+ DefiningProjectFullPath: 'string',
493
+ DefiningProjectDirectory: 'string',
494
+ DefiningProjectName: 'string',
495
+ DefiningProjectExtension: 'string',
496
+ 'SubType?': ' string | undefined',
497
+ 'TargetFrameworkIdentifier?': 'string | undefined',
498
+ 'TargetPlatformMoniker?': 'string | undefined',
499
+ 'CopyUpToDateMarker?': 'string | undefined',
500
+ 'TargetPlatformIdentifier?': 'string | undefined',
501
+ 'TargetFrameworkVersion?': 'string | undefined',
502
+ 'ReferenceAssembly?': 'string | undefined',
503
+ }).array(),
504
+ }),
505
+ Properties: type.Record('string', 'string').or(T_NPP),
506
+ Targets: type.string.array(),
507
+ TargetResults: msbuildEvaluationOutput.get('TargetResults').exclude('undefined').array(),
508
+
509
+ });
510
+
511
+ /** ArkType type definitions for internal usage, but may be re-used elsewhere */
512
+ export const _InternalMSBuildEvaluationTypes = type.scope({
513
+ msbuildEvaluationOutput,
514
+ });
515
+
516
+ /**
517
+ * Resolve a path if it is not already absolute.
518
+ * @param _path A filesystem path.
519
+ * @returns A full path to a filesystem entry. The path is unchecked for whether or not the path (or its parts) exist.
520
+ */
521
+ function makeAbsolute(_path: string) {
522
+ return path.isAbsolute(_path) ? _path : path.resolve(_path);
523
+ }
524
+
525
+ /**
526
+ * Use this in your catch statement or .catch call to return `undefined` when
527
+ * MSBuild error CSC2012 (e.g. "file in use by another process") is reported.
528
+ * @param error Probably an Error object
529
+ * @returns `undefined` if CSC2012 (file in use by another process) occurs
530
+ */
531
+ export function catchCsc2012(error: unknown): undefined {
532
+ if (isNativeError(error)) {
533
+ // check for error reported when "file in use by another process" i.e. EBUSY
534
+ // (UNIX), NTSTATUS.ERROR_SHARING_VIOLATION == 0x20 == 32 (Windows)
535
+ if ('stderr' in error && typeof error.stderr === 'string'
536
+ && /^CSC ?:.+CS2012:/gm.test(
537
+ // '\uFF1A'.normalize('NFKC') === ':' === true;
538
+ error.stderr.normalize('NFKC'),
539
+ )
540
+ ) {
541
+ return undefined; /* retry */
542
+ }
543
+ /**
544
+ * some known warnings/errors:
545
+ * - warning MSB3073:
546
+ * The command "dotnet tool list kuinox.nupkgdeterministicator"
547
+ * exited with code 145.
548
+ * > $ dotnet tool list kuinox.nupkgdeterministicator
549
+ * > The command could not be loaded, possibly because:
550
+ * > * You intended to execute a .NET application:
551
+ * > The application 'tool' does not exist.
552
+ * > * You intended to execute a .NET SDK command:
553
+ * > No .NET SDKs were found.
554
+ * >
555
+ * > Download a .NET SDK:
556
+ * > https://aka.ms/dotnet/download
557
+ * >
558
+ * > Learn about SDK resolution:
559
+ * > https://aka.ms/dotnet/sdk-not-found
560
+ */
561
+ else throw error;
562
+ }
563
+ else throw new Error('unknown error', { cause: error });
83
564
  }