diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
new file mode 100644
index 0000000..6523eec
--- /dev/null
+++ b/.config/dotnet-tools.json
@@ -0,0 +1,10 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {
+ "tcli": {
+ "version": "0.2.4",
+ "commands": ["tcli"]
+ }
+ }
+}
diff --git a/.gitignore b/.gitignore
index b236c3f..fcbb774 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,10 @@ build/
/*/package/patchers/
/*/package/plugins/
+# Local credentials
+.env
+.env.*
+
# Agent files
/.omo/
/.worktrees/
diff --git a/Publish-Mod.ps1 b/Publish-Mod.ps1
new file mode 100644
index 0000000..1e19755
--- /dev/null
+++ b/Publish-Mod.ps1
@@ -0,0 +1,386 @@
+#requires -Version 5.1
+<#
+.SYNOPSIS
+Builds and publishes one mod to the Dyson Sphere Program Thunderstore community.
+.PARAMETER EnvFile
+Optional token file. Defaults to .env in the caller's current directory when present,
+otherwise TCLI_AUTH_TOKEN is read from the process environment.
+.EXAMPLE
+.\Publish-Mod.ps1 -Project UXAssist -Namespace soarqin -DryRun
+.EXAMPLE
+.\Publish-Mod.ps1 -Project Dustbin -Namespace soarqin -EnvFile C:\Secrets\thunderstore.env
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory = $true)]
+ [ValidatePattern('^[A-Za-z0-9_][A-Za-z0-9_.-]*\z')]
+ [string]$Project,
+
+ [Parameter(Mandatory = $true)]
+ [ValidatePattern('^[A-Za-z0-9_]+\z')]
+ [string]$Namespace,
+
+ [string]$EnvFile,
+ [switch]$DryRun
+)
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = 'Stop'
+
+function Invoke-PublishDotNet {
+ param([string[]]$Arguments, [switch]$Capture, [string]$Secret)
+
+ $previousOutputEncoding = [Console]::OutputEncoding
+ try {
+ # Localized .NET SDK output is UTF-8. PowerShell decodes native output
+ # with Console.OutputEncoding, which can still be a legacy code page.
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
+
+ # Windows PowerShell turns native stderr into error records. Check the exit
+ # code ourselves and redact credentials before forwarding any tcli output.
+ $ErrorActionPreference = 'Continue'
+ $lines = New-Object 'System.Collections.Generic.List[string]'
+ & dotnet @Arguments 2>&1 | ForEach-Object {
+ $line = $_.ToString()
+ if (-not [string]::IsNullOrEmpty($Secret)) { $line = $line.Replace($Secret, '[REDACTED]') }
+ if ($Capture) { $lines.Add($line) } else { Write-Host $line }
+ }
+ $commandExit = $LASTEXITCODE
+ if ($commandExit -ne 0) {
+ if ($Capture) { foreach ($line in $lines) { Write-Host $line } }
+ throw "dotnet $($Arguments[0]) failed (exit $commandExit). No further publishing steps were run."
+ }
+ if ($Capture) { return ($lines -join [Environment]::NewLine) }
+ } finally { [Console]::OutputEncoding = $previousOutputEncoding }
+}
+
+function Get-PublishJsonProperty {
+ param($Object, [string]$Name)
+ if ($null -ne $Object) {
+ $property = $Object.PSObject.Properties[$Name]
+ if ($null -ne $property) { return $property.Value }
+ }
+ return $null
+}
+
+function Read-PublishJson {
+ param([string]$Path)
+ try { return ([IO.File]::ReadAllText($Path) | ConvertFrom-Json -ErrorAction Stop) }
+ catch { throw "Cannot read JSON from '$Path'. Check that it is a valid JSON object." }
+}
+
+function Get-PublishProject {
+ param([string]$Path)
+ $query = Invoke-PublishDotNet -Capture -Arguments @(
+ 'msbuild', $Path, '-nologo', '-verbosity:quiet', '-property:Configuration=Release',
+ '-getProperty:Version,ProjectName,TargetPath,PackHasChangelog,PackUsePluginsLayout,PackPreloaderTargetDir,ProjectAssetsFile',
+ '-getItem:ProjectReference'
+ )
+ try { $result = $query | ConvertFrom-Json -ErrorAction Stop }
+ catch { throw "Cannot evaluate '$Path'. MSBuild 17.8 or newer is required; check 'dotnet msbuild -version'." }
+ if ($null -eq (Get-PublishJsonProperty $result 'Properties')) { throw "MSBuild returned no properties for '$Path'." }
+ return $result
+}
+
+function Test-PublishPathWithin {
+ param([string]$Path, [string]$Directory)
+ $fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\', '/')
+ $fullDirectory = [IO.Path]::GetFullPath($Directory).TrimEnd('\', '/')
+ return ($fullPath.Equals($fullDirectory, [StringComparison]::OrdinalIgnoreCase) -or
+ $fullPath.StartsWith($fullDirectory + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase))
+}
+
+function Get-PublishPhysicalPath {
+ param([string]$Path)
+ # Resolve parent junctions as well as file symlinks on .NET Framework 4.x.
+ if (-not ('DSPModPublish.PhysicalPath' -as [type])) {
+ Add-Type -TypeDefinition @'
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+namespace DSPModPublish {
+ public static class PhysicalPath {
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string name, uint access, uint share,
+ IntPtr security, uint disposition, uint flags, IntPtr template);
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetFinalPathNameByHandle(SafeFileHandle file,
+ StringBuilder path, uint length, uint flags);
+ public static string Resolve(string path) {
+ using (var handle = CreateFile(path, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) {
+ if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var buffer = new StringBuilder(32768);
+ var length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
+ if (length == 0 || length >= buffer.Capacity)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ var result = buffer.ToString();
+ if (result.StartsWith(@"\\?\UNC\")) return @"\\" + result.Substring(8);
+ return result.StartsWith(@"\\?\") ? result.Substring(4) : result;
+ }
+ }
+ }
+}
+'@
+ }
+ return [DSPModPublish.PhysicalPath]::Resolve([IO.Path]::GetFullPath($Path))
+}
+
+function Get-PublishToken {
+ param([string]$EnvironmentFile)
+ if ([string]::IsNullOrWhiteSpace($EnvironmentFile)) {
+ $defaultFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.env')
+ if ([IO.File]::Exists($defaultFile)) { $EnvironmentFile = $defaultFile }
+ }
+ if (-not [string]::IsNullOrWhiteSpace($EnvironmentFile)) {
+ $filePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($EnvironmentFile)
+ if (-not [IO.File]::Exists($filePath)) { throw 'The environment file does not exist. Supply a UTF-8 file with TCLI_AUTH_TOKEN.' }
+ $token = $null
+ foreach ($line in [IO.File]::ReadAllLines($filePath, [Text.UTF8Encoding]::new($false, $true))) {
+ if ($line -match '^\s*(#.*)?$') { continue }
+ if ($line -notmatch '^\s*TCLI_AUTH_TOKEN\s*=\s*(.*?)\s*$' -or $null -ne $token) {
+ throw 'Invalid environment file. Use one TCLI_AUTH_TOKEN assignment, optional blank lines, and full-line comments.'
+ }
+ $token = $Matches[1]
+ if ($token.StartsWith('"') -or $token.StartsWith("'")) {
+ if ($token.Length -lt 2 -or $token[0] -ne $token[$token.Length - 1]) { throw 'The token has unmatched quotes in the environment file.' }
+ $token = $token.Substring(1, $token.Length - 2)
+ }
+ }
+ } else {
+ $token = [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')
+ }
+ if ([string]::IsNullOrWhiteSpace($token) -or $token -match '\s') {
+ throw 'Set a non-empty TCLI_AUTH_TOKEN without whitespace, create .env in the current directory, or supply -EnvFile.'
+ }
+ # tcli 0.2.4 reads the persisted Windows User value before the process value.
+ $userToken = Get-PublishUserToken
+ if (-not [string]::IsNullOrWhiteSpace($userToken) -and $userToken -cne $token) {
+ throw 'A different User-scoped TCLI_AUTH_TOKEN overrides the selected token in tcli. Remove or reconcile that setting before retrying.'
+ }
+ return $token
+}
+
+function Get-PublishUserToken {
+ return [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'User')
+}
+
+function Assert-PublishChangelog {
+ param([string]$Text, [string]$Version)
+ $sections = @([regex]::Matches($Text, '(?is)]*>(.*?) ') | ForEach-Object { $_.Groups[1].Value })
+ if ($sections.Count -eq 0) { $sections = @($Text) }
+ foreach ($section in $sections) {
+ $latest = [regex]::Match($section, '(?m)^\s*(?:[*-]\s+|#{1,6}\s+)(\d+\.\d+\.\d+)(?=\s|$)')
+ if (-not $latest.Success -or $latest.Groups[1].Value -cne $Version) {
+ throw "The latest changelog entry in every language must match project version $Version. Update the release notes before publishing."
+ }
+ }
+}
+
+function Get-PublishStreamHash {
+ param([IO.Stream]$Stream)
+ $hash = [Security.Cryptography.SHA256]::Create()
+ try { return [BitConverter]::ToString($hash.ComputeHash($Stream)) }
+ finally { $hash.Dispose() }
+}
+
+function Assert-PublishArchive {
+ param([string]$ZipPath, [string]$PackageName, [string]$Version, [hashtable]$Files, [bool]$HasChangelog)
+ Add-Type -AssemblyName System.IO.Compression.FileSystem
+ Add-Type -AssemblyName System.Drawing
+ $archive = [IO.Compression.ZipFile]::OpenRead($ZipPath)
+ try {
+ $entries = @{}
+ foreach ($entry in $archive.Entries) {
+ $entryName = $entry.FullName.Replace('\', '/')
+ if ($entryName -match '(^/|:|(^|/)\.\.(/|$))' -or $entries.ContainsKey($entryName)) {
+ throw 'The ZIP contains an unsafe path or duplicate entry. Rebuild the package.'
+ }
+ if ($entryName -match '(^|/)(\.env(?:\..*)?|thunderstore\.toml)$') { throw 'The ZIP contains a local publishing or credential file.' }
+ $entries[$entryName] = $entry
+ }
+ foreach ($entryName in $Files.Keys) {
+ if (-not $entries.ContainsKey($entryName) -or $entries[$entryName].FullName -cne $entryName) {
+ throw "The ZIP is missing the expected file '$entryName'. Rebuild the package."
+ }
+ $zipStream = $entries[$entryName].Open()
+ $fileStream = [IO.File]::OpenRead($Files[$entryName])
+ try {
+ if ((Get-PublishStreamHash $zipStream) -cne (Get-PublishStreamHash $fileStream)) {
+ throw "The ZIP file '$entryName' differs from its current source or build output. Rebuild the package."
+ }
+ } finally { $zipStream.Dispose(); $fileStream.Dispose() }
+ }
+ $reader = [IO.StreamReader]::new($entries['manifest.json'].Open(), [Text.Encoding]::UTF8, $true)
+ try { $manifest = $reader.ReadToEnd() | ConvertFrom-Json -ErrorAction Stop } finally { $reader.Dispose() }
+ if ((Get-PublishJsonProperty $manifest 'name') -cne $PackageName -or
+ (Get-PublishJsonProperty $manifest 'version_number') -cne $Version) {
+ throw 'The ZIP manifest does not match the selected package name and project version.'
+ }
+ $iconStream = $entries['icon.png'].Open()
+ try {
+ $icon = [Drawing.Image]::FromStream($iconStream)
+ try {
+ if ($icon.RawFormat.Guid -ne [Drawing.Imaging.ImageFormat]::Png.Guid -or $icon.Width -ne 256 -or $icon.Height -ne 256) {
+ throw 'The package icon must be a 256x256 PNG.'
+ }
+ } finally { $icon.Dispose() }
+ } finally { $iconStream.Dispose() }
+ if ($HasChangelog) {
+ $reader = [IO.StreamReader]::new($entries['CHANGELOG.md'].Open(), [Text.Encoding]::UTF8, $true)
+ try { Assert-PublishChangelog $reader.ReadToEnd() $Version } finally { $reader.Dispose() }
+ }
+ } finally { $archive.Dispose() }
+}
+
+function Assert-PublishVersionAvailable {
+ param([string]$Namespace, [string]$PackageName, [string]$Version)
+ $endpoint = "https://thunderstore.io/api/experimental/package/$Namespace/$PackageName/$Version/"
+ try {
+ $response = Invoke-RestMethod -Uri $endpoint -Method Get -TimeoutSec 30 -ErrorAction Stop
+ } catch {
+ $httpResponse = Get-PublishJsonProperty $_.Exception 'Response'
+ $status = Get-PublishJsonProperty $httpResponse 'StatusCode'
+ if ($null -ne $status -and [int]$status -eq 404) { return }
+ throw "Cannot check the remote version at $endpoint. Check connectivity and the server response before retrying; nothing was uploaded."
+ }
+ if ((Get-PublishJsonProperty $response 'namespace') -cne $Namespace -or
+ (Get-PublishJsonProperty $response 'name') -cne $PackageName -or
+ (Get-PublishJsonProperty $response 'version_number') -cne $Version) {
+ throw 'The package-version endpoint returned an unexpected response. Nothing was uploaded.'
+ }
+ throw "Version $Namespace-$PackageName-$Version already exists. Select an unpublished project version; this script does not bump versions."
+}
+
+function Invoke-ModPublish {
+ param([string]$RepositoryRoot, [string]$Project, [string]$Namespace, [string]$EnvFile, [switch]$DryRun)
+ if ($Project -notmatch '^[A-Za-z0-9_][A-Za-z0-9_.-]*\z' -or $Namespace -notmatch '^[A-Za-z0-9_]+\z') {
+ throw 'Supply one top-level -Project directory name and a non-empty alphanumeric/underscore -Namespace.'
+ }
+ $projectDir = Join-Path $RepositoryRoot $Project
+ $projectPath = Join-Path $projectDir "$Project.csproj"
+ $packageDir = Join-Path $projectDir 'package'
+ foreach ($required in @($projectPath, (Join-Path $packageDir 'manifest.json'), (Join-Path $packageDir 'icon.png'), (Join-Path $projectDir 'README.md'))) {
+ if (-not [IO.File]::Exists($required)) {
+ if ($Project.EndsWith('Preloader', [StringComparison]::OrdinalIgnoreCase)) {
+ throw "Select the main mod with -Project $($Project.Substring(0, $Project.Length - 9)); preloaders are bundled, not published separately."
+ }
+ throw "Required project/package file not found: $required. Select a packaged main mod, not a helper project."
+ }
+ }
+ $manifestPath = Join-Path $packageDir 'manifest.json'
+ $packageName = Get-PublishJsonProperty (Read-PublishJson $manifestPath) 'name'
+ if ($packageName -isnot [string] -or $packageName -notmatch '^[A-Za-z0-9_]+\z') { throw 'The manifest must have a valid, non-empty string name.' }
+ $token = $null
+ # Resolve token files before changing to the repository's build directory.
+ if (-not $DryRun) { $token = Get-PublishToken $EnvFile }
+ $oldToken = [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')
+ $configDir = $null
+ $configPath = $null
+ $configBase = Join-Path $projectDir 'obj\thunderstore-publish'
+ Push-Location -LiteralPath $RepositoryRoot
+ try {
+ $null = Get-Command dotnet -CommandType Application -ErrorAction Stop
+ if (-not $DryRun) {
+ try { Invoke-PublishDotNet -Arguments @('tool', 'run', 'tcli', '--', '--version') }
+ catch { throw 'The pinned tcli tool cannot run. Run dotnet tool restore in the repository root and check its required .NET runtime.' }
+ }
+ $metadata = Get-PublishProject $projectPath
+ $properties = $metadata.Properties
+ if (-not [string]::IsNullOrEmpty($properties.PackPreloaderTargetDir)) { throw 'Select a main mod; this project is a preloader or helper.' }
+ $version = $properties.Version
+ if ($version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+\z') { throw 'The evaluated project Version must have the Thunderstore format major.minor.patch.' }
+ $bundled = @()
+ $needsRestore = -not [IO.File]::Exists($properties.ProjectAssetsFile)
+ foreach ($reference in @($metadata.Items.ProjectReference)) {
+ $referenceMetadata = Get-PublishProject $reference.FullPath
+ $referenceProperties = $referenceMetadata.Properties
+ if (-not [IO.File]::Exists($referenceProperties.ProjectAssetsFile)) { $needsRestore = $true }
+ if ([string]::IsNullOrEmpty($referenceProperties.PackPreloaderTargetDir)) { continue }
+ $targetDir = $referenceProperties.PackPreloaderTargetDir
+ if (-not [IO.Path]::IsPathRooted($targetDir)) { $targetDir = Join-Path ([IO.Path]::GetDirectoryName($reference.FullPath)) $targetDir }
+ $targetDir = [IO.Path]::GetFullPath($targetDir)
+ if (Test-PublishPathWithin $targetDir $packageDir) {
+ $bundled += [pscustomobject]@{ Path = $reference.FullPath; TargetDir = $targetDir; Output = $referenceProperties.TargetPath }
+ }
+ }
+ if ($needsRestore) { Invoke-PublishDotNet -Arguments @('restore', $projectPath) }
+ foreach ($preloader in $bundled) {
+ Invoke-PublishDotNet -Arguments @('build', $preloader.Path, '-t:CopyToParentPackage', '-c', 'Release', '--no-restore')
+ }
+ Invoke-PublishDotNet -Arguments @('build', $projectPath, '-t:ZipMod', '-c', 'Release', '--no-restore')
+ $zipPath = Join-Path $packageDir "$($properties.ProjectName)-$version.zip"
+ if (-not [IO.File]::Exists($zipPath)) { throw "The build did not produce the expected ZIP: $zipPath" }
+ $files = @{
+ 'manifest.json' = $manifestPath
+ 'icon.png' = Join-Path $packageDir 'icon.png'
+ 'README.md' = Join-Path $projectDir 'README.md'
+ }
+ $dllName = [IO.Path]::GetFileName($properties.TargetPath)
+ $hasChangelog = $properties.PackHasChangelog -eq 'true'
+ if ($properties.PackUsePluginsLayout -eq 'true') { $files["plugins/$dllName"] = $properties.TargetPath }
+ else { $files[$dllName] = $properties.TargetPath }
+ foreach ($preloader in $bundled) {
+ $relativeDir = $preloader.TargetDir.Substring($packageDir.Length).TrimStart('\', '/').Replace('\', '/')
+ $entryName = ($relativeDir + '/' + [IO.Path]::GetFileName($preloader.Output)).TrimStart('/')
+ $files[$entryName] = $preloader.Output
+ }
+ if ($hasChangelog) { $files['CHANGELOG.md'] = Join-Path $projectDir 'CHANGELOG.md' }
+ Assert-PublishArchive $zipPath $packageName $version $files $hasChangelog
+
+ $configDir = Join-Path $configBase ([Guid]::NewGuid().ToString('N'))
+ $null = [IO.Directory]::CreateDirectory($configDir)
+ $configPath = Join-Path $configDir 'thunderstore.toml'
+ $configText = @"
+[config]
+schemaVersion = "0.0.1"
+
+[package]
+namespace = "$Namespace"
+name = "$packageName"
+versionNumber = "$version"
+
+[build]
+outdir = "."
+
+[publish]
+repository = "https://thunderstore.io"
+communities = ["dyson-sphere-program"]
+categories = []
+"@
+ [IO.File]::WriteAllText($configPath, $configText + [Environment]::NewLine, [Text.UTF8Encoding]::new($false))
+ Write-Host "Project: $Project | Team: $Namespace | Package: $packageName | Version: $version"
+ Write-Host 'Community: dyson-sphere-program | Categories: empty (retain existing listing categories)'
+ Write-Host "ZIP: $zipPath"
+ Write-Host ('dotnet tool run tcli -- publish --config-path "{0}" --file "{1}"' -f $configPath, $zipPath)
+ if ($DryRun) { Write-Host 'Dry run complete. Package validated; no upload was attempted.'; return }
+
+ Assert-PublishVersionAvailable $Namespace $packageName $version
+ [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $token, 'Process')
+ try { Invoke-PublishDotNet -Arguments @('tool', 'run', 'tcli', '--', 'publish', '--config-path', $configPath, '--file', $zipPath) -Secret $token }
+ catch { throw "Publication did not finish successfully. Inspect https://thunderstore.io/c/dyson-sphere-program/p/$Namespace/$packageName/v/$version/ before retrying; a submission may already have succeeded." }
+ Write-Host "Published: https://thunderstore.io/c/dyson-sphere-program/p/$Namespace/$packageName/"
+ } finally {
+ # PowerShell converts $null to an empty string for this .NET call.
+ # Modern runtimes preserve empty environment values; use a true null.
+ if ($null -eq $oldToken) { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', [NullString]::Value, 'Process') }
+ else { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $oldToken, 'Process') }
+ Pop-Location
+ if ($null -ne $configDir -and (Test-PublishPathWithin $configDir $configBase) -and
+ [IO.Directory]::Exists($configDir) -and
+ (Test-PublishPathWithin (Get-PublishPhysicalPath $configDir) (Get-PublishPhysicalPath $configBase))) {
+ try {
+ if ([IO.File]::Exists($configPath)) { [IO.File]::Delete($configPath) }
+ [IO.Directory]::Delete($configDir, $false)
+ } catch { Write-Warning "Could not remove generated configuration directory: $configDir. Remove it when no longer needed." }
+ }
+ }
+}
+
+try {
+ Invoke-ModPublish -RepositoryRoot $PSScriptRoot -Project $Project -Namespace $Namespace -EnvFile $EnvFile -DryRun:$DryRun
+} catch {
+ Write-Error -Message $_.Exception.Message -ErrorAction Continue
+ exit 1
+}
diff --git a/README.md b/README.md
index ad99678..90f68d1 100644
--- a/README.md
+++ b/README.md
@@ -68,3 +68,55 @@ Some functions and patches for better user experience
## [LiveStreamAssist](LiveStreamAssist)
Keeps the statistics window active for live streams by switching between the Production Statistics and Dyson Sphere tabs every 15 to 30 seconds.
+
+## Publishing to Thunderstore
+
+Use Windows PowerShell 5.1 or PowerShell 7, a .NET SDK with MSBuild 17.8 or newer, and the repository's normal game references and build prerequisites. Restore the pinned local tcli tool once from the repository root:
+
+```powershell
+dotnet tool restore
+```
+
+Select a single main mod with `-Project` and supply its Thunderstore Team with the required `-Namespace` parameter. Package Name comes from `/package/manifest.json`; version comes from the project file. Preview the build and package without a token or upload:
+
+```powershell
+.\Publish-Mod.ps1 -Project UXAssist -Namespace soarqin -DryRun
+```
+
+To publish, put a Team service-account token in a UTF-8 `.env` file in the directory where the command is invoked, then run the same command without `-DryRun`. If `.env` is absent, the script reads the process environment variable `TCLI_AUTH_TOKEN`. To select another file, pass `-EnvFile`:
+
+```powershell
+.\Publish-Mod.ps1 -Project Dustbin -Namespace soarqin -EnvFile "$env:USERPROFILE\.config\DSP_Mods\thunderstore.env"
+```
+
+The file accepts one `TCLI_AUTH_TOKEN=...` assignment, optional quotes, blank lines, and full-line comments. Token selection follows this order: explicit `-EnvFile`, the caller directory's `.env`, then the process variable. A selected file with an invalid or missing token is an error. `.env` and `.env.*` are ignored by Git; keep real tokens out of version control and shell command history. tcli 0.2.4 prioritizes a persisted Windows User-scoped token over the process token; if the values conflict, the script stops so that the stale setting can be reconciled.
+
+The script always uses Release builds and the existing `ZipMod` target. It refreshes bundled preloaders before packaging, validates the exact ZIP, rejects an already published version, and uploads only the selected main mod. `-DryRun` still creates normal build/package outputs but skips remote version checks and uploads. Publication always targets **Dyson Sphere Program** (`dyson-sphere-program`) with empty Category input, preserving the existing listing's categories; a first release starts without categories. Versions are never bumped automatically. After an interrupted or failed submission, check the printed version page before retrying because the release may already exist.
+
+Run the focused script checks with `powershell.exe -NoProfile -File tools/tests/Test-PublishMod.ps1` or `pwsh -NoProfile -File tools/tests/Test-PublishMod.ps1`. They use synthetic credentials and stubbed network/publication commands; scratch files stay under `UXAssist/obj/publish-mod-check`.
+
+## 发布到 Thunderstore
+
+使用 Windows PowerShell 5.1 或 PowerShell 7,并安装包含 MSBuild 17.8 或更新版本的 .NET SDK。游戏引用和其他构建依赖与正常编译一致。首次使用时,在仓库根目录还原固定版本的本地 tcli 工具:
+
+```powershell
+dotnet tool restore
+```
+
+通过 `-Project` 选择一个主 mod,通过必填参数 `-Namespace` 指定 Thunderstore Team。Package Name 读取 `/package/manifest.json`,版本读取项目文件。可以先预览构建和打包,无需 token,也不会上传:
+
+```powershell
+.\Publish-Mod.ps1 -Project UXAssist -Namespace soarqin -DryRun
+```
+
+正式发布时,将 Team 服务账号的 token 写入调用目录下的 UTF-8 `.env` 文件,再去掉 `-DryRun` 执行。如果 `.env` 不存在,脚本会读取进程环境变量 `TCLI_AUTH_TOKEN`。也可以通过 `-EnvFile` 指定其他文件:
+
+```powershell
+.\Publish-Mod.ps1 -Project Dustbin -Namespace soarqin -EnvFile "$env:USERPROFILE\.config\DSP_Mods\thunderstore.env"
+```
+
+文件允许一条 `TCLI_AUTH_TOKEN=...` 赋值,以及可选的引号、空行和整行注释。token 的读取优先级为:显式 `-EnvFile`、调用目录下的 `.env`、进程环境变量。选中的文件缺少 token 或格式无效时,脚本会报错。`.env` 和 `.env.*` 已加入 Git 忽略规则;真实 token 不应提交到版本控制,也不要写入 shell 命令历史。tcli 0.2.4 会优先读取 Windows 持久化的用户级 token;如果它与本次选定的 token 不同,脚本会停止,需先处理旧设置。
+
+脚本始终使用 Release 构建和现有的 `ZipMod` 目标。它会在打包前更新附带的 preloader,检查本次生成的确切 ZIP,拒绝重复发布已有版本,并且只上传选定的主 mod。`-DryRun` 仍会生成正常的构建和打包产物,但跳过远程版本检查和上传。发布社区固定为 **Dyson Sphere Program**(`dyson-sphere-program`);Category 输入留空,保留已有条目的分类,首次发布则不设置分类。脚本不会自动修改版本号。提交中断或失败后,应先检查输出的版本页面,再决定是否重试,因为该版本可能已经发布成功。
+
+可以运行 `powershell.exe -NoProfile -File tools/tests/Test-PublishMod.ps1` 或 `pwsh -NoProfile -File tools/tests/Test-PublishMod.ps1` 检查脚本。测试使用虚构的凭据,以及模拟的网络和发布命令;临时文件保存在 `UXAssist/obj/publish-mod-check` 下。
diff --git a/docs/ThunderstorePublishingPlan.md b/docs/ThunderstorePublishingPlan.md
new file mode 100644
index 0000000..ea972d1
--- /dev/null
+++ b/docs/ThunderstorePublishingPlan.md
@@ -0,0 +1,151 @@
+# Local Thunderstore Publishing Plan
+
+Status: implemented as a local PowerShell script. No real package upload has been performed.
+
+## Goal and scope
+
+Add a repository-root `Publish-Mod.ps1` that builds, packages, and publishes one explicitly named mod to the Dyson Sphere Program community through tcli. Reuse the existing MSBuild packaging targets and upload their ZIP without rebuilding it through tcli. Keep credentials out of version control.
+
+This proposal covers a local PowerShell command. It does not add a GitHub Actions workflow, change mod versions, upload dependencies, or publish packages during implementation checks.
+
+## Metadata source
+
+Use the existing `/package/manifest.json` for package metadata. Read Team from the required `-Namespace` parameter and Package Name from the manifest's `name` field. Keep the manifest's existing schema; no additional package metadata file or Team field is needed.
+
+Pass the supplied namespace to tcli as its package namespace. Require an explicit, non-empty value on every invocation, including `-DryRun`; do not default to `soarqin` or infer Team from other metadata. The service-account token must have permission to publish under the selected Team.
+
+| Publishing value | Source and rule |
+| --- | --- |
+| Team / tcli package namespace | Required `-Namespace` parameter; non-empty and preserving capitalization. |
+| Package Name | `manifest.json.name`, preserving capitalization. |
+| Version | Evaluated `.csproj` `Version`; `ZipMod` synchronizes `manifest.json.version_number`. Check the packaged value afterward. |
+| Community | Constant `dyson-sphere-program`. |
+| Repository | Constant `https://thunderstore.io`. |
+| Category | Explicitly empty tcli category configuration; preserve existing listing categories. |
+| Package contents | Existing `ZipMod` output, including its manifest, README, icon, DLLs, and optional changelog. |
+
+## Command interface
+
+```powershell
+# Publish using the caller directory's .env, or TCLI_AUTH_TOKEN if no file exists.
+.\Publish-Mod.ps1 -Project UXAssist -Namespace soarqin
+
+# Read the token from an explicitly selected file.
+.\Publish-Mod.ps1 -Project Dustbin -Namespace soarqin -EnvFile "$env:USERPROFILE\.config\DSP_Mods\thunderstore.env"
+
+# Build and inspect the package without uploading; a token is not required.
+.\Publish-Mod.ps1 -Project UXAssist -Namespace soarqin -DryRun
+```
+
+| Parameter | Behavior |
+| --- | --- |
+| `-Project ` | Required. Select one top-level project by directory name, such as `UXAssist` or `Dustbin`. Resolve paths from `$PSScriptRoot`, independently of the caller's current directory. |
+| `-Namespace ` | Required. Select the Thunderstore Team. Reject empty, whitespace-only, or invalid identifiers; preserve capitalization and use this value in tcli configuration and package-version lookups. |
+| `-EnvFile ` | Optional. Read `TCLI_AUTH_TOKEN` from an explicitly selected file. When omitted, use `.env` in the caller's current directory if present, otherwise use the process variable. |
+| `-DryRun` | Build, package, validate, and show the intended publish command and metadata. Skip token requirements, remote package checks, and tcli publication. This mode still writes normal build and package outputs. |
+
+Use Release configuration. Omit package-name, category, community, version-override, publish-all, and skip-build parameters from the initial interface. Selecting a preloader or helper project directly must fail with an actionable message identifying the main mod where applicable.
+
+Target Windows PowerShell 5.1 and PowerShell 7. The existing packaging targets invoke `powershell.exe`, so this proposal does not promise cross-platform packaging.
+
+## Build and publish sequence
+
+1. Resolve the named project within the repository. Require `/.csproj`, `package/manifest.json`, `package/icon.png`, and `README.md`. Reject traversal, wildcard input, helpers, and projects with `PackPreloaderTargetDir` set. Validate `-Namespace` and the manifest's `name` before building.
+2. Evaluate Release MSBuild properties instead of guessing output paths or parsing only literal XML: `Version`, `ProjectName`, `TargetPath`, `PackHasChangelog`, `PackUsePluginsLayout`, and `PackPreloaderTargetDir`. Read evaluated `ProjectReference` items to find bundled preloaders. MSBuild 17.8 or newer provides the required `-getProperty` and `-getItem` JSON output.
+3. For a real publish, resolve the token before changing to the repository's build directory and check the pinned local tcli tool before the expensive build. For `-DryRun`, neither a token nor an installed tcli tool is required. Restore project NuGet assets when missing, then use `--no-restore` for packaging.
+4. For each referenced preloader whose evaluated `PackPreloaderTargetDir` belongs to the selected mod's package, run `CopyToParentPackage` in Release before packaging the main mod. This refreshes Dustbin's bundled preloader even if an old DLL already exists under `package/patchers`. Do not upload preloaders or referenced mods separately.
+5. Run `dotnet build /.csproj -t:ZipMod -c Release --no-restore`. Every native command must have its exit code checked; stop immediately on a nonzero result. Retain the existing warning policy.
+6. Select the exact ZIP path defined by the existing target: `/package/-.zip`. Do not select the newest ZIP by timestamp or a wildcard. Read the ZIP and check its root manifest identity and version, required root files, 256x256 PNG icon, expected DLL layout, and optional changelog. Compare bundled main/preloader DLLs with the current evaluated build outputs. When a separate changelog is included, require its latest English and Chinese headings to match the project version. Do not change any version automatically.
+7. Write a generated, non-secret tcli configuration under `/obj/thunderstore-publish//thunderstore.toml`. Print the project, Team, Package Name, version, community, ZIP path, and category-preservation behavior. In `-DryRun`, stop successfully here and retain the ZIP for inspection.
+8. Before a real upload, query the exact package-version endpoint using the supplied namespace, manifest package name, and evaluated project version. If the version exists, stop without uploading. Treat only HTTP 404 as an absent version; authentication, network, server, and response-format errors must remain errors. Do not automatically increment versions or retry a publish with an uncertain result.
+9. Provide the token to the tcli child process and run `dotnet tool run tcli -- publish --config-path --file `. Restore process environment and working directory in `finally`. Remove only this invocation's generated configuration directory after verifying its resolved path. Preserve the ZIP.
+10. Return success only after tcli reports successful publication. Show the package page and tcli's download URL. After a submission timeout or failure, explain how to inspect the exact version before retrying; a failed command does not prove that the server created no release.
+
+For example, Dustbin's packaging commands are:
+
+```powershell
+dotnet build DustbinPreloader/DustbinPreloader.csproj -t:CopyToParentPackage -c Release --no-restore
+dotnet build Dustbin/Dustbin.csproj -t:ZipMod -c Release --no-restore
+```
+
+Only the selected mod is published. Existing dependency declarations remain authoritative; packaging a dependent mod does not publish UXAssist. Retired LabOpt is excluded from routine implementation checks.
+
+## Generated tcli configuration
+
+Use a repository-local .NET tool manifest at `.config/dotnet-tools.json` and pin tcli to `0.2.4`, the latest version currently available from NuGet. First-time setup is `dotnet tool restore`; do not silently install or update a global tcli. Recheck the available version when implementation begins, and change the pin only after checking the behavior below.
+
+Example configuration for an existing UXAssist version:
+
+```toml
+[config]
+schemaVersion = "0.0.1"
+
+[package]
+namespace = "soarqin"
+name = "UXAssist"
+versionNumber = "1.6.2"
+
+[build]
+outdir = "."
+
+[publish]
+repository = "https://thunderstore.io"
+communities = ["dyson-sphere-program"]
+categories = []
+```
+
+Generate `namespace` from `-Namespace`, `name` from `package/manifest.json.name`, and `versionNumber` from the evaluated project version. The values above illustrate `-Project UXAssist -Namespace soarqin`; they are not defaults. Validate permitted identifier/version characters before writing TOML, and pass command arguments as an array rather than composing executable PowerShell text. `[build].outdir` satisfies tcli's publish-time configuration validation; `--file` prevents tcli from building a second ZIP. The uploaded archive supplies the actual package description, dependencies, website, and other manifest content.
+
+`categories = []` is deliberate. In tcli 0.2.4, omitting the setting leaves example `riskofrain2` categories from the configuration model. An empty array produces empty legacy categories and an empty per-community category map. The inspected Thunderstore server code only adds categories when the submitted list is non-empty, so an existing listing retains its current categories. Categories belong to the community listing, rather than an individual package version. A first release has no previous categories to inherit and starts without categories. No category lookup or local category cache is necessary.
+
+## Token handling
+
+Use a Thunderstore Team service-account token through `TCLI_AUTH_TOKEN`. Select an explicit `-EnvFile` first, otherwise read `.env` in the caller's current directory if it exists, and finally fall back to the inherited process variable when no default file exists. Resolve this before changing directories. A missing explicit file or invalid token in a selected file is an error, not a reason to use another source. Do not add a token parameter or pass `--token` to tcli. Never write the token into TOML, the tool manifest, package metadata, a generated script, or a log.
+
+The environment file contains one token assignment:
+
+```dotenv
+TCLI_AUTH_TOKEN=
+```
+
+Read it as UTF-8 data. Support blank lines, full-line comments, and an optional matching pair of single or double quotes around the value. Reject duplicate token assignments, empty values, malformed lines, and unsupported keys. Do not evaluate PowerShell, expand variables, or execute the file. Do not print offending file contents in errors.
+
+Allow local environment files inside or outside the checkout. Keep `.env` and `.env.*` ignored by Git so that a repository-local `.env` remains untracked. Use only synthetic tokens in implementation checks.
+
+The pinned tcli version has a Windows-specific behavior: it reads the persisted User-scoped `TCLI_AUTH_TOKEN` before the process value. Before publication, compare that User-scoped value with the selected token without logging either value. If a different non-empty User value exists, stop and explain that the caller must remove or reconcile the stale setting. Do not change User or Machine environment variables automatically. Otherwise, temporarily set only the process variable immediately around tcli invocation and restore its original presence and value in `finally`.
+
+## Implementation work
+
+- [x] Implement required `-Project` and `-Namespace` parameters. Read Package Name from the existing manifest and verify that it agrees with the archive manifest.
+- [x] Add the pinned `.config/dotnet-tools.json`, the `Publish-Mod.ps1` entry point, and environment-file ignore patterns. Keep packaging logic in the existing MSBuild targets.
+- [x] Add a short English/Chinese publishing section to the root README covering tool restoration, project and namespace selection, credential sources, category retention, and `-DryRun`.
+- [x] Verify local preparation and failure handling without making a real upload. Leave mod versions, release changelogs, runtime code, `AGENTS.md`, and GitHub Actions unchanged.
+
+## Acceptance checks
+
+| Check | Expected result |
+| --- | --- |
+| `UXAssist -Namespace soarqin -DryRun`, invoked from another directory | Uses repository-relative inputs, produces the normal flat ZIP, and shows the correct identity and DSP community without requiring a token. |
+| `Dustbin -Namespace soarqin -DryRun` with an existing preloader DLL | Refreshes `DustbinPreloader`, packages `plugins/` and `patchers/`, and includes the current build outputs. |
+| A different explicit namespace for the same project | Uses that Team in generated configuration, version lookups, and package links while continuing to read Package Name from the existing manifest. |
+| Missing project, malformed metadata, missing/empty/invalid namespace, preloader/helper selection, or traversal input | Stops before publication and identifies the invalid input. |
+| Explicit `-EnvFile`, default caller-directory `.env`, and process token are all available | Uses the explicit file first; without it, uses the caller's `.env`; without either file, uses the process variable. Repository-local `.env` files are supported. |
+| Missing token, missing explicit file, malformed selected file, or conflicting Windows User-scoped token | Stops without exposing credentials or changing persisted environment variables. |
+| Failed restore/build/pack or invalid ZIP | Never invokes tcli publication and never falls back to an older ZIP. |
+| Generated configuration | Contains only `dyson-sphere-program`, explicitly empty categories, and no credential values. Check the parsed tcli metadata as well as the TOML text. |
+| Existing remote version, unexpected HTTP failure, tcli failure, or uncertain timeout | Returns a nonzero result and provides an appropriate next step; no automatic republish or version bump. |
+| Stubbed successful tcli invocation | Receives the exact validated ZIP and intended token through its environment; receives no token argument. Process environment and working directory are restored after both success and failure. |
+
+Use focused command stubs for publication/error-path checks with a synthetic token. Run actual packaging preparation for UXAssist and Dustbin and run `git diff --check` before implementation handoff. A real release is a separate operation against an explicitly selected project/version; validate the resulting listing and retained categories when that operation is requested.
+
+## Verified upstream behavior
+
+Sources checked on 2026-10-17:
+
+- [tcli publishing and authentication documentation](https://github.com/thunderstore-io/thunderstore-cli/wiki): `TCLI_AUTH_TOKEN`, namespace, and publishing an existing ZIP with `--file`.
+- [NuGet tcli versions](https://api.nuget.org/v3-flatcontainer/tcli/index.json): currently available tool versions.
+- [MSBuild property and item evaluation](https://learn.microsoft.com/en-us/visualstudio/msbuild/evaluate-items-and-properties): evaluated metadata and JSON output in MSBuild 17.8 and newer.
+- [tcli 0.2.4 configuration model](https://github.com/thunderstore-io/thunderstore-cli/blob/0.2.4/ThunderstoreCLI/Models/ThunderstoreProject.cs) and [upload metadata](https://github.com/thunderstore-io/thunderstore-cli/blob/0.2.4/ThunderstoreCLI/Configuration/Config.cs): category defaults, the empty-array mapping, and publishing metadata.
+- [tcli 0.2.4 environment provider](https://github.com/thunderstore-io/thunderstore-cli/blob/0.2.4/ThunderstoreCLI/Configuration/EnvironmentConfig.cs): Windows User-scope precedence.
+- [Thunderstore upload form](https://github.com/thunderstore-io/Thunderstore/blob/685b2743035e0ac0786180d10813d67b72fcdc2d/django/thunderstore/repository/package_upload.py) and [listing update behavior](https://github.com/thunderstore-io/Thunderstore/blob/685b2743035e0ac0786180d10813d67b72fcdc2d/django/thunderstore/repository/models/package.py): empty submitted categories retain existing listing categories.
+- [Thunderstore manifest serializer](https://github.com/thunderstore-io/Thunderstore/blob/685b2743035e0ac0786180d10813d67b72fcdc2d/django/thunderstore/repository/package_manifest.py): standard manifest fields and duplicate-version validation.
diff --git a/tools/tests/Test-PublishMod.ps1 b/tools/tests/Test-PublishMod.ps1
new file mode 100644
index 0000000..8929234
--- /dev/null
+++ b/tools/tests/Test-PublishMod.ps1
@@ -0,0 +1,348 @@
+#requires -Version 5.1
+# Run from any directory with Windows PowerShell 5.1 or PowerShell 7.
+# All uploads and remote checks use stubs; credentials are synthetic.
+[CmdletBinding()]
+param()
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = 'Stop'
+$repoRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
+$scriptPath = Join-Path $repoRoot 'Publish-Mod.ps1'
+$parseTokens = $null
+$parseErrors = $null
+$ast = [Management.Automation.Language.Parser]::ParseFile($scriptPath, [ref]$parseTokens, [ref]$parseErrors)
+if ($parseErrors.Count -ne 0) { throw 'Publish-Mod.ps1 has parse errors.' }
+# Load helpers without running the publishing entry point or touching real tokens.
+foreach ($statement in $ast.EndBlock.Statements) {
+ if ($statement -is [Management.Automation.Language.FunctionDefinitionAst]) {
+ . ([scriptblock]::Create($statement.Extent.Text))
+ }
+}
+$script:realInvokeDotNet = ${function:Invoke-PublishDotNet}
+Add-Type -AssemblyName System.IO.Compression
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+Add-Type -TypeDefinition @'
+using System;
+public sealed class PublishCheckHttpResponse {
+ public int StatusCode { get; set; }
+}
+public sealed class PublishCheckHttpException : Exception {
+ public PublishCheckHttpResponse Response { get; private set; }
+ public PublishCheckHttpException(int status) : base("Synthetic HTTP error") {
+ Response = new PublishCheckHttpResponse { StatusCode = status };
+ }
+}
+'@
+$script:checkCount = 0
+$script:userToken = $null
+function Get-PublishUserToken { return $script:userToken }
+function Assert-Check([bool]$Condition, [string]$Message) {
+ if (-not $Condition) { throw $Message }
+ $script:checkCount++
+}
+function Assert-CheckThrows([scriptblock]$Action, [string]$MessagePattern) {
+ $caught = $false
+ try { & $Action 6>$null } catch {
+ $caught = $true
+ if ($_.Exception.Message -notlike $MessagePattern) { throw }
+ }
+ Assert-Check $caught "Expected failure: $MessagePattern"
+}
+
+$checkBase = Join-Path $repoRoot 'UXAssist\obj\publish-mod-check'
+$sandbox = Join-Path $checkBase ([Guid]::NewGuid().ToString('N'))
+$null = [IO.Directory]::CreateDirectory($sandbox)
+$savedToken = [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')
+$savedLocation = (Get-Location).Path
+$script:syntheticToken = 'synthetic-publish-check-only'
+$script:callerToken = 'synthetic-caller-value'
+
+function New-PublishFixture {
+ $script:fixtureRoot = Join-Path $sandbox (([Guid]::NewGuid().ToString('N')) + ' repo with spaces')
+ $script:fixtureDir = Join-Path $script:fixtureRoot 'Fixture'
+ $script:fixturePackage = Join-Path $script:fixtureDir 'package'
+ $script:fixtureOutput = Join-Path $script:fixtureDir 'bin\Release\Fixture.dll'
+ $script:fixtureAssets = Join-Path $script:fixtureDir 'obj\project.assets.json'
+ $script:fixtureZip = Join-Path $script:fixturePackage 'Fixture-1.2.3.zip'
+ foreach ($dir in @($script:fixturePackage, [IO.Path]::GetDirectoryName($script:fixtureOutput), [IO.Path]::GetDirectoryName($script:fixtureAssets))) {
+ $null = [IO.Directory]::CreateDirectory($dir)
+ }
+ [IO.File]::WriteAllText((Join-Path $script:fixtureDir 'Fixture.csproj'), '')
+ [IO.File]::WriteAllText($script:fixtureAssets, '{}')
+ [IO.File]::WriteAllText((Join-Path $script:fixturePackage 'manifest.json'), '{"name":"ManifestPackage","version_number":"1.2.2"}')
+ [IO.File]::WriteAllText((Join-Path $script:fixtureDir 'README.md'), '# Fixture')
+ [IO.File]::Copy((Join-Path $repoRoot 'UXAssist\package\icon.png'), (Join-Path $script:fixturePackage 'icon.png'))
+ [IO.File]::WriteAllText((Join-Path $script:fixtureDir 'CHANGELOG.md'), 'English
' + "`n* 1.2.3`nSecond language
`n* 1.2.3`n ")
+ $script:calls = New-Object 'System.Collections.Generic.List[string]'
+ $script:requests = New-Object 'System.Collections.Generic.List[string]'
+ $script:layout = $false
+ $script:failStep = ''
+ $script:badArchive = ''
+ $script:remoteState = 'available'
+ $script:expectedNamespace = 'AnotherTeam'
+ $script:published = $false
+ $script:capturedConfig = $null
+ $script:capturedConfigPath = $null
+}
+
+function Invoke-PublishDotNet {
+ param([string[]]$Arguments, [switch]$Capture, [string]$Secret)
+ $script:calls.Add(($Arguments -join '|'))
+ if ($Arguments[0] -eq 'msbuild') {
+ if ($script:failStep -eq 'evaluate') { return 'not JSON' }
+ $isPreloader = $Arguments[1] -like '*FixturePreloader.csproj'
+ $properties = @{
+ Version = '1.2.3'; ProjectName = 'Fixture'; TargetPath = $script:fixtureOutput
+ PackHasChangelog = 'true'; PackUsePluginsLayout = $script:layout.ToString().ToLowerInvariant()
+ PackPreloaderTargetDir = ''; ProjectAssetsFile = $script:fixtureAssets
+ }
+ $references = @()
+ if ($isPreloader) {
+ $properties.TargetPath = Join-Path $script:fixtureRoot 'FixturePreloader\bin\FixturePreloader.dll'
+ $properties.PackPreloaderTargetDir = '..\Fixture\package\patchers'
+ } elseif ($script:layout) {
+ $references = @(@{ FullPath = Join-Path $script:fixtureRoot 'FixturePreloader\FixturePreloader.csproj' })
+ }
+ return (@{ Properties = $properties; Items = @{ ProjectReference = $references } } | ConvertTo-Json -Depth 6 -Compress)
+ }
+ if ($Arguments[0] -eq 'restore') {
+ if ($script:failStep -eq 'restore') { throw 'Synthetic restore failure' }
+ [IO.File]::WriteAllText($script:fixtureAssets, '{}')
+ return
+ }
+ if ($Arguments[0] -eq 'build') {
+ if ($Arguments -contains '-t:CopyToParentPackage') {
+ if ($script:failStep -eq 'preloader') { throw 'Synthetic preloader failure' }
+ $preloaderOutput = Join-Path $script:fixtureRoot 'FixturePreloader\bin\FixturePreloader.dll'
+ $null = [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($preloaderOutput))
+ $null = [IO.Directory]::CreateDirectory((Join-Path $script:fixturePackage 'patchers'))
+ [IO.File]::WriteAllText($preloaderOutput, 'fresh preloader')
+ [IO.File]::Copy($preloaderOutput, (Join-Path $script:fixturePackage 'patchers\FixturePreloader.dll'), $true)
+ return
+ }
+ if ($script:failStep -eq 'build') { throw 'Synthetic build failure' }
+ [IO.File]::WriteAllText($script:fixtureOutput, 'fresh main DLL')
+ [IO.File]::WriteAllText((Join-Path $script:fixturePackage 'manifest.json'), '{"name":"ManifestPackage","version_number":"1.2.3"}')
+ if ($script:badArchive -eq 'wrong version') {
+ [IO.File]::WriteAllText((Join-Path $script:fixturePackage 'manifest.json'), '{"name":"ManifestPackage","version_number":"1.2.2"}')
+ }
+ if ([IO.File]::Exists($script:fixtureZip)) { [IO.File]::Delete($script:fixtureZip) }
+ $zip = [IO.Compression.ZipFile]::Open($script:fixtureZip, [IO.Compression.ZipArchiveMode]::Create)
+ try {
+ $files = @{
+ 'manifest.json' = Join-Path $script:fixturePackage 'manifest.json'
+ 'icon.png' = Join-Path $script:fixturePackage 'icon.png'
+ 'README.md' = Join-Path $script:fixtureDir 'README.md'
+ 'CHANGELOG.md' = Join-Path $script:fixtureDir 'CHANGELOG.md'
+ }
+ if ($script:layout) {
+ $files['plugins/Fixture.dll'] = $script:fixtureOutput
+ $files['patchers/FixturePreloader.dll'] = Join-Path $script:fixturePackage 'patchers\FixturePreloader.dll'
+ } else { $files['Fixture.dll'] = $script:fixtureOutput }
+ foreach ($entryName in $files.Keys) {
+ if ($script:badArchive -eq 'missing DLL' -and $entryName -eq 'Fixture.dll') { continue }
+ $null = [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $files[$entryName], $entryName)
+ }
+ if ($script:badArchive -eq 'unsafe') { $null = $zip.CreateEntry('../bad.dll') }
+ if ($script:badArchive -eq 'duplicate') { $null = $zip.CreateEntry('README.md') }
+ if ($script:badArchive -eq 'credential') { $null = $zip.CreateEntry('plugins/.env') }
+ } finally { $zip.Dispose() }
+ if ($script:badArchive -eq 'stale DLL') { [IO.File]::WriteAllText($script:fixtureOutput, 'different DLL') }
+ return
+ }
+ if ($Arguments -contains 'publish') {
+ Assert-Check ($Secret -ceq $script:syntheticToken) 'The output-redaction token is incorrect.'
+ Assert-Check ([Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process') -ceq $script:syntheticToken) 'The child process token is incorrect.'
+ Assert-Check (-not ($Arguments -contains '--token')) 'A token was put in the command line.'
+ $script:capturedConfigPath = $Arguments[[Array]::IndexOf($Arguments, '--config-path') + 1]
+ $script:capturedConfig = [IO.File]::ReadAllText($script:capturedConfigPath)
+ Assert-Check ($script:capturedConfig -match ('namespace = "' + $script:expectedNamespace + '"')) 'The supplied namespace was not used.'
+ Assert-Check ($script:capturedConfig -match 'name = "ManifestPackage"') 'Package Name was not read from the manifest.'
+ Assert-Check ($script:capturedConfig -match 'communities = \["dyson-sphere-program"\]' -and $script:capturedConfig -match 'categories = \[\]') 'Community/categories are incorrect.'
+ Assert-Check (-not $script:capturedConfig.Contains($script:syntheticToken)) 'A token was written to TOML.'
+ Assert-Check ($Arguments[[Array]::IndexOf($Arguments, '--file') + 1] -ceq $script:fixtureZip) 'The exact ZIP was not used.'
+ if ($script:failStep -eq 'publish') { throw 'Synthetic submission timeout' }
+ $script:published = $true
+ }
+}
+
+function Invoke-RestMethod {
+ param([string]$Uri, [string]$Method, [int]$TimeoutSec, [string]$ErrorAction)
+ $script:requests.Add($Uri)
+ if ($script:remoteState -eq 'available') { throw [PublishCheckHttpException]::new(404) }
+ if ($script:remoteState -eq 'server error') { throw [PublishCheckHttpException]::new(503) }
+ if ($script:remoteState -eq 'offline') { throw 'Synthetic connection failure' }
+ if ($script:remoteState -eq 'malformed') { return [pscustomobject]@{ unexpected = 'response' } }
+ return [pscustomobject]@{ namespace = $script:expectedNamespace; name = 'ManifestPackage'; version_number = '1.2.3' }
+}
+
+try {
+ New-PublishFixture
+ $externalTokenFile = Join-Path $sandbox 'synthetic.env'
+ [IO.File]::WriteAllText($externalTokenFile, "# Synthetic credentials only`nTCLI_AUTH_TOKEN='$script:syntheticToken'`n")
+ [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $script:callerToken, 'Process')
+ Push-Location -LiteralPath $script:fixtureRoot
+ try {
+ Assert-Check ((Get-PublishToken $externalTokenFile) -ceq $script:syntheticToken) 'Explicit environment file did not take precedence.'
+ Assert-Check ((Get-PublishToken) -ceq $script:callerToken) 'Inherited process token was not used when .env was absent.'
+ foreach ($invalid in @('TCLI_AUTH_TOKEN=', 'OTHER_KEY=value', "TCLI_AUTH_TOKEN=one`nTCLI_AUTH_TOKEN=two", 'TCLI_AUTH_TOKEN="unclosed', 'TCLI_AUTH_TOKEN=two words')) {
+ [IO.File]::WriteAllText($externalTokenFile, $invalid)
+ Assert-CheckThrows { Get-PublishToken $externalTokenFile } '*'
+ }
+ [IO.File]::WriteAllText($externalTokenFile, 'TCLI_AUTH_TOKEN=$env:SHOULD_NOT_EXPAND')
+ Assert-Check ((Get-PublishToken $externalTokenFile) -ceq '$env:SHOULD_NOT_EXPAND') 'Environment file content was expanded.'
+ [IO.File]::WriteAllText($externalTokenFile, "TCLI_AUTH_TOKEN=$script:syntheticToken")
+ $script:userToken = 'synthetic-stale-user-value'
+ Assert-CheckThrows { Get-PublishToken $externalTokenFile } '*User-scoped*'
+ $script:userToken = $null
+ [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', [NullString]::Value, 'Process')
+ Assert-CheckThrows { Get-PublishToken } '*Set a non-empty*'
+ [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $script:callerToken, 'Process')
+ $defaultTokenFile = Join-Path $script:fixtureRoot '.env'
+ [IO.File]::WriteAllText($defaultTokenFile, 'TCLI_AUTH_TOKEN=synthetic-current-directory-token')
+ Assert-Check ((Get-PublishToken) -ceq 'synthetic-current-directory-token') 'The current directory .env did not override the process token.'
+ Assert-Check ((Get-PublishToken $externalTokenFile) -ceq $script:syntheticToken) 'Explicit -EnvFile did not override the default .env.'
+ Assert-Check ((Get-PublishToken '.env') -ceq 'synthetic-current-directory-token') 'An explicit in-checkout .env was rejected.'
+ Assert-CheckThrows { Get-PublishToken 'missing.env' } '*does not exist*'
+ [IO.File]::WriteAllText($defaultTokenFile, 'TCLI_AUTH_TOKEN=')
+ Assert-CheckThrows { Get-PublishToken } '*Set a non-empty*'
+ } finally { Pop-Location }
+
+ Invoke-ModPublish -RepositoryRoot $script:fixtureRoot -Project Fixture -Namespace AnotherTeam -DryRun -EnvFile 'does-not-exist' 6>$null
+ Assert-Check (-not $script:published -and $script:requests.Count -eq 0) 'DryRun attempted publication or remote checks.'
+ Assert-Check (@($script:calls | Where-Object { $_ -like 'tool|*' }).Count -eq 0) 'DryRun required tcli.'
+ foreach ($invalidNamespace in @('', 'Bad Team', "Team`n")) {
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture $invalidNamespace -DryRun } '*-Namespace*'
+ }
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot '..\Fixture' AnotherTeam -DryRun } '*-Project*'
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot FixturePreloader AnotherTeam -DryRun } '*main mod*'
+
+ New-PublishFixture
+ $script:layout = $true
+ $null = [IO.Directory]::CreateDirectory((Join-Path $script:fixturePackage 'patchers'))
+ [IO.File]::WriteAllText((Join-Path $script:fixturePackage 'patchers\FixturePreloader.dll'), 'stale preloader')
+ Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam -DryRun 6>$null
+ Assert-Check (($script:calls | Where-Object { $_ -like 'build|*' } | Select-Object -First 1) -like '*CopyToParentPackage*') 'The preloader was not copied before the main mod was packaged.'
+ Assert-Check ([IO.File]::ReadAllText((Join-Path $script:fixturePackage 'patchers\FixturePreloader.dll')) -ceq 'fresh preloader') 'A stale preloader was packaged.'
+
+ foreach ($badZip in @('unsafe', 'duplicate', 'credential', 'missing DLL', 'stale DLL', 'wrong version')) {
+ New-PublishFixture
+ $script:badArchive = $badZip
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam -DryRun } '*ZIP*'
+ Assert-Check (-not $script:published) 'An invalid ZIP was published.'
+ }
+ New-PublishFixture
+ [IO.File]::WriteAllText((Join-Path $script:fixtureDir 'CHANGELOG.md'), "`n* 1.2.3`n `n* 1.2.2`n ")
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam -DryRun } '*every language*'
+ New-PublishFixture
+ $smallIcon = New-Object Drawing.Bitmap(128, 128)
+ try { $smallIcon.Save((Join-Path $script:fixturePackage 'icon.png'), [Drawing.Imaging.ImageFormat]::Png) } finally { $smallIcon.Dispose() }
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam -DryRun } '*256x256 PNG*'
+
+ foreach ($failure in @('evaluate', 'restore', 'preloader', 'build')) {
+ New-PublishFixture
+ $script:failStep = $failure
+ if ($failure -eq 'restore') { [IO.File]::Delete($script:fixtureAssets) }
+ if ($failure -eq 'preloader') { $script:layout = $true }
+ # Leave an older ZIP to ensure a failed build never publishes it.
+ [IO.File]::WriteAllText($script:fixtureZip, 'old zip')
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam $externalTokenFile } '*'
+ Assert-Check (-not $script:published -and $script:requests.Count -eq 0) 'A build failure fell through to publication.'
+ }
+ foreach ($remote in @('existing', 'server error', 'offline', 'malformed')) {
+ New-PublishFixture
+ $script:remoteState = $remote
+ Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam $externalTokenFile } '*'
+ Assert-Check (-not $script:published) 'An existing/unverifiable version was published.'
+ Assert-Check ($script:requests[0] -like '*/AnotherTeam/ManifestPackage/1.2.3/') 'The version lookup did not use the selected Team and manifest name.'
+ }
+
+ foreach ($failure in @('', 'publish')) {
+ New-PublishFixture
+ $script:failStep = $failure
+ if ($failure) { Assert-CheckThrows { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam $externalTokenFile } '*Inspect https://*before retrying*' }
+ else { Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam $externalTokenFile 6>$null }
+ Assert-Check ([Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process') -ceq $script:callerToken) 'The process token was not restored.'
+ Assert-Check ((Get-Location).Path -ceq $savedLocation) 'The caller directory was not restored.'
+ Assert-Check (-not [IO.Directory]::Exists([IO.Path]::GetDirectoryName($script:capturedConfigPath))) 'Generated configuration was not cleaned up.'
+ Assert-Check ([IO.File]::Exists($script:fixtureZip)) 'The prepared ZIP was removed.'
+ }
+ [IO.File]::WriteAllText((Join-Path $checkBase 'verified-thunderstore.toml'), $script:capturedConfig)
+
+ New-PublishFixture
+ Push-Location -LiteralPath $sandbox
+ try {
+ Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam 'synthetic.env' 6>$null
+ Assert-Check ((Get-Location).Path -ceq $sandbox) 'The external caller directory was not restored.'
+ [IO.File]::WriteAllText((Join-Path $sandbox '.env'), "TCLI_AUTH_TOKEN=$script:syntheticToken")
+ [IO.File]::WriteAllText((Join-Path $script:fixtureRoot '.env'), 'TCLI_AUTH_TOKEN=synthetic-wrong-repository-token')
+ $script:published = $false
+ Invoke-ModPublish -RepositoryRoot $script:fixtureRoot -Project Fixture -Namespace AnotherTeam 6>$null
+ Assert-Check $script:published 'Publication did not use .env from the caller directory.'
+ Assert-Check ((Get-Location).Path -ceq $sandbox) 'Default .env lookup did not restore the caller directory.'
+ } finally { Pop-Location }
+ [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', [NullString]::Value, 'Process')
+ New-PublishFixture
+ Invoke-ModPublish $script:fixtureRoot Fixture AnotherTeam $externalTokenFile 6>$null
+ Assert-Check ($null -eq [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')) 'An originally absent process token was not removed.'
+
+ # Use real MSBuild output: string stubs cannot reproduce native decoding bugs.
+ $encodingProject = Join-Path $sandbox 'Encoding.proj'
+ [IO.File]::WriteAllText($encodingProject, @'
+
+
+
+
+
+
+
+
+'@)
+ $expectedNativeText = -join ([char[]]@(0x4e2d, 0x6587, 0x8f93, 0x51fa))
+ $previousOutputEncoding = [Console]::OutputEncoding
+ $previousPipelineEncoding = $OutputEncoding
+ try {
+ foreach ($codePage in @(936, 65001)) {
+ [Console]::OutputEncoding = [Text.Encoding]::GetEncoding($codePage)
+ $nativeArguments = @('msbuild', $encodingProject, '-nologo', '-verbosity:minimal', '-nodeReuse:false')
+ $captured = & $script:realInvokeDotNet -Capture -Arguments $nativeArguments
+ Assert-Check ($captured.Contains($expectedNativeText)) "Captured MSBuild output was corrupted with code page $codePage."
+ Assert-Check ([Console]::OutputEncoding.CodePage -eq $codePage) 'Capture did not restore the console encoding.'
+ $displayed = & $script:realInvokeDotNet -Arguments $nativeArguments 6>&1
+ Assert-Check (($displayed -join "`n").Contains($expectedNativeText)) "Displayed MSBuild output was corrupted with code page $codePage."
+ Assert-Check ([Console]::OutputEncoding.CodePage -eq $codePage) 'Display did not restore the console encoding.'
+ $failureOutput = New-Object 'System.Collections.Generic.List[string]'
+ $failed = $false
+ try {
+ & $script:realInvokeDotNet -Capture -Arguments ($nativeArguments + '-target:Fail') 6>&1 |
+ ForEach-Object { $failureOutput.Add($_.ToString()) }
+ } catch {
+ $failed = $true
+ Assert-Check ($_.Exception.Message -like '*exit 1*') 'MSBuild returned an unexpected failure.'
+ }
+ Assert-Check ($failed -and ($failureOutput -join "`n").Contains($expectedNativeText)) 'MSBuild failure output was lost or corrupted.'
+ Assert-Check ([Console]::OutputEncoding.CodePage -eq $codePage) 'Failure did not restore the console encoding.'
+ }
+ Assert-Check ($OutputEncoding -eq $previousPipelineEncoding) 'Native output handling changed the input pipeline encoding.'
+ } finally { [Console]::OutputEncoding = $previousOutputEncoding }
+
+ # Exercise redaction and nonzero exits without starting another process.
+ $script:nativeExit = 0
+ function dotnet {
+ param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
+ $global:LASTEXITCODE = $script:nativeExit
+ return "Synthetic tool output: $script:syntheticToken"
+ }
+ try {
+ $redacted = & $script:realInvokeDotNet -Capture -Arguments @('stub') -Secret $script:syntheticToken
+ Assert-Check ($redacted.Contains('[REDACTED]') -and -not $redacted.Contains($script:syntheticToken)) 'Native output exposed the token.'
+ $script:nativeExit = 17
+ Assert-CheckThrows { & $script:realInvokeDotNet -Arguments @('stub') -Secret $script:syntheticToken } '*exit 17*'
+ Assert-CheckThrows { & $script:realInvokeDotNet -Capture -Arguments @('stub') -Secret $script:syntheticToken } '*exit 17*'
+ } finally { Remove-Item -LiteralPath Function:dotnet }
+ Write-Host "Publish-Mod checks passed: $script:checkCount assertions. No real upload or remote lookup was made."
+} finally {
+ if ($null -eq $savedToken) { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', [NullString]::Value, 'Process') }
+ else { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $savedToken, 'Process') }
+ Set-Location -LiteralPath $savedLocation
+}