ts-pantry 0.11.166 → 0.11.167

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,L,W,ke,ve,n,X,z,u,Z,E,_,O,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-45qn2m08.js";import{a,C}from"../chunk-tbmjqfgg.js";import"../chunk-azp1r9fw.js";import"../chunk-3bs6jc4d.js";import{Sa}from"../chunk-q48x6dfb.js";import{d}from"../chunk-05jvxr50.js";import m from"node:fs";import v from"node:path";import s from"node:process";C();async function ae(t="src/pantry"){if(!m.existsSync(t))throw Error(`Pantry directory not found: ${t}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function o(i,c=""){let g=m.readdirSync(i,{withFileTypes:!0}),p=v.join(i,"package.yml");if(c&&m.existsSync(p))e.push(c);for(let S of g)if(S.isDirectory()&&!S.name.startsWith(".")){let w=c?`${c}/${S.name}`:S.name,x=v.join(i,S.name);o(x,w)}}return o(t),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ce(t=!1){async function e(p){let S=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(S.searchParams.set("list-type","2"),S.searchParams.set("prefix",""),S.searchParams.set("max-keys","1000"),p)S.searchParams.set("continuation-token",p);let w=await fetch(S.toString());if(!w.ok)throw Error(`Failed to fetch S3 listing: ${w.status}`);let x=await w.text(),B=[],J=x.match(/<Key>([^<]+)<\/Key>/g);if(J)for(let G of J){let U=G.replace(/<Key>([^<]+)<\/Key>/,"$1");B.push({Key:U})}let y=x.includes("<IsTruncated>true</IsTruncated>"),F=x.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),h=F?F[1]:void 0;return{IsTruncated:y,NextContinuationToken:h,Contents:B}}console.log("Scraping packages from S3 registry...");let o=new Set,i;do{let p=await e(i);for(let S of p.Contents){let w=S.Key,x=w.split("/");if(x.length===0)continue;if(x[0].startsWith(".")||x[0].includes(" ")||w.match(/\.(md|txt|yml|yaml|json)$/i))continue;let B=["darwin","linux","windows"],J=-1;for(let y=1;y<x.length;y++)if(B.includes(x[y])){J=y;break}if(J>0){let y=x.slice(0,J).join("/");if(y.includes("."))o.add(y)}else if(x.length>=2&&x[0].includes(".")&&!x[1].startsWith("v")&&!x[1].match(/^\d/)){let y=`${x[0]}/${x[1]}`;o.add(y)}else if(x.length>=1&&x[0].includes("."))o.add(x[0])}i=p.NextContinuationToken,console.log(`Found ${o.size} packages so far...`)}while(i);let c=Array.from(o).sort(),g=[];for(let p of c){if(!p.includes(".")||p.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(p.endsWith("/README.rst")||p.endsWith("/README")||p.includes("/docs/"))continue;if(p.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(p))continue;g.push(p)}return console.log(`\uD83D\uDCE6 Found ${g.length} valid packages in registry`),g}async function le(t,e){let i=`/**
2
+ import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,L,W,ke,ve,n,X,z,u,Z,E,_,O,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-nr2yvehm.js";import{a,C}from"../chunk-365xgy2v.js";import"../chunk-frrv46sd.js";import"../chunk-3sc39cqf.js";import{Sa}from"../chunk-0e4jg545.js";import{d}from"../chunk-egf4sf0n.js";import m from"node:fs";import v from"node:path";import s from"node:process";C();async function ae(t="src/pantry"){if(!m.existsSync(t))throw Error(`Pantry directory not found: ${t}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function o(i,c=""){let g=m.readdirSync(i,{withFileTypes:!0}),p=v.join(i,"package.yml");if(c&&m.existsSync(p))e.push(c);for(let S of g)if(S.isDirectory()&&!S.name.startsWith(".")){let w=c?`${c}/${S.name}`:S.name,x=v.join(i,S.name);o(x,w)}}return o(t),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ce(t=!1){async function e(p){let S=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(S.searchParams.set("list-type","2"),S.searchParams.set("prefix",""),S.searchParams.set("max-keys","1000"),p)S.searchParams.set("continuation-token",p);let w=await fetch(S.toString());if(!w.ok)throw Error(`Failed to fetch S3 listing: ${w.status}`);let x=await w.text(),B=[],J=x.match(/<Key>([^<]+)<\/Key>/g);if(J)for(let G of J){let U=G.replace(/<Key>([^<]+)<\/Key>/,"$1");B.push({Key:U})}let y=x.includes("<IsTruncated>true</IsTruncated>"),F=x.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),h=F?F[1]:void 0;return{IsTruncated:y,NextContinuationToken:h,Contents:B}}console.log("Scraping packages from S3 registry...");let o=new Set,i;do{let p=await e(i);for(let S of p.Contents){let w=S.Key,x=w.split("/");if(x.length===0)continue;if(x[0].startsWith(".")||x[0].includes(" ")||w.match(/\.(md|txt|yml|yaml|json)$/i))continue;let B=["darwin","linux","windows"],J=-1;for(let y=1;y<x.length;y++)if(B.includes(x[y])){J=y;break}if(J>0){let y=x.slice(0,J).join("/");if(y.includes("."))o.add(y)}else if(x.length>=2&&x[0].includes(".")&&!x[1].startsWith("v")&&!x[1].match(/^\d/)){let y=`${x[0]}/${x[1]}`;o.add(y)}else if(x.length>=1&&x[0].includes("."))o.add(x[0])}i=p.NextContinuationToken,console.log(`Found ${o.size} packages so far...`)}while(i);let c=Array.from(o).sort(),g=[];for(let p of c){if(!p.includes(".")||p.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(p.endsWith("/README.rst")||p.endsWith("/README")||p.includes("/docs/"))continue;if(p.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(p))continue;g.push(p)}return console.log(`\uD83D\uDCE6 Found ${g.length} valid packages in registry`),g}async function le(t,e){let i=`/**
3
3
  * Constants used throughout the ts-pantry package
4
4
  * This file is auto-generated from ${e}. Do not edit manually.
5
5
  * Generated on ${new Date().toISOString()}
@@ -62,17 +62,17 @@ ${c.join(`
62
62
  Conflicts found:`),y.conflicts.forEach((h)=>{console.log(` ${h.package}: ${h.versions.join(", ")}`)});if(console.log(`
63
63
  \uD83D\uDCCB All unique packages to install:`),y.uniquePackages.forEach((h,G)=>{let U=y.allDependencies.find((N)=>N.name===h),P=U&&U.version&&U.version!=="latest"?` (${U.version})`:"";console.log(` ${G+1}. ${h}${P}`)}),x)console.log(`
64
64
  \uD83D\uDE80 Install command:`),console.log(`pantry install ${y.uniquePackages.join(" ")}`);if(Object.values(y.osSpecificDeps).reduce((h,G)=>h+G.length,0)>0)console.log(`
65
- \uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(y.osSpecificDeps).forEach(([h,G])=>{if(G.length>0)console.log(` ${h}: ${G.map((U)=>U.name).join(", ")}`)})}s.exit(0)}catch(o){if(e.json){let i={success:!1,error:String(o),timestamp:new Date().toISOString()};console.log(JSON.stringify(i))}else console.error("Error resolving dependencies:",o);s.exit(1)}});j.command("get-php-versions","Get PHP versions suitable for CI/CD workflows").option("--format <type>","Output format: json (default), yaml, or csv",{default:"json"}).option("--branches <branches>","Comma-separated list of PHP branches to include (e.g., 8.4,8.3,8.2)").option("--fallback <versions>","Comma-separated list of fallback versions if detection fails").action(async(t)=>{try{let{getPhpVersionsForWorkflow:e}=await import("../chunk-0187s9a8.js"),o={};if(t.branches)o.supportedBranches=t.branches.split(",").map((c)=>c.trim());if(t.fallback)o.fallbackVersions=t.fallback.split(",").map((c)=>c.trim());let i=e(o);switch(t.format.toLowerCase()){case"yaml":console.log(`php_versions:
65
+ \uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(y.osSpecificDeps).forEach(([h,G])=>{if(G.length>0)console.log(` ${h}: ${G.map((U)=>U.name).join(", ")}`)})}s.exit(0)}catch(o){if(e.json){let i={success:!1,error:String(o),timestamp:new Date().toISOString()};console.log(JSON.stringify(i))}else console.error("Error resolving dependencies:",o);s.exit(1)}});j.command("get-php-versions","Get PHP versions suitable for CI/CD workflows").option("--format <type>","Output format: json (default), yaml, or csv",{default:"json"}).option("--branches <branches>","Comma-separated list of PHP branches to include (e.g., 8.4,8.3,8.2)").option("--fallback <versions>","Comma-separated list of fallback versions if detection fails").action(async(t)=>{try{let{getPhpVersionsForWorkflow:e}=await import("../chunk-e20vgg36.js"),o={};if(t.branches)o.supportedBranches=t.branches.split(",").map((c)=>c.trim());if(t.fallback)o.fallbackVersions=t.fallback.split(",").map((c)=>c.trim());let i=e(o);switch(t.format.toLowerCase()){case"yaml":console.log(`php_versions:
66
66
  ${i.map((c)=>` - "${c}"`).join(`
67
- `)}`);break;case"csv":console.log(i.join(","));break;case"json":default:console.log(JSON.stringify(i));break}s.exit(0)}catch(e){console.error("Error getting PHP versions:",e),s.exit(1)}});j.command("generate-zig","Generate Zig package definitions from TypeScript packages").option("--packages-dir <dir>","Directory containing TypeScript package files",{default:"src/packages"}).option("--output <file>","Output Zig file path",{default:"packages.zig"}).option("--aliases","Also generate aliases file").option("--aliases-output <file>","Output file for Zig aliases",{default:"aliases.zig"}).action(async(t)=>{try{let{generateZigDefinitions:e,generateZigAliases:o}=await import("../chunk-h1jf79nn.js"),{packagesDir:i="src/packages",output:c="packages.zig",aliases:g=!1,aliasesOutput:p="aliases.zig"}=t;if(console.log("\uD83D\uDE80 Generating Zig package definitions..."),await e(i,c),g)console.log(`
67
+ `)}`);break;case"csv":console.log(i.join(","));break;case"json":default:console.log(JSON.stringify(i));break}s.exit(0)}catch(e){console.error("Error getting PHP versions:",e),s.exit(1)}});j.command("generate-zig","Generate Zig package definitions from TypeScript packages").option("--packages-dir <dir>","Directory containing TypeScript package files",{default:"src/packages"}).option("--output <file>","Output Zig file path",{default:"packages.zig"}).option("--aliases","Also generate aliases file").option("--aliases-output <file>","Output file for Zig aliases",{default:"aliases.zig"}).action(async(t)=>{try{let{generateZigDefinitions:e,generateZigAliases:o}=await import("../chunk-wgpsgdr0.js"),{packagesDir:i="src/packages",output:c="packages.zig",aliases:g=!1,aliasesOutput:p="aliases.zig"}=t;if(console.log("\uD83D\uDE80 Generating Zig package definitions..."),await e(i,c),g)console.log(`
68
68
  \uD83D\uDE80 Generating Zig package aliases...`),await o(i,p);console.log(`
69
- ✅ Zig code generation complete!`),s.exit(0)}catch(e){console.error("Error generating Zig definitions:",e),s.exit(1)}});j.command("release [type]","Release a Zig package (changelog, bump, commit, tag, push, publish)").option("-y, --yes","Non-interactive mode (skip confirmation prompts)").option("--dry-run","Preview the release without changing anything").option("--no-changelog","Skip changelog generation").option("--no-push","Skip pushing the commit and tag").option("--no-publish","Skip publishing to the pantry registry").action(async(t,e)=>{let o=(t??"patch").toLowerCase();if(!["patch","minor","major"].includes(o))console.error(`error: invalid release type "${o}" (expected: patch | minor | major)`),s.exit(1);let{runRelease:i}=await import("../chunk-cwa30yjr.js"),c=await i({type:o,yes:e.yes,dryRun:e.dryRun,noChangelog:e.changelog===!1,noPush:e.push===!1,noPublish:e.publish===!1});s.exit(c.exitCode)});j.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(t)=>{try{let{scanInstalledApps:e}=await import("../chunk-192e9bs7.js"),o=e();if(t.json)console.log(JSON.stringify({success:!0,apps:o,total:o.length}));else{console.log(`
69
+ ✅ Zig code generation complete!`),s.exit(0)}catch(e){console.error("Error generating Zig definitions:",e),s.exit(1)}});j.command("release [type]","Release a Zig package (changelog, bump, commit, tag, push, publish)").option("-y, --yes","Non-interactive mode (skip confirmation prompts)").option("--dry-run","Preview the release without changing anything").option("--no-changelog","Skip changelog generation").option("--no-push","Skip pushing the commit and tag").option("--no-publish","Skip publishing to the pantry registry").action(async(t,e)=>{let o=(t??"patch").toLowerCase();if(!["patch","minor","major"].includes(o))console.error(`error: invalid release type "${o}" (expected: patch | minor | major)`),s.exit(1);let{runRelease:i}=await import("../chunk-cwa30yjr.js"),c=await i({type:o,yes:e.yes,dryRun:e.dryRun,noChangelog:e.changelog===!1,noPush:e.push===!1,noPublish:e.publish===!1});s.exit(c.exitCode)});j.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(t)=>{try{let{scanInstalledApps:e}=await import("../chunk-cv2tknjc.js"),o=e();if(t.json)console.log(JSON.stringify({success:!0,apps:o,total:o.length}));else{console.log(`
70
70
  Installed Desktop Apps (${o.length}):
71
- `),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let i of o)console.log(`${i.name.padEnd(40)}${i.version}`)}s.exit(0)}catch(e){console.error("Error listing apps:",e),s.exit(1)}});j.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(t)=>{try{let{checkAppUpdates:e}=await import("../chunk-192e9bs7.js");if(!t.json)console.log("Checking desktop apps for updates...");let o=await e(),i=o.filter((c)=>c.updateAvailable);if(t.json)console.log(JSON.stringify({success:!0,apps:o,outdated:i.length,total:o.length,timestamp:new Date().toISOString()}));else{if(i.length>0){console.log(`
71
+ `),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let i of o)console.log(`${i.name.padEnd(40)}${i.version}`)}s.exit(0)}catch(e){console.error("Error listing apps:",e),s.exit(1)}});j.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(t)=>{try{let{checkAppUpdates:e}=await import("../chunk-cv2tknjc.js");if(!t.json)console.log("Checking desktop apps for updates...");let o=await e(),i=o.filter((c)=>c.updateAvailable);if(t.json)console.log(JSON.stringify({success:!0,apps:o,outdated:i.length,total:o.length,timestamp:new Date().toISOString()}));else{if(i.length>0){console.log(`
72
72
  Outdated Apps (${i.length}):
73
73
  `),console.log("Application".padEnd(30)+"Current".padEnd(16)+"Latest".padEnd(16)+"Source"),console.log("-".repeat(75));for(let g of i)console.log(`${g.name.padEnd(30)}${g.currentVersion.padEnd(16)}${(g.latestVersion||"?").padEnd(16)}${g.source}`)}else console.log(`
74
74
  All desktop apps are up to date!`);let c=o.filter((g)=>!g.updateAvailable&&g.source!=="system"&&g.source!=="unknown");if(c.length>0)console.log(`
75
- ${c.length} app(s) up to date, ${o.filter((g)=>g.source==="unknown").length} unchecked`)}s.exit(0)}catch(e){console.error("Error checking app updates:",e),s.exit(1)}});j.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(t)=>{try{let{updateApp:e}=await import("../chunk-192e9bs7.js");console.log(`Updating ${t} from the pantry registry...`);let o=await e(t);if(o.success)console.log(`Successfully updated ${t} to ${o.version}`);else console.error(`Failed to update ${t}: ${o.error}`),s.exit(1);s.exit(0)}catch(e){console.error("Error updating app:",e),s.exit(1)}});j.command("install <pkg>","Install a system package (e.g. ziglang.org@0.17.0-dev)").option("--global","Link binaries into the user-level global bin so they appear on PATH").option("--install-dir <dir>","Where to download into (default: ./pantry)").option("--platform <target>","Install for a target platform (e.g. linux-x86_64)").option("--no-bin-links","Skip creating local .bin/ symlinks").option("--quiet","Suppress progress output").action(async(t,e)=>{let o=t.lastIndexOf("@"),i=o>0,c=i?t.slice(0,o):t,g=i?t.slice(o+1):"latest";try{let p=await R(c,g,{installDir:e.installDir,platform:pe(e.platform),createBinLinks:e.binLinks!==!1,quiet:e.quiet,globalBin:e.global?!0:void 0});if(!e.quiet){if(console.log(`
75
+ ${c.length} app(s) up to date, ${o.filter((g)=>g.source==="unknown").length} unchecked`)}s.exit(0)}catch(e){console.error("Error checking app updates:",e),s.exit(1)}});j.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(t)=>{try{let{updateApp:e}=await import("../chunk-cv2tknjc.js");console.log(`Updating ${t} from the pantry registry...`);let o=await e(t);if(o.success)console.log(`Successfully updated ${t} to ${o.version}`);else console.error(`Failed to update ${t}: ${o.error}`),s.exit(1);s.exit(0)}catch(e){console.error("Error updating app:",e),s.exit(1)}});j.command("install <pkg>","Install a system package (e.g. ziglang.org@0.17.0-dev)").option("--global","Link binaries into the user-level global bin so they appear on PATH").option("--install-dir <dir>","Where to download into (default: ./pantry)").option("--platform <target>","Install for a target platform (e.g. linux-x86_64)").option("--no-bin-links","Skip creating local .bin/ symlinks").option("--quiet","Suppress progress output").action(async(t,e)=>{let o=t.lastIndexOf("@"),i=o>0,c=i?t.slice(0,o):t,g=i?t.slice(o+1):"latest";try{let p=await R(c,g,{installDir:e.installDir,platform:pe(e.platform),createBinLinks:e.binLinks!==!1,quiet:e.quiet,globalBin:e.global?!0:void 0});if(!e.quiet){if(console.log(`
76
76
  ✓ ${p.name}@${p.version}`),console.log(` installed to: ${p.installPath}`),p.globalLinks&&p.globalLinks.length>0){if(console.log(` linked into: ${v.dirname(p.globalLinks[0])}`),!s.env.PATH?.split(v.delimiter).includes(v.dirname(p.globalLinks[0])))console.log(`
77
77
  ⚠ ${v.dirname(p.globalLinks[0])} is not on your PATH yet.`),console.log(" Run `ts-pantry shell-init --install` once to fix that.")}}s.exit(0)}catch(p){console.error(`Error installing ${t}:`,p instanceof Error?p.message:p),s.exit(1)}});function ue(t){let e=ye(t);if(e.length===0)return[];try{return D(e[0]).map((o)=>o.version&&o.version!=="latest"?`${o.name}@${String(o.version).replace(/^[\^~>=<]+/,"")}`:o.name)}catch{return[]}}j.command("env","Print the environment pantry-installed packages need, for a program to consume").option("--json","Print JSON instead of shell assignments").option("--dir <path>","A project directory, whose dependency file is included (default: cwd)").option("--install","Install anything the dependency file names that is missing").action(async(t)=>{let e=v.resolve(t.dir??s.cwd()),o=ue(e);if(t.install&&o.length>0)for(let g of o){let p=g.lastIndexOf("@"),S=p>0;await R(S?g.slice(0,p):g,S?g.slice(p+1):"latest",{globalBin:!0,quiet:!0}).catch((w)=>{console.error(`# could not install ${g}: ${w instanceof Error?w.message:w}`)})}let i=k(),c=[v.join(e,".bin"),i].filter((g)=>m.existsSync(g));if(t.json)console.log(JSON.stringify({path:c,PATH:[...c,s.env.PATH??""].filter(Boolean).join(v.delimiter),dependencies:o,globalBin:i},null,2)),s.exit(0);console.log(`export PATH="${[...c,"$PATH"].join(v.delimiter)}"`),s.exit(0)});j.command("shell-init","Print the shell snippet that puts pantry-installed packages on PATH").option("--install","Append the snippet to your shell rc file (idempotent)").option("--uninstall","Remove a previously installed snippet").option("--shell <shell>","Force a shell (zsh|bash|fish) instead of autodetect").action(async(t)=>{let e=t.shell??I();try{if(t.uninstall){let i=ve({shell:e});console.log(i.changed?`✓ Removed pantry shell-init from ${i.rcFile}`:`Nothing to remove (no pantry shell-init block in ${i.rcFile})`),s.exit(0)}if(t.install){let i=ke({shell:e});if(i.changed)console.log(`✓ Added pantry shell-init to ${i.rcFile}`),console.log(` Restart your shell or run: source ${i.rcFile}`);else console.log(`✓ Already integrated in ${i.rcFile}`);s.exit(0)}let o=L(e);if(s.stdout.isTTY){if(console.log(`# Detected shell: ${e}`),console.log(`# Global bin dir: ${k()}`),o)console.log(`# Append this to: ${o}`);console.log("# Or run: ts-pantry shell-init --install"),console.log()}s.stdout.write(W({shell:e})),s.exit(0)}catch(o){console.error("Error:",o instanceof Error?o.message:o),s.exit(1)}});j.command("build [context]","Build a Dockerfile into an OCI image (no Docker daemon required)").option("-f, --file <path>","Path to the Dockerfile (default: <context>/Dockerfile)").option("-t, --tag <tag>","Image tag, e.g. myapp:latest (repeatable)").option("--target <stage>","Target stage for a multi-stage build").option("--build-arg <kv>","Set a build arg KEY=VALUE (repeatable)").option("--platform <os/arch>","Target platform (default: linux/<host-arch>)").option("--output <dir>","Where to write the image archive + OCI layout (default: <context>/.pantry/images)").option("--run-mode <mode>","How to run RUN steps: auto|chroot|host|skip (default: auto)").option("--push","Push the built image to the pantry registry after building").option("--quiet","Suppress step output").action(async(t,e)=>{try{let o=[].concat(e.tag??[]),i={};for(let g of[].concat(e.buildArg??[])){let p=g.indexOf("=");if(p!==-1)i[g.slice(0,p)]=g.slice(p+1)}let c=await je({context:t??".",dockerfile:e.file,tags:o,target:e.target,buildArgs:i,platform:e.platform,outputDir:e.output,runMode:e.runMode,quiet:e.quiet});if(!e.quiet){if(console.log(`
78
78
  ✓ Built ${c.imageId}`),o.length)console.log(` tags: ${o.join(", ")}`);console.log(` archive: ${c.archivePath}`),console.log(` oci layout: ${c.ociLayoutPath}`)}if(e.push){let g=ee(o[0]||"app:latest");if(!e.quiet)console.log(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- import{q}from"../chunk-7q8as4h2.js";import"../chunk-3bs6jc4d.js";import"../chunk-6rsaa2nw.js";import{G,K,fe,Ye}from"../chunk-tea3kznx.js";import{d}from"../chunk-05jvxr50.js";import{chmodSync as k,mkdirSync as h,renameSync as P,rmSync as b,writeFileSync as f}from"node:fs";import{homedir as S}from"node:os";import{isAbsolute as x,join as s}from"node:path";var a=(t)=>t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;");function D(t,e,r){return`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{q}from"../chunk-7q8as4h2.js";import"../chunk-3sc39cqf.js";import"../chunk-mvzv8skb.js";import{G,K,fe,Ye}from"../chunk-2x8yyzhm.js";import{d}from"../chunk-egf4sf0n.js";import{chmodSync as k,mkdirSync as h,renameSync as P,rmSync as b,writeFileSync as f}from"node:fs";import{homedir as S}from"node:os";import{isAbsolute as x,join as s}from"node:path";var a=(t)=>t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;");function D(t,e,r){return`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4
4
  <plist version="1.0"><dict>
5
5
  <key>Label</key><string>dev.pantry.desktop</string>
@@ -1,2 +1,2 @@
1
- import{spawnSync as k}from"node:child_process";import{createHash as B,createPrivateKey as U,createPublicKey as F,sign as J,X509Certificate as H}from"node:crypto";import{existsSync as z,readFileSync as G}from"node:fs";var Y="https://api.appstoreconnect.apple.com/v1";function N(e){let t=[e.detail??e.title??e.code].filter((r)=>Boolean(r));for(let r of Object.values(e.meta?.associatedErrors??{}))for(let i of r)t.push(...N(i));return t}function O(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function K(e){let t={keyId:e.keyId||process.env.APP_STORE_CONNECT_API_KEY_ID||"",issuerId:e.issuerId||process.env.APP_STORE_CONNECT_API_ISSUER_ID||"",keyPath:e.keyPath||process.env.APP_STORE_CONNECT_API_KEY_PATH||""};if(!t.keyId)throw Error("[pantry] APP_STORE_CONNECT_API_KEY_ID is required");if(!t.issuerId)throw Error("[pantry] APP_STORE_CONNECT_API_ISSUER_ID is required");if(!t.keyPath||!z(t.keyPath))throw Error("[pantry] APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file");return t}function so(e,t=Math.floor(Date.now()/1000)){let r={alg:"ES256",kid:e.keyId,typ:"JWT"},i={iss:e.issuerId,iat:t,exp:t+120,aud:"appstoreconnect-v1"},n=`${O(r)}.${O(i)}`,s;try{s=U(G(e.keyPath,"utf8"))}catch(o){throw Error(`[pantry] App Store Connect API key could not be parsed: ${o instanceof Error?o.message:String(o)}`)}let a=J("sha256",Buffer.from(n),{key:s,dsaEncoding:"ieee-p1363"});return`${n}.${a.toString("base64url")}`}class T{auth;baseUrl;fetcher;now;constructor(e={}){this.auth=K(e),this.baseUrl=(e.baseUrl??Y).replace(/\/$/,""),this.fetcher=e.fetch??globalThis.fetch,this.now=e.now??(()=>Math.floor(Date.now()/1000))}async request(e,t={}){let r=/^https?:\/\//.test(e)?e:/^\/v\d+\//.test(e)?`${new URL(this.baseUrl).origin}${e}`:`${this.baseUrl}${e}`,i=await this.fetcher(r,{...t,headers:{Accept:"application/json",Authorization:`Bearer ${so(this.auth,this.now())}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}});if(!i.ok){let n=await i.json().catch(()=>({})),s=[...new Set(n.errors?.flatMap(N)??[])].join("; ");throw Error(`[pantry] App Store Connect ${t.method??"GET"} ${e} failed (${i.status})${s?`: ${s}`:""}`)}if(i.status===204)return;return await i.json()}async upload(e,t){let r=new Headers(t.headers),i=t.body,n;if(ArrayBuffer.isView(i)){let o=new ArrayBuffer(i.byteLength);n=new Uint8Array(o),n.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),i=o}else if(i instanceof ArrayBuffer)n=new Uint8Array(i);if(n)r.set("Content-Length",String(n.byteLength));let s=await this.fetcher(e,{...t,headers:r,body:i});if(!s.ok)throw Error(`[pantry] App Store Connect asset upload failed (${s.status})`);let a=s.headers.get("etag")?.replaceAll('"',"");if(n&&a&&/^[a-f\d]{32}$/i.test(a)&&B("md5").update(n).digest("hex")!==a.toLowerCase())throw Error("[pantry] App Store Connect received an asset part with a different checksum")}async findBundleId(e){let t=new URLSearchParams({"filter[identifier]":e});return(await this.request(`/bundleIds?${t}`)).data.find((i)=>i.attributes.identifier===e)}async registerBundleId(e,t,r="MAC_OS"){return(await this.request("/bundleIds",{method:"POST",body:JSON.stringify({data:{type:"bundleIds",attributes:{identifier:e,name:t,platform:r}}})})).data}async ensureBundleId(e,t,r={}){let i=await this.findBundleId(e);if(i)return{bundleId:i,created:!1};if(r.checkOnly)return{created:!1};return{bundleId:await this.registerBundleId(e,t,r.platform),created:!0}}async listBundleIdCapabilities(e){return(await this.request(`/bundleIds/${e}/bundleIdCapabilities`)).data}async enableBundleIdCapability(e,t,r=[]){return(await this.request("/bundleIdCapabilities",{method:"POST",body:JSON.stringify({data:{type:"bundleIdCapabilities",attributes:{capabilityType:t,...r.length?{settings:r}:{}},relationships:{bundleId:{data:{type:"bundleIds",id:e}}}}})})).data}async listCertificates(e){let t=new URLSearchParams({"filter[certificateType]":e,"fields[certificates]":"name,certificateType,displayName,serialNumber,platform,expirationDate,certificateContent,activated",limit:"200"});return(await this.request(`/certificates?${t}`)).data}async createCertificate(e,t){return(await this.request("/certificates",{method:"POST",body:JSON.stringify({data:{type:"certificates",attributes:{certificateType:e,csrContent:t}}})})).data}async listProfiles(e){let t=new URLSearchParams({"filter[profileType]":"MAC_APP_STORE","fields[profiles]":"name,platform,profileContent,uuid,createdDate,expirationDate,profileState,profileType,bundleId,certificates",include:"bundleId,certificates",limit:"200"});return(await this.request(`/profiles?${t}`)).data.filter((i)=>D(i,"bundleId").includes(e))}async createMacAppStoreProfile(e,t,r){return(await this.request("/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e,profileType:"MAC_APP_STORE"},relationships:{bundleId:{data:{type:"bundleIds",id:t}},certificates:{data:[{type:"certificates",id:r}]}}}})})).data}async findApp(e){let t=new URLSearchParams({"filter[bundleId]":e});return(await this.request(`/apps?${t}`)).data.find((i)=>i.attributes.bundleId===e)}async listAppStoreVersions(e){return(await this.request(`/apps/${e}/appStoreVersions?limit=200`)).data}async createAppStoreVersion(e,t,r){return(await this.request("/appStoreVersions",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersions",attributes:{platform:t,versionString:r},relationships:{app:{data:{type:"apps",id:e}}}}})})).data}async updateAppStoreVersion(e,t){return(await this.request(`/appStoreVersions/${e}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersions",id:e,attributes:{versionString:t}}})})).data}async listBuilds(e,t){let r=new URLSearchParams({"filter[app]":e,"filter[version]":t,include:"preReleaseVersion",limit:"20","fields[builds]":"version,uploadedDate,expired,processingState,preReleaseVersion","fields[preReleaseVersions]":"version,platform"}),i=await this.request(`/builds?${r}`),n=new Map((i.included??[]).filter((s)=>s.type==="preReleaseVersions").map((s)=>[s.id,s.attributes]));return i.data.flatMap((s)=>{let a=s.relationships?.preReleaseVersion?.data?.id,o=a?n.get(a):void 0;if(!o)return[];return[{id:s.id,buildNumber:s.attributes.version,version:o.version,platform:o.platform,processingState:s.attributes.processingState}]})}async attachBuild(e,t){await this.request(`/appStoreVersions/${e}/relationships/build`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t}})})}}var x=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED","INVALID_BINARY"]),v=new Set(["READY_FOR_DISTRIBUTION","READY_FOR_SALE","DEVELOPER_REMOVED_FROM_SALE","REMOVED_FROM_SALE"]);async function De(e,t,r){let i=await e.listAppStoreVersions(t),n=[],s=new Map(r.map((a)=>[a.platform,a]));for(let{platform:a,version:o}of s.values()){let p=i.find((c)=>c.attributes.platform===a&&c.attributes.versionString===o);if(p){let c=p.attributes.appStoreState,l=x.has(c)?"ready":v.has(c)?"published":"deferred";n.push({platform:a,version:o,created:!1,updated:!1,id:p.id,status:l,appStoreState:c,...l==="deferred"?{reason:`${a} version ${o} is already ${c}`}:{}});continue}let u=i.find((c)=>c.attributes.platform===a&&x.has(c.attributes.appStoreState));if(u){let c=await e.updateAppStoreVersion(u.id,o);u.attributes.versionString=o,n.push({platform:a,version:o,created:!1,updated:!0,id:c.id,status:"ready",appStoreState:c.attributes.appStoreState});continue}let f=i.find((c)=>c.attributes.platform===a&&!v.has(c.attributes.appStoreState));if(f){n.push({platform:a,version:o,created:!1,updated:!1,id:f.id,status:"deferred",appStoreState:f.attributes.appStoreState,reason:`${a} version ${o} is queued behind ${f.attributes.versionString} (${f.attributes.appStoreState})`});continue}let d=await e.createAppStoreVersion(t,a,o);i.push(d),n.push({platform:a,version:o,created:!0,updated:!1,id:d.id,status:"ready",appStoreState:d.attributes.appStoreState})}return n}async function Ae(e,t,r,i,n={}){let s=n.timeoutMs??1200000,a=n.pollIntervalMs??15000,o=n.now??Date.now,p=n.sleep??((f)=>new Promise((d)=>setTimeout(d,f))),u=o()+s;while(!0){let f=await e.listBuilds(t,i),d=[];for(let c of r){let l=f.find((b)=>b.platform===c.platform&&b.version===c.version);if(!l)continue;if(l.processingState==="FAILED"||l.processingState==="INVALID")throw Error(`[pantry] ${c.platform} build ${i} failed App Store Connect processing (${l.processingState})`);if(l.processingState!=="VALID")continue;d.push({platform:c.platform,versionId:c.id,buildId:l.id,buildNumber:i})}if(d.length===r.length){for(let c of d)await e.attachBuild(c.versionId,c.buildId);return d}if(o()>=u){let c=r.map((l)=>l.platform).join(", ");throw Error(`[pantry] timed out waiting for ${c} build ${i} to finish App Store Connect processing`)}await p(a)}}function _(e,t=Date.now()){return e.filter((r)=>r.attributes.activated!==!1).filter((r)=>!r.attributes.expirationDate||Date.parse(r.attributes.expirationDate)>t).sort((r,i)=>Date.parse(i.attributes.expirationDate||"9999-12-31")-Date.parse(r.attributes.expirationDate||"9999-12-31"))[0]}function W(e){try{return F(e).export({type:"spki",format:"der"}).toString("base64")}catch{return}}function no(e){let t=k("openssl",["req","-pubkey","-noout"],{input:e,encoding:"utf8"});if(t.error||t.status!==0)return;return W(t.stdout)}function ro(e){if(!e)return;try{return new H(Buffer.from(e,"base64")).publicKey.export({type:"spki",format:"der"}).toString("base64")}catch{return}}function D(e,t){let r=e.relationships?.[t]?.data;if(!r)return[];return(Array.isArray(r)?r:[r]).map((i)=>i.id)}async function Sa(e){let t=new T(e),r=e.checkOnly!==!1,i=[],n=await t.ensureBundleId(e.identifier,e.name,{checkOnly:r,platform:"MAC_OS"}),s=n.bundleId;if(!s)i.push(`Register macOS Bundle ID ${e.identifier}`);let a=[],o=[...new Set(e.capabilities??[])].filter(Boolean).sort(),p=s?await t.listBundleIdCapabilities(s.id):[];for(let A of o){if(p.find((m)=>m.attributes.capabilityType===A)){a.push({type:A,enabled:!0,created:!1});continue}if(i.push(`Enable ${A} for ${e.identifier}`),!r&&s)await t.enableBundleIdCapability(s.id,A),a.push({type:A,enabled:!0,created:!0});else a.push({type:A,enabled:!1,created:!1})}let u=[],f=[["MAC_APP_DISTRIBUTION",e.appCertificateCsr],["MAC_INSTALLER_DISTRIBUTION",e.installerCertificateCsr]];for(let[A,y]of f){let m=await t.listCertificates(A),w=y?no(y):void 0;if(y&&!w)throw Error(`[pantry] ${A} CSR could not be read; is it a PEM certificate request?`);let E=_(w?m.filter((P)=>ro(P.attributes.certificateContent)===w):m);if(E){u.push({type:A,id:E.id,exists:!0,created:!1,expirationDate:E.attributes.expirationDate,certificateContent:E.attributes.certificateContent});continue}if(i.push(w&&_(m)?`Create ${A} certificate (the active ones were issued for a different private key)`:`Create ${A} certificate`),!r){if(!y)throw Error(`[pantry] ${A} certificate is missing; provide its CSR to apply the provisioning plan`);let P=await t.createCertificate(A,y);u.push({type:A,id:P.id,exists:!0,created:!0,expirationDate:P.attributes.expirationDate,certificateContent:P.attributes.certificateContent})}else u.push({type:A,exists:!1,created:!1})}let d=u.find((A)=>A.type==="MAC_APP_DISTRIBUTION"),c=e.profileName||`${e.name} Mac App Store`,l=s?await t.listProfiles(s.id):[],b=l.find((A)=>A.attributes.profileState==="ACTIVE"&&(!A.attributes.expirationDate||Date.parse(A.attributes.expirationDate)>Date.now())&&(!d?.id||D(A,"certificates").includes(d.id))),R;if(b)R={id:b.id,name:b.attributes.name,exists:!0,created:!1,expirationDate:b.attributes.expirationDate,profileContent:b.attributes.profileContent};else if(i.push(`Create MAC_APP_STORE profile ${c}`),!r){if(!s)throw Error("[pantry] Bundle ID was not created");if(!d?.id)throw Error("[pantry] MAC_APP_DISTRIBUTION certificate is required to create the profile");let A=await t.createMacAppStoreProfile(l.some((y)=>y.attributes.name===c)?`${c} ${d.id.slice(0,8)}`:c,s.id,d.id);R={id:A.id,name:A.attributes.name,exists:!0,created:!0,expirationDate:A.attributes.expirationDate,profileContent:A.attributes.profileContent}}else R={name:c,exists:!1,created:!1};let S=await t.findApp(e.identifier);if(!S)i.push(`Create the ${e.identifier} app record in App Store Connect (manual Apple step)`);return{mode:r?"plan":"apply",bundleId:{identifier:e.identifier,id:s?.id,exists:Boolean(s),created:n.created},capabilities:a,certificates:u,profile:R,appRecord:{exists:Boolean(S),id:S?.id,...!S?{manualAction:"Create the app record in App Store Connect; Apple does not expose an app-creation API."}:{}},actions:i}}import{createHash as j}from"node:crypto";import{basename as X,resolve as Q}from"node:path";import{readFile as Z}from"node:fs/promises";var ee=["alcoholTobaccoOrDrugUseOrReferences","contests","gamblingSimulated","gunsOrOtherWeapons","medicalOrTreatmentInformation","profanityOrCrudeHumor","sexualContentGraphicAndNudity","sexualContentOrNudity","horrorOrFearThemes","matureOrSuggestiveThemes","violenceCartoonOrFantasy","violenceRealisticProlongedGraphicOrSadistic","violenceRealistic"],te=["advertising","gambling","healthOrWellnessTopics","lootBox","messagingAndChat","parentalControls","ageAssurance","socialMedia","socialMediaAgeRestricted","unrestrictedWebAccess","userGeneratedContent"],re=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED"]);function ie(e={}){let t={ageRatingOverrideV2:"NONE",koreaAgeRatingOverride:"NONE"};for(let r of ee)t[r]=e[r]??"NONE";for(let r of te)t[r]=e[r]??!1;return t}function V(e){return e==="ios"?"IOS":"MAC_OS"}async function se(e,t,r){await e.request(`/apps/${t}`,{method:"PATCH",body:JSON.stringify({data:{type:"apps",id:t,attributes:{contentRightsDeclaration:r.contentRightsDeclaration}}})});let i=await e.request(`/apps/${t}/appInfos?limit=10`),n=i.data.find((p)=>p.attributes.appStoreState==="PREPARE_FOR_SUBMISSION")??i.data[0];if(!n)throw Error("[pantry] App Store Connect has no editable app information resource");await e.request(`/appInfos/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfos",id:n.id,relationships:{primaryCategory:{data:{type:"appCategories",id:r.primaryCategory}}}}})});let s=await e.request(`/appInfos/${n.id}/appInfoLocalizations?limit=200`),a=r.locale??"en-US",o=s.data.find((p)=>p.attributes.locale===a);if(!o)throw Error(`[pantry] App Store Connect app information is missing the ${a} localization`);return await e.request(`/appInfoLocalizations/${o.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfoLocalizations",id:o.id,attributes:{subtitle:r.subtitle,privacyPolicyUrl:r.privacyPolicyUrl}}})}),await e.request(`/ageRatingDeclarations/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"ageRatingDeclarations",id:n.id,attributes:ie(r.ageRating)}})}),n.id}async function ne(e,t,r){try{if((await e.request(`/appPriceSchedules/${t}/manualPrices?limit=200`)).data.length)return}catch(p){if(!(p instanceof Error)||!p.message.includes("(404)"))throw p}let i=r.baseTerritory??"USA",n=await e.request(`/apps/${t}/appPricePoints?filter[territory]=${encodeURIComponent(i)}&limit=200`),s=Number(r.price),a=n.data.find((p)=>Number(p.attributes.customerPrice)===s);if(!a)throw Error(`[pantry] App Store price ${r.price} is unavailable in ${i}`);let o="${price}";await e.request("/appPriceSchedules",{method:"POST",body:JSON.stringify({data:{type:"appPriceSchedules",relationships:{app:{data:{type:"apps",id:t}},baseTerritory:{data:{type:"territories",id:i}},manualPrices:{data:[{type:"appPrices",id:o}]}}},included:[{type:"appPrices",id:o,attributes:{startDate:null,endDate:null},relationships:{appPricePoint:{data:{type:"appPricePoints",id:a.id}}}}]})})}async function ae(e,t,r=!0){try{if((await e.request(`/apps/${t}/appAvailabilityV2`)).data.attributes.availableInNewTerritories===r)return;return}catch(s){if(!(s instanceof Error)||!s.message.includes("(404)"))throw s}let n=(await e.request("/territories?limit=200")).data.map((s,a)=>({type:"territoryAvailabilities",id:`\${territory-${a}}`,attributes:{available:!0},relationships:{territory:{data:{type:"territories",id:s.id}}}}));await e.request("/v2/appAvailabilities",{method:"POST",body:JSON.stringify({data:{type:"appAvailabilities",attributes:{availableInNewTerritories:r},relationships:{app:{data:{type:"apps",id:t}},territoryAvailabilities:{data:n.map((s)=>({type:s.type,id:s.id}))}}},included:n})})}async function oe(e,t,r){let i=r.locale??"en-US",s=(await e.request(`/appStoreVersions/${t}/appStoreVersionLocalizations?limit=200`)).data.find((a)=>a.attributes.locale===i);if(!s)s=(await e.request("/appStoreVersionLocalizations",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",attributes:{locale:i},relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})).data;return await e.request(`/appStoreVersionLocalizations/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",id:s.id,attributes:{description:r.description,keywords:r.keywords,supportUrl:r.supportUrl,...r.marketingUrl?{marketingUrl:r.marketingUrl}:{},...r.promotionalText?{promotionalText:r.promotionalText}:{},...r.whatsNew?{whatsNew:r.whatsNew}:{}}}})}),s.id}async function pe(e,t,r){let i=await e.request(`/appStoreVersions/${t}/appStoreReviewDetail`),n={contactFirstName:r.reviewContact.firstName,contactLastName:r.reviewContact.lastName,contactPhone:r.reviewContact.phone,contactEmail:r.reviewContact.email,demoAccountRequired:!1,...r.reviewContact.notes?{notes:r.reviewContact.notes}:{}};if(i.data){await e.request(`/appStoreReviewDetails/${i.data.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreReviewDetails",id:i.data.id,attributes:n}})});return}await e.request("/appStoreReviewDetails",{method:"POST",body:JSON.stringify({data:{type:"appStoreReviewDetails",attributes:n,relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})}async function L(e,t){let r=[],i=t;while(i){let n=await e.request(i);r.push(...n.data),i=n.links?.next}return r}async function ce(e,t,r,i){let n=Date.now()+r;while(!0){let{data:s}=await e.request(`/appAssetLibraryImages/${t}`);if(s.attributes.specId&&!["AWAITING_UPLOAD","UPLOAD_COMPLETE","PROCESSING","FAILED","REJECTED","ARCHIVED"].includes(s.attributes.state))return s;if(["FAILED","REJECTED","ARCHIVED"].includes(s.attributes.state))throw Error(`[pantry] App Store image ${s.attributes.fileName} ${s.attributes.state}: ${JSON.stringify(s.attributes.stateDetails)}`);if(Date.now()>=n)throw Error(`[pantry] timed out processing App Store image ${s.attributes.fileName}`);await new Promise((a)=>setTimeout(a,i))}}function de(e){if(Array.isArray(e))return e;let t={APP_DESKTOP:"MAC_APP_STORE",APP_IPHONE_67:"IPHONE_APP_STORE",APP_IPAD_PRO_3GEN_129:"IPAD_APP_STORE"};return Object.entries(e).flatMap(([r,i])=>i?[{platform:t[r],files:i}]:[])}async function ue(e,t,r,i,n,s,a){if(!i.some((l)=>l.files.length))return;let{data:o}=await e.request(`/apps/${t}/assetLibrary`),{data:p}=await e.request("/appAssetLibraryRefData"),u=p[0]?.attributes;if(!u)throw Error("[pantry] Apple returned no asset specification catalog");let f=await L(e,`/appAssetLibraries/${o.id}/images?limit=200`),d=await L(e,`/appStoreVersionLocalizations/${r}/placements?filter[placementType]=APP_SCREENSHOT&include=image&limit=200`),c=new Map;for(let l of i)for(let b of l.files){let R=Q(n,b),S=await Z(R),A=`sha256:${j("sha256").update(S).digest("hex")}`,y=f.find((h)=>h.attributes.referenceName===A);if(y?.attributes.state==="FAILED")await e.request(`/appAssetLibraryImages/${y.id}`,{method:"DELETE"});let m=y?.attributes.state==="FAILED"?void 0:y;if(m&&["REJECTED","ARCHIVED"].includes(m.attributes.state))throw Error(`[pantry] Existing image ${b} is ${m.attributes.state}`);if(!m)m=(await e.request("/appAssetLibraryImages",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryImages",attributes:{fileName:X(R),fileSize:S.byteLength,category:"APP_SCREENSHOTS_AND_PREVIEWS",referenceName:A},relationships:{assetLibrary:{data:{type:"appAssetLibraries",id:o.id}}}}})})).data;if(m.attributes.state==="AWAITING_UPLOAD"){if(!m.attributes.uploadOperations)m=(await e.request(`/appAssetLibraryImages/${m.id}`)).data;let h=0;for(let g of m.attributes.uploadOperations??[]){if(g.offset!==h||!Number.isSafeInteger(g.length)||g.length<=0||g.offset+g.length>S.byteLength)throw Error("[pantry] Invalid Apple image upload byte range");await e.upload(g.url,{method:g.method,headers:Object.fromEntries(g.requestHeaders.map((I)=>[I.name,I.value])),body:S.subarray(g.offset,g.offset+g.length)}),h+=g.length}if(h!==S.byteLength)throw Error("[pantry] Apple image upload operations do not cover the entire file");await e.request(`/appAssetLibraryImages/${m.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appAssetLibraryImages",id:m.id,attributes:{uploaded:!0}}})})}if(m=await ce(e,m.id,s,a),!f.some((h)=>h.id===m.id))f.push(m);let E=(u.placementTypes.find((h)=>h.placementTypeId==="APP_SCREENSHOT")?.specMappings??[]).find((h)=>h.specs.includes(m.attributes.specId)&&u.placementProfileGroups.some((g)=>g.placementProfileGroupId===h.placementGroupId&&g.platform===l.platform))?.placementGroupId;if(!E)throw Error(`[pantry] Image ${b} does not match an Apple screenshot specification for ${l.platform}`);let P=c.get(E)??[];if(!P.includes(m.id))P.push(m.id);c.set(E,P)}for(let[l,b]of c){let R=u.features.find((y)=>y.featureId==="APP_STORE_VERSIONS")?.placementPolicies.find((y)=>y.placementType==="APP_SCREENSHOT")?.groupLimits.find((y)=>y.groupIds.includes(l))?.maxCount;if(R===void 0||b.length>R)throw Error(`[pantry] Screenshot count exceeds Apple's limit for ${l}`);let S=d.filter((y)=>y.attributes.placementGroup===l),A=[];for(let y of b){let m=S.find((w)=>w.relationships?.image?.data&&!Array.isArray(w.relationships.image.data)&&w.relationships.image.data.id===y);if(!m)m=(await e.request("/appAssetLibraryPlacements",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacements",attributes:{placementType:"APP_SCREENSHOT",placementGroup:l},relationships:{image:{data:{type:"appAssetLibraryImages",id:y}},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})).data;A.push({type:"appAssetLibraryPlacements",id:m.id})}for(let y of S)if(!A.some((m)=>m.id===y.id))await e.request(`/appAssetLibraryPlacements/${y.id}`,{method:"DELETE"});await e.request("/appAssetLibraryPlacementOrderingRequests",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacementOrderingRequests",attributes:{placementGroup:l},relationships:{orderedPlacements:{data:A},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})}}async function le(e,t,r){if(await e.request(`/appStoreVersions/${t.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersions",id:t.id,attributes:{copyright:r.copyright,releaseType:r.releaseType??"AFTER_APPROVAL",usesIdfa:r.usesIdfa??!1}}})}),t.buildId){if(r.encryptionDeclarationId){await io(e,t.buildId,r.encryptionDeclarationId);return}let i=r.usesNonExemptEncryption??!1,n=await e.request(`/builds/${t.buildId}?fields[builds]=usesNonExemptEncryption`);if(n.data.attributes.usesNonExemptEncryption===void 0||n.data.attributes.usesNonExemptEncryption===null)await e.request(`/builds/${t.buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t.buildId,attributes:{usesNonExemptEncryption:i}}})})}}async function io(e,t,r){let i=await e.request(`/appEncryptionDeclarations/${encodeURIComponent(r)}?include=app`);if(i.data.attributes.appEncryptionDeclarationState!=="APPROVED")throw Error("[pantry] App Store encryption declaration must be APPROVED before attaching a build");let n=await e.request(`/builds/${encodeURIComponent(t)}?include=app,appEncryptionDeclaration`),s=i.data.relationships?.app?.data,a=n.data.relationships?.app?.data;if(!s||Array.isArray(s)||!a||Array.isArray(a)||s.id!==a.id)throw Error("[pantry] App Store encryption declaration and build must belong to the same app");let o=n.data.relationships?.appEncryptionDeclaration?.data;if(o&&!Array.isArray(o)&&o.id===r)return;if(n.data.attributes.usesNonExemptEncryption===!1)throw Error("[pantry] Refusing to attach a non-exempt declaration to a build marked exempt");await e.request(`/builds/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t,attributes:{usesNonExemptEncryption:!0},relationships:{appEncryptionDeclaration:{data:{type:"appEncryptionDeclarations",id:r}}}}})})}async function M(e,t,r){let i=await e.request(`/apps/${t}/reviewSubmissions?limit=200`),n=[];for(let s of r){let a=V(s.platform),o=i.data.filter((d)=>d.attributes.platform===a&&d.attributes.state!=="COMPLETE"),p;for(let d of o){if(!((await e.request(`/reviewSubmissions/${d.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((b)=>b.type==="appStoreVersions"&&b.id===s.id))continue;if(p=d,d.attributes.state!=="READY_FOR_REVIEW"){n.push(d.id);break}}if(p&&p.attributes.state!=="READY_FOR_REVIEW")continue;if(p??=o.find((d)=>d.attributes.state==="READY_FOR_REVIEW"),!p)p=(await e.request("/reviewSubmissions",{method:"POST",body:JSON.stringify({data:{type:"reviewSubmissions",attributes:{platform:a},relationships:{app:{data:{type:"apps",id:t}}}}})})).data;if(!((await e.request(`/reviewSubmissions/${p.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((d)=>d.type==="appStoreVersions"&&d.id===s.id))await e.request("/reviewSubmissionItems",{method:"POST",body:JSON.stringify({data:{type:"reviewSubmissionItems",relationships:{reviewSubmission:{data:{type:"reviewSubmissions",id:p.id}},appStoreVersion:{data:{type:"appStoreVersions",id:s.id}}}}})});await e.request(`/reviewSubmissions/${p.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"reviewSubmissions",id:p.id,attributes:{submitted:!0}}})}),n.push(p.id)}return n}async function Ie(e,t,r,i,n={}){if(t.encryptionDeclarationId&&t.usesNonExemptEncryption!==!0)throw Error("[pantry] An encryption declaration requires usesNonExemptEncryption: true");if(t.usesNonExemptEncryption===!0&&!t.encryptionDeclarationId)throw Error("[pantry] Non-exempt encryption requires an Apple-approved encryptionDeclarationId");let s=n.cwd??process.cwd(),a=n.screenshotTimeoutMs??600000,o=n.screenshotPollIntervalMs??5000;await se(e,r,t),await ne(e,r,t),await ae(e,r,t.availableInNewTerritories??!0);let p=[];for(let f of i){await le(e,f,t);let d=await oe(e,f.id,t);await pe(e,f.id,t);let c=de(t.screenshots).filter((l)=>f.platform==="macos"?l.platform==="MAC_APP_STORE":l.platform!=="MAC_APP_STORE");await ue(e,r,d,c,s,a,o),p.push({platform:f.platform,versionId:f.id,localizationId:d})}let u=n.submit??t.submitForReview??!1;return{appId:r,versions:p,reviewSubmissionIds:u?await M(e,r,i):[]}}async function Da(e,t){if(!t.bundleId)throw Error("[pantry] App Store submission requires a bundle ID");let r=new T(t),i=await r.findApp(t.bundleId);if(!i)throw Error("[pantry] the App Store Connect app record is missing");let n=t.platforms??["macos"],s=await r.listAppStoreVersions(i.id),a=[],o=[];for(let u of n){let f=s.find((c)=>c.attributes.platform===V(u)&&c.attributes.versionString===t.version);if(!f)throw Error(`[pantry] ${u} App Store version ${t.version} does not exist`);let d=await r.request(`/appStoreVersions/${f.id}/build`);a.push({platform:u,id:f.id,buildId:d.data?.id}),o.push(f.attributes.appStoreState)}if((t.submit??e.submitForReview??!1)&&o.every((u)=>!re.has(u))){let u=await Promise.all(a.map(async(f)=>{let d=await r.request(`/appStoreVersions/${f.id}/appStoreVersionLocalizations?limit=200`);return{platform:f.platform,versionId:f.id,localizationId:d.data[0]?.id??""}}));return{appId:i.id,versions:u,reviewSubmissionIds:await M(r,i.id,a)}}return await Ie(r,e,i.id,a,t)}import{execFileSync as fe}from"node:child_process";import{createReadStream as me}from"node:fs";import{createHash as ye}from"node:crypto";class C extends Error{}async function be(e){let t=ye("sha256");return await new Promise((r,i)=>{let n=me(e);n.on("data",(s)=>t.update(s)),n.once("end",r),n.once("error",i)}),t.digest("hex")}async function q(e){return e.json().catch(async()=>({error:await e.text().catch(()=>e.statusText)}))}function ge(e){let t=(e.registryUrl||process.env.PANTRY_REGISTRY_URL||process.env.REGISTRY_URL||"https://registry.pantry.dev").replace(/\/+$/,""),r=e.token||process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN||"";if(!r)throw Error("PANTRY_REGISTRY_TOKEN or PANTRY_TOKEN is required for binary publication");return{registryUrl:t,token:r}}var bt=3600000,Aa=30000,co=Math.ceil(bt/Aa)+10;function lo(e,t){let r=t.retryable?" (retryable)":"",i=t.scan?` [scan verdict=${t.scan.verdict}${t.scan.signature?` signature=${t.scan.signature}`:""}${t.scan.reason?` reason=${t.scan.reason}`:""}${t.scan.engineVersion?` engine=${t.scan.engineVersion}`:""}${t.scan.databaseVersion?` db=${t.scan.databaseVersion}`:""}${t.scan.durationMs?` durationMs=${t.scan.durationMs}`:""}]`:"";return Error(`${t.code||e.status}: ${t.error||e.statusText}${r}${i}`)}function Se(e,t){let r=Number(t?.retryAfterSeconds);if(Number.isFinite(r)&&r>0)return r*1000;let i=Number(e.headers?.get?.("Retry-After"));if(Number.isFinite(i)&&i>0)return i*1000;return null}function he(e,t){return e.status===408||e.status===425||e.status===429||t?.retryable===!0||e.status>=500&&!t.code||e.status===404&&t.code==="BINARY_STAGING_NOT_FOUND"}async function po(e,t,r,i={}){let n=Math.max(1,i.attempts??co),s=Date.now()+(i.deadlineMs??bt),a=i.fetch??fetch,o=i.sleep??((d)=>new Promise((c)=>setTimeout(c,d))),p=Error("binary upload completion did not run"),u=Date.now(),f=0;for(let d=1;d<=n;d++){f=d;let c=Math.min(Aa,1000*2**Math.min(d-1,5));try{let l=await a(`${e}/api/v1/binaries/uploads/complete`,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({uploadId:t})}),b=await q(l);if(l.ok&&b.success===!0)return b;if(p=lo(l,b),!he(l,b))throw new C(p.message);c=Math.max(c,Se(l,b)??0)}catch(l){if(l instanceof C)throw l;p=l instanceof Error?l:Error(String(l))}if(d>=n||Date.now()>=s)break;if(Date.now()+c>s){p=Error(`${p.message} - registry asked for ${Math.round(c/1000)}s more than the ${Math.round((s-u)/60000)} min completion budget allows`);break}await o(c)}throw Error(`Binary upload completion remained ambiguous after ${f} attempts over ${Math.round((Date.now()-u)/1000)}s: ${p.message}`)}var go=4;function Re(e){return e.status===408||e.status===429||e.status>=500}async function we(e,t,r,i){let n=Math.max(1,i.initiateAttempts??go),s=i.fetch??fetch,a=i.sleep??((p)=>new Promise((u)=>setTimeout(u,p))),o=Error("binary upload initiation did not run");for(let p=1;p<=n;p++){try{let u=await s(`${e}/api/v1/binaries/uploads`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:r}),f=await q(u);if(u.ok||!Re(u))return{response:u,initiated:f};o=Error(`${f.code||u.status}: ${f.error||u.statusText}`)}catch(u){o=u instanceof Error?u:Error(String(u))}if(p>=n)break;await a(Math.min(Aa,1000*2**(p-1)))}throw Error(`Could not reach the registry to start the upload after ${n} attempts: ${o.message}`)}async function Ia(e){let{registryUrl:t,token:r}=ge(e),i=await be(e.filePath),n={Authorization:`Bearer ${r}`},{response:s,initiated:a}=await we(t,n,JSON.stringify({domain:e.domain,version:e.version,platforms:e.platforms,filename:e.filename,size:e.size,sha256:i}),e);if(!s.ok||!a.uploadId||!a.uploadUrl)throw Error(`${a.code||s.status}: ${a.error||s.statusText}`);let o=["-fsS","--connect-timeout","30","--speed-limit","1024","--speed-time","120","--retry","3","--retry-all-errors","-X","PUT"];for(let[u,f]of Object.entries(a.uploadHeaders||{}))o.push("-H",`${u}: ${f}`);o.push("-T",e.filePath,a.uploadUrl),fe("curl",o,{stdio:["ignore","ignore","inherit"]});let p=await po(t,a.uploadId,n);if(p.scan?.artifactSha256!==i||p.scan?.verdict!=="clean")throw Error("Registry returned an invalid binary malware-scan attestation");return p}
2
- export{so,T,De,Ae,no,ro,Sa,io,Ie,Da,bt,Aa,co,lo,po,go,Ia};
1
+ import{spawnSync as k}from"node:child_process";import{createHash as B,createPrivateKey as U,createPublicKey as F,sign as J,X509Certificate as H}from"node:crypto";import{existsSync as z,readFileSync as G}from"node:fs";var Y="https://api.appstoreconnect.apple.com/v1";function N(e){let t=[e.detail??e.title??e.code].filter((r)=>Boolean(r));for(let r of Object.values(e.meta?.associatedErrors??{}))for(let i of r)t.push(...N(i));return t}function O(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function K(e){let t={keyId:e.keyId||process.env.APP_STORE_CONNECT_API_KEY_ID||"",issuerId:e.issuerId||process.env.APP_STORE_CONNECT_API_ISSUER_ID||"",keyPath:e.keyPath||process.env.APP_STORE_CONNECT_API_KEY_PATH||""};if(!t.keyId)throw Error("[pantry] APP_STORE_CONNECT_API_KEY_ID is required");if(!t.issuerId)throw Error("[pantry] APP_STORE_CONNECT_API_ISSUER_ID is required");if(!t.keyPath||!z(t.keyPath))throw Error("[pantry] APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file");return t}function no(e,t=Math.floor(Date.now()/1000)){let r={alg:"ES256",kid:e.keyId,typ:"JWT"},i={iss:e.issuerId,iat:t,exp:t+120,aud:"appstoreconnect-v1"},n=`${O(r)}.${O(i)}`,s;try{s=U(G(e.keyPath,"utf8"))}catch(o){throw Error(`[pantry] App Store Connect API key could not be parsed: ${o instanceof Error?o.message:String(o)}`)}let a=J("sha256",Buffer.from(n),{key:s,dsaEncoding:"ieee-p1363"});return`${n}.${a.toString("base64url")}`}class T{auth;baseUrl;fetcher;now;constructor(e={}){this.auth=K(e),this.baseUrl=(e.baseUrl??Y).replace(/\/$/,""),this.fetcher=e.fetch??globalThis.fetch,this.now=e.now??(()=>Math.floor(Date.now()/1000))}async request(e,t={}){let r=/^https?:\/\//.test(e)?e:/^\/v\d+\//.test(e)?`${new URL(this.baseUrl).origin}${e}`:`${this.baseUrl}${e}`,i=await this.fetcher(r,{...t,headers:{Accept:"application/json",Authorization:`Bearer ${no(this.auth,this.now())}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}});if(!i.ok){let n=await i.json().catch(()=>({})),s=[...new Set(n.errors?.flatMap(N)??[])].join("; ");throw Error(`[pantry] App Store Connect ${t.method??"GET"} ${e} failed (${i.status})${s?`: ${s}`:""}`)}if(i.status===204)return;return await i.json()}async upload(e,t){let r=new Headers(t.headers),i=t.body,n;if(ArrayBuffer.isView(i)){let o=new ArrayBuffer(i.byteLength);n=new Uint8Array(o),n.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),i=o}else if(i instanceof ArrayBuffer)n=new Uint8Array(i);if(n)r.set("Content-Length",String(n.byteLength));let s=await this.fetcher(e,{...t,headers:r,body:i});if(!s.ok)throw Error(`[pantry] App Store Connect asset upload failed (${s.status})`);let a=s.headers.get("etag")?.replaceAll('"',"");if(n&&a&&/^[a-f\d]{32}$/i.test(a)&&B("md5").update(n).digest("hex")!==a.toLowerCase())throw Error("[pantry] App Store Connect received an asset part with a different checksum")}async findBundleId(e){let t=new URLSearchParams({"filter[identifier]":e});return(await this.request(`/bundleIds?${t}`)).data.find((i)=>i.attributes.identifier===e)}async registerBundleId(e,t,r="MAC_OS"){return(await this.request("/bundleIds",{method:"POST",body:JSON.stringify({data:{type:"bundleIds",attributes:{identifier:e,name:t,platform:r}}})})).data}async ensureBundleId(e,t,r={}){let i=await this.findBundleId(e);if(i)return{bundleId:i,created:!1};if(r.checkOnly)return{created:!1};return{bundleId:await this.registerBundleId(e,t,r.platform),created:!0}}async listBundleIdCapabilities(e){return(await this.request(`/bundleIds/${e}/bundleIdCapabilities`)).data}async enableBundleIdCapability(e,t,r=[]){return(await this.request("/bundleIdCapabilities",{method:"POST",body:JSON.stringify({data:{type:"bundleIdCapabilities",attributes:{capabilityType:t,...r.length?{settings:r}:{}},relationships:{bundleId:{data:{type:"bundleIds",id:e}}}}})})).data}async listCertificates(e){let t=new URLSearchParams({"filter[certificateType]":e,"fields[certificates]":"name,certificateType,displayName,serialNumber,platform,expirationDate,certificateContent,activated",limit:"200"});return(await this.request(`/certificates?${t}`)).data}async createCertificate(e,t){return(await this.request("/certificates",{method:"POST",body:JSON.stringify({data:{type:"certificates",attributes:{certificateType:e,csrContent:t}}})})).data}async listProfiles(e){let t=new URLSearchParams({"filter[profileType]":"MAC_APP_STORE","fields[profiles]":"name,platform,profileContent,uuid,createdDate,expirationDate,profileState,profileType,bundleId,certificates",include:"bundleId,certificates",limit:"200"});return(await this.request(`/profiles?${t}`)).data.filter((i)=>D(i,"bundleId").includes(e))}async createMacAppStoreProfile(e,t,r){return(await this.request("/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e,profileType:"MAC_APP_STORE"},relationships:{bundleId:{data:{type:"bundleIds",id:t}},certificates:{data:[{type:"certificates",id:r}]}}}})})).data}async findApp(e){let t=new URLSearchParams({"filter[bundleId]":e});return(await this.request(`/apps?${t}`)).data.find((i)=>i.attributes.bundleId===e)}async listAppStoreVersions(e){return(await this.request(`/apps/${e}/appStoreVersions?limit=200`)).data}async createAppStoreVersion(e,t,r){return(await this.request("/appStoreVersions",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersions",attributes:{platform:t,versionString:r},relationships:{app:{data:{type:"apps",id:e}}}}})})).data}async updateAppStoreVersion(e,t){return(await this.request(`/appStoreVersions/${e}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersions",id:e,attributes:{versionString:t}}})})).data}async listBuilds(e,t){let r=new URLSearchParams({"filter[app]":e,"filter[version]":t,include:"preReleaseVersion",limit:"20","fields[builds]":"version,uploadedDate,expired,processingState,preReleaseVersion","fields[preReleaseVersions]":"version,platform"}),i=await this.request(`/builds?${r}`),n=new Map((i.included??[]).filter((s)=>s.type==="preReleaseVersions").map((s)=>[s.id,s.attributes]));return i.data.flatMap((s)=>{let a=s.relationships?.preReleaseVersion?.data?.id,o=a?n.get(a):void 0;if(!o)return[];return[{id:s.id,buildNumber:s.attributes.version,version:o.version,platform:o.platform,processingState:s.attributes.processingState}]})}async attachBuild(e,t){await this.request(`/appStoreVersions/${e}/relationships/build`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t}})})}}var x=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED","INVALID_BINARY"]),v=new Set(["READY_FOR_DISTRIBUTION","READY_FOR_SALE","DEVELOPER_REMOVED_FROM_SALE","REMOVED_FROM_SALE"]);async function De(e,t,r){let i=await e.listAppStoreVersions(t),n=[],s=new Map(r.map((a)=>[a.platform,a]));for(let{platform:a,version:o}of s.values()){let p=i.find((c)=>c.attributes.platform===a&&c.attributes.versionString===o);if(p){let c=p.attributes.appStoreState,l=x.has(c)?"ready":v.has(c)?"published":"deferred";n.push({platform:a,version:o,created:!1,updated:!1,id:p.id,status:l,appStoreState:c,...l==="deferred"?{reason:`${a} version ${o} is already ${c}`}:{}});continue}let u=i.find((c)=>c.attributes.platform===a&&x.has(c.attributes.appStoreState));if(u){let c=await e.updateAppStoreVersion(u.id,o);u.attributes.versionString=o,n.push({platform:a,version:o,created:!1,updated:!0,id:c.id,status:"ready",appStoreState:c.attributes.appStoreState});continue}let f=i.find((c)=>c.attributes.platform===a&&!v.has(c.attributes.appStoreState));if(f){n.push({platform:a,version:o,created:!1,updated:!1,id:f.id,status:"deferred",appStoreState:f.attributes.appStoreState,reason:`${a} version ${o} is queued behind ${f.attributes.versionString} (${f.attributes.appStoreState})`});continue}let d=await e.createAppStoreVersion(t,a,o);i.push(d),n.push({platform:a,version:o,created:!0,updated:!1,id:d.id,status:"ready",appStoreState:d.attributes.appStoreState})}return n}async function Ae(e,t,r,i,n={}){let s=n.timeoutMs??1200000,a=n.pollIntervalMs??15000,o=n.now??Date.now,p=n.sleep??((f)=>new Promise((d)=>setTimeout(d,f))),u=o()+s;while(!0){let f=await e.listBuilds(t,i),d=[];for(let c of r){let l=f.find((b)=>b.platform===c.platform&&b.version===c.version);if(!l)continue;if(l.processingState==="FAILED"||l.processingState==="INVALID")throw Error(`[pantry] ${c.platform} build ${i} failed App Store Connect processing (${l.processingState})`);if(l.processingState!=="VALID")continue;d.push({platform:c.platform,versionId:c.id,buildId:l.id,buildNumber:i})}if(d.length===r.length){for(let c of d)await e.attachBuild(c.versionId,c.buildId);return d}if(o()>=u){let c=r.map((l)=>l.platform).join(", ");throw Error(`[pantry] timed out waiting for ${c} build ${i} to finish App Store Connect processing`)}await p(a)}}function _(e,t=Date.now()){return e.filter((r)=>r.attributes.activated!==!1).filter((r)=>!r.attributes.expirationDate||Date.parse(r.attributes.expirationDate)>t).sort((r,i)=>Date.parse(i.attributes.expirationDate||"9999-12-31")-Date.parse(r.attributes.expirationDate||"9999-12-31"))[0]}function W(e){try{return F(e).export({type:"spki",format:"der"}).toString("base64")}catch{return}}function ro(e){let t=k("openssl",["req","-pubkey","-noout"],{input:e,encoding:"utf8"});if(t.error||t.status!==0)return;return W(t.stdout)}function io(e){if(!e)return;try{return new H(Buffer.from(e,"base64")).publicKey.export({type:"spki",format:"der"}).toString("base64")}catch{return}}function D(e,t){let r=e.relationships?.[t]?.data;if(!r)return[];return(Array.isArray(r)?r:[r]).map((i)=>i.id)}async function Sa(e){let t=new T(e),r=e.checkOnly!==!1,i=[],n=await t.ensureBundleId(e.identifier,e.name,{checkOnly:r,platform:"MAC_OS"}),s=n.bundleId;if(!s)i.push(`Register macOS Bundle ID ${e.identifier}`);let a=[],o=[...new Set(e.capabilities??[])].filter(Boolean).sort(),p=s?await t.listBundleIdCapabilities(s.id):[];for(let A of o){if(p.find((m)=>m.attributes.capabilityType===A)){a.push({type:A,enabled:!0,created:!1});continue}if(i.push(`Enable ${A} for ${e.identifier}`),!r&&s)await t.enableBundleIdCapability(s.id,A),a.push({type:A,enabled:!0,created:!0});else a.push({type:A,enabled:!1,created:!1})}let u=[],f=[["MAC_APP_DISTRIBUTION",e.appCertificateCsr],["MAC_INSTALLER_DISTRIBUTION",e.installerCertificateCsr]];for(let[A,y]of f){let m=await t.listCertificates(A),w=y?ro(y):void 0;if(y&&!w)throw Error(`[pantry] ${A} CSR could not be read; is it a PEM certificate request?`);let E=_(w?m.filter((P)=>io(P.attributes.certificateContent)===w):m);if(E){u.push({type:A,id:E.id,exists:!0,created:!1,expirationDate:E.attributes.expirationDate,certificateContent:E.attributes.certificateContent});continue}if(i.push(w&&_(m)?`Create ${A} certificate (the active ones were issued for a different private key)`:`Create ${A} certificate`),!r){if(!y)throw Error(`[pantry] ${A} certificate is missing; provide its CSR to apply the provisioning plan`);let P=await t.createCertificate(A,y);u.push({type:A,id:P.id,exists:!0,created:!0,expirationDate:P.attributes.expirationDate,certificateContent:P.attributes.certificateContent})}else u.push({type:A,exists:!1,created:!1})}let d=u.find((A)=>A.type==="MAC_APP_DISTRIBUTION"),c=e.profileName||`${e.name} Mac App Store`,l=s?await t.listProfiles(s.id):[],b=l.find((A)=>A.attributes.profileState==="ACTIVE"&&(!A.attributes.expirationDate||Date.parse(A.attributes.expirationDate)>Date.now())&&(!d?.id||D(A,"certificates").includes(d.id))),R;if(b)R={id:b.id,name:b.attributes.name,exists:!0,created:!1,expirationDate:b.attributes.expirationDate,profileContent:b.attributes.profileContent};else if(i.push(`Create MAC_APP_STORE profile ${c}`),!r){if(!s)throw Error("[pantry] Bundle ID was not created");if(!d?.id)throw Error("[pantry] MAC_APP_DISTRIBUTION certificate is required to create the profile");let A=await t.createMacAppStoreProfile(l.some((y)=>y.attributes.name===c)?`${c} ${d.id.slice(0,8)}`:c,s.id,d.id);R={id:A.id,name:A.attributes.name,exists:!0,created:!0,expirationDate:A.attributes.expirationDate,profileContent:A.attributes.profileContent}}else R={name:c,exists:!1,created:!1};let S=await t.findApp(e.identifier);if(!S)i.push(`Create the ${e.identifier} app record in App Store Connect (manual Apple step)`);return{mode:r?"plan":"apply",bundleId:{identifier:e.identifier,id:s?.id,exists:Boolean(s),created:n.created},capabilities:a,certificates:u,profile:R,appRecord:{exists:Boolean(S),id:S?.id,...!S?{manualAction:"Create the app record in App Store Connect; Apple does not expose an app-creation API."}:{}},actions:i}}import{createHash as j}from"node:crypto";import{basename as X,resolve as Q}from"node:path";import{readFile as Z}from"node:fs/promises";var ee=["alcoholTobaccoOrDrugUseOrReferences","contests","gamblingSimulated","gunsOrOtherWeapons","medicalOrTreatmentInformation","profanityOrCrudeHumor","sexualContentGraphicAndNudity","sexualContentOrNudity","horrorOrFearThemes","matureOrSuggestiveThemes","violenceCartoonOrFantasy","violenceRealisticProlongedGraphicOrSadistic","violenceRealistic"],te=["advertising","gambling","healthOrWellnessTopics","lootBox","messagingAndChat","parentalControls","ageAssurance","socialMedia","socialMediaAgeRestricted","unrestrictedWebAccess","userGeneratedContent"],re=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED"]);function ie(e={}){let t={ageRatingOverrideV2:"NONE",koreaAgeRatingOverride:"NONE"};for(let r of ee)t[r]=e[r]??"NONE";for(let r of te)t[r]=e[r]??!1;return t}function V(e){return e==="ios"?"IOS":"MAC_OS"}async function se(e,t,r){await e.request(`/apps/${t}`,{method:"PATCH",body:JSON.stringify({data:{type:"apps",id:t,attributes:{contentRightsDeclaration:r.contentRightsDeclaration}}})});let i=await e.request(`/apps/${t}/appInfos?limit=10`),n=i.data.find((p)=>p.attributes.appStoreState==="PREPARE_FOR_SUBMISSION")??i.data[0];if(!n)throw Error("[pantry] App Store Connect has no editable app information resource");await e.request(`/appInfos/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfos",id:n.id,relationships:{primaryCategory:{data:{type:"appCategories",id:r.primaryCategory}}}}})});let s=await e.request(`/appInfos/${n.id}/appInfoLocalizations?limit=200`),a=r.locale??"en-US",o=s.data.find((p)=>p.attributes.locale===a);if(!o)throw Error(`[pantry] App Store Connect app information is missing the ${a} localization`);return await e.request(`/appInfoLocalizations/${o.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfoLocalizations",id:o.id,attributes:{subtitle:r.subtitle,privacyPolicyUrl:r.privacyPolicyUrl}}})}),await e.request(`/ageRatingDeclarations/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"ageRatingDeclarations",id:n.id,attributes:ie(r.ageRating)}})}),n.id}async function ne(e,t,r){try{if((await e.request(`/appPriceSchedules/${t}/manualPrices?limit=200`)).data.length)return}catch(p){if(!(p instanceof Error)||!p.message.includes("(404)"))throw p}let i=r.baseTerritory??"USA",n=await e.request(`/apps/${t}/appPricePoints?filter[territory]=${encodeURIComponent(i)}&limit=200`),s=Number(r.price),a=n.data.find((p)=>Number(p.attributes.customerPrice)===s);if(!a)throw Error(`[pantry] App Store price ${r.price} is unavailable in ${i}`);let o="${price}";await e.request("/appPriceSchedules",{method:"POST",body:JSON.stringify({data:{type:"appPriceSchedules",relationships:{app:{data:{type:"apps",id:t}},baseTerritory:{data:{type:"territories",id:i}},manualPrices:{data:[{type:"appPrices",id:o}]}}},included:[{type:"appPrices",id:o,attributes:{startDate:null,endDate:null},relationships:{appPricePoint:{data:{type:"appPricePoints",id:a.id}}}}]})})}async function ae(e,t,r=!0){try{if((await e.request(`/apps/${t}/appAvailabilityV2`)).data.attributes.availableInNewTerritories===r)return;return}catch(s){if(!(s instanceof Error)||!s.message.includes("(404)"))throw s}let n=(await e.request("/territories?limit=200")).data.map((s,a)=>({type:"territoryAvailabilities",id:`\${territory-${a}}`,attributes:{available:!0},relationships:{territory:{data:{type:"territories",id:s.id}}}}));await e.request("/v2/appAvailabilities",{method:"POST",body:JSON.stringify({data:{type:"appAvailabilities",attributes:{availableInNewTerritories:r},relationships:{app:{data:{type:"apps",id:t}},territoryAvailabilities:{data:n.map((s)=>({type:s.type,id:s.id}))}}},included:n})})}async function oe(e,t,r){let i=r.locale??"en-US",s=(await e.request(`/appStoreVersions/${t}/appStoreVersionLocalizations?limit=200`)).data.find((a)=>a.attributes.locale===i);if(!s)s=(await e.request("/appStoreVersionLocalizations",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",attributes:{locale:i},relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})).data;return await e.request(`/appStoreVersionLocalizations/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",id:s.id,attributes:{description:r.description,keywords:r.keywords,supportUrl:r.supportUrl,...r.marketingUrl?{marketingUrl:r.marketingUrl}:{},...r.promotionalText?{promotionalText:r.promotionalText}:{},...r.whatsNew?{whatsNew:r.whatsNew}:{}}}})}),s.id}async function pe(e,t,r){let i=await e.request(`/appStoreVersions/${t}/appStoreReviewDetail`),n={contactFirstName:r.reviewContact.firstName,contactLastName:r.reviewContact.lastName,contactPhone:r.reviewContact.phone,contactEmail:r.reviewContact.email,demoAccountRequired:!1,...r.reviewContact.notes?{notes:r.reviewContact.notes}:{}};if(i.data){await e.request(`/appStoreReviewDetails/${i.data.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreReviewDetails",id:i.data.id,attributes:n}})});return}await e.request("/appStoreReviewDetails",{method:"POST",body:JSON.stringify({data:{type:"appStoreReviewDetails",attributes:n,relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})}async function L(e,t){let r=[],i=t;while(i){let n=await e.request(i);r.push(...n.data),i=n.links?.next}return r}async function ce(e,t,r,i){let n=Date.now()+r;while(!0){let{data:s}=await e.request(`/appAssetLibraryImages/${t}`);if(s.attributes.specId&&!["AWAITING_UPLOAD","UPLOAD_COMPLETE","PROCESSING","FAILED","REJECTED","ARCHIVED"].includes(s.attributes.state))return s;if(["FAILED","REJECTED","ARCHIVED"].includes(s.attributes.state))throw Error(`[pantry] App Store image ${s.attributes.fileName} ${s.attributes.state}: ${JSON.stringify(s.attributes.stateDetails)}`);if(Date.now()>=n)throw Error(`[pantry] timed out processing App Store image ${s.attributes.fileName}`);await new Promise((a)=>setTimeout(a,i))}}function de(e){if(Array.isArray(e))return e;let t={APP_DESKTOP:"MAC_APP_STORE",APP_IPHONE_67:"IPHONE_APP_STORE",APP_IPAD_PRO_3GEN_129:"IPAD_APP_STORE"};return Object.entries(e).flatMap(([r,i])=>i?[{platform:t[r],files:i}]:[])}async function ue(e,t,r,i,n,s,a){if(!i.some((l)=>l.files.length))return;let{data:o}=await e.request(`/apps/${t}/assetLibrary`),{data:p}=await e.request("/appAssetLibraryRefData"),u=p[0]?.attributes;if(!u)throw Error("[pantry] Apple returned no asset specification catalog");let f=await L(e,`/appAssetLibraries/${o.id}/images?limit=200`),d=await L(e,`/appStoreVersionLocalizations/${r}/placements?filter[placementType]=APP_SCREENSHOT&include=image&limit=200`),c=new Map;for(let l of i)for(let b of l.files){let R=Q(n,b),S=await Z(R),A=`sha256:${j("sha256").update(S).digest("hex")}`,y=f.find((h)=>h.attributes.referenceName===A);if(y?.attributes.state==="FAILED")await e.request(`/appAssetLibraryImages/${y.id}`,{method:"DELETE"});let m=y?.attributes.state==="FAILED"?void 0:y;if(m&&["REJECTED","ARCHIVED"].includes(m.attributes.state))throw Error(`[pantry] Existing image ${b} is ${m.attributes.state}`);if(!m)m=(await e.request("/appAssetLibraryImages",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryImages",attributes:{fileName:X(R),fileSize:S.byteLength,category:"APP_SCREENSHOTS_AND_PREVIEWS",referenceName:A},relationships:{assetLibrary:{data:{type:"appAssetLibraries",id:o.id}}}}})})).data;if(m.attributes.state==="AWAITING_UPLOAD"){if(!m.attributes.uploadOperations)m=(await e.request(`/appAssetLibraryImages/${m.id}`)).data;let h=0;for(let g of m.attributes.uploadOperations??[]){if(g.offset!==h||!Number.isSafeInteger(g.length)||g.length<=0||g.offset+g.length>S.byteLength)throw Error("[pantry] Invalid Apple image upload byte range");await e.upload(g.url,{method:g.method,headers:Object.fromEntries(g.requestHeaders.map((I)=>[I.name,I.value])),body:S.subarray(g.offset,g.offset+g.length)}),h+=g.length}if(h!==S.byteLength)throw Error("[pantry] Apple image upload operations do not cover the entire file");await e.request(`/appAssetLibraryImages/${m.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appAssetLibraryImages",id:m.id,attributes:{uploaded:!0}}})})}if(m=await ce(e,m.id,s,a),!f.some((h)=>h.id===m.id))f.push(m);let E=(u.placementTypes.find((h)=>h.placementTypeId==="APP_SCREENSHOT")?.specMappings??[]).find((h)=>h.specs.includes(m.attributes.specId)&&u.placementProfileGroups.some((g)=>g.placementProfileGroupId===h.placementGroupId&&g.platform===l.platform))?.placementGroupId;if(!E)throw Error(`[pantry] Image ${b} does not match an Apple screenshot specification for ${l.platform}`);let P=c.get(E)??[];if(!P.includes(m.id))P.push(m.id);c.set(E,P)}for(let[l,b]of c){let R=u.features.find((y)=>y.featureId==="APP_STORE_VERSIONS")?.placementPolicies.find((y)=>y.placementType==="APP_SCREENSHOT")?.groupLimits.find((y)=>y.groupIds.includes(l))?.maxCount;if(R===void 0||b.length>R)throw Error(`[pantry] Screenshot count exceeds Apple's limit for ${l}`);let S=d.filter((y)=>y.attributes.placementGroup===l),A=[];for(let y of b){let m=S.find((w)=>w.relationships?.image?.data&&!Array.isArray(w.relationships.image.data)&&w.relationships.image.data.id===y);if(!m)m=(await e.request("/appAssetLibraryPlacements",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacements",attributes:{placementType:"APP_SCREENSHOT",placementGroup:l},relationships:{image:{data:{type:"appAssetLibraryImages",id:y}},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})).data;A.push({type:"appAssetLibraryPlacements",id:m.id})}for(let y of S)if(!A.some((m)=>m.id===y.id))await e.request(`/appAssetLibraryPlacements/${y.id}`,{method:"DELETE"});await e.request("/appAssetLibraryPlacementOrderingRequests",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacementOrderingRequests",attributes:{placementGroup:l},relationships:{orderedPlacements:{data:A},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})}}async function le(e,t,r){if(await e.request(`/appStoreVersions/${t.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersions",id:t.id,attributes:{copyright:r.copyright,releaseType:r.releaseType??"AFTER_APPROVAL",usesIdfa:r.usesIdfa??!1}}})}),t.buildId){if(r.encryptionDeclarationId){await co(e,t.buildId,r.encryptionDeclarationId);return}let i=r.usesNonExemptEncryption??!1,n=await e.request(`/builds/${t.buildId}?fields[builds]=usesNonExemptEncryption`);if(n.data.attributes.usesNonExemptEncryption===void 0||n.data.attributes.usesNonExemptEncryption===null)await e.request(`/builds/${t.buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t.buildId,attributes:{usesNonExemptEncryption:i}}})})}}async function co(e,t,r){let i=await e.request(`/appEncryptionDeclarations/${encodeURIComponent(r)}?include=app`);if(i.data.attributes.appEncryptionDeclarationState!=="APPROVED")throw Error("[pantry] App Store encryption declaration must be APPROVED before attaching a build");let n=await e.request(`/builds/${encodeURIComponent(t)}?include=app,appEncryptionDeclaration`),s=i.data.relationships?.app?.data,a=n.data.relationships?.app?.data;if(!s||Array.isArray(s)||!a||Array.isArray(a)||s.id!==a.id)throw Error("[pantry] App Store encryption declaration and build must belong to the same app");let o=n.data.relationships?.appEncryptionDeclaration?.data;if(o&&!Array.isArray(o)&&o.id===r)return;if(n.data.attributes.usesNonExemptEncryption===!1)throw Error("[pantry] Refusing to attach a non-exempt declaration to a build marked exempt");await e.request(`/builds/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t,attributes:{usesNonExemptEncryption:!0},relationships:{appEncryptionDeclaration:{data:{type:"appEncryptionDeclarations",id:r}}}}})})}async function M(e,t,r){let i=await e.request(`/apps/${t}/reviewSubmissions?limit=200`),n=[];for(let s of r){let a=V(s.platform),o=i.data.filter((d)=>d.attributes.platform===a&&d.attributes.state!=="COMPLETE"),p;for(let d of o){if(!((await e.request(`/reviewSubmissions/${d.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((b)=>b.type==="appStoreVersions"&&b.id===s.id))continue;if(p=d,d.attributes.state!=="READY_FOR_REVIEW"){n.push(d.id);break}}if(p&&p.attributes.state!=="READY_FOR_REVIEW")continue;if(p??=o.find((d)=>d.attributes.state==="READY_FOR_REVIEW"),!p)p=(await e.request("/reviewSubmissions",{method:"POST",body:JSON.stringify({data:{type:"reviewSubmissions",attributes:{platform:a},relationships:{app:{data:{type:"apps",id:t}}}}})})).data;if(!((await e.request(`/reviewSubmissions/${p.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((d)=>d.type==="appStoreVersions"&&d.id===s.id))await e.request("/reviewSubmissionItems",{method:"POST",body:JSON.stringify({data:{type:"reviewSubmissionItems",relationships:{reviewSubmission:{data:{type:"reviewSubmissions",id:p.id}},appStoreVersion:{data:{type:"appStoreVersions",id:s.id}}}}})});await e.request(`/reviewSubmissions/${p.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"reviewSubmissions",id:p.id,attributes:{submitted:!0}}})}),n.push(p.id)}return n}async function Ie(e,t,r,i,n={}){if(t.encryptionDeclarationId&&t.usesNonExemptEncryption!==!0)throw Error("[pantry] An encryption declaration requires usesNonExemptEncryption: true");if(t.usesNonExemptEncryption===!0&&!t.encryptionDeclarationId)throw Error("[pantry] Non-exempt encryption requires an Apple-approved encryptionDeclarationId");let s=n.cwd??process.cwd(),a=n.screenshotTimeoutMs??600000,o=n.screenshotPollIntervalMs??5000;await se(e,r,t),await ne(e,r,t),await ae(e,r,t.availableInNewTerritories??!0);let p=[];for(let f of i){await le(e,f,t);let d=await oe(e,f.id,t);await pe(e,f.id,t);let c=de(t.screenshots).filter((l)=>f.platform==="macos"?l.platform==="MAC_APP_STORE":l.platform!=="MAC_APP_STORE");await ue(e,r,d,c,s,a,o),p.push({platform:f.platform,versionId:f.id,localizationId:d})}let u=n.submit??t.submitForReview??!1;return{appId:r,versions:p,reviewSubmissionIds:u?await M(e,r,i):[]}}async function Da(e,t){if(!t.bundleId)throw Error("[pantry] App Store submission requires a bundle ID");let r=new T(t),i=await r.findApp(t.bundleId);if(!i)throw Error("[pantry] the App Store Connect app record is missing");let n=t.platforms??["macos"],s=await r.listAppStoreVersions(i.id),a=[],o=[];for(let u of n){let f=s.find((c)=>c.attributes.platform===V(u)&&c.attributes.versionString===t.version);if(!f)throw Error(`[pantry] ${u} App Store version ${t.version} does not exist`);let d=await r.request(`/appStoreVersions/${f.id}/build`);a.push({platform:u,id:f.id,buildId:d.data?.id}),o.push(f.attributes.appStoreState)}if((t.submit??e.submitForReview??!1)&&o.every((u)=>!re.has(u))){let u=await Promise.all(a.map(async(f)=>{let d=await r.request(`/appStoreVersions/${f.id}/appStoreVersionLocalizations?limit=200`);return{platform:f.platform,versionId:f.id,localizationId:d.data[0]?.id??""}}));return{appId:i.id,versions:u,reviewSubmissionIds:await M(r,i.id,a)}}return await Ie(r,e,i.id,a,t)}import{execFileSync as fe}from"node:child_process";import{createReadStream as me}from"node:fs";import{createHash as ye}from"node:crypto";class C extends Error{}async function be(e){let t=ye("sha256");return await new Promise((r,i)=>{let n=me(e);n.on("data",(s)=>t.update(s)),n.once("end",r),n.once("error",i)}),t.digest("hex")}async function q(e){return e.json().catch(async()=>({error:await e.text().catch(()=>e.statusText)}))}function ge(e){let t=(e.registryUrl||process.env.PANTRY_REGISTRY_URL||process.env.REGISTRY_URL||"https://registry.pantry.dev").replace(/\/+$/,""),r=e.token||process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN||"";if(!r)throw Error("PANTRY_REGISTRY_TOKEN or PANTRY_TOKEN is required for binary publication");return{registryUrl:t,token:r}}var bt=3600000,Aa=30000,lo=Math.ceil(bt/Aa)+10;function po(e,t){let r=t.retryable?" (retryable)":"",i=t.scan?` [scan verdict=${t.scan.verdict}${t.scan.signature?` signature=${t.scan.signature}`:""}${t.scan.reason?` reason=${t.scan.reason}`:""}${t.scan.engineVersion?` engine=${t.scan.engineVersion}`:""}${t.scan.databaseVersion?` db=${t.scan.databaseVersion}`:""}${t.scan.durationMs?` durationMs=${t.scan.durationMs}`:""}]`:"";return Error(`${t.code||e.status}: ${t.error||e.statusText}${r}${i}`)}function Se(e,t){let r=Number(t?.retryAfterSeconds);if(Number.isFinite(r)&&r>0)return r*1000;let i=Number(e.headers?.get?.("Retry-After"));if(Number.isFinite(i)&&i>0)return i*1000;return null}function he(e,t){return e.status===408||e.status===425||e.status===429||t?.retryable===!0||e.status>=500&&!t.code||e.status===404&&t.code==="BINARY_STAGING_NOT_FOUND"}async function go(e,t,r,i={}){let n=Math.max(1,i.attempts??lo),s=Date.now()+(i.deadlineMs??bt),a=i.fetch??fetch,o=i.sleep??((d)=>new Promise((c)=>setTimeout(c,d))),p=Error("binary upload completion did not run"),u=Date.now(),f=0;for(let d=1;d<=n;d++){f=d;let c=Math.min(Aa,1000*2**Math.min(d-1,5));try{let l=await a(`${e}/api/v1/binaries/uploads/complete`,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({uploadId:t})}),b=await q(l);if(l.ok&&b.success===!0)return b;if(p=po(l,b),!he(l,b))throw new C(p.message);c=Math.max(c,Se(l,b)??0)}catch(l){if(l instanceof C)throw l;p=l instanceof Error?l:Error(String(l))}if(d>=n||Date.now()>=s)break;if(Date.now()+c>s){p=Error(`${p.message} - registry asked for ${Math.round(c/1000)}s more than the ${Math.round((s-u)/60000)} min completion budget allows`);break}await o(c)}throw Error(`Binary upload completion remained ambiguous after ${f} attempts over ${Math.round((Date.now()-u)/1000)}s: ${p.message}`)}var mo=4;function Re(e){return e.status===408||e.status===429||e.status>=500}async function we(e,t,r,i){let n=Math.max(1,i.initiateAttempts??mo),s=i.fetch??fetch,a=i.sleep??((p)=>new Promise((u)=>setTimeout(u,p))),o=Error("binary upload initiation did not run");for(let p=1;p<=n;p++){try{let u=await s(`${e}/api/v1/binaries/uploads`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:r}),f=await q(u);if(u.ok||!Re(u))return{response:u,initiated:f};o=Error(`${f.code||u.status}: ${f.error||u.statusText}`)}catch(u){o=u instanceof Error?u:Error(String(u))}if(p>=n)break;await a(Math.min(Aa,1000*2**(p-1)))}throw Error(`Could not reach the registry to start the upload after ${n} attempts: ${o.message}`)}async function Ia(e){let{registryUrl:t,token:r}=ge(e),i=await be(e.filePath),n={Authorization:`Bearer ${r}`},{response:s,initiated:a}=await we(t,n,JSON.stringify({domain:e.domain,version:e.version,platforms:e.platforms,filename:e.filename,size:e.size,sha256:i}),e);if(!s.ok||!a.uploadId||!a.uploadUrl)throw Error(`${a.code||s.status}: ${a.error||s.statusText}`);let o=["-fsS","--connect-timeout","30","--speed-limit","1024","--speed-time","120","--retry","3","--retry-all-errors","-X","PUT"];for(let[u,f]of Object.entries(a.uploadHeaders||{}))o.push("-H",`${u}: ${f}`);o.push("-T",e.filePath,a.uploadUrl),fe("curl",o,{stdio:["ignore","ignore","inherit"]});let p=await go(t,a.uploadId,n);if(p.scan?.artifactSha256!==i||p.scan?.verdict!=="clean")throw Error("Registry returned an invalid binary malware-scan attestation");return p}
2
+ export{no,T,De,Ae,ro,io,Sa,co,Ie,Da,bt,Aa,lo,po,go,mo,Ia};
@@ -1,2 +1,2 @@
1
- import{de}from"./chunk-3bs6jc4d.js";import{Be}from"./chunk-6rsaa2nw.js";import{createHash as U,randomBytes as H,randomInt as N,timingSafeEqual as q}from"node:crypto";import{chmodSync as F,existsSync as O,lstatSync as J,mkdirSync as M,readFileSync as _,renameSync as V,writeFileSync as W}from"node:fs";import{homedir as z}from"node:os";import{isAbsolute as X,join as h}from"node:path";var v=(r)=>U("sha256").update(r).digest("hex"),Z=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;function G(){return h(process.env.XDG_DATA_HOME||h(z(),".local/share"),"pantry/desktop")}function K(r){M(r,{recursive:!0,mode:448});let n=J(r);if(n.isSymbolicLink()||!n.isDirectory()||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only directory")}function T(r){let n=J(r);if(!n.isFile()||n.isSymbolicLink()||n.nlink!==1||n.size>40000000||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only file");return JSON.parse(_(r,"utf8"))}function A(r,n){let d=`${r}.${crypto.randomUUID()}.tmp`;W(d,JSON.stringify(n),{mode:384,flag:"wx"}),V(d,r),F(r,384)}function fe(r=G(),n=Date.now()){K(r);let d=String(N(1e7,1e8));return A(h(r,"pairing.json"),{hash:v(d),expiresAt:n+300000}),d}function B(r,n){return/^[a-f0-9]{64}$/.test(r)&&/^[a-f0-9]{64}$/.test(n)&&q(Buffer.from(r,"hex"),Buffer.from(n,"hex"))}function w(r){let{clientId:n,...d}=r;return d}function At(r){if(process.platform!=="darwin")return[];let n=(s)=>s.toLowerCase().replace(/[^a-z0-9]/g,""),d=new Map(r.filter((s)=>s.kind==="app").map((s)=>[n(s.name),s.domain]));return["/Applications",h(z(),"Applications")].flatMap((s)=>de(s)).flatMap((s)=>{let a=d.get(n(s.name));return a?[{name:a,version:s.version,applicationPath:s.path}]:[]})}function Ye(r={}){let n=r.now??Date.now,d=r.stateDirectory??G();K(d);let s=h(d,"state.json"),a=O(s)?T(s):{clients:[],jobs:[]};if(!Array.isArray(a.clients)||!Array.isArray(a.jobs))throw Error("Invalid Pantry Desktop state");let m=()=>A(s,a);for(let e of a.jobs)if(e.status==="queued"||e.status==="running")e.status="failed",e.error="Pantry restarted before this installation completed. Check installed packages before retrying.",e.finishedAt=new Date(n()).toISOString(),e.timezoneOffset=new Date(n()).getTimezoneOffset();m();let E=r.catalog??Be(),D=new Map(E.map((e)=>[e.domain,e])),P=r.pantryExecutable??Bun.which("pantry");if(!r.run&&(!P||!X(P)))throw Error("Install the Pantry CLI before starting its desktop bridge");let I,L=r.run??(async(e,c)=>{let i=Bun.spawn([P,...e],{cwd:d,stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,NO_COLOR:"1",CI:"1"}});I=i;let p=async(g)=>{let t=g.getReader(),f=new TextDecoder;try{while(!0){let l=await t.read();if(l.done)break;c(f.decode(l.value,{stream:!0}))}}finally{t.releaseLock()}};try{return await Promise.all([p(i.stdout),p(i.stderr)]),await i.exited}finally{I=void 0}}),S=Promise.resolve(),C=(e,c)=>{let i=S.then(()=>{if(b)throw Error("Pantry Desktop is stopping");return L(e,c)});return S=i.catch(()=>{}),i},k=!1,b=!1,j;async function R(){if(k||b)return;k=!0;try{while(!b){let e=a.jobs.find((i)=>i.status==="queued");if(!e)break;e.status="running",e.startedAt=new Date(n()).toISOString(),m();try{let i=D.get(e.domain).kind,p=await C(["install","--user",...["app","font"].includes(i)?["--kind",i]:[],e.domain],(g)=>{e.output=(e.output+g).slice(-32000)});if(e.status=p===0?"succeeded":"failed",p)e.error=`Pantry installation exited with code ${p}`}catch(i){e.status="failed",e.error=i instanceof Error?i.message:"Pantry installation failed"}let c=new Date(n());e.finishedAt=c.toISOString(),e.timezoneOffset=c.getTimezoneOffset(),m()}}finally{k=!1}}let o=(e,c=200)=>Response.json(e,{status:c,headers:{"cache-control":"no-store"}}),y=[],x=Bun.serve({hostname:"127.0.0.1",port:r.port??46473,maxRequestBodySize:4096,async fetch(e){let c=new URL(e.url);if(e.headers.has("origin")||e.headers.get("host")!==`127.0.0.1:${x.port}`)return o({error:"Forbidden origin or host"},403);if(c.pathname==="/health"&&e.method==="GET")return o({protocolVersion:1,service:"pantry-desktop",capabilities:["install:user","installed","jobs"]});if(c.pathname==="/pair"&&e.method==="POST"){while(y.length&&y[0]<n()-60000)y.shift();if(y.length>=10)return o({error:"Too many pairing attempts. Try again in a minute."},429);y.push(n());let t=await e.json().catch(()=>null);if(!t||typeof t.code!=="string"||!/^\d{8}$/.test(t.code)||typeof t.name!=="string"||!t.name.trim()||t.name.length>80)return o({error:"Provide the pairing code and application name."},422);let f=h(d,"pairing.json");if(!O(f))return o({error:"Create a pairing code from the Pantry CLI first."},401);let l=T(f);if(l.expiresAt<=n()||!B(l.hash,v(t.code)))return o({error:"The Pantry pairing code is invalid or expired."},401);if(a.clients.length>=100)return o({error:"Remove unused Pantry Desktop connections before pairing another app."},409);let u=H(32).toString("base64url");return a.clients.push({id:crypto.randomUUID(),name:t.name.trim(),tokenHash:v(u)}),A(f,{hash:"",expiresAt:0}),m(),o({token:u},201)}let i=e.headers.get("authorization")?.match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1],p=i?a.clients.find((t)=>B(t.tokenHash,v(i))):void 0;if(!p)return o({error:"Connect this application to Pantry first."},401);if(c.pathname==="/v1/connection"&&e.method==="DELETE")return a.clients=a.clients.filter((t)=>t.id!==p.id),m(),o({disconnected:!0});if(c.pathname==="/v1/installed"&&e.method==="GET"){let t="";if(await C(["list","--format","json"],(l)=>{if(t.length<4000000)t+=l}))return o({error:"Pantry could not list installed packages."},502);try{let l=JSON.parse(t);if(!Array.isArray(l)||l.some((u)=>typeof u.name!=="string"||typeof u.version!=="string"))throw Error("Invalid installed package list");return o({packages:[...l.map((u)=>({name:u.name,version:u.version})),...r.run?[]:At(E)]})}catch{return o({error:"Pantry returned an invalid installed package list."},502)}}if(c.pathname==="/v1/install"&&e.method==="POST"){let t=await e.json().catch(()=>null);if(!t||typeof t.domain!=="string"||!D.has(t.domain)||typeof t.requestId!=="string"||!Z.test(t.requestId))return o({error:"Choose a package from the Pantry catalog and provide a request ID."},422);let f=a.jobs.find((u)=>u.clientId===p.id&&u.requestId===t.requestId);if(f)return f.domain===t.domain?o({job:w(f)},202):o({error:"This request ID already belongs to another package."},409);if(a.jobs.filter((u)=>u.status==="queued"||u.status==="running").length>=3)return o({error:"Wait for current Pantry installations to finish."},429);let l={id:crypto.randomUUID(),requestId:t.requestId,clientId:p.id,domain:t.domain,kind:D.get(t.domain).kind,status:"queued",output:"",createdAt:new Date(n()).toISOString()};if(a.jobs.push(l),a.jobs.length>1000)a.jobs.splice(0,a.jobs.length-1000);if(m(),!k)j=R();return o({job:w(l)},202)}if(c.pathname==="/v1/jobs"&&e.method==="GET")return o({jobs:a.jobs.filter((t)=>t.clientId===p.id).slice(-50).reverse().map(w)});let g=c.pathname.match(/^\/v1\/jobs\/([a-f0-9-]{36})$/i);if(g&&e.method==="GET"){let t=a.jobs.find((f)=>f.id===g[1]&&f.clientId===p.id);return t?o({job:w(t)}):o({error:"Pantry installation was not found."},404)}return o({error:"Not found"},404)},error(){return o({error:"Pantry Desktop could not complete this request."},500)}});return{server:x,async close(){b=!0,I?.kill(),await j,await S,await x.stop(!0)}}}
2
- export{G,K,fe,At,Ye};
1
+ import{de}from"./chunk-3sc39cqf.js";import{Be}from"./chunk-mvzv8skb.js";import{createHash as U,randomBytes as H,randomInt as N,timingSafeEqual as q}from"node:crypto";import{chmodSync as F,existsSync as O,lstatSync as J,mkdirSync as M,readFileSync as _,renameSync as V,writeFileSync as W}from"node:fs";import{homedir as z}from"node:os";import{isAbsolute as X,join as h}from"node:path";var v=(r)=>U("sha256").update(r).digest("hex"),Z=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;function G(){return h(process.env.XDG_DATA_HOME||h(z(),".local/share"),"pantry/desktop")}function K(r){M(r,{recursive:!0,mode:448});let n=J(r);if(n.isSymbolicLink()||!n.isDirectory()||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only directory")}function T(r){let n=J(r);if(!n.isFile()||n.isSymbolicLink()||n.nlink!==1||n.size>40000000||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only file");return JSON.parse(_(r,"utf8"))}function A(r,n){let d=`${r}.${crypto.randomUUID()}.tmp`;W(d,JSON.stringify(n),{mode:384,flag:"wx"}),V(d,r),F(r,384)}function fe(r=G(),n=Date.now()){K(r);let d=String(N(1e7,1e8));return A(h(r,"pairing.json"),{hash:v(d),expiresAt:n+300000}),d}function B(r,n){return/^[a-f0-9]{64}$/.test(r)&&/^[a-f0-9]{64}$/.test(n)&&q(Buffer.from(r,"hex"),Buffer.from(n,"hex"))}function w(r){let{clientId:n,...d}=r;return d}function It(r){if(process.platform!=="darwin")return[];let n=(s)=>s.toLowerCase().replace(/[^a-z0-9]/g,""),d=new Map(r.filter((s)=>s.kind==="app").map((s)=>[n(s.name),s.domain]));return["/Applications",h(z(),"Applications")].flatMap((s)=>de(s)).flatMap((s)=>{let a=d.get(n(s.name));return a?[{name:a,version:s.version,applicationPath:s.path}]:[]})}function Ye(r={}){let n=r.now??Date.now,d=r.stateDirectory??G();K(d);let s=h(d,"state.json"),a=O(s)?T(s):{clients:[],jobs:[]};if(!Array.isArray(a.clients)||!Array.isArray(a.jobs))throw Error("Invalid Pantry Desktop state");let m=()=>A(s,a);for(let e of a.jobs)if(e.status==="queued"||e.status==="running")e.status="failed",e.error="Pantry restarted before this installation completed. Check installed packages before retrying.",e.finishedAt=new Date(n()).toISOString(),e.timezoneOffset=new Date(n()).getTimezoneOffset();m();let E=r.catalog??Be(),D=new Map(E.map((e)=>[e.domain,e])),P=r.pantryExecutable??Bun.which("pantry");if(!r.run&&(!P||!X(P)))throw Error("Install the Pantry CLI before starting its desktop bridge");let I,L=r.run??(async(e,c)=>{let i=Bun.spawn([P,...e],{cwd:d,stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,NO_COLOR:"1",CI:"1"}});I=i;let p=async(g)=>{let t=g.getReader(),f=new TextDecoder;try{while(!0){let l=await t.read();if(l.done)break;c(f.decode(l.value,{stream:!0}))}}finally{t.releaseLock()}};try{return await Promise.all([p(i.stdout),p(i.stderr)]),await i.exited}finally{I=void 0}}),S=Promise.resolve(),C=(e,c)=>{let i=S.then(()=>{if(b)throw Error("Pantry Desktop is stopping");return L(e,c)});return S=i.catch(()=>{}),i},k=!1,b=!1,j;async function R(){if(k||b)return;k=!0;try{while(!b){let e=a.jobs.find((i)=>i.status==="queued");if(!e)break;e.status="running",e.startedAt=new Date(n()).toISOString(),m();try{let i=D.get(e.domain).kind,p=await C(["install","--user",...["app","font"].includes(i)?["--kind",i]:[],e.domain],(g)=>{e.output=(e.output+g).slice(-32000)});if(e.status=p===0?"succeeded":"failed",p)e.error=`Pantry installation exited with code ${p}`}catch(i){e.status="failed",e.error=i instanceof Error?i.message:"Pantry installation failed"}let c=new Date(n());e.finishedAt=c.toISOString(),e.timezoneOffset=c.getTimezoneOffset(),m()}}finally{k=!1}}let o=(e,c=200)=>Response.json(e,{status:c,headers:{"cache-control":"no-store"}}),y=[],x=Bun.serve({hostname:"127.0.0.1",port:r.port??46473,maxRequestBodySize:4096,async fetch(e){let c=new URL(e.url);if(e.headers.has("origin")||e.headers.get("host")!==`127.0.0.1:${x.port}`)return o({error:"Forbidden origin or host"},403);if(c.pathname==="/health"&&e.method==="GET")return o({protocolVersion:1,service:"pantry-desktop",capabilities:["install:user","installed","jobs"]});if(c.pathname==="/pair"&&e.method==="POST"){while(y.length&&y[0]<n()-60000)y.shift();if(y.length>=10)return o({error:"Too many pairing attempts. Try again in a minute."},429);y.push(n());let t=await e.json().catch(()=>null);if(!t||typeof t.code!=="string"||!/^\d{8}$/.test(t.code)||typeof t.name!=="string"||!t.name.trim()||t.name.length>80)return o({error:"Provide the pairing code and application name."},422);let f=h(d,"pairing.json");if(!O(f))return o({error:"Create a pairing code from the Pantry CLI first."},401);let l=T(f);if(l.expiresAt<=n()||!B(l.hash,v(t.code)))return o({error:"The Pantry pairing code is invalid or expired."},401);if(a.clients.length>=100)return o({error:"Remove unused Pantry Desktop connections before pairing another app."},409);let u=H(32).toString("base64url");return a.clients.push({id:crypto.randomUUID(),name:t.name.trim(),tokenHash:v(u)}),A(f,{hash:"",expiresAt:0}),m(),o({token:u},201)}let i=e.headers.get("authorization")?.match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1],p=i?a.clients.find((t)=>B(t.tokenHash,v(i))):void 0;if(!p)return o({error:"Connect this application to Pantry first."},401);if(c.pathname==="/v1/connection"&&e.method==="DELETE")return a.clients=a.clients.filter((t)=>t.id!==p.id),m(),o({disconnected:!0});if(c.pathname==="/v1/installed"&&e.method==="GET"){let t="";if(await C(["list","--format","json"],(l)=>{if(t.length<4000000)t+=l}))return o({error:"Pantry could not list installed packages."},502);try{let l=JSON.parse(t);if(!Array.isArray(l)||l.some((u)=>typeof u.name!=="string"||typeof u.version!=="string"))throw Error("Invalid installed package list");return o({packages:[...l.map((u)=>({name:u.name,version:u.version})),...r.run?[]:It(E)]})}catch{return o({error:"Pantry returned an invalid installed package list."},502)}}if(c.pathname==="/v1/install"&&e.method==="POST"){let t=await e.json().catch(()=>null);if(!t||typeof t.domain!=="string"||!D.has(t.domain)||typeof t.requestId!=="string"||!Z.test(t.requestId))return o({error:"Choose a package from the Pantry catalog and provide a request ID."},422);let f=a.jobs.find((u)=>u.clientId===p.id&&u.requestId===t.requestId);if(f)return f.domain===t.domain?o({job:w(f)},202):o({error:"This request ID already belongs to another package."},409);if(a.jobs.filter((u)=>u.status==="queued"||u.status==="running").length>=3)return o({error:"Wait for current Pantry installations to finish."},429);let l={id:crypto.randomUUID(),requestId:t.requestId,clientId:p.id,domain:t.domain,kind:D.get(t.domain).kind,status:"queued",output:"",createdAt:new Date(n()).toISOString()};if(a.jobs.push(l),a.jobs.length>1000)a.jobs.splice(0,a.jobs.length-1000);if(m(),!k)j=R();return o({job:w(l)},202)}if(c.pathname==="/v1/jobs"&&e.method==="GET")return o({jobs:a.jobs.filter((t)=>t.clientId===p.id).slice(-50).reverse().map(w)});let g=c.pathname.match(/^\/v1\/jobs\/([a-f0-9-]{36})$/i);if(g&&e.method==="GET"){let t=a.jobs.find((f)=>f.id===g[1]&&f.clientId===p.id);return t?o({job:w(t)}):o({error:"Pantry installation was not found."},404)}return o({error:"Not found"},404)},error(){return o({error:"Pantry Desktop could not complete this request."},500)}});return{server:x,async close(){b=!0,I?.kill(),await j,await S,await x.stop(!0)}}}
2
+ export{G,K,fe,It,Ye};