diff --git a/README.md b/README.md index c4ab3e4..4356316 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,14 @@ Live site: - Core tools: Git, Node.js, pnpm, Python, uv, Bun, Docker Desktop, Docker Engine (Colima on macOS or Docker CE in WSL2 Ubuntu on Windows), and Windows WSL2. - Editor tools: VS Code and the Claude Code VS Code extension. -- AI tools: Claude Desktop, Claude Code CLI, Codex App, and Codex CLI. +- AI tools: Claude Desktop, Claude Code CLI, ChatGPT desktop app (includes Codex; Store product `9PLM9XGG6VKS`, shown as Codex App on macOS), and Codex CLI. - Media tools: FFmpeg, yt-dlp, and Deno (the JavaScript runtime yt-dlp needs for YouTube). yt-dlp pulls in Deno automatically. On Windows these use WinGet portable packages (`Gyan.FFmpeg.Essentials`, `yt-dlp.yt-dlp`, `DenoLand.Deno`) with `--scope user`; on macOS they use Homebrew formulae. +- Project folder: downloads a zip over HTTPS (GitHub archive or release asset) into `Documents/`, verifies an optional SHA-256, never overwrites an existing folder (uses `-YYYYMMDD` or skips), and never runs downloaded files. Folder names allow only letters, digits, `.`, `_`, `-`. +- Media verify step: when FFmpeg, yt-dlp, or Deno is selected, the script ends with a Korean per-tool summary (installed + version, or failed + what to do), checks that `ffmpeg -filters` contains `drawtext`, and tells the user to fully quit and reopen the ChatGPT app. The Windows `.bat` stays ASCII-only: Korean strings are emitted as `\uXXXX` escapes and decoded by PowerShell. - Source control tools: GitHub CLI, GitHub auth check, GitLab CLI, and Git identity defaults. - Optional deployment tool: Vercel CLI. -The `video-class` preset (`presetSelection("video-class")`) selects Codex App, FFmpeg, yt-dlp, and Deno for non-developer video classes. It does not add WSL2, Git, or Node.js. +The `video-class` preset (`presetSelection("video-class")`) selects Codex App, FFmpeg, yt-dlp, and Deno for non-developer video classes. It does not add WSL2, Git, or Node.js. Presets are also UI buttons and URL parameters: `?os=win&preset=video-class&project=&name=[&sha256=]` preselects the items and fills the project fields, and the copy-link button produces that short form when the selection matches a preset. Advanced observability settings for Claude Code CLI and Codex CLI are opt-in. They stay off by default, and the UI's "select all" action does not enable them. Prompt/body collection toggles are also off by default. diff --git a/src/App.jsx b/src/App.jsx index 733732b..1a977ed 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -30,6 +30,8 @@ import { autoAdded, buildScript, deselectWithDependents, + presetSelection, + projectFolderErrors, fileName, resolveSelection, selectWithDependencies, @@ -60,9 +62,20 @@ const DEFAULT_SETTINGS = { codexLogExporter: "otlp", codexTraceExporter: "none", codexMetricsExporter: "none", - codexLogUserPrompt: false + codexLogUserPrompt: false, + projectUrl: "", + projectName: "", + projectSha256: "" }; +const PRESETS = [ + ["minimal", "기본 개발 환경"], + ["agent", "AI 에이전트 개발"], + ["video-class", "영상 수업"] +]; +const PRESET_NAMES = new Set(PRESETS.map(([name]) => name)); +const URL_PARAM_ALIASES = { projectUrl: "project", projectName: "name", projectSha256: "sha256" }; + const OTEL_PROTOCOL_OPTIONS = [ ["grpc", "gRPC"], ["http/protobuf", "HTTP/protobuf"], @@ -117,6 +130,7 @@ const GROUP_LABELS = { Editor: "에디터", "AI tools": "AI 도구", Media: "미디어 도구", + Project: "프로젝트", "Web deploy": "웹 배포", "Source control": "소스 관리", Advanced: "고급 설정" @@ -146,7 +160,11 @@ const PACKAGE_TEXT = { "claude-code": { note: "Claude Code 명령줄 도구입니다. 공식 설치 순서를 우선 사용합니다." }, "claude-code-telemetry": { label: "Claude Code 관측 로그", note: "Claude Code 실행 로그 설정을 추가합니다." }, "claude-extension": { label: "Claude Code VS Code 확장", note: "VS Code에서 Claude Code를 쓰기 위한 확장입니다." }, - "codex-app": { note: "Codex 데스크톱 앱입니다." }, + "codex-app": { + label: { mac: "Codex App", win: "ChatGPT 데스크톱 앱 (Codex 포함)" }, + note: { mac: "Codex 데스크톱 앱입니다.", win: "OpenAI ChatGPT 데스크톱 앱입니다. Codex가 포함되어 있습니다." } + }, + "project-folder": { label: "프로젝트 폴더", note: "ZIP 주소에서 내려받아 문서 폴더에 풉니다. 기존 폴더를 덮어쓰지 않고, 받은 파일을 실행하지 않습니다." }, codex: { note: "Codex 명령줄 도구입니다. 공식 설치 순서를 우선 사용합니다." }, "codex-telemetry": { label: "Codex 관측 로그", note: "Codex 실행 로그 설정을 추가합니다." }, ffmpeg: { note: "영상과 오디오를 변환하고 자르는 ffmpeg 명령을 설치합니다." }, @@ -233,8 +251,12 @@ const PERMISSION_HELP = { ] }; -function packageLabel(item) { - return PACKAGE_TEXT[item.id]?.label || item.label; +function packageLabel(item, os) { + const label = PACKAGE_TEXT[item.id]?.label; + if (label && typeof label === "object") { + return label[os] || item.label; + } + return label || item.label; } function packageNote(item, os) { @@ -242,7 +264,7 @@ function packageNote(item, os) { const base = typeof note === "object" ? note[os] : note || item.note; const dependencies = (item.deps[os] || []).map((id) => { const dependency = PACKAGE_BY_ID.get(id); - return dependency ? packageLabel(dependency) : SYSTEM_PACKAGE_LABELS[id] || id; + return dependency ? packageLabel(dependency, os) : SYSTEM_PACKAGE_LABELS[id] || id; }); return dependencies.length ? `${base} 필요 항목: ${dependencies.join(", ")} (자동 선택).` : base; } @@ -296,7 +318,7 @@ function SettingTextInput(props) { } function allSelection() { - return new Set(PACKAGES.filter((item) => !ADVANCED_PACKAGE_IDS.has(item.id) && item.id !== "docker").map((item) => item.id)); + return new Set(PACKAGES.filter((item) => !ADVANCED_PACKAGE_IDS.has(item.id) && item.id !== "docker" && item.id !== "project-folder").map((item) => item.id)); } function parseUrlState() { @@ -307,21 +329,29 @@ function parseUrlState() { const params = new URLSearchParams(window.location.search); const targetOs = params.get("os") === "win" ? "win" : "mac"; let selected = allSelection(); + const projectUrl = params.get("project") ?? params.get("projectUrl") ?? ""; + const preset = params.get("preset"); if (params.has("tools")) { selected = new Set(params.get("tools").split(",").filter((id) => PACKAGE_IDS.has(id))); if (selected.has("docker-engine")) { selected.delete("docker"); } + } else if (PRESET_NAMES.has(preset)) { + selected = presetSelection(preset); + } + if (!params.has("tools") && projectUrl) { + selected.add("project-folder"); } selected = selectWithDependencies(selected, targetOs); const settings = { ...DEFAULT_SETTINGS }; for (const key of URL_SETTING_KEYS) { - if (!params.has(key)) { + const paramName = [URL_PARAM_ALIASES[key], key].find((name) => name && params.has(name)); + if (!paramName) { continue; } - const value = params.get(key); + const value = params.get(paramName); settings[key] = typeof DEFAULT_SETTINGS[key] === "boolean" ? value === "1" : value; } @@ -336,15 +366,28 @@ function settingParam(value) { return typeof value === "boolean" ? (value ? "1" : "0") : value; } +function matchingPreset(selected, os, settings) { + const expectedExtra = settings.projectUrl ? ["project-folder"] : []; + return PRESETS.map(([name]) => name).find((name) => { + const expected = selectWithDependencies(new Set([...presetSelection(name), ...expectedExtra]), os); + return expected.size === selected.size && [...expected].every((id) => selected.has(id)); + }); +} + function urlSearch(os, selected, settings) { const params = new URLSearchParams(); params.set("os", os); - params.set("tools", selectedParam(selected, os)); + const preset = matchingPreset(selected, os, settings); + if (preset) { + params.set("preset", preset); + } else { + params.set("tools", selectedParam(selected, os)); + } for (const key of URL_SETTING_KEYS) { const value = settings[key]; if (value !== DEFAULT_SETTINGS[key]) { - params.set(key, settingParam(value)); + params.set(URL_PARAM_ALIASES[key] || key, settingParam(value)); } } @@ -459,6 +502,16 @@ function App() { }); } + function applyPreset(name) { + const base = new Set(presetSelection(name)); + if (settings.projectUrl) { + base.add("project-folder"); + } + setSelected(selectWithDependencies(base, os)); + setStatus(STATUS_TEXT.ready); + setLastAction(""); + } + function updateSetting(key, value) { setSettings((current) => ({ ...current, [key]: value })); } @@ -502,6 +555,45 @@ function App() { ); } + if (item.id === "project-folder") { + const projectErrors = projectFolderErrors(settings); + return ( + + + updateSetting("projectUrl", value)} + placeholder="https://github.com/owner/repo/archive/refs/heads/main.zip" + /> + + updateSetting("projectName", value)} + placeholder="my-project" + /> + updateSetting("projectSha256", value)} + placeholder="64자리 16진수" + /> + + {projectErrors.length ? ( + + {projectErrors.map((message) => {message})} + 입력을 고치기 전에는 프로젝트 폴더 단계가 스크립트에 들어가지 않습니다. + + ) : null} + + + ); + } + if (item.id === "claude-code-telemetry") { return ( @@ -664,6 +756,11 @@ function App() { setSelected(allSelection())} size="sm" variant="secondary" /> setSelected(new Set())} size="sm" variant="secondary" /> + + {PRESETS.map(([name, label]) => ( + applyPreset(name)} size="sm" variant="secondary" /> + ))} + @@ -704,7 +801,7 @@ function App() { > ["install_codex_app"], @@ -197,6 +197,16 @@ export const PACKAGES = [ mac: () => ['brew_formula "yt-dlp" "yt-dlp" "yt-dlp"'], win: () => ["Install-Winget -Label 'yt-dlp' -PackageId 'yt-dlp.yt-dlp' -Command 'yt-dlp' -ExtraArgs @('--scope','user','--skip-dependencies')"] }, + { + id: "project-folder", + group: "Project", + label: "Project folder", + note: "Downloads a zip over HTTPS into Documents. Never overwrites an existing folder and never runs downloaded files.", + presets: [], + deps: { mac: [], win: [] }, + mac: (settings) => projectFolderLines(settings, (url, name, sha) => `install_project_folder ${sh(url)} ${sh(name)} ${sh(sha)}`), + win: (settings) => projectFolderLines(settings, (url, name, sha) => `Install-ProjectFolder -Url ${ps(url)} -Name ${ps(name)} -Sha256 ${ps(sha)}`) + }, { id: "vercel", group: "Web deploy", @@ -298,8 +308,55 @@ function sh(value) { return `'${String(value).replace(/'/g, `'\\''`)}'`; } +// PowerShell treats ASCII ' and the typographic quotes U+2018, U+2019, U+201A, U+201B as single-quote delimiters. +// Doubling any of them inside a single-quoted string yields the literal character. function ps(value) { - return `'${String(value).replace(/'/g, "''")}'`; + return `'${String(value).replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`; +} + +function projectArg(settings, key) { + return String(settings?.[key] ?? "").trim(); +} + +const PROJECT_URL_PATTERN = /^https:\/\/[A-Za-z0-9\-._~:/?#[\]@!$&()*+,;=%]+$/; +const PROJECT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const PROJECT_SHA_PATTERN = /^[0-9a-fA-F]{64}$/; + +// Returns Korean error messages; an empty URL means "no project", so the other fields are ignored. +export function projectFolderErrors(settings) { + const url = projectArg(settings, "projectUrl"); + if (!url) { + return []; + } + const errors = []; + if (!PROJECT_URL_PATTERN.test(url)) { + errors.push("ZIP 주소는 https:// 로 시작해야 하며 공백, 따옴표, 백틱, 한글 같은 문자를 쓸 수 없습니다."); + } + if (!PROJECT_NAME_PATTERN.test(projectArg(settings, "projectName"))) { + errors.push("폴더 이름은 영문 또는 숫자로 시작하고 영문, 숫자, 점, 밑줄, 하이픈만 쓸 수 있습니다(최대 64자)."); + } + const sha = projectArg(settings, "projectSha256"); + if (sha && !PROJECT_SHA_PATTERN.test(sha)) { + errors.push("SHA-256은 64자리 16진수여야 합니다."); + } + return errors; +} + +// Invalid values never reach the script: the step is omitted and the UI shows projectFolderErrors(). +function projectFolderLines(settings, build) { + if (projectFolderErrors(settings).length) { + return []; + } + const url = projectArg(settings, "projectUrl"); + return [url ? build(url, projectArg(settings, "projectName"), projectArg(settings, "projectSha256")) : build("", "", "")]; +} + +// Escapes non-ASCII characters so the generated .bat stays ASCII-only and survives any editor or mail re-encoding. +function psUnicodeEscape(text) { + return [...text].map((char) => { + const code = char.codePointAt(0); + return code < 128 ? char : `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`; + }).join(""); } function boolSetting(settings, key) { @@ -381,6 +438,7 @@ export function autoAdded(original, resolved) { export function buildMacScript(resolved, settings) { const body = []; + const verify = hasMediaTools(resolved); if (resolved.has("homebrew")) { body.push("install_homebrew"); } @@ -390,6 +448,13 @@ export function buildMacScript(resolved, settings) { body.push(...item.mac(settings)); } } + if (verify) { + body.push("", "verify_media_tools"); + } + const macExtras = [ + ...(resolved.has("project-folder") ? [...macProjectFolderHelper(), ""] : []), + ...(verify ? [...macVerifyHelper(resolved), ""] : []) + ]; return [ "#!/bin/bash", "# Generated by Dev Setup Builder.", @@ -706,6 +771,7 @@ export function buildMacScript(resolved, settings) { ' ok "Git identity defaults set"', "}", "", + ...macExtras, "refresh_path", "", ...body, @@ -714,12 +780,190 @@ export function buildMacScript(resolved, settings) { 'if [ "${#FAILED_ITEMS[@]}" -gt 0 ]; then', ' printf "Failed items:\\n"', ' printf " - %s\\n" "${FAILED_ITEMS[@]}"', + ...(verify ? [" show_end_notes"] : []), " exit 1", "fi", - 'printf "Done. Open a new terminal before using newly installed commands.\\n"' + 'printf "Done. Open a new terminal before using newly installed commands.\\n"', + ...(verify ? ["show_end_notes"] : []) ].join("\n"); } + +const MEDIA_TOOL_IDS = ["ffmpeg", "yt-dlp", "deno"]; + +function ko(text) { + return psUnicodeEscape(text); +} + +function winProjectFolderHelper() { + return String.raw`function Install-ProjectFolder { + param([string]$Url, [string]$Name, [string]$Sha256) + Step 'Project folder' + if (-not $Url) { Warn (KR '${ko("프로젝트 URL이 없어 이 단계를 건너뜁니다.")}'); return } + if ($Url -notmatch '^https://[^\s]+$') { Fail (KR '${ko("프로젝트 URL은 https:// 로 시작해야 합니다.")}'); return } + if ($Name -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$') { Fail (KR '${ko("폴더 이름은 영문, 숫자, 점, 밑줄, 하이픈만 쓸 수 있습니다.")}'); return } + if ($Sha256 -and $Sha256 -notmatch '^[0-9a-fA-F]{64}$') { Fail (KR '${ko("SHA-256 값은 64자리 16진수여야 합니다.")}'); return } + $documents = [Environment]::GetFolderPath('MyDocuments') + if (-not $documents) { $documents = Join-Path $env:USERPROFILE 'Documents' } + $target = Join-Path $documents $Name + if (Test-Path -LiteralPath $target) { + $target = "$target-$(Get-Date -Format 'yyyyMMdd')" + if (Test-Path -LiteralPath $target) { Warn ((KR '${ko("같은 이름의 폴더가 이미 있어 건너뜁니다:")}') + " $target"); return } + Warn ((KR '${ko("기존 폴더는 그대로 두고 새 폴더에 저장합니다:")}') + " $target") + } + $zip = Join-Path $env:TEMP ('project-{0}.zip' -f [guid]::NewGuid().ToString('N')) + $stage = Join-Path $env:TEMP ('project-{0}' -f [guid]::NewGuid().ToString('N')) + try { + try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch {} + $response = Invoke-WebRequest -Uri $Url -OutFile $zip -UseBasicParsing -PassThru + $finalUri = $null + try { $finalUri = $response.BaseResponse.ResponseUri } catch {} + if (-not $finalUri) { try { $finalUri = $response.BaseResponse.RequestMessage.RequestUri } catch {} } + if ($finalUri -and $finalUri.Scheme -ne 'https') { Fail (KR '${ko("다운로드가 https가 아닌 주소로 이동해 중단했습니다.")}'); return } + if ($Sha256) { + $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $zip).Hash + if ($actual -ine $Sha256) { Fail ((KR '${ko("SHA-256이 일치하지 않아 중단했습니다. 받은 값:")}') + " $actual"); return } + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + New-Item -ItemType Directory -Path $stage -Force | Out-Null + $sep = [IO.Path]::DirectorySeparatorChar + $stageFull = [IO.Path]::GetFullPath($stage).TrimEnd($sep) + $sep + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + foreach ($entry in $archive.Entries) { + $dest = [IO.Path]::GetFullPath((Join-Path $stage $entry.FullName)) + if (-not $dest.StartsWith($stageFull, [StringComparison]::OrdinalIgnoreCase)) { throw 'unsafe path in zip' } + if ($entry.FullName.EndsWith('/') -or $entry.FullName.EndsWith('\')) { New-Item -ItemType Directory -Path $dest -Force | Out-Null; continue } + New-Item -ItemType Directory -Path (Split-Path -Parent $dest) -Force | Out-Null + [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $dest, $true) + } + } finally { $archive.Dispose() } + $items = @(Get-ChildItem -LiteralPath $stage -Force) + $source = $stage + if ($items.Count -eq 1 -and $items[0].PSIsContainer) { $source = $items[0].FullName } + New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null + Move-Item -LiteralPath $source -Destination $target + Ok ((KR '${ko("프로젝트 폴더를 만들었습니다:")}') + " $target") + } catch { + $_ | Out-String | Add-Content -Path $LogFile + Fail ((KR '${ko("프로젝트 폴더 준비에 실패했습니다. 인터넷 연결과 URL을 확인한 뒤 다시 실행하세요. 로그:")}') + " $LogFile") + } finally { + Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + } +}`.split("\n"); +} + +function winVerifyHelper(resolved) { + const lines = String.raw`function Test-Tool { + param([string]$Label, [string]$Command, [string[]]$VersionArgs) + Refresh-Path + if (-not (Has-Command $Command)) { + Fail ("$Label " + (KR '${ko("실패 - 설치되지 않았습니다. 새 PowerShell 창에서 이 파일을 다시 실행하거나 로그를 확인하세요:")}') + " $LogFile") + return $false + } + $version = '' + try { $version = (& $Command @VersionArgs 2>&1 | Select-Object -First 1 | Out-String).Trim() } catch {} + Ok ("$Label " + (KR '${ko("설치됨")}') + " - $version") + return $true +} + +function Test-MediaTools { + Step (KR '${ko("설치 확인")}')`.split("\n"); + if (resolved.has("codex-app")) { + lines.push(...String.raw` if (Test-CodexApp) { Ok ('ChatGPT ' + (KR '${ko("앱 설치됨")}')) } else { Fail ('ChatGPT ' + (KR '${ko("앱 실패 - Microsoft Store에서 ChatGPT를 직접 설치하세요.")}')) }`.split("\n")); + } + const tools = [["ffmpeg", "FFmpeg", "'ffmpeg' -VersionArgs @('-version')"], ["deno", "Deno", "'deno' -VersionArgs @('--version')"], ["yt-dlp", "yt-dlp", "'yt-dlp' -VersionArgs @('--version')"]]; + for (const [id, label, args] of tools) { + if (resolved.has(id)) { + lines.push(` $null = Test-Tool -Label '${label}' -Command ${args}`); + } + } + if (resolved.has("ffmpeg")) { + lines.push(...String.raw` if (Has-Command 'ffmpeg') { + $filters = '' + try { $filters = (& ffmpeg -hide_banner -filters 2>&1 | Out-String) } catch {} + if ($filters -match 'drawtext') { Ok ('FFmpeg drawtext ' + (KR '${ko("사용 가능")}')) } else { Fail ('FFmpeg drawtext ' + (KR '${ko("실패 - 자막 글자 합성 필터가 없습니다. FFmpeg를 지우고 이 파일을 다시 실행하세요.")}')) } + }`.split("\n")); + } + lines.push("}", ""); + lines.push(...String.raw`function Show-EndNotes { + Write-Host '' + Write-Host (KR '${ko("ChatGPT 앱을 완전히 종료한 뒤 다시 열어 주세요.")}') + Write-Host (KR '${ko("(새로 설치한 도구는 앱을 다시 열어야 인식됩니다.)")}') +}`.split("\n")); + return lines; +} + +function macProjectFolderHelper() { + return String.raw`install_project_folder() { + url="$1"; name="$2"; expected_sha="$3" + info "Project folder" + if [ -z "$url" ]; then warn "프로젝트 URL이 없어 이 단계를 건너뜁니다."; return 0; fi + case "$url" in https://*) ;; *) fail "프로젝트 URL은 https:// 로 시작해야 합니다."; return 1 ;; esac + if ! printf '%s' "$name" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$'; then fail "폴더 이름은 영문, 숫자, 점, 밑줄, 하이픈만 쓸 수 있습니다."; return 1; fi + if [ -n "$expected_sha" ] && ! printf '%s' "$expected_sha" | grep -Eq '^[0-9a-fA-F]{64}$'; then fail "SHA-256 값은 64자리 16진수여야 합니다."; return 1; fi + target="$HOME/Documents/$name" + if [ -e "$target" ]; then + target="$target-$(date +%Y%m%d)" + if [ -e "$target" ]; then warn "같은 이름의 폴더가 이미 있어 건너뜁니다: $target"; return 0; fi + warn "기존 폴더는 그대로 두고 새 폴더에 저장합니다: $target" + fi + work="$(mktemp -d "${"$"}{TMPDIR:-/tmp}/project-folder.XXXXXX")" || { fail "임시 폴더를 만들지 못했습니다."; return 1; } + stage="$work/stage"; zip_file="$work/project.zip"; mkdir -p "$stage" + if ! curl -fL --proto '=https' --proto-redir '=https' -o "$zip_file" "$url" >> "$LOG" 2>&1; then fail "프로젝트 다운로드에 실패했습니다. 인터넷 연결과 URL을 확인하세요."; rm -rf "$work"; return 1; fi + if [ -n "$expected_sha" ]; then + actual_sha="$(shasum -a 256 "$zip_file" | awk '{print tolower($1)}')" + expected_lower="$(printf '%s' "$expected_sha" | tr 'A-F' 'a-f')" + if [ "$actual_sha" != "$expected_lower" ]; then fail "SHA-256이 일치하지 않아 중단했습니다. 받은 값: $actual_sha"; rm -rf "$work"; return 1; fi + fi + if ! unzip -q "$zip_file" -d "$stage" >> "$LOG" 2>&1; then fail "압축을 풀지 못했습니다."; rm -rf "$work"; return 1; fi + rm -rf "$stage/__MACOSX" + source_dir="$stage" + if [ "$(find "$stage" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')" = "1" ] && [ -d "$(find "$stage" -mindepth 1 -maxdepth 1)" ]; then source_dir="$(find "$stage" -mindepth 1 -maxdepth 1)"; fi + mkdir -p "$HOME/Documents" + if mv "$source_dir" "$target"; then ok "프로젝트 폴더를 만들었습니다: $target"; else fail "프로젝트 폴더를 옮기지 못했습니다."; fi + rm -rf "$work" +}`.split("\n"); +} + +function macVerifyHelper(resolved) { + const lines = String.raw`verify_tool() { + label="$1"; command_name="$2"; shift 2 + refresh_path + if has "$command_name"; then + version_line="$("$command_name" "$@" 2>&1 | head -n 1)" + ok "$label 설치됨 - $version_line" + else + fail "$label 실패 - 새 터미널 창에서 이 파일을 다시 실행하거나 로그를 확인하세요: $LOG" + fi +} + +verify_media_tools() { + info "설치 확인"`.split("\n"); + if (resolved.has("codex-app")) { + lines.push(' if app_exists "Codex.app"; then ok "Codex 앱 설치됨"; else fail "Codex 앱 실패 - 이 파일을 다시 실행하세요."; fi'); + } + if (resolved.has("ffmpeg")) lines.push(' verify_tool "FFmpeg" ffmpeg -version'); + if (resolved.has("deno")) lines.push(' verify_tool "Deno" deno --version'); + if (resolved.has("yt-dlp")) lines.push(' verify_tool "yt-dlp" yt-dlp --version'); + if (resolved.has("ffmpeg")) { + lines.push(...String.raw` if has ffmpeg; then + filters_output="$(ffmpeg -hide_banner -filters 2>&1 || true)" + case "$filters_output" in + *drawtext*) ok "FFmpeg drawtext 사용 가능" ;; + *) fail "FFmpeg drawtext 실패 - 자막 글자 합성 필터가 없습니다. brew reinstall ffmpeg 를 실행하세요." ;; + esac + fi`.split("\n")); + } + lines.push("}", "", "show_end_notes() {", ' printf "\\nChatGPT 앱을 완전히 종료한 뒤 다시 열어 주세요.\\n"', ' printf "(새로 설치한 도구는 앱을 다시 열어야 인식됩니다.)\\n"', "}"); + return lines; +} + +function hasMediaTools(resolved) { + return MEDIA_TOOL_IDS.some((id) => resolved.has(id)); +} + const PS_FUNCTION_START = /^function ([\w-]+)/; function escapeRegExp(text) { @@ -771,6 +1015,16 @@ export function buildWindowsScript(resolved, settings) { body.push(...item.win(settings)); } } + const verify = hasMediaTools(resolved); + const extraHelpers = [ + "function KR([string]$Escaped) { return [regex]::Unescape($Escaped) }", + "", + ...(resolved.has("project-folder") ? [...winProjectFolderHelper(), ""] : []), + ...(verify ? [...winVerifyHelper(resolved), ""] : []) + ]; + if (verify) { + body.push("", "Test-MediaTools"); + } const header = [ "@echo off", "rem Generated by Dev Setup Builder.", @@ -1093,15 +1347,15 @@ export function buildWindowsScript(resolved, settings) { "}", "", "function Install-CodexApp {", - " Step 'Codex App'", - " if (Test-CodexApp) { Ok 'Codex App installed'; return }", - " if (-not (Has-Command 'winget')) { Fail 'Codex App (winget missing)'; return }", - " # Official install docs: https://developers.openai.com/codex/app/windows", + " Step 'ChatGPT desktop app (includes Codex)'", + " if (Test-CodexApp) { Ok 'ChatGPT desktop app installed'; return }", + " if (-not (Has-Command 'winget')) { Fail 'ChatGPT desktop app (winget missing)'; return }", + " # Official install docs: https://learn.chatgpt.com/docs/windows/windows-app (Store product ID 9PLM9XGG6VKS)", " & winget install --id 9PLM9XGG6VKS --exact --source msstore --accept-source-agreements --accept-package-agreements --silent --disable-interactivity *>> $LogFile", " $exitCode = $LASTEXITCODE", " Refresh-Path", - " if (Test-CodexApp) { Ok 'Codex App installed'; return }", - " if ($exitCode -eq 0) { Ok 'Codex App installer completed; launch from Start menu if needed' } else { Fail 'Codex App' }", + " if (Test-CodexApp) { Ok 'ChatGPT desktop app installed'; return }", + " if ($exitCode -eq 0) { Ok 'ChatGPT desktop app installer completed; launch from Start menu if needed' } else { Fail 'ChatGPT desktop app' }", "}", "", "function Set-ClaudeCodeTelemetry {", @@ -1228,6 +1482,7 @@ export function buildWindowsScript(resolved, settings) { "}", "", ]; + const endNotes = verify ? [" Show-EndNotes"] : []; const footer = [ "Refresh-Path", "", @@ -1238,12 +1493,14 @@ export function buildWindowsScript(resolved, settings) { "if ($script:Failed.Count -gt 0) {", " Write-Host 'Failed items:'", " foreach ($item in $script:Failed) { Write-Host \" - $item\" }", + ...endNotes, " exit 1", "}", "Write-Host 'Done. Open a new terminal before using newly installed commands.'", + ...endNotes.map((line) => line.trim()), "exit 0" ]; - return [...header, ...pruneUnusedFunctions(helpers, footer), ...footer].join("\r\n"); + return [...header, ...pruneUnusedFunctions([...helpers, ...extraHelpers], footer), ...footer].join("\r\n"); } export function buildScript(ids, os, settings) { diff --git a/src/styles.css b/src/styles.css index e697ec8..87d31d8 100644 --- a/src/styles.css +++ b/src/styles.css @@ -172,6 +172,13 @@ body { gap: 8px; } +.preset-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; +} + .package-list { overflow-y: auto; overflow-x: hidden; @@ -780,3 +787,10 @@ body { margin: 0 14px 14px; } } + +.project-errors { + margin: 8px 0 0; + padding-left: 18px; + color: #b42318; + font-size: 13px; +} diff --git a/tests/e2e/app.spec.js b/tests/e2e/app.spec.js index bbd368a..9225776 100644 --- a/tests/e2e/app.spec.js +++ b/tests/e2e/app.spec.js @@ -26,7 +26,7 @@ test("builds scripts and captures primary states", async ({ page }) => { await expect(page.getByRole("heading", { name: "개발 환경 설치 도우미" })).toBeVisible(); await expect(page.getByRole("radio", { name: "macOS" })).toHaveAttribute("aria-checked", "true"); await expect(toolList.getByRole("checkbox", { name: /Windows WSL2/ })).toHaveCount(0); - await expect(toolList.getByRole("checkbox")).toHaveCount(22); + await expect(toolList.getByRole("checkbox")).toHaveCount(23); await expect(toolList.getByRole("checkbox", { name: /Bun/ })).toBeChecked(); await expect(toolList.getByRole("checkbox", { name: /Codex App/ })).toBeChecked(); await expect(toolList.getByRole("checkbox", { name: /Git 사용자 정보 기본값/ })).toBeChecked(); @@ -239,3 +239,64 @@ test("checks dependencies and removes dependents consistently", async ({ page }) await expect(wsl2).not.toBeChecked(); await expect(engine).not.toBeChecked(); }); + +test("preselects the video-class preset from the URL and fills project fields", async ({ page }) => { + await page.goto("./?os=win&preset=video-class&project=https%3A%2F%2Fexample.com%2Flab.zip&name=kaist-shorts-lab"); + + const toolList = page.getByLabel("설치할 도구"); + const preview = page.getByRole("textbox", { name: "생성된 설치 스크립트" }); + + for (const name of [/ChatGPT 데스크톱 앱 \(Codex 포함\)/, /FFmpeg/, /yt-dlp/, /Deno/, /프로젝트 폴더/]) { + await expect(toolList.getByRole("checkbox", { name })).toBeChecked(); + } + for (const name of [/Windows WSL2/, /^Node\.js/]) { + await expect(toolList.getByRole("checkbox", { name })).not.toBeChecked(); + } + await expect(page.getByRole("textbox", { name: /ZIP 주소/ })).toHaveValue("https://example.com/lab.zip"); + await expect(page.getByRole("textbox", { name: "폴더 이름" })).toHaveValue("kaist-shorts-lab"); + await expect(preview).toHaveValue(/Install-ProjectFolder -Url 'https:\/\/example\.com\/lab\.zip' -Name 'kaist-shorts-lab'/); + await expect(preview).toHaveValue(/Test-MediaTools/); + await expect(preview).not.toHaveValue(/irm https|Invoke-Expression/); + await expect.poll(() => page.url()).toContain("preset=video-class"); + await expect.poll(() => page.url()).toContain("project=https%3A%2F%2Fexample.com%2Flab.zip"); + await expect.poll(() => page.url()).toContain("name=kaist-shorts-lab"); +}); + +test("applies preset buttons and copies a preset link", async ({ page }) => { + await page.goto("./?os=win"); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(page.url()).origin }); + + await page.getByRole("button", { name: "영상 수업" }).click(); + const toolList = page.getByLabel("설치할 도구"); + await expect(toolList.getByRole("checkbox", { name: /FFmpeg/ })).toBeChecked(); + await expect(toolList.getByRole("checkbox", { name: /Node\.js/ })).not.toBeChecked(); + await expect(page.getByRole("textbox", { name: "생성된 설치 스크립트" })).toHaveValue(/Test-MediaTools/); + + await page.getByRole("button", { name: /링크 복사/ }).click(); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + expect(copied).toContain("os=win"); + expect(copied).toContain("preset=video-class"); + expect(copied).not.toContain("tools="); + + await page.getByRole("button", { name: "기본 개발 환경" }).click(); + await expect(toolList.getByRole("checkbox", { name: /FFmpeg/ })).not.toBeChecked(); + await expect(toolList.getByRole("checkbox", { name: /^Node\.js/ })).toBeChecked(); +}); + +test("shows the macOS Codex label and the Windows ChatGPT label", async ({ page }) => { + await page.goto("./?os=mac"); + await expect(page.getByLabel("설치할 도구").getByRole("checkbox", { name: /Codex App/ })).toBeVisible(); + await page.getByRole("radio", { name: "Windows" }).click(); + await expect(page.getByLabel("설치할 도구").getByRole("checkbox", { name: /ChatGPT 데스크톱 앱 \(Codex 포함\)/ })).toBeVisible(); +}); + +test("rejects unsafe project values from a shared link", async ({ page }) => { + const url = encodeURIComponent("https://x/a’;calc;’"); + await page.goto(`./?os=win&preset=video-class&project=${url}&name=${encodeURIComponent("a$(calc)")}`); + + const preview = page.getByRole("textbox", { name: "생성된 설치 스크립트" }); + await expect(page.getByRole("alert").filter({ hasText: "ZIP 주소는 https://" })).toBeVisible(); + await expect(page.getByRole("alert").filter({ hasText: "폴더 이름은" })).toBeVisible(); + await expect(preview).not.toHaveValue(/Install-ProjectFolder -Url/); + await expect(preview).not.toHaveValue(/calc/); +}); diff --git a/tests/mac.test.js b/tests/mac.test.js index 864d4c8..d7ada61 100644 --- a/tests/mac.test.js +++ b/tests/mac.test.js @@ -1,4 +1,8 @@ import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { PACKAGES, buildMacScript, @@ -32,6 +36,54 @@ assert.match(videoClassMacScript, /brew_formula "Deno" "deno" "deno"/); assert.match(videoClassMacScript, /brew_formula "yt-dlp" "yt-dlp" "yt-dlp"/); assert.equal(videoClassMacScript.indexOf('brew_formula "Deno"') < videoClassMacScript.indexOf('brew_formula "yt-dlp"'), true); +assert.match(videoClassMacScript, /verify_media_tools/); +assert.match(videoClassMacScript, /ffmpeg -hide_banner -filters/); +assert.match(videoClassMacScript, /drawtext/); +assert.match(videoClassMacScript, /ChatGPT 앱을 완전히 종료한 뒤 다시 열어 주세요/); +assert.doesNotMatch(buildMacScript(resolveSelection(new Set(["pnpm"]), "mac"), settings), /verify_media_tools|show_end_notes/); +assert.doesNotMatch(videoClassMacScript, /install_project_folder\(\)/); + +const projectMac = buildMacScript(resolveSelection(new Set(["project-folder"]), "mac"), { ...settings, projectUrl: "https://example.com/a;b$c.zip", projectName: "lab", projectSha256: "" }); +assert.match(projectMac, /install_project_folder 'https:\/\/example\.com\/a;b\$c\.zip' 'lab' ''/); +assert.match(projectMac, /--proto '=https' --proto-redir '=https'/); +assert.match(projectMac, /\$HOME\/Documents\/\$name/); +assert.doesNotMatch(projectMac, /\beval\b.*\$zip|source "\$stage|bash "\$stage/); + +{ + // Run the generated macOS project-folder function with a stubbed curl and a temporary HOME. + const work = mkdtempSync(join(tmpdir(), "dev-setup-project-mac-")); + try { + mkdirSync(join(work, "src", "repo-main", "sub"), { recursive: true }); + writeFileSync(join(work, "src", "repo-main", "README.md"), "# demo\n"); + writeFileSync(join(work, "src", "repo-main", "sub", "a.txt"), "hi\n"); + const zipPath = join(work, "p.zip"); + assert.equal(spawnSync("zip", ["-qr", zipPath, "repo-main"], { cwd: join(work, "src") }).status, 0); + const sha = spawnSync("shasum", ["-a", "256", zipPath], { encoding: "utf8" }).stdout.split(" ")[0]; + const fnStart = projectMac.indexOf("install_project_folder() {"); + const fnEnd = projectMac.indexOf("\nrefresh_path\n"); + const home = join(work, "home"); + mkdirSync(home); + const run = (call) => spawnSync("bash", ["-c", [ + "set -u", + `HOME='${home}'; TMPDIR='${work}'; LOG='${join(work, "log.txt")}'`, + 'info() { :; }; ok() { echo "OK: $1"; }; warn() { echo "WARN: $1"; }; fail() { echo "FAIL: $1"; }', + `curl() { out=""; while [ $# -gt 0 ]; do [ "$1" = "-o" ] && out="$2"; shift; done; cp '${zipPath}' "$out"; }`, + projectMac.slice(fnStart, fnEnd), + call + ].join("\n")], { encoding: "utf8" }); + const first = run(`install_project_folder 'https://example.com/r.zip' 'lab' '${sha.toUpperCase()}'`); + assert.match(first.stdout, /OK: .*lab/); + assert.equal(readFileSync(join(home, "Documents", "lab", "sub", "a.txt"), "utf8"), "hi\n"); + assert.match(run("install_project_folder 'https://example.com/r.zip' 'lab' ''").stdout, /WARN: .*lab-\d{8}/); + assert.match(run(`install_project_folder 'https://example.com/r.zip' 'other' '${"0".repeat(64)}'`).stdout, /FAIL: .*SHA-256/); + assert.match(run("install_project_folder 'http://example.com/r.zip' 'x' ''").stdout, /FAIL:/); + assert.match(run("install_project_folder 'https://example.com/r.zip' '../x' ''").stdout, /FAIL:/); + assert.match(run("install_project_folder '' 'x' ''").stdout, /WARN:/); + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + const claudeCode = resolveSelection(new Set(["claude-code"]), "mac"); const claudeCodeScript = buildMacScript(claudeCode, settings); const claudeNativeIndex = claudeCodeScript.indexOf("https://claude.ai/install.sh"); diff --git a/tests/windows.test.js b/tests/windows.test.js index d07d76b..00441bf 100644 --- a/tests/windows.test.js +++ b/tests/windows.test.js @@ -4,7 +4,9 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { join } from "node:path"; import { + buildMacScript, buildWindowsScript, + projectFolderErrors, presetSelection, resolveSelection, selfTest @@ -66,6 +68,20 @@ const pnpmOnly = buildWindowsScript(resolveSelection(new Set(["pnpm"]), "win"), assert.doesNotMatch(pnpmOnly, /function Install-CodexApp/); assert.doesNotMatch(videoClassScript, /^Set-(ClaudeCode|Codex)Telemetry /m); +// Generated .bat stays ASCII-only; Korean text is emitted as \\uXXXX escapes decoded by PowerShell. +assert.equal(/[^\x00-\x7f]/.test(videoClassScript), false); +assert.match(videoClassScript, /function KR\(\[string\]\$Escaped\) \{ return \[regex\]::Unescape\(\$Escaped\) \}/); +assert.match(videoClassScript, /(^|\r\n)Test-MediaTools(\r\n|$)/); +assert.match(videoClassScript, /ffmpeg -hide_banner -filters/); +assert.match(videoClassScript, /drawtext/); +assert.match(videoClassScript, /function Show-EndNotes/); +assert.match(videoClassScript, /\r\nShow-EndNotes\r\nexit 0$/); +assert.match(videoClassScript, /ChatGPT \\uC571\\uC744 \\uC644\\uC804\\uD788 \\uC885\\uB8CC/); +assert.doesNotMatch(videoClassScript, /function Install-ProjectFolder/); +assert.doesNotMatch(buildWindowsScript(resolveSelection(new Set(["pnpm"]), "win"), settings), /Test-MediaTools|Show-EndNotes/); +assert.match(buildWindowsScript(resolveSelection(new Set(["codex-app"]), "win"), settings), /ChatGPT desktop app \(includes Codex\)/); +assert.match(videoClassScript, /9PLM9XGG6VKS/); + const ytDlp = resolveSelection(new Set(["yt-dlp"]), "win"); assert.equal(ytDlp.has("deno"), true); @@ -128,6 +144,128 @@ assert.match(commandDetector, /--version/); assert.match(pythonBody, /-DeferFailure/); assert.match(pythonBody, /if \(-not \$pythonOk\) \{ Fail 'Python' \}/); +// Project folder: static content checks. +const projectSettings = { ...settings, projectUrl: "https://example.com/a;b$c/repo.zip", projectName: "kaist-shorts-lab", projectSha256: "" }; +const projectScript = buildWindowsScript(resolveSelection(new Set(["project-folder"]), "win"), projectSettings); +assert.match(projectScript, /Install-ProjectFolder -Url 'https:\/\/example\.com\/a;b\$c\/repo\.zip' -Name 'kaist-shorts-lab' -Sha256 ''/); +assert.match(projectScript, /\^https:\/\//); +assert.match(projectScript, /Get-FileHash -Algorithm SHA256/); +assert.match(projectScript, /unsafe path in zip/); +assert.doesNotMatch(projectScript, /Expand-Archive|Start-Process|Invoke-Expression|\biex\b|\birm\b/); +assert.equal(/[^\x00-\x7f]/.test(projectScript), false); + +// Injection payloads must be rejected and never reach the generated script. +{ + const goodName = "lab"; + const goodUrl = "https://example.com/a.zip"; + const badUrls = [ + "https://x/a\u2019;calc;\u2019", + "https://x/a\u2018;calc;\u2018", + "https://x/a\u201A;calc;\u201B", + "https://x/a';calc;'", + 'https://x/a";calc;"', + "https://x/a`calc`", + "https://x/a b.zip", + "https://x/a\nInvoke-Expression x", + "http://x/a.zip", + "https://x/\uD55C\uAE00.zip" + ]; + const badNames = ["a\u2019;calc;\u2019", "a\u2018b", "a;b", "a$(calc)", "a`calc`", "a b", "../x", "", ".hidden", "x".repeat(65)]; + for (const url of badUrls) { + assert.equal(projectFolderErrors({ projectUrl: url, projectName: goodName }).length > 0, true, `url ${JSON.stringify(url)}`); + } + for (const name of badNames) { + assert.equal(projectFolderErrors({ projectUrl: goodUrl, projectName: name }).length > 0, true, `name ${JSON.stringify(name)}`); + } + assert.equal(projectFolderErrors({ projectUrl: goodUrl, projectName: goodName, projectSha256: "g".repeat(64) }).length > 0, true); + assert.equal(projectFolderErrors({ projectUrl: goodUrl, projectName: goodName, projectSha256: "ab" }).length > 0, true); + assert.equal(projectFolderErrors({ projectUrl: goodUrl, projectName: goodName, projectSha256: "A".repeat(64) }).length, 0); + assert.equal(projectFolderErrors({ projectUrl: "", projectName: "ignored;value" }).length, 0); + + const select = new Set(["project-folder"]); + for (const bad of [ + { projectUrl: "https://x/a\u2019;calc;\u2019", projectName: goodName }, + { projectUrl: goodUrl, projectName: "a\u2019;calc;\u2019" }, + { projectUrl: goodUrl, projectName: "a$(calc)" }, + { projectUrl: goodUrl, projectName: goodName, projectSha256: "x'; calc; '" } + ]) { + const out = buildWindowsScript(resolveSelection(select, "win"), { ...settings, ...bad }); + assert.doesNotMatch(out, /(^|\r\n)Install-ProjectFolder /); + assert.doesNotMatch(out, /calc/); + const mac = buildMacScript(resolveSelection(select, "mac"), { ...settings, ...bad }); + assert.doesNotMatch(mac, /(^|\n)install_project_folder /); + assert.doesNotMatch(mac, /calc/); + } + + // ps() doubles typographic single quotes too (checked through another free-text setting). + const quoted = buildWindowsScript(resolveSelection(new Set(["git", "git-config"]), "win"), { + gitName: "a\u2019;calc;\u2019 b\u2018c\u201Ad\u201Be'f", + gitEmail: "x@example.com" + }); + assert.match(quoted, /-Name 'a\u2019\u2019;calc;\u2019\u2019 b\u2018\u2018c\u201A\u201Ad\u201B\u201Be''f'/); +} + +// Project folder: run the generated function in PowerShell with a stubbed download. +{ + const work = mkdtempSync(join(tmpdir(), "dev-setup-project-")); + try { + const zipSource = join(work, "src"); + mkdirSync(join(zipSource, "repo-main", "sub"), { recursive: true }); + writeFileSync(join(zipSource, "repo-main", "README.md"), "# demo\n"); + writeFileSync(join(zipSource, "repo-main", "sub", "a.txt"), "hi\n"); + const zipPath = join(work, "p.zip"); + const zipResult = spawnSync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", `Add-Type -AssemblyName System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory('${zipSource}', '${zipPath}')`], { encoding: "utf8" }); + assert.equal(zipResult.status, 0, zipResult.stderr || zipResult.stdout); + const sha = spawnSync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", `(Get-FileHash -Algorithm SHA256 -LiteralPath '${zipPath}').Hash`], { encoding: "utf8" }).stdout.trim(); + assert.match(sha, /^[0-9A-F]{64}$/); + + const fnStart = projectScript.indexOf("function KR"); + const fnEnd = projectScript.indexOf("\r\nRefresh-Path\r\n"); + const helperText = projectScript.slice(fnStart, fnEnd) + .replace("[Environment]::GetFolderPath('MyDocuments')", `'${join(work, "Documents")}'`); + const run = (calls) => spawnSync("pwsh", ["-NoProfile", "-NonInteractive", "-Command", "-"], { + input: [ + "$script:Failed = @()", + `$env:TEMP = '${work}'`, + "$LogFile = Join-Path $env:TEMP 'log.txt'", + "function Step([string]$Text) {}", + "function Ok([string]$Text) { Write-Output \"OK: $Text\" }", + "function Warn([string]$Text) { Write-Output \"WARN: $Text\" }", + "function Fail([string]$Text) { Write-Output \"FAIL: $Text\"; $script:Failed += $Text }", + `function Invoke-WebRequest { param($Uri, $OutFile, [switch]$UseBasicParsing, [switch]$PassThru) Copy-Item '${zipPath}' $OutFile; return [pscustomobject]@{ BaseResponse = [pscustomobject]@{ ResponseUri = [uri]$Uri } } }`, + helperText, + ...calls + ].join("\n"), + encoding: "utf8", + env: { ...process.env, LC_ALL: "C.UTF-8" } + }); + const url = "https://example.com/repo.zip"; + const first = run([`Install-ProjectFolder -Url '${url}' -Name 'lab' -Sha256 '${sha.toLowerCase()}'`]); + assert.match(first.stdout, /OK: .*lab/); + assert.equal(readFileSync(join(work, "Documents", "lab", "README.md"), "utf8"), "# demo\n"); + assert.equal(readFileSync(join(work, "Documents", "lab", "sub", "a.txt"), "utf8"), "hi\n"); + + const second = run([`Install-ProjectFolder -Url '${url}' -Name 'lab' -Sha256 ''`]); + assert.match(second.stdout, /WARN: .*lab-\d{8}/); + assert.equal(readFileSync(join(work, "Documents", "lab", "README.md"), "utf8"), "# demo\n"); + + const third = run([`Install-ProjectFolder -Url '${url}' -Name 'lab' -Sha256 ''`]); + assert.match(third.stdout, /WARN: .*lab-\d{8}/); + assert.doesNotMatch(third.stdout, /OK:/); + + const mismatch = run([`Install-ProjectFolder -Url '${url}' -Name 'other' -Sha256 '${"0".repeat(64)}'`]); + assert.match(mismatch.stdout, /FAIL: .*SHA-256/); + assert.equal(spawnSync("pwsh", ["-NoProfile", "-Command", `Test-Path '${join(work, "Documents", "other")}'`], { encoding: "utf8" }).stdout.trim(), "False"); + + for (const [name, args] of [["http", `-Url 'http://example.com/a.zip' -Name 'x' -Sha256 ''`], ["name", `-Url '${url}' -Name '../x' -Sha256 ''`], ["sha", `-Url '${url}' -Name 'x' -Sha256 'zz'`]]) { + assert.match(run([`Install-ProjectFolder ${args}`]).stdout, /FAIL:/, name); + } + assert.match(run(["Install-ProjectFolder -Url '' -Name 'x' -Sha256 ''"]).stdout, /WARN:/); + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + const claudeTelemetry = resolveSelection(new Set(["claude-code-telemetry"]), "win"); const claudeTelemetryScript = buildWindowsScript(claudeTelemetry, { ...settings,