ts-pantry 0.11.211 → 0.11.213

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/bin/cli.js +7 -7
  2. package/dist/bin/desktop.js +1 -1
  3. package/dist/chunk-5dxmfkha.js +1 -0
  4. package/dist/{chunk-ajp6hkpq.js → chunk-5zf7b4jc.js} +2 -2
  5. package/dist/chunk-7a3zc10s.js +1 -0
  6. package/dist/chunk-7ack6wjh.js +2 -0
  7. package/dist/{chunk-8zdkfn4a.js → chunk-9pr6bpwv.js} +1 -1
  8. package/dist/{chunk-50ncbz12.js → chunk-ac3pv9sr.js} +1 -1
  9. package/dist/chunk-ap6wjg88.js +1 -0
  10. package/dist/chunk-aqj6x63m.js +1 -0
  11. package/dist/chunk-bgsw3npc.js +1 -0
  12. package/dist/{chunk-nxesx524.js → chunk-c68xv4et.js} +2 -2
  13. package/dist/{chunk-hqh3n68z.js → chunk-g8p539wc.js} +2 -2
  14. package/dist/{chunk-m7khfs2w.js → chunk-ggzxbqkc.js} +2 -2
  15. package/dist/chunk-nwf76w87.js +1 -0
  16. package/dist/chunk-nxc33043.js +2 -0
  17. package/dist/chunk-pvf4zah9.js +1 -0
  18. package/dist/{chunk-wswnsdes.js → chunk-qr5x62k5.js} +88 -79
  19. package/dist/chunk-qt7gg2j9.js +1 -0
  20. package/dist/{chunk-m40m8kcg.js → chunk-vv7ytdgg.js} +2 -2
  21. package/dist/{chunk-jw7904zp.js → chunk-xyhbhw1y.js} +7 -7
  22. package/dist/{chunk-kcxrq2bb.js → chunk-zg9t7nk0.js} +3 -3
  23. package/dist/src/catalog/client.js +1 -1
  24. package/dist/src/desktop/service.js +1 -1
  25. package/dist/src/generated-package-names.d.ts +1 -1
  26. package/dist/src/index.js +1 -1
  27. package/dist/src/installer.d.ts +16 -0
  28. package/dist/src/native/index.js +3 -3
  29. package/dist/src/native/release.js +1 -1
  30. package/dist/src/packages/craft-native.org.d.ts +3 -3
  31. package/dist/src/testing/index.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-4gyts75b.js +0 -1
  34. package/dist/chunk-6bx0jrrj.js +0 -1
  35. package/dist/chunk-8082n3je.js +0 -1
  36. package/dist/chunk-ajp23b6n.js +0 -1
  37. package/dist/chunk-jjs7xkpc.js +0 -2
  38. package/dist/chunk-pd72mfsb.js +0 -1
  39. package/dist/chunk-qx84hzbc.js +0 -1
  40. package/dist/chunk-s1xdyq1s.js +0 -2
  41. package/dist/chunk-vxqxpm4b.js +0 -1
  42. package/dist/chunk-zd4apwjm.js +0 -1
package/dist/bin/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{T}from"../chunk-x5etgagm.js";import{Ee,_e}from"../chunk-nxesx524.js";import{f,K,Ze,j,H,Ce,y,V,D,R,W,je,Se,q,J,A,Q,I,O,L,i,Z,Ie,ze,$e,xa,wa}from"../chunk-wswnsdes.js";import{t,U,M}from"../chunk-jjs7xkpc.js";import"../chunk-8zdkfn4a.js";import"../chunk-ajp6hkpq.js";import{g}from"../chunk-s1xdyq1s.js";import p from"node:fs";import h from"node:path";import a from"node:process";U();async function te(o="src/pantry"){if(!p.existsSync(o))throw Error(`Pantry directory not found: ${o}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function n(r,s=""){let l=p.readdirSync(r,{withFileTypes:!0}),c=h.join(r,"package.yml");if(s&&p.existsSync(c))e.push(s);for(let u of l)if(u.isDirectory()&&!u.name.startsWith(".")){let S=s?`${s}/${u.name}`:u.name,m=h.join(r,u.name);n(m,S)}}return n(o),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ne(o=!1){async function e(c){let u=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(u.searchParams.set("list-type","2"),u.searchParams.set("prefix",""),u.searchParams.set("max-keys","1000"),c)u.searchParams.set("continuation-token",c);let S=await fetch(u.toString());if(!S.ok)throw Error(`Failed to fetch S3 listing: ${S.status}`);let m=await S.text(),P=[],E=m.match(/<Key>([^<]+)<\/Key>/g);if(E)for(let _ of E){let v=_.replace(/<Key>([^<]+)<\/Key>/,"$1");P.push({Key:v})}let d=m.includes("<IsTruncated>true</IsTruncated>"),k=m.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),w=k?k[1]:void 0;return{IsTruncated:d,NextContinuationToken:w,Contents:P}}console.log("Scraping packages from S3 registry...");let n=new Set,r;do{let c=await e(r);for(let u of c.Contents){let S=u.Key,m=S.split("/");if(m.length===0)continue;if(m[0].startsWith(".")||m[0].includes(" ")||S.match(/\.(md|txt|yml|yaml|json)$/i))continue;let P=["darwin","linux","windows"],E=-1;for(let d=1;d<m.length;d++)if(P.includes(m[d])){E=d;break}if(E>0){let d=m.slice(0,E).join("/");if(d.includes("."))n.add(d)}else if(m.length>=2&&m[0].includes(".")&&!m[1].startsWith("v")&&!m[1].match(/^\d/)){let d=`${m[0]}/${m[1]}`;n.add(d)}else if(m.length>=1&&m[0].includes("."))n.add(m[0])}r=c.NextContinuationToken,console.log(`Found ${n.size} packages so far...`)}while(r);let s=Array.from(n).sort(),l=[];for(let c of s){if(!c.includes(".")||c.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(c.endsWith("/README.rst")||c.endsWith("/README")||c.includes("/docs/"))continue;if(c.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(c))continue;l.push(c)}return console.log(`\uD83D\uDCE6 Found ${l.length} valid packages in registry`),l}async function oe(o,e){let r=`/**
2
+ import{T}from"../chunk-x5etgagm.js";import{Ee,_e}from"../chunk-c68xv4et.js";import{f,K,Ze,j,H,Ce,y,V,D,R,W,je,Se,q,J,A,Q,I,O,L,i,Z,Ie,ze,$e,wa,Pa}from"../chunk-qr5x62k5.js";import{t,U,M}from"../chunk-nxc33043.js";import"../chunk-9pr6bpwv.js";import"../chunk-5zf7b4jc.js";import{g}from"../chunk-7ack6wjh.js";import p from"node:fs";import h from"node:path";import a from"node:process";U();async function te(o="src/pantry"){if(!p.existsSync(o))throw Error(`Pantry directory not found: ${o}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function n(r,s=""){let l=p.readdirSync(r,{withFileTypes:!0}),c=h.join(r,"package.yml");if(s&&p.existsSync(c))e.push(s);for(let u of l)if(u.isDirectory()&&!u.name.startsWith(".")){let S=s?`${s}/${u.name}`:u.name,m=h.join(r,u.name);n(m,S)}}return n(o),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ne(o=!1){async function e(c){let u=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(u.searchParams.set("list-type","2"),u.searchParams.set("prefix",""),u.searchParams.set("max-keys","1000"),c)u.searchParams.set("continuation-token",c);let S=await fetch(u.toString());if(!S.ok)throw Error(`Failed to fetch S3 listing: ${S.status}`);let m=await S.text(),P=[],E=m.match(/<Key>([^<]+)<\/Key>/g);if(E)for(let _ of E){let v=_.replace(/<Key>([^<]+)<\/Key>/,"$1");P.push({Key:v})}let d=m.includes("<IsTruncated>true</IsTruncated>"),k=m.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),w=k?k[1]:void 0;return{IsTruncated:d,NextContinuationToken:w,Contents:P}}console.log("Scraping packages from S3 registry...");let n=new Set,r;do{let c=await e(r);for(let u of c.Contents){let S=u.Key,m=S.split("/");if(m.length===0)continue;if(m[0].startsWith(".")||m[0].includes(" ")||S.match(/\.(md|txt|yml|yaml|json)$/i))continue;let P=["darwin","linux","windows"],E=-1;for(let d=1;d<m.length;d++)if(P.includes(m[d])){E=d;break}if(E>0){let d=m.slice(0,E).join("/");if(d.includes("."))n.add(d)}else if(m.length>=2&&m[0].includes(".")&&!m[1].startsWith("v")&&!m[1].match(/^\d/)){let d=`${m[0]}/${m[1]}`;n.add(d)}else if(m.length>=1&&m[0].includes("."))n.add(m[0])}r=c.NextContinuationToken,console.log(`Found ${n.size} packages so far...`)}while(r);let s=Array.from(n).sort(),l=[];for(let c of s){if(!c.includes(".")||c.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(c.endsWith("/README.rst")||c.endsWith("/README")||c.includes("/docs/"))continue;if(c.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(c))continue;l.push(c)}return console.log(`\uD83D\uDCE6 Found ${l.length} valid packages in registry`),l}async function oe(o,e){let r=`/**
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()}
@@ -61,19 +61,19 @@ ${s.join(`
61
61
  Conflicts found:`),d.conflicts.forEach((w)=>{console.log(` ${w.package}: ${w.versions.join(", ")}`)});if(console.log(`
62
62
  \uD83D\uDCCB All unique packages to install:`),d.uniquePackages.forEach((w,_)=>{let v=d.allDependencies.find((b)=>b.name===w),C=v&&v.version&&v.version!=="latest"?` (${v.version})`:"";console.log(` ${_+1}. ${w}${C}`)}),m)console.log(`
63
63
  \uD83D\uDE80 Install command:`),console.log(`pantry install ${d.uniquePackages.join(" ")}`);if(Object.values(d.osSpecificDeps).reduce((w,_)=>w+_.length,0)>0)console.log(`
64
- \uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(d.osSpecificDeps).forEach(([w,_])=>{if(_.length>0)console.log(` ${w}: ${_.map((v)=>v.name).join(", ")}`)})}a.exit(0)}catch(n){if(e.json){let r={success:!1,error:String(n),timestamp:new Date().toISOString()};console.log(JSON.stringify(r))}else console.error("Error resolving dependencies:",n);a.exit(1)}});x.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(o)=>{try{let{getPhpVersionsForWorkflow:e}=await import("../chunk-ajp23b6n.js"),n={};if(o.branches)n.supportedBranches=o.branches.split(",").map((s)=>s.trim());if(o.fallback)n.fallbackVersions=o.fallback.split(",").map((s)=>s.trim());let r=e(n);switch(o.format.toLowerCase()){case"yaml":console.log(`php_versions:
64
+ \uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(d.osSpecificDeps).forEach(([w,_])=>{if(_.length>0)console.log(` ${w}: ${_.map((v)=>v.name).join(", ")}`)})}a.exit(0)}catch(n){if(e.json){let r={success:!1,error:String(n),timestamp:new Date().toISOString()};console.log(JSON.stringify(r))}else console.error("Error resolving dependencies:",n);a.exit(1)}});x.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(o)=>{try{let{getPhpVersionsForWorkflow:e}=await import("../chunk-pvf4zah9.js"),n={};if(o.branches)n.supportedBranches=o.branches.split(",").map((s)=>s.trim());if(o.fallback)n.fallbackVersions=o.fallback.split(",").map((s)=>s.trim());let r=e(n);switch(o.format.toLowerCase()){case"yaml":console.log(`php_versions:
65
65
  ${r.map((s)=>` - "${s}"`).join(`
66
- `)}`);break;case"csv":console.log(r.join(","));break;case"json":default:console.log(JSON.stringify(r));break}a.exit(0)}catch(e){console.error("Error getting PHP versions:",e),a.exit(1)}});x.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(o)=>{try{let{generateZigDefinitions:e,generateZigAliases:n}=await import("../chunk-vxqxpm4b.js"),{packagesDir:r="src/packages",output:s="packages.zig",aliases:l=!1,aliasesOutput:c="aliases.zig"}=o;if(console.log("\uD83D\uDE80 Generating Zig package definitions..."),await e(r,s),l)console.log(`
66
+ `)}`);break;case"csv":console.log(r.join(","));break;case"json":default:console.log(JSON.stringify(r));break}a.exit(0)}catch(e){console.error("Error getting PHP versions:",e),a.exit(1)}});x.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(o)=>{try{let{generateZigDefinitions:e,generateZigAliases:n}=await import("../chunk-qt7gg2j9.js"),{packagesDir:r="src/packages",output:s="packages.zig",aliases:l=!1,aliasesOutput:c="aliases.zig"}=o;if(console.log("\uD83D\uDE80 Generating Zig package definitions..."),await e(r,s),l)console.log(`
67
67
  \uD83D\uDE80 Generating Zig package aliases...`),await n(r,c);console.log(`
68
- ✅ Zig code generation complete!`),a.exit(0)}catch(e){console.error("Error generating Zig definitions:",e),a.exit(1)}});x.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(o,e)=>{let n=(o??"patch").toLowerCase();if(!["patch","minor","major"].includes(n))console.error(`error: invalid release type "${n}" (expected: patch | minor | major)`),a.exit(1);let{runRelease:r}=await import("../chunk-cwa30yjr.js"),s=await r({type:n,yes:e.yes,dryRun:e.dryRun,noChangelog:e.changelog===!1,noPush:e.push===!1,noPublish:e.publish===!1});a.exit(s.exitCode)});x.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(o)=>{try{let{scanInstalledApps:e}=await import("../chunk-4gyts75b.js"),n=e();if(o.json)console.log(JSON.stringify({success:!0,apps:n,total:n.length}));else{console.log(`
68
+ ✅ Zig code generation complete!`),a.exit(0)}catch(e){console.error("Error generating Zig definitions:",e),a.exit(1)}});x.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(o,e)=>{let n=(o??"patch").toLowerCase();if(!["patch","minor","major"].includes(n))console.error(`error: invalid release type "${n}" (expected: patch | minor | major)`),a.exit(1);let{runRelease:r}=await import("../chunk-cwa30yjr.js"),s=await r({type:n,yes:e.yes,dryRun:e.dryRun,noChangelog:e.changelog===!1,noPush:e.push===!1,noPublish:e.publish===!1});a.exit(s.exitCode)});x.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(o)=>{try{let{scanInstalledApps:e}=await import("../chunk-bgsw3npc.js"),n=e();if(o.json)console.log(JSON.stringify({success:!0,apps:n,total:n.length}));else{console.log(`
69
69
  Installed Desktop Apps (${n.length}):
70
- `),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let r of n)console.log(`${r.name.padEnd(40)}${r.version}`)}a.exit(0)}catch(e){console.error("Error listing apps:",e),a.exit(1)}});x.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(o)=>{try{let{checkAppUpdates:e}=await import("../chunk-4gyts75b.js");if(!o.json)console.log("Checking desktop apps for updates...");let n=await e(),r=n.filter((s)=>s.updateAvailable);if(o.json)console.log(JSON.stringify({success:!0,apps:n,outdated:r.length,total:n.length,timestamp:new Date().toISOString()}));else{if(r.length>0){console.log(`
70
+ `),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let r of n)console.log(`${r.name.padEnd(40)}${r.version}`)}a.exit(0)}catch(e){console.error("Error listing apps:",e),a.exit(1)}});x.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(o)=>{try{let{checkAppUpdates:e}=await import("../chunk-bgsw3npc.js");if(!o.json)console.log("Checking desktop apps for updates...");let n=await e(),r=n.filter((s)=>s.updateAvailable);if(o.json)console.log(JSON.stringify({success:!0,apps:n,outdated:r.length,total:n.length,timestamp:new Date().toISOString()}));else{if(r.length>0){console.log(`
71
71
  Outdated Apps (${r.length}):
72
72
  `),console.log("Application".padEnd(30)+"Current".padEnd(16)+"Latest".padEnd(16)+"Source"),console.log("-".repeat(75));for(let l of r)console.log(`${l.name.padEnd(30)}${l.currentVersion.padEnd(16)}${(l.latestVersion||"?").padEnd(16)}${l.source}`)}else console.log(`
73
73
  All desktop apps are up to date!`);let s=n.filter((l)=>!l.updateAvailable&&l.source!=="system"&&l.source!=="unknown");if(s.length>0)console.log(`
74
- ${s.length} app(s) up to date, ${n.filter((l)=>l.source==="unknown").length} unchecked`)}a.exit(0)}catch(e){console.error("Error checking app updates:",e),a.exit(1)}});x.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(o)=>{try{let{updateApp:e}=await import("../chunk-4gyts75b.js");console.log(`Updating ${o} from the pantry registry...`);let n=await e(o);if(n.success)console.log(`Successfully updated ${o} to ${n.version}`);else console.error(`Failed to update ${o}: ${n.error}`),a.exit(1);a.exit(0)}catch(e){console.error("Error updating app:",e),a.exit(1)}});x.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(o,e)=>{let n=o.lastIndexOf("@"),r=n>0,s=r?o.slice(0,n):o,l=r?o.slice(n+1):"latest";try{let c=await V(s,l,{installDir:e.installDir,platform:ie(e.platform),createBinLinks:e.binLinks!==!1,quiet:e.quiet,globalBin:e.global?!0:void 0});if(!e.quiet){if(console.log(`
74
+ ${s.length} app(s) up to date, ${n.filter((l)=>l.source==="unknown").length} unchecked`)}a.exit(0)}catch(e){console.error("Error checking app updates:",e),a.exit(1)}});x.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(o)=>{try{let{updateApp:e}=await import("../chunk-bgsw3npc.js");console.log(`Updating ${o} from the pantry registry...`);let n=await e(o);if(n.success)console.log(`Successfully updated ${o} to ${n.version}`);else console.error(`Failed to update ${o}: ${n.error}`),a.exit(1);a.exit(0)}catch(e){console.error("Error updating app:",e),a.exit(1)}});x.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(o,e)=>{let n=o.lastIndexOf("@"),r=n>0,s=r?o.slice(0,n):o,l=r?o.slice(n+1):"latest";try{let c=await V(s,l,{installDir:e.installDir,platform:ie(e.platform),createBinLinks:e.binLinks!==!1,quiet:e.quiet,globalBin:e.global?!0:void 0});if(!e.quiet){if(console.log(`
75
75
  ✓ ${c.name}@${c.version}`),console.log(` installed to: ${c.installPath}`),c.globalLinks&&c.globalLinks.length>0){if(console.log(` linked into: ${h.dirname(c.globalLinks[0])}`),!a.env.PATH?.split(h.delimiter).includes(h.dirname(c.globalLinks[0])))console.log(`
76
76
  ⚠ ${h.dirname(c.globalLinks[0])} is not on your PATH yet.`),console.log(" Run `ts-pantry shell-init --install` once to fix that.")}}a.exit(0)}catch(c){console.error(`Error installing ${o}:`,c instanceof Error?c.message:c),a.exit(1)}});function re(o){let e=Ce(o);if(e.length===0)return[];try{return j(e[0]).map((n)=>n.version&&n.version!=="latest"?`${n.name}@${String(n.version).replace(/^[\^~>=<]+/,"")}`:n.name)}catch{return[]}}x.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(o)=>{let e=h.resolve(o.dir??a.cwd()),n=re(e);if(o.install&&n.length>0)for(let l of n){let c=l.lastIndexOf("@"),u=c>0;await V(u?l.slice(0,c):l,u?l.slice(c+1):"latest",{globalBin:!0,quiet:!0}).catch((S)=>{console.error(`# could not install ${l}: ${S instanceof Error?S.message:S}`)})}let r=y(),s=[h.join(e,".bin"),r].filter((l)=>p.existsSync(l));if(o.json)console.log(JSON.stringify({path:s,PATH:[...s,a.env.PATH??""].filter(Boolean).join(h.delimiter),dependencies:n,globalBin:r},null,2)),a.exit(0);console.log(`export PATH="${[...s,"$PATH"].join(h.delimiter)}"`),a.exit(0)});x.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(o)=>{let e=o.shell??D();try{if(o.uninstall){let r=Se({shell:e});console.log(r.changed?`✓ Removed pantry shell-init from ${r.rcFile}`:`Nothing to remove (no pantry shell-init block in ${r.rcFile})`),a.exit(0)}if(o.install){let r=je({shell:e});if(r.changed)console.log(`✓ Added pantry shell-init to ${r.rcFile}`),console.log(` Restart your shell or run: source ${r.rcFile}`);else console.log(`✓ Already integrated in ${r.rcFile}`);a.exit(0)}let n=R(e);if(a.stdout.isTTY){if(console.log(`# Detected shell: ${e}`),console.log(`# Global bin dir: ${y()}`),n)console.log(`# Append this to: ${n}`);console.log("# Or run: ts-pantry shell-init --install"),console.log()}a.stdout.write(W({shell:e})),a.exit(0)}catch(n){console.error("Error:",n instanceof Error?n.message:n),a.exit(1)}});x.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(o,e)=>{try{let n=[].concat(e.tag??[]),r={};for(let l of[].concat(e.buildArg??[])){let c=l.indexOf("=");if(c!==-1)r[l.slice(0,c)]=l.slice(c+1)}let s=await ze({context:o??".",dockerfile:e.file,tags:n,target:e.target,buildArgs:r,platform:e.platform,outputDir:e.output,runMode:e.runMode,quiet:e.quiet});if(!e.quiet){if(console.log(`
77
77
  ✓ Built ${s.imageId}`),n.length)console.log(` tags: ${n.join(", ")}`);console.log(` archive: ${s.archivePath}`),console.log(` oci layout: ${s.ociLayoutPath}`)}if(e.push){let l=Z(n[0]||"app:latest");if(!e.quiet)console.log(`
78
- Pushing ${l.repository}:${l.tag} → ${i} ...`);let c=await Ie({repository:l.repository,tag:l.tag,registry:l.implicitRegistry?void 0:`https://${l.registry}`,configBytes:Buffer.from(s.configBytes),configDigest:s.configDigest,layers:s.layers.map((u)=>({digest:u.digest,path:u.path,size:u.size})),manifestBytes:Buffer.from(s.manifestBytes),manifestMediaType:s.manifestMediaType,quiet:e.quiet});console.log(`✓ Pushed ${c.ref} (${c.digest})`)}a.exit(0)}catch(n){console.error("Build failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("container:generate [outDir]","Generate a Dockerfile + .freezer (default outDir: storage/framework)").alias("freeze").option("--base <image>","Base image (default: oven/bun:1.3.10)").option("--workdir <dir>","Working directory in the image (default: /app)").option("--install <cmd>","Install command (default: bun install --frozen-lockfile)").option("--build <cmd>","Optional build command run after install").option("--start <cmd>","Start command (default: bun start)").option("--port <port>","Exposed port (default: 3000)").option("--force","Overwrite existing files").action(async(o,e)=>{try{let n=$e({outDir:o??"storage/framework",baseImage:e.base,workdir:e.workdir,installCommand:e.install,buildCommand:e.build,startCommand:e.start?e.start.split(/\s+/):void 0,port:e.port?Number(e.port):void 0,force:e.force});console.log(`${n.wroteDockerfile?"✓ wrote":"• kept"} ${n.dockerfilePath}`),console.log(`${n.wroteFreezer?"✓ wrote":"• kept"} ${n.freezerPath}`),a.exit(0)}catch(n){console.error("Generate failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("native:release","Qualify, version, commit and push a native app release through Pantry").option("--bump <bump>","patch, minor or major (default: patch)").option("--dry-run","Validate and preview without changing the version or publishing").action(async(o)=>{let{releaseNativeApp:e}=await import("../src/native/release.js");await e(a.cwd(),{bump:o.bump||"patch",dryRun:o.dryRun})});x.command("native:check","Build and verify the native app declared in pantry.json").action(async()=>{let{prepareNativeRelease:o}=await import("../src/native/index.js");console.log(JSON.stringify(await o(a.cwd(),"check"),null,2))});x.command("native:prepare-release","Sign, verify, notarize and package configured native release targets").action(async()=>{let{prepareNativeRelease:o}=await import("../src/native/index.js");console.log(JSON.stringify(await o(a.cwd(),"release"),null,2))});x.command("app-store:package <app>","Package a signed, sandboxed .app as a signed App Store installer package").option("--output <pkg>","Path of the .pkg to write (must not exist)").option("--installer-identity <identity>","Mac Installer Distribution identity name or SHA-1 fingerprint").action(async(o,e)=>{try{let n=e.installerIdentity||a.env.APPLE_STORE_INSTALLER_IDENTITY;if(!e.output||!n)throw Error("--output and --installer-identity (or APPLE_STORE_INSTALLER_IDENTITY) are required");let{packageNativeAppStore:r}=await import("../chunk-8082n3je.js"),s=await r(h.resolve(o),h.resolve(e.output),n);console.log(JSON.stringify({package:s},null,2)),a.exit(0)}catch(n){console.error("App Store packaging failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("app-store:deliver <pkg>","Validate, and unless --validate-only upload, an installer package to App Store Connect").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_ISSUER_ID)").option("--api-key-path <path>","AuthKey .p8 file (or APP_STORE_CONNECT_API_KEY_PATH / APP_STORE_CONNECT_PRIVATE_KEY)").option("--bundle-id <id>","Bundle identifier, recorded in the receipt").option("--app-version <version>","Marketing version, recorded in the receipt").option("--build-number <number>","Build number, recorded in the receipt").option("--validate-only","Validate against App Store Connect without uploading").option("--retry-existing","Treat an already-uploaded build number as delivered").action(async(o,e)=>{try{let n=e.apiKeyId||a.env.APP_STORE_CONNECT_API_KEY_ID||"",r=e.apiIssuerId||a.env.APP_STORE_CONNECT_ISSUER_ID||a.env.APP_STORE_CONNECT_API_ISSUER_ID||"",s=e.apiKeyPath||a.env.APP_STORE_CONNECT_API_KEY_PATH,l=s?p.readFileSync(h.resolve(s),"utf8"):a.env.APP_STORE_CONNECT_PRIVATE_KEY||"",{deliverReleaseToAppStore:c}=await import("../chunk-yey5x5zw.js"),u=await c({package:h.resolve(o),bundleId:e.bundleId,version:e.appVersion,buildNumber:e.buildNumber,apiKeyId:n,issuerId:r,privateKey:l,validateOnly:Boolean(e.validateOnly),retryExisting:Boolean(e.retryExisting),dryRun:!1});console.log(JSON.stringify(u,null,2)),a.exit(0)}catch(n){console.error("App Store delivery failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("app-store:listing","Apply app-store.config.ts to the Mac App Store version, and with --submit send it to App Review").option("--bundle-id <id>","Bundle identifier of the App Store Connect app").option("--app-version <version>","Marketing version (default: the version in package.json)").option("--build-number <number>","Wait for this uploaded build to process and select it for the version").option("--submit","Submit the version for App Review once the listing is applied").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_ISSUER_ID)").option("--api-key-path <path>","AuthKey .p8 file (or APP_STORE_CONNECT_API_KEY_PATH)").action(async(o)=>{try{let e=a.cwd();if(!o.bundleId)throw Error("Pass --bundle-id");if(o.buildNumber!==void 0&&!/^[1-9]\d*$/.test(String(o.buildNumber)))throw Error("--build-number must be a positive integer");let n=Boolean(o.submit),{readAppStoreMetadata:r}=await import("../chunk-qx84hzbc.js"),{AppStoreConnectClient:s,ensureAppStoreVersions:l,waitForAppStoreBuilds:c}=await import("../chunk-pd72mfsb.js"),{prepareAppStoreSubmission:u}=await import("../chunk-50ncbz12.js"),S=await r(e,a.env,{requireReviewContact:n}),m=o.appVersion||JSON.parse(p.readFileSync(h.join(e,"package.json"),"utf8")).version,P=new s({keyId:o.apiKeyId,issuerId:o.apiIssuerId||a.env.APP_STORE_CONNECT_ISSUER_ID,keyPath:o.apiKeyPath?h.resolve(o.apiKeyPath):void 0}),E=await P.findApp(o.bundleId);if(!E)throw Error(`No App Store Connect app has the bundle ID ${o.bundleId}`);let d=await l(P,E.id,[{platform:"MAC_OS",version:m}]),k=d.find((v)=>v.status!=="ready");if(k)throw Error(k.reason??`The App Store version ${m} is not editable`);let w=o.buildNumber?await c(P,E.id,d,String(o.buildNumber)):[];if(!S.reviewContact)console.warn("No review contact yet: the listing is applied, but App Review needs one before you submit.");let _=await u(P,S,E.id,d.map((v)=>({platform:"macos",id:v.id,buildId:w.find((C)=>C.versionId===v.id)?.buildId})),{cwd:e,submit:n});console.log(JSON.stringify({version:m,builds:w,..._},null,2)),a.exit(0)}catch(e){console.error("App Store listing failed:",e instanceof Error?e.message:e),a.exit(1)}});x.command("app-store:csr","Generate private keys and CSRs for Mac App Store certificates").option("--name <name>","App name used in certificate request common names").option("--output <dir>","Output directory (default: .pantry/apple)").action((o)=>{try{if(!o.name)throw Error("--name is required");let e=xa({outputDirectory:o.output??".pantry/apple",commonName:o.name});console.log(JSON.stringify({requests:e},null,2)),a.exit(0)}catch(e){console.error("Apple CSR generation failed:",e instanceof Error?e.message:e),a.exit(1)}});x.command("app-store:provision","Plan or reconcile macOS App Store Connect resources").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--name <name>","Mac App Store display name").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <dir>","Output directory (default: .pantry/apple)").option("--p12-password <password>","Export newly issued certificates as password-protected P12 files").option("--ignore-local-identities","Do not prefer certificates whose private keys are in this machine's keychain").option("--apply","Apply the plan; the default only reports missing resources").action(async(o)=>{try{if(!o.bundleId||!o.name)throw Error("--bundle-id and --name are required");let e=(S)=>{if(!S)return;return p.readFileSync(h.resolve(S),"utf8")},n=h.resolve(o.output??".pantry/apple");p.mkdirSync(n,{recursive:!0});let r=await _e({identifier:o.bundleId,name:o.name,capabilities:o.capabilities?.split(",").map((S)=>S.trim()).filter(Boolean),appCertificateCsr:e(o.appCertificateCsr),installerCertificateCsr:e(o.installerCertificateCsr),profileName:o.profileName,keyId:o.apiKeyId,issuerId:o.apiIssuerId,keyPath:o.apiKeyPath,checkOnly:!o.apply,signingFingerprints:o.ignoreLocalIdentities?void 0:Ee()});for(let S of r.certificates){if(!S.certificateContent)continue;let m=S.type==="MAC_INSTALLER_DISTRIBUTION"?"mac-installer-distribution":"mac-app-distribution",P=h.join(n,`${m}.cer`);p.writeFileSync(P,Buffer.from(S.certificateContent,"base64"),{mode:384});let E=S.type==="MAC_INSTALLER_DISTRIBUTION"?o.installerCertificateCsr:o.appCertificateCsr;if(o.p12Password&&E)wa({certificatePath:P,privateKeyPath:h.resolve(E.replace(/\.csr$/i,".key")),outputPath:h.join(n,`${m}.p12`),password:o.p12Password,name:`${o.name} ${S.type==="MAC_INSTALLER_DISTRIBUTION"?"Mac Installer Distribution":"Mac App Distribution"}`})}if(r.profile.profileContent)p.writeFileSync(h.join(n,"mac-app-store.provisionprofile"),Buffer.from(r.profile.profileContent,"base64"),{mode:384});let s=r.certificates.map((S)=>{let m={...S};return delete m.certificateContent,m}),l={...r.profile};delete l.profileContent;let c={...r,certificates:s,profile:l},u=h.join(n,"provisioning-plan.json");p.writeFileSync(u,`${JSON.stringify(c,null,2)}
78
+ Pushing ${l.repository}:${l.tag} → ${i} ...`);let c=await Ie({repository:l.repository,tag:l.tag,registry:l.implicitRegistry?void 0:`https://${l.registry}`,configBytes:Buffer.from(s.configBytes),configDigest:s.configDigest,layers:s.layers.map((u)=>({digest:u.digest,path:u.path,size:u.size})),manifestBytes:Buffer.from(s.manifestBytes),manifestMediaType:s.manifestMediaType,quiet:e.quiet});console.log(`✓ Pushed ${c.ref} (${c.digest})`)}a.exit(0)}catch(n){console.error("Build failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("container:generate [outDir]","Generate a Dockerfile + .freezer (default outDir: storage/framework)").alias("freeze").option("--base <image>","Base image (default: oven/bun:1.3.10)").option("--workdir <dir>","Working directory in the image (default: /app)").option("--install <cmd>","Install command (default: bun install --frozen-lockfile)").option("--build <cmd>","Optional build command run after install").option("--start <cmd>","Start command (default: bun start)").option("--port <port>","Exposed port (default: 3000)").option("--force","Overwrite existing files").action(async(o,e)=>{try{let n=$e({outDir:o??"storage/framework",baseImage:e.base,workdir:e.workdir,installCommand:e.install,buildCommand:e.build,startCommand:e.start?e.start.split(/\s+/):void 0,port:e.port?Number(e.port):void 0,force:e.force});console.log(`${n.wroteDockerfile?"✓ wrote":"• kept"} ${n.dockerfilePath}`),console.log(`${n.wroteFreezer?"✓ wrote":"• kept"} ${n.freezerPath}`),a.exit(0)}catch(n){console.error("Generate failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("native:release","Qualify, version, commit and push a native app release through Pantry").option("--bump <bump>","patch, minor or major (default: patch)").option("--dry-run","Validate and preview without changing the version or publishing").action(async(o)=>{let{releaseNativeApp:e}=await import("../src/native/release.js");await e(a.cwd(),{bump:o.bump||"patch",dryRun:o.dryRun})});x.command("native:check","Build and verify the native app declared in pantry.json").action(async()=>{let{prepareNativeRelease:o}=await import("../src/native/index.js");console.log(JSON.stringify(await o(a.cwd(),"check"),null,2))});x.command("native:prepare-release","Sign, verify, notarize and package configured native release targets").action(async()=>{let{prepareNativeRelease:o}=await import("../src/native/index.js");console.log(JSON.stringify(await o(a.cwd(),"release"),null,2))});x.command("app-store:package <app>","Package a signed, sandboxed .app as a signed App Store installer package").option("--output <pkg>","Path of the .pkg to write (must not exist)").option("--installer-identity <identity>","Mac Installer Distribution identity name or SHA-1 fingerprint").action(async(o,e)=>{try{let n=e.installerIdentity||a.env.APPLE_STORE_INSTALLER_IDENTITY;if(!e.output||!n)throw Error("--output and --installer-identity (or APPLE_STORE_INSTALLER_IDENTITY) are required");let{packageNativeAppStore:r}=await import("../chunk-aqj6x63m.js"),s=await r(h.resolve(o),h.resolve(e.output),n);console.log(JSON.stringify({package:s},null,2)),a.exit(0)}catch(n){console.error("App Store packaging failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("app-store:deliver <pkg>","Validate, and unless --validate-only upload, an installer package to App Store Connect").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_ISSUER_ID)").option("--api-key-path <path>","AuthKey .p8 file (or APP_STORE_CONNECT_API_KEY_PATH / APP_STORE_CONNECT_PRIVATE_KEY)").option("--bundle-id <id>","Bundle identifier, recorded in the receipt").option("--app-version <version>","Marketing version, recorded in the receipt").option("--build-number <number>","Build number, recorded in the receipt").option("--validate-only","Validate against App Store Connect without uploading").option("--retry-existing","Treat an already-uploaded build number as delivered").action(async(o,e)=>{try{let n=e.apiKeyId||a.env.APP_STORE_CONNECT_API_KEY_ID||"",r=e.apiIssuerId||a.env.APP_STORE_CONNECT_ISSUER_ID||a.env.APP_STORE_CONNECT_API_ISSUER_ID||"",s=e.apiKeyPath||a.env.APP_STORE_CONNECT_API_KEY_PATH,l=s?p.readFileSync(h.resolve(s),"utf8"):a.env.APP_STORE_CONNECT_PRIVATE_KEY||"",{deliverReleaseToAppStore:c}=await import("../chunk-yey5x5zw.js"),u=await c({package:h.resolve(o),bundleId:e.bundleId,version:e.appVersion,buildNumber:e.buildNumber,apiKeyId:n,issuerId:r,privateKey:l,validateOnly:Boolean(e.validateOnly),retryExisting:Boolean(e.retryExisting),dryRun:!1});console.log(JSON.stringify(u,null,2)),a.exit(0)}catch(n){console.error("App Store delivery failed:",n instanceof Error?n.message:n),a.exit(1)}});x.command("app-store:listing","Apply app-store.config.ts to the Mac App Store version, and with --submit send it to App Review").option("--bundle-id <id>","Bundle identifier of the App Store Connect app").option("--app-version <version>","Marketing version (default: the version in package.json)").option("--build-number <number>","Wait for this uploaded build to process and select it for the version").option("--submit","Submit the version for App Review once the listing is applied").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_ISSUER_ID)").option("--api-key-path <path>","AuthKey .p8 file (or APP_STORE_CONNECT_API_KEY_PATH)").action(async(o)=>{try{let e=a.cwd();if(!o.bundleId)throw Error("Pass --bundle-id");if(o.buildNumber!==void 0&&!/^[1-9]\d*$/.test(String(o.buildNumber)))throw Error("--build-number must be a positive integer");let n=Boolean(o.submit),{readAppStoreMetadata:r}=await import("../chunk-ap6wjg88.js"),{AppStoreConnectClient:s,ensureAppStoreVersions:l,waitForAppStoreBuilds:c}=await import("../chunk-5dxmfkha.js"),{prepareAppStoreSubmission:u}=await import("../chunk-ac3pv9sr.js"),S=await r(e,a.env,{requireReviewContact:n}),m=o.appVersion||JSON.parse(p.readFileSync(h.join(e,"package.json"),"utf8")).version,P=new s({keyId:o.apiKeyId,issuerId:o.apiIssuerId||a.env.APP_STORE_CONNECT_ISSUER_ID,keyPath:o.apiKeyPath?h.resolve(o.apiKeyPath):void 0}),E=await P.findApp(o.bundleId);if(!E)throw Error(`No App Store Connect app has the bundle ID ${o.bundleId}`);let d=await l(P,E.id,[{platform:"MAC_OS",version:m}]),k=d.find((v)=>v.status!=="ready");if(k)throw Error(k.reason??`The App Store version ${m} is not editable`);let w=o.buildNumber?await c(P,E.id,d,String(o.buildNumber)):[];if(!S.reviewContact)console.warn("No review contact yet: the listing is applied, but App Review needs one before you submit.");let _=await u(P,S,E.id,d.map((v)=>({platform:"macos",id:v.id,buildId:w.find((C)=>C.versionId===v.id)?.buildId})),{cwd:e,submit:n});console.log(JSON.stringify({version:m,builds:w,..._},null,2)),a.exit(0)}catch(e){console.error("App Store listing failed:",e instanceof Error?e.message:e),a.exit(1)}});x.command("app-store:csr","Generate private keys and CSRs for Mac App Store certificates").option("--name <name>","App name used in certificate request common names").option("--output <dir>","Output directory (default: .pantry/apple)").action((o)=>{try{if(!o.name)throw Error("--name is required");let e=wa({outputDirectory:o.output??".pantry/apple",commonName:o.name});console.log(JSON.stringify({requests:e},null,2)),a.exit(0)}catch(e){console.error("Apple CSR generation failed:",e instanceof Error?e.message:e),a.exit(1)}});x.command("app-store:provision","Plan or reconcile macOS App Store Connect resources").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--name <name>","Mac App Store display name").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <dir>","Output directory (default: .pantry/apple)").option("--p12-password <password>","Export newly issued certificates as password-protected P12 files").option("--ignore-local-identities","Do not prefer certificates whose private keys are in this machine's keychain").option("--apply","Apply the plan; the default only reports missing resources").action(async(o)=>{try{if(!o.bundleId||!o.name)throw Error("--bundle-id and --name are required");let e=(S)=>{if(!S)return;return p.readFileSync(h.resolve(S),"utf8")},n=h.resolve(o.output??".pantry/apple");p.mkdirSync(n,{recursive:!0});let r=await _e({identifier:o.bundleId,name:o.name,capabilities:o.capabilities?.split(",").map((S)=>S.trim()).filter(Boolean),appCertificateCsr:e(o.appCertificateCsr),installerCertificateCsr:e(o.installerCertificateCsr),profileName:o.profileName,keyId:o.apiKeyId,issuerId:o.apiIssuerId,keyPath:o.apiKeyPath,checkOnly:!o.apply,signingFingerprints:o.ignoreLocalIdentities?void 0:Ee()});for(let S of r.certificates){if(!S.certificateContent)continue;let m=S.type==="MAC_INSTALLER_DISTRIBUTION"?"mac-installer-distribution":"mac-app-distribution",P=h.join(n,`${m}.cer`);p.writeFileSync(P,Buffer.from(S.certificateContent,"base64"),{mode:384});let E=S.type==="MAC_INSTALLER_DISTRIBUTION"?o.installerCertificateCsr:o.appCertificateCsr;if(o.p12Password&&E)Pa({certificatePath:P,privateKeyPath:h.resolve(E.replace(/\.csr$/i,".key")),outputPath:h.join(n,`${m}.p12`),password:o.p12Password,name:`${o.name} ${S.type==="MAC_INSTALLER_DISTRIBUTION"?"Mac Installer Distribution":"Mac App Distribution"}`})}if(r.profile.profileContent)p.writeFileSync(h.join(n,"mac-app-store.provisionprofile"),Buffer.from(r.profile.profileContent,"base64"),{mode:384});let s=r.certificates.map((S)=>{let m={...S};return delete m.certificateContent,m}),l={...r.profile};delete l.profileContent;let c={...r,certificates:s,profile:l},u=h.join(n,"provisioning-plan.json");p.writeFileSync(u,`${JSON.stringify(c,null,2)}
79
79
  `,{mode:384}),console.log(JSON.stringify({reportPath:u,...c},null,2)),a.exit(0)}catch(e){console.error("App Store provisioning failed:",e instanceof Error?e.message:e),a.exit(1)}});x.help();x.version(g);var be=x.parse();if(a.argv.length<=2||a.argv.includes("--help")||a.argv.includes("-h"))a.exit(0);
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- import{T}from"../chunk-x5etgagm.js";import"../chunk-ajp6hkpq.js";import"../chunk-hqh3n68z.js";import{B,G,Pe,Xe}from"../chunk-kcxrq2bb.js";import{g}from"../chunk-s1xdyq1s.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{T}from"../chunk-x5etgagm.js";import"../chunk-5zf7b4jc.js";import"../chunk-g8p539wc.js";import{B,G,Pe,Xe}from"../chunk-zg9t7nk0.js";import{g}from"../chunk-7ack6wjh.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>
@@ -0,0 +1 @@
1
+ import{xt,P,ce,le,wt,_a,Ee,Pt,_e}from"./chunk-c68xv4et.js";export{P as AppStoreConnectClient,xt as appStoreConnectToken,_a as certificateFingerprint,Pt as certificatePublicKey,wt as certificateRequestPublicKey,ce as ensureAppStoreVersions,Ee as localSigningFingerprints,_e as provisionMacApp,le as waitForAppStoreBuilds};
@@ -1,3 +1,3 @@
1
- import{execFileSync as v,execSync as g}from"node:child_process";import a from"node:fs";import B from"node:os";import u from"node:path";var w=process.env.PANTRY_REGISTRY_URL||"https://registry.pantry.dev",R={"Logi Options+":"logitech.com/options-plus",logioptionsplus:"logitech.com/options-plus","Logi Options Plus":"logitech.com/options-plus",logioptionsplus_installer:"logitech.com/options-plus"},St=new Set(["Safari","Numbers","Pages","Keynote","GarageBand","iMovie","Color Picker","Simulator","Simulator (Watch)","Preview","TextEdit","Automator","Font Book","Migration Assistant","Photo Booth","System Preferences","System Settings","Disk Utility","Terminal","Activity Monitor","Console","Grapher","Script Editor","Time Machine","Photos","Mail","Calendar","Contacts","Reminders","Notes","Maps","Messages","FaceTime","Books","News","Stocks","Weather","Home","Podcasts","Music","TV","Voice Memos","Freeform","Shortcuts","Chess","Dictionary","Stickies","Image Capture","Xcode"]),Dt=new Set(["Xcode","Numbers","Pages","Keynote","GarageBand","iMovie","Things3","Grammarly for Safari","AdBlock","HP Smart","Audible","Mini Motorways","Snake.io+","WhatsApp Messenger","Honey","Wappalyzer"]);function At(r,s){if(!r||!s||r===s)return!1;if(s==="?")return!!r;let i=(n)=>n.replace(/[,+].*/g,"").replace(/-.*$/,"").split(".").map((o)=>Number.parseInt(o,10)||0),e=i(r),t=i(s);for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]||0,c=t[n]||0;if(o>c)return!0;if(o<c)return!1}return!1}function k(r){return r.toLowerCase().replace(/[^a-z0-9]/g,"")}function he(r="/Applications"){if(process.platform!=="darwin")return[];let s=[];if(!a.existsSync(r))return s;let i=a.readdirSync(r).filter((e)=>e.endsWith(".app"));for(let e of i){let t=e.replace(/\.app$/,""),n=`${r}/${e}`,o="?",c;try{let l=`${n}/Contents/Info.plist`;if(!a.existsSync(l))continue;let p=v("/usr/libexec/PlistBuddy",["-c","Print :CFBundleExecutable",l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(!p||p!==u.basename(p))continue;let f=u.join(n,"Contents/MacOS",p);if(a.accessSync(f,a.constants.X_OK),!a.statSync(f).isFile()||a.statSync(f).size===0)continue;for(let m of["CFBundleShortVersionString","CFBundleVersion"])try{let d=v("/usr/libexec/PlistBuddy",["-c",`Print :${m}`,l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(d){o=d;break}}catch{}try{c=v("/usr/libexec/PlistBuddy",["-c","Print :CFBundleIdentifier",l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{}}catch{continue}s.push({name:t,version:o,path:n,bundleId:c})}return s}async function qa(){try{let r=await fetch(`${w}/desktop-apps`);if(!r.ok)return[];let s=await r.json();return(s.apps??s??[]).filter((e)=>e&&e.domain).map((e)=>({domain:e.domain,label:e.label??e.name??e.domain,version:e.version??null,platforms:e.platforms}))}catch{return[]}}function E(r,s){let i=R[r];if(i){let t=s.find((n)=>n.domain===i);if(t)return t}let e=k(r);return s.find((t)=>k(t.label)===e||k(t.domain.replace(/\.(com|app|io|net|dev|org|ai|so|rest|fr)$/,""))===e)??null}async function So(r){let s=r||he(),i=await qa(),e=[];for(let t of s){let n="unknown",o=null,c=!1,l=null;if(St.has(t.name))n="system";else{let p=E(t.name,i);if(p)n="pantry",l=p.domain,o=p.version,c=!!o&&At(o,t.version);else if(Dt.has(t.name))n="mas"}e.push({name:t.name,currentVersion:t.version,latestVersion:o,updateAvailable:c,source:n,domain:l})}return e.sort((t,n)=>{if(t.updateAvailable&&!n.updateAvailable)return-1;if(!t.updateAvailable&&n.updateAvailable)return 1;return t.name.localeCompare(n.name)}),e}async function Do(r){if(process.platform!=="darwin")return{success:!1,error:"Desktop app updates are macOS-only"};try{let s=await qa(),i=E(r,s);if(!i)return{success:!1,error:`"${r}" is not a pantry-published desktop app`};let e=i.domain,t=await fetch(`${w}/binaries/${encodeURI(e)}/metadata.json`);if(!t.ok)return{success:!1,error:`no registry metadata for ${e}`};let n=await t.json(),o=n.latestVersion,c=B.arch()==="arm64"?"darwin-arm64":"darwin-x86-64",l=n.versions?.[o]?.platforms??{},p=l[c]??l["darwin-arm64"]??l["darwin-x86-64"];if(!p?.tarball)return{success:!1,error:`no ${c} build published for ${e}@${o}`};let f=`${w}/${String(p.tarball).replace(/^\/?/,"")}`,m=a.mkdtempSync(u.join(B.tmpdir(),"pantry-app-"));try{let d=u.join(m,"pkg.tar.gz"),y=await fetch(f);if(!y.ok)return{success:!1,error:`failed to download ${f} (${y.status})`};a.writeFileSync(d,Buffer.from(await y.arrayBuffer()));let h=u.join(m,"x");a.mkdirSync(h,{recursive:!0}),g(`tar -xzf "${d}" -C "${h}"`,{timeout:120000});let x=(P,C)=>{for(let A of a.readdirSync(P,{withFileTypes:!0})){if(!A.isDirectory())continue;let I=u.join(P,A.name);if(A.name.endsWith(".app"))return I;if(C>0){let M=x(I,C-1);if(M)return M}}return null},S=x(h,3);if(!S)return{success:!1,error:`tarball for ${e} contained no .app bundle`};let b=`/Applications/${u.basename(S)}`;return g(`rm -rf "${b}"`,{timeout:30000}),g(`ditto "${S}" "${b}"`,{timeout:120000}),g(`xattr -dr com.apple.quarantine "${b}" 2>/dev/null || true`,{timeout:30000}),{success:!0,version:o}}finally{try{a.rmSync(m,{recursive:!0,force:!0})}catch{}}}catch(s){return{success:!1,error:(s?.message||"Update failed").toString().trim().split(`
1
+ import{execFileSync as v,execSync as g}from"node:child_process";import a from"node:fs";import B from"node:os";import u from"node:path";var w=process.env.PANTRY_REGISTRY_URL||"https://registry.pantry.dev",R={"Logi Options+":"logitech.com/options-plus",logioptionsplus:"logitech.com/options-plus","Logi Options Plus":"logitech.com/options-plus",logioptionsplus_installer:"logitech.com/options-plus"},Dt=new Set(["Safari","Numbers","Pages","Keynote","GarageBand","iMovie","Color Picker","Simulator","Simulator (Watch)","Preview","TextEdit","Automator","Font Book","Migration Assistant","Photo Booth","System Preferences","System Settings","Disk Utility","Terminal","Activity Monitor","Console","Grapher","Script Editor","Time Machine","Photos","Mail","Calendar","Contacts","Reminders","Notes","Maps","Messages","FaceTime","Books","News","Stocks","Weather","Home","Podcasts","Music","TV","Voice Memos","Freeform","Shortcuts","Chess","Dictionary","Stickies","Image Capture","Xcode"]),At=new Set(["Xcode","Numbers","Pages","Keynote","GarageBand","iMovie","Things3","Grammarly for Safari","AdBlock","HP Smart","Audible","Mini Motorways","Snake.io+","WhatsApp Messenger","Honey","Wappalyzer"]);function It(r,s){if(!r||!s||r===s)return!1;if(s==="?")return!!r;let i=(n)=>n.replace(/[,+].*/g,"").replace(/-.*$/,"").split(".").map((o)=>Number.parseInt(o,10)||0),e=i(r),t=i(s);for(let n=0;n<Math.max(e.length,t.length);n++){let o=e[n]||0,c=t[n]||0;if(o>c)return!0;if(o<c)return!1}return!1}function k(r){return r.toLowerCase().replace(/[^a-z0-9]/g,"")}function he(r="/Applications"){if(process.platform!=="darwin")return[];let s=[];if(!a.existsSync(r))return s;let i=a.readdirSync(r).filter((e)=>e.endsWith(".app"));for(let e of i){let t=e.replace(/\.app$/,""),n=`${r}/${e}`,o="?",c;try{let l=`${n}/Contents/Info.plist`;if(!a.existsSync(l))continue;let p=v("/usr/libexec/PlistBuddy",["-c","Print :CFBundleExecutable",l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(!p||p!==u.basename(p))continue;let f=u.join(n,"Contents/MacOS",p);if(a.accessSync(f,a.constants.X_OK),!a.statSync(f).isFile()||a.statSync(f).size===0)continue;for(let m of["CFBundleShortVersionString","CFBundleVersion"])try{let d=v("/usr/libexec/PlistBuddy",["-c",`Print :${m}`,l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(d){o=d;break}}catch{}try{c=v("/usr/libexec/PlistBuddy",["-c","Print :CFBundleIdentifier",l],{timeout:5000,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{}}catch{continue}s.push({name:t,version:o,path:n,bundleId:c})}return s}async function Oa(){try{let r=await fetch(`${w}/desktop-apps`);if(!r.ok)return[];let s=await r.json();return(s.apps??s??[]).filter((e)=>e&&e.domain).map((e)=>({domain:e.domain,label:e.label??e.name??e.domain,version:e.version??null,platforms:e.platforms}))}catch{return[]}}function E(r,s){let i=R[r];if(i){let t=s.find((n)=>n.domain===i);if(t)return t}let e=k(r);return s.find((t)=>k(t.label)===e||k(t.domain.replace(/\.(com|app|io|net|dev|org|ai|so|rest|fr)$/,""))===e)??null}async function Io(r){let s=r||he(),i=await Oa(),e=[];for(let t of s){let n="unknown",o=null,c=!1,l=null;if(Dt.has(t.name))n="system";else{let p=E(t.name,i);if(p)n="pantry",l=p.domain,o=p.version,c=!!o&&It(o,t.version);else if(At.has(t.name))n="mas"}e.push({name:t.name,currentVersion:t.version,latestVersion:o,updateAvailable:c,source:n,domain:l})}return e.sort((t,n)=>{if(t.updateAvailable&&!n.updateAvailable)return-1;if(!t.updateAvailable&&n.updateAvailable)return 1;return t.name.localeCompare(n.name)}),e}async function zo(r){if(process.platform!=="darwin")return{success:!1,error:"Desktop app updates are macOS-only"};try{let s=await Oa(),i=E(r,s);if(!i)return{success:!1,error:`"${r}" is not a pantry-published desktop app`};let e=i.domain,t=await fetch(`${w}/binaries/${encodeURI(e)}/metadata.json`);if(!t.ok)return{success:!1,error:`no registry metadata for ${e}`};let n=await t.json(),o=n.latestVersion,c=B.arch()==="arm64"?"darwin-arm64":"darwin-x86-64",l=n.versions?.[o]?.platforms??{},p=l[c]??l["darwin-arm64"]??l["darwin-x86-64"];if(!p?.tarball)return{success:!1,error:`no ${c} build published for ${e}@${o}`};let f=`${w}/${String(p.tarball).replace(/^\/?/,"")}`,m=a.mkdtempSync(u.join(B.tmpdir(),"pantry-app-"));try{let d=u.join(m,"pkg.tar.gz"),y=await fetch(f);if(!y.ok)return{success:!1,error:`failed to download ${f} (${y.status})`};a.writeFileSync(d,Buffer.from(await y.arrayBuffer()));let h=u.join(m,"x");a.mkdirSync(h,{recursive:!0}),g(`tar -xzf "${d}" -C "${h}"`,{timeout:120000});let x=(P,C)=>{for(let A of a.readdirSync(P,{withFileTypes:!0})){if(!A.isDirectory())continue;let I=u.join(P,A.name);if(A.name.endsWith(".app"))return I;if(C>0){let M=x(I,C-1);if(M)return M}}return null},S=x(h,3);if(!S)return{success:!1,error:`tarball for ${e} contained no .app bundle`};let b=`/Applications/${u.basename(S)}`;return g(`rm -rf "${b}"`,{timeout:30000}),g(`ditto "${S}" "${b}"`,{timeout:120000}),g(`xattr -dr com.apple.quarantine "${b}" 2>/dev/null || true`,{timeout:30000}),{success:!0,version:o}}finally{try{a.rmSync(m,{recursive:!0,force:!0})}catch{}}}catch(s){return{success:!1,error:(s?.message||"Update failed").toString().trim().split(`
2
2
  `).pop()}}}
3
- export{St,Dt,At,he,qa,So,Do};
3
+ export{Dt,At,It,he,Oa,Io,zo};
@@ -0,0 +1 @@
1
+ import{t,M,jt,Ve}from"./chunk-nxc33043.js";Ve();export{t as aliases,jt as packages,M as pantry};
@@ -0,0 +1,2 @@
1
+ var g="0.11.213";
2
+ export{g};
@@ -1 +1 @@
1
- import{execSync as c}from"node:child_process";var i=new Set,m=!1;function T(){if(m)return;m=!0;let t=()=>{for(let e of i)try{c(`pantry stop ${e}`,{stdio:"ignore",timeout:1e4})}catch{}i.clear()};process.on("exit",t),process.on("SIGINT",()=>{t(),process.exit(130)}),process.on("SIGTERM",()=>{t(),process.exit(143)})}function o(t,e=!1){let r={encoding:"utf-8",timeout:30000,stdio:e?"pipe":["pipe","pipe","pipe"]};return c(`pantry ${t}`,r)}function v(t){let e=t.match(/Name:\s+(\S+)/)?.[1]??"",r=/Status:\s+running/i.test(t),s=t.match(/Port:\s+(\d+)/),n=t.match(/PID:\s+(\d+)/),f=t.match(/Data Dir:\s+(.+)/);return{name:e,running:r,port:s?Number.parseInt(s[1],10):null,pid:n?Number.parseInt(n[1],10):null,dataDir:f?f[1].trim():null}}class p{config;_startedByUs=!1;constructor(t){this.config={name:t.name,port:t.port??0,readyTimeoutMs:t.readyTimeoutMs??15000,pollIntervalMs:t.pollIntervalMs??200,quiet:t.quiet??!0}}static isAvailable(){try{return c("pantry --version",{stdio:"ignore",timeout:5000}),!0}catch{return!1}}status(){try{let t=o(`inspect ${this.config.name}`,!0);return v(t)}catch{return{name:this.config.name,running:!1,port:null,pid:null,dataDir:null}}}isRunning(){return this.status().running}getPort(){return this.status().port}async start(){if(T(),this.isRunning())return this.status();return o(`start ${this.config.name}`,this.config.quiet),this._startedByUs=!0,i.add(this.config.name),await this.waitReady(),this.status()}async stop(){if(!this._startedByUs)return;try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async forceStop(){try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async ensureRunning(){if(this.isRunning())return this.status();return this.start()}async waitReady(){let t=Date.now()+this.config.readyTimeoutMs;while(Date.now()<t){if(this.isRunning())return;await new Promise((e)=>setTimeout(e,this.config.pollIntervalMs))}throw Error(`Service '${this.config.name}' did not become ready within ${this.config.readyTimeoutMs}ms`)}}var y=new p({name:"mysql"});async function ee(t){let e=await y.ensureRunning();return{port:t?.port??e.port??3306,host:t?.host??"localhost",database:t?.database??"test",username:t?.username??"root"}}async function ae(){await y.stop()}function Pa(t){let e=null;return{get connection(){if(!e)throw Error("MySQL not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await ee(t)},afterAll:async()=>{await ae(),e=null}}}async function Ua(t,e){let r=await ee(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await ae()}}var g=new p({name:"postgres"});async function te(t){let e=await g.ensureRunning();return{port:t?.port??e.port??5432,host:t?.host??"localhost",database:t?.database??"postgres",username:t?.username??process.env.USER??"postgres"}}async function oe(){await g.stop()}function Ca(t){let e=null;return{get connection(){if(!e)throw Error("Postgres not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await te(t)},afterAll:async()=>{await oe(),e=null}}}async function ja(t,e){let r=await te(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await oe()}}var d=new p({name:"redis"});async function se(t){let e=await d.ensureRunning(),r=t?.port??e.port??6379,s=t?.host??"localhost";return{port:r,host:s,url:`redis://${s}:${r}`}}async function ne(){await d.stop()}function Sa(t){let e=null;return{get connection(){if(!e)throw Error("Redis not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await se(t)},afterAll:async()=>{await ne(),e=null}}}async function Da(t,e){let r=await se(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await ne()}}import{existsSync as u,mkdirSync as P,mkdtempSync as S,rmSync as w,writeFileSync as R}from"node:fs";import{tmpdir as x}from"node:os";import{join as l}from"node:path";var a=new Set,h=!1;function M(){if(h)return;h=!0;let t=()=>{for(let e of a)try{if(u(e))w(e,{recursive:!0,force:!0})}catch{}a.clear()};process.on("exit",t),process.on("SIGINT",()=>{t(),process.exit(130)}),process.on("SIGTERM",()=>{t(),process.exit(143)})}function re(t="pantry-test-"){M();let e=S(l(x(),t));return a.add(e),e}function ie(t){a.delete(t);try{if(u(t))w(t,{recursive:!0,force:!0})}catch{}}async function Aa(t,e){let r=re(t);try{return await e(r)}finally{ie(r)}}function Ia(t,e){let r=re(t);try{return e(r)}finally{ie(r)}}function za(t,e,r){let s=l(t,e),n=s.substring(0,s.lastIndexOf("/"));if(n&&!u(n))P(n,{recursive:!0});return R(s,r),s}function $a(t,e){let r=l(t,e);return P(r,{recursive:!0}),r}var vo={createTempDir:re,createTestDir:$a,createTestFile:za,PantryService:p,removeTempDir:ie,startMysql:ee,startPostgres:te,startRedis:se,stopMysql:ae,stopPostgres:oe,stopRedis:ne,useMysql:Pa,usePostgres:Ca,useRedis:Sa,withMysql:Ua,withPostgres:ja,withRedis:Da,withTempDir:Aa,withTempDirSync:Ia};export{p,ee,ae,Pa,Ua,te,oe,Ca,ja,se,ne,Sa,Da,re,ie,Aa,Ia,za,$a,vo};
1
+ import{execSync as c}from"node:child_process";var i=new Set,m=!1;function T(){if(m)return;m=!0;let t=()=>{for(let e of i)try{c(`pantry stop ${e}`,{stdio:"ignore",timeout:1e4})}catch{}i.clear()};process.on("exit",t),process.on("SIGINT",()=>{t(),process.exit(130)}),process.on("SIGTERM",()=>{t(),process.exit(143)})}function o(t,e=!1){let r={encoding:"utf-8",timeout:30000,stdio:e?"pipe":["pipe","pipe","pipe"]};return c(`pantry ${t}`,r)}function v(t){let e=t.match(/Name:\s+(\S+)/)?.[1]??"",r=/Status:\s+running/i.test(t),s=t.match(/Port:\s+(\d+)/),n=t.match(/PID:\s+(\d+)/),f=t.match(/Data Dir:\s+(.+)/);return{name:e,running:r,port:s?Number.parseInt(s[1],10):null,pid:n?Number.parseInt(n[1],10):null,dataDir:f?f[1].trim():null}}class p{config;_startedByUs=!1;constructor(t){this.config={name:t.name,port:t.port??0,readyTimeoutMs:t.readyTimeoutMs??15000,pollIntervalMs:t.pollIntervalMs??200,quiet:t.quiet??!0}}static isAvailable(){try{return c("pantry --version",{stdio:"ignore",timeout:5000}),!0}catch{return!1}}status(){try{let t=o(`inspect ${this.config.name}`,!0);return v(t)}catch{return{name:this.config.name,running:!1,port:null,pid:null,dataDir:null}}}isRunning(){return this.status().running}getPort(){return this.status().port}async start(){if(T(),this.isRunning())return this.status();return o(`start ${this.config.name}`,this.config.quiet),this._startedByUs=!0,i.add(this.config.name),await this.waitReady(),this.status()}async stop(){if(!this._startedByUs)return;try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async forceStop(){try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async ensureRunning(){if(this.isRunning())return this.status();return this.start()}async waitReady(){let t=Date.now()+this.config.readyTimeoutMs;while(Date.now()<t){if(this.isRunning())return;await new Promise((e)=>setTimeout(e,this.config.pollIntervalMs))}throw Error(`Service '${this.config.name}' did not become ready within ${this.config.readyTimeoutMs}ms`)}}var y=new p({name:"mysql"});async function ee(t){let e=await y.ensureRunning();return{port:t?.port??e.port??3306,host:t?.host??"localhost",database:t?.database??"test",username:t?.username??"root"}}async function ae(){await y.stop()}function Ua(t){let e=null;return{get connection(){if(!e)throw Error("MySQL not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await ee(t)},afterAll:async()=>{await ae(),e=null}}}async function Ca(t,e){let r=await ee(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await ae()}}var g=new p({name:"postgres"});async function te(t){let e=await g.ensureRunning();return{port:t?.port??e.port??5432,host:t?.host??"localhost",database:t?.database??"postgres",username:t?.username??process.env.USER??"postgres"}}async function oe(){await g.stop()}function ja(t){let e=null;return{get connection(){if(!e)throw Error("Postgres not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await te(t)},afterAll:async()=>{await oe(),e=null}}}async function Sa(t,e){let r=await te(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await oe()}}var d=new p({name:"redis"});async function se(t){let e=await d.ensureRunning(),r=t?.port??e.port??6379,s=t?.host??"localhost";return{port:r,host:s,url:`redis://${s}:${r}`}}async function ne(){await d.stop()}function Da(t){let e=null;return{get connection(){if(!e)throw Error("Redis not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await se(t)},afterAll:async()=>{await ne(),e=null}}}async function Aa(t,e){let r=await se(e);try{return await t(r)}finally{if(e?.stopAfter!==!1)await ne()}}import{existsSync as u,mkdirSync as P,mkdtempSync as S,rmSync as w,writeFileSync as R}from"node:fs";import{tmpdir as x}from"node:os";import{join as l}from"node:path";var a=new Set,h=!1;function M(){if(h)return;h=!0;let t=()=>{for(let e of a)try{if(u(e))w(e,{recursive:!0,force:!0})}catch{}a.clear()};process.on("exit",t),process.on("SIGINT",()=>{t(),process.exit(130)}),process.on("SIGTERM",()=>{t(),process.exit(143)})}function re(t="pantry-test-"){M();let e=S(l(x(),t));return a.add(e),e}function ie(t){a.delete(t);try{if(u(t))w(t,{recursive:!0,force:!0})}catch{}}async function Ia(t,e){let r=re(t);try{return await e(r)}finally{ie(r)}}function za(t,e){let r=re(t);try{return e(r)}finally{ie(r)}}function $a(t,e,r){let s=l(t,e),n=s.substring(0,s.lastIndexOf("/"));if(n&&!u(n))P(n,{recursive:!0});return R(s,r),s}function Ea(t,e){let r=l(t,e);return P(r,{recursive:!0}),r}var Po={createTempDir:re,createTestDir:Ea,createTestFile:$a,PantryService:p,removeTempDir:ie,startMysql:ee,startPostgres:te,startRedis:se,stopMysql:ae,stopPostgres:oe,stopRedis:ne,useMysql:Ua,usePostgres:ja,useRedis:Da,withMysql:Ca,withPostgres:Sa,withRedis:Aa,withTempDir:Ia,withTempDirSync:za};export{p,ee,ae,Ua,Ca,te,oe,ja,Sa,se,ne,Da,Aa,re,ie,Ia,za,$a,Ea,Po};
@@ -1 +1 @@
1
- import{z,Pt,pe,Te}from"./chunk-nxesx524.js";export{Pt as attachAppStoreEncryptionDeclaration,z as hasReviewContact,pe as prepareAppStoreSubmission,Te as submitAppStore};
1
+ import{z,Ut,pe,Te}from"./chunk-c68xv4et.js";export{Ut as attachAppStoreEncryptionDeclaration,z as hasReviewContact,pe as prepareAppStoreSubmission,Te as submitAppStore};
@@ -0,0 +1 @@
1
+ import{Ne,zt,$t}from"./chunk-vv7ytdgg.js";import"./chunk-e079tc8m.js";import"./chunk-xyhbhw1y.js";import"./chunk-ggzxbqkc.js";import"./chunk-nxc33043.js";export{zt as publishNativeApple,Ne as readAppStoreMetadata,$t as submitNativeApple};
@@ -0,0 +1 @@
1
+ import{ke,ve,C,_,xe,Ga,we}from"./chunk-ggzxbqkc.js";export{C as assessNativeMacArtifact,xe as notarizeNativeArtifact,Ga as ownerOnlyFiles,we as packageNativeAppStore,ke as resolveNotaryCredentials,_ as runStapler,ve as signNativeDiskImage};
@@ -0,0 +1 @@
1
+ import{Dt,At,It,he,Oa,Io,zo}from"./chunk-5zf7b4jc.js";export{At as MAS_APPS,Dt as SYSTEM_APPS,Io as checkAppUpdates,Oa as fetchDesktopCatalogue,It as isNewerVersion,he as scanInstalledApps,zo as updateApp};
@@ -1,2 +1,2 @@
1
- import T from"node:process";import{spawnSync as L}from"node:child_process";import{createHash as M,createPrivateKey as Y,createPublicKey as K,sign as W,X509Certificate as j}from"node:crypto";import{existsSync as X,readFileSync as Q}from"node:fs";var Z="https://api.appstoreconnect.apple.com/v1";function V(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(...V(i));return t}function N(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function ee(e){let t={keyId:e.keyId||T.env.APP_STORE_CONNECT_API_KEY_ID||"",issuerId:e.issuerId||T.env.APP_STORE_CONNECT_API_ISSUER_ID||"",keyPath:e.keyPath||T.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||!X(t.keyPath))throw Error("[pantry] APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file");return t}function vt(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"},s=`${N(r)}.${N(i)}`,n;try{n=Y(Q(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=W("sha256",Buffer.from(s),{key:n,dsaEncoding:"ieee-p1363"});return`${s}.${a.toString("base64url")}`}class P{auth;baseUrl;fetcher;now;constructor(e={}){this.auth=ee(e),this.baseUrl=(e.baseUrl??Z).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 ${vt(this.auth,this.now())}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}});if(!i.ok){let s=await i.json().catch(()=>({})),n=[...new Set(s.errors?.flatMap(V)??[])].join("; ");throw Error(`[pantry] App Store Connect ${t.method??"GET"} ${e} failed (${i.status})${n?`: ${n}`:""}`)}if(i.status===204)return;return await i.json()}async upload(e,t){let r=new Headers(t.headers),i=t.body,s;if(ArrayBuffer.isView(i)){let o=new ArrayBuffer(i.byteLength);s=new Uint8Array(o),s.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),i=o}else if(i instanceof ArrayBuffer)s=new Uint8Array(i);if(s)r.set("Content-Length",String(s.byteLength));let n=await this.fetcher(e,{...t,headers:r,body:i});if(!n.ok)throw Error(`[pantry] App Store Connect asset upload failed (${n.status})`);let a=n.headers.get("etag")?.replaceAll('"',"");if(s&&a&&/^[a-f\d]{32}$/i.test(a)&&M("md5").update(s).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)=>q(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}`),s=new Map((i.included??[]).filter((n)=>n.type==="preReleaseVersions").map((n)=>[n.id,n.attributes]));return i.data.flatMap((n)=>{let a=n.relationships?.preReleaseVersion?.data?.id,o=a?s.get(a):void 0;if(!o)return[];return[{id:n.id,buildNumber:n.attributes.version,version:o.version,platform:o.platform,processingState:n.attributes.processingState}]})}async attachBuild(e,t){await this.request(`/appStoreVersions/${e}/relationships/build`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t}})})}}var _=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED","INVALID_BINARY"]),D=new Set(["READY_FOR_DISTRIBUTION","READY_FOR_SALE","DEVELOPER_REMOVED_FROM_SALE","REMOVED_FROM_SALE"]);async function ce(e,t,r){let i=await e.listAppStoreVersions(t),s=[],n=new Map(r.map((a)=>[a.platform,a]));for(let{platform:a,version:o}of n.values()){let p=i.find((d)=>d.attributes.platform===a&&d.attributes.versionString===o);if(p){let d=p.attributes.appStoreState,c=_.has(d)?"ready":D.has(d)?"published":"deferred";s.push({platform:a,version:o,created:!1,updated:!1,id:p.id,status:c,appStoreState:d,...c==="deferred"?{reason:`${a} version ${o} is already ${d}`}:{}});continue}let f=i.find((d)=>d.attributes.platform===a&&_.has(d.attributes.appStoreState));if(f){let d=await e.updateAppStoreVersion(f.id,o);f.attributes.versionString=o,s.push({platform:a,version:o,created:!1,updated:!0,id:d.id,status:"ready",appStoreState:d.attributes.appStoreState});continue}let A=i.find((d)=>d.attributes.platform===a&&!D.has(d.attributes.appStoreState));if(A){s.push({platform:a,version:o,created:!1,updated:!1,id:A.id,status:"deferred",appStoreState:A.attributes.appStoreState,reason:`${a} version ${o} is queued behind ${A.attributes.versionString} (${A.attributes.appStoreState})`});continue}let l=await e.createAppStoreVersion(t,a,o);i.push(l),s.push({platform:a,version:o,created:!0,updated:!1,id:l.id,status:"ready",appStoreState:l.attributes.appStoreState})}return s}async function le(e,t,r,i,s={}){let n=s.timeoutMs??1200000,a=s.pollIntervalMs??15000,o=s.now??Date.now,p=s.sleep??((A)=>new Promise((l)=>setTimeout(l,A))),f=o()+n;while(!0){let A=await e.listBuilds(t,i),l=[];for(let d of r){let c=A.find((y)=>y.platform===d.platform&&y.version===d.version);if(!c)continue;if(c.processingState==="FAILED"||c.processingState==="INVALID")throw Error(`[pantry] ${d.platform} build ${i} failed App Store Connect processing (${c.processingState})`);if(c.processingState!=="VALID")continue;l.push({platform:d.platform,versionId:d.id,buildId:c.id,buildNumber:i})}if(l.length===r.length){for(let d of l)await e.attachBuild(d.versionId,d.buildId);return l}if(o()>=f){let d=r.map((c)=>c.platform).join(", ");throw Error(`[pantry] timed out waiting for ${d} build ${i} to finish App Store Connect processing`)}await p(a)}}function O(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 te(e){try{return K(e).export({type:"spki",format:"der"}).toString("base64")}catch{return}}function xt(e){let t=L("openssl",["req","-pubkey","-noout"],{input:e,encoding:"utf8"});if(t.error||t.status!==0)return;return te(t.stdout)}function Ea(e){if(!e)return;return M("sha1").update(Buffer.from(e,"base64")).digest("hex").toUpperCase()}function Ee(e=L){if(T.platform!=="darwin")return[];let t=new Set;for(let r of[["find-identity","-v","-p","codesigning"],["find-identity","-v","-p","basic"]]){let i=e("security",r,{encoding:"utf8"});for(let s of String(i.stdout??"").matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s/gm))t.add(s[1])}return[...t]}function wt(e){if(!e)return;try{return new j(Buffer.from(e,"base64")).publicKey.export({type:"spki",format:"der"}).toString("base64")}catch{return}}function q(e,t){let r=e.relationships?.[t]?.data;if(!r)return[];return(Array.isArray(r)?r:[r]).map((i)=>i.id)}async function _e(e){let t=new P(e),r=e.checkOnly!==!1,i=[],s=await t.ensureBundleId(e.identifier,e.name,{checkOnly:r,platform:"MAC_OS"}),n=s.bundleId;if(!n)i.push(`Register macOS Bundle ID ${e.identifier}`);let a=[],o=[...new Set(e.capabilities??[])].filter(Boolean).sort(),p=n?await t.listBundleIdCapabilities(n.id):[];for(let u of o){if(p.find((w)=>w.attributes.capabilityType===u)){a.push({type:u,enabled:!0,created:!1});continue}if(i.push(`Enable ${u} for ${e.identifier}`),!r&&n)await t.enableBundleIdCapability(n.id,u),a.push({type:u,enabled:!0,created:!0});else a.push({type:u,enabled:!1,created:!1})}let f=[],A=[["MAC_APP_DISTRIBUTION",e.appCertificateCsr],["MAC_INSTALLER_DISTRIBUTION",e.installerCertificateCsr]],l=new Set((e.signingFingerprints??[]).map((u)=>u.toUpperCase()));for(let[u,m]of A){if(!m&&l.size>0){let b=u==="MAC_APP_DISTRIBUTION"?["MAC_APP_DISTRIBUTION","DISTRIBUTION"]:[u],g,C=u;for(let v of b){let H=(await t.listCertificates(v)).filter((G)=>l.has(Ea(G.attributes.certificateContent)??""));if(g=O(H),g){C=v;break}}if(g){f.push({type:C,id:g.id,exists:!0,created:!1,expirationDate:g.attributes.expirationDate,certificateContent:g.attributes.certificateContent,localKey:!0});continue}i.push(`No active ${b.join(" or ")} certificate has its private key on this machine; signing here will fail until one is imported or issued from a local CSR`)}let w=await t.listCertificates(u),I=m?xt(m):void 0;if(m&&!I)throw Error(`[pantry] ${u} CSR could not be read; is it a PEM certificate request?`);let E=O(I?w.filter((b)=>wt(b.attributes.certificateContent)===I):w);if(E){f.push({type:u,id:E.id,exists:!0,created:!1,expirationDate:E.attributes.expirationDate,certificateContent:E.attributes.certificateContent,...l.size>0&&!m?{localKey:l.has(Ea(E.attributes.certificateContent)??"")}:{}});continue}if(i.push(I&&O(w)?`Create ${u} certificate (the active ones were issued for a different private key)`:`Create ${u} certificate`),!r){if(!m)throw Error(`[pantry] ${u} certificate is missing; provide its CSR to apply the provisioning plan`);let b=await t.createCertificate(u,m);f.push({type:u,id:b.id,exists:!0,created:!0,expirationDate:b.attributes.expirationDate,certificateContent:b.attributes.certificateContent})}else f.push({type:u,exists:!1,created:!1})}let d=f.find((u)=>u.type==="MAC_APP_DISTRIBUTION"||u.type==="DISTRIBUTION"),c=e.profileName||`${e.name} Mac App Store`,y=n?await t.listProfiles(n.id):[],h=y.find((u)=>u.attributes.profileState==="ACTIVE"&&(!u.attributes.expirationDate||Date.parse(u.attributes.expirationDate)>Date.now())&&(!d?.id||q(u,"certificates").includes(d.id))),S;if(h)S={id:h.id,name:h.attributes.name,exists:!0,created:!1,expirationDate:h.attributes.expirationDate,profileContent:h.attributes.profileContent};else if(i.push(`Create MAC_APP_STORE profile ${c}`),!r){if(!n)throw Error("[pantry] Bundle ID was not created");if(!d?.id)throw Error("[pantry] A MAC_APP_DISTRIBUTION or DISTRIBUTION certificate is required to create the profile");let u=await t.createMacAppStoreProfile(y.some((m)=>m.attributes.name===c)?`${c} ${d.id.slice(0,8)}`:c,n.id,d.id);S={id:u.id,name:u.attributes.name,exists:!0,created:!0,expirationDate:u.attributes.expirationDate,profileContent:u.attributes.profileContent}}else S={name:c,exists:!1,created:!1};let R=await t.findApp(e.identifier);if(!R)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:n?.id,exists:Boolean(n),created:s.created},capabilities:a,certificates:f,profile:S,appRecord:{exists:Boolean(R),id:R?.id,...!R?{manualAction:"Create the app record in App Store Connect; Apple does not expose an app-creation API."}:{}},actions:i}}import{createHash as re}from"node:crypto";import{basename as ie,resolve as se}from"node:path";import{readFile as ne}from"node:fs/promises";var ae=["alcoholTobaccoOrDrugUseOrReferences","contests","gamblingSimulated","gunsOrOtherWeapons","medicalOrTreatmentInformation","profanityOrCrudeHumor","sexualContentGraphicAndNudity","sexualContentOrNudity","horrorOrFearThemes","matureOrSuggestiveThemes","violenceCartoonOrFantasy","violenceRealisticProlongedGraphicOrSadistic","violenceRealistic"],oe=["advertising","gambling","healthOrWellnessTopics","lootBox","messagingAndChat","parentalControls","ageAssurance","socialMedia","socialMediaAgeRestricted","unrestrictedWebAccess","userGeneratedContent"],de=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED"]);function ue(e={}){let t={ageRatingOverrideV2:"NONE",koreaAgeRatingOverride:"NONE"};for(let r of ae)t[r]=e[r]??"NONE";for(let r of oe)t[r]=e[r]??!1;return t}function B(e){return e==="ios"?"IOS":"MAC_OS"}async function fe(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`),s=i.data.find((p)=>p.attributes.appStoreState==="PREPARE_FOR_SUBMISSION")??i.data[0];if(!s)throw Error("[pantry] App Store Connect has no editable app information resource");await e.request(`/appInfos/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfos",id:s.id,relationships:{primaryCategory:{data:{type:"appCategories",id:r.primaryCategory}}}}})});let n=await e.request(`/appInfos/${s.id}/appInfoLocalizations?limit=200`),a=r.locale??"en-US",o=n.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/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"ageRatingDeclarations",id:s.id,attributes:ue(r.ageRating)}})}),s.id}async function Ae(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",s=await e.request(`/apps/${t}/appPricePoints?filter[territory]=${encodeURIComponent(i)}&limit=200`),n=Number(r.price),a=s.data.find((p)=>Number(p.attributes.customerPrice)===n);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 me(e,t,r=!0,i=[]){let s=new Set(i.map((o)=>o.toUpperCase()));try{let o=await e.request(`/apps/${t}/appAvailabilityV2`);if(s.size)await ye(e,o.data.id,s);return}catch(o){if(!(o instanceof Error)||!o.message.includes("(404)"))throw o}let a=(await e.request("/territories?limit=200")).data.map((o,p)=>({type:"territoryAvailabilities",id:`\${territory-${p}}`,attributes:{available:!s.has(o.id)},relationships:{territory:{data:{type:"territories",id:o.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:a.map((o)=>({type:o.type,id:o.id}))}}},included:a})})}async function ye(e,t,r){let i=await e.request(`/v2/appAvailabilities/${t}/territoryAvailabilities?include=territory&limit=200`);for(let s of i.data){let n=s.relationships?.territory?.data,a=n&&!Array.isArray(n)?n.id:void 0;if(!a||!r.has(a)||s.attributes.available===!1)continue;await e.request(`/territoryAvailabilities/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"territoryAvailabilities",id:s.id,attributes:{available:!1}}})})}}async function ge(e,t,r){let i=r.locale??"en-US",n=(await e.request(`/appStoreVersions/${t}/appStoreVersionLocalizations?limit=200`)).data.find((p)=>p.attributes.locale===i);if(!n)n=(await e.request("/appStoreVersionLocalizations",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",attributes:{locale:i},relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})).data;let a={description:r.description,keywords:r.keywords,supportUrl:r.supportUrl,...r.marketingUrl?{marketingUrl:r.marketingUrl}:{},...r.promotionalText?{promotionalText:r.promotionalText}:{},...r.whatsNew?{whatsNew:r.whatsNew}:{}},o=(p)=>e.request(`/appStoreVersionLocalizations/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",id:n.id,attributes:p}})});try{await o(a)}catch(p){if(!a.whatsNew||!(p instanceof Error)||!/\(409\)/.test(p.message)||!p.message.includes("whatsNew"))throw p;let f={...a};delete f.whatsNew,await o(f)}return n.id}function z(e){return Boolean(e?.firstName&&e.lastName&&e.phone&&e.email)}async function be(e,t,r){let i=r.reviewContact;if(!z(i))return;let s=await e.request(`/appStoreVersions/${t}/appStoreReviewDetail`),n={contactFirstName:i.firstName,contactLastName:i.lastName,contactPhone:i.phone,contactEmail:i.email,demoAccountRequired:!1,...i.notes?{notes:i.notes}:{}};if(s.data){await e.request(`/appStoreReviewDetails/${s.data.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreReviewDetails",id:s.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 k(e,t){let r=[],i=t;while(i){let s=await e.request(i);r.push(...s.data),i=s.links?.next}return r}async function Se(e,t,r,i){let s=Date.now()+r;while(!0){let{data:n}=await e.request(`/appAssetLibraryImages/${t}`);if(n.attributes.specId&&!["AWAITING_UPLOAD","UPLOAD_COMPLETE","PROCESSING","FAILED","REJECTED","ARCHIVED"].includes(n.attributes.state))return n;if(["FAILED","REJECTED","ARCHIVED"].includes(n.attributes.state))throw Error(`[pantry] App Store image ${n.attributes.fileName} ${n.attributes.state}: ${JSON.stringify(n.attributes.stateDetails)}`);if(Date.now()>=s)throw Error(`[pantry] timed out processing App Store image ${n.attributes.fileName}`);await new Promise((a)=>setTimeout(a,i))}}function he(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 Re(e,t,r,i,s,n,a){if(!i.some((c)=>c.files.length))return;let{data:o}=await e.request(`/apps/${t}/assetLibrary`),{data:p}=await e.request("/appAssetLibraryRefData"),f=p[0]?.attributes;if(!f)throw Error("[pantry] Apple returned no asset specification catalog");let A=await k(e,`/appAssetLibraries/${o.id}/images?limit=200`),l=await k(e,`/appStoreVersionLocalizations/${r}/placements?filter[placementType]=APP_SCREENSHOT&include=image&limit=200`),d=new Map;for(let c of i)for(let y of c.files){let h=se(s,y),S=await ne(h),R=`sha256:${re("sha256").update(S).digest("hex")}`,u=A.find((b)=>b.attributes.referenceName===R);if(u?.attributes.state==="FAILED")await e.request(`/appAssetLibraryImages/${u.id}`,{method:"DELETE"});let m=u?.attributes.state==="FAILED"?void 0:u;if(m&&["REJECTED","ARCHIVED"].includes(m.attributes.state))throw Error(`[pantry] Existing image ${y} is ${m.attributes.state}`);if(!m)m=(await e.request("/appAssetLibraryImages",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryImages",attributes:{fileName:ie(h),fileSize:S.byteLength,category:"APP_SCREENSHOTS_AND_PREVIEWS",referenceName:R},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 b=0;for(let g of m.attributes.uploadOperations??[]){if(g.offset!==b||!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((C)=>[C.name,C.value])),body:S.subarray(g.offset,g.offset+g.length)}),b+=g.length}if(b!==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 Se(e,m.id,n,a),!A.some((b)=>b.id===m.id))A.push(m);let I=(f.placementTypes.find((b)=>b.placementTypeId==="APP_SCREENSHOT")?.specMappings??[]).find((b)=>b.specs.includes(m.attributes.specId)&&f.placementProfileGroups.some((g)=>g.placementProfileGroupId===b.placementGroupId&&g.platform===c.platform))?.placementGroupId;if(!I)throw Error(`[pantry] Image ${y} does not match an Apple screenshot specification for ${c.platform}`);let E=d.get(I)??[];if(!E.includes(m.id))E.push(m.id);d.set(I,E)}for(let[c,y]of d){let h=f.features.find((u)=>u.featureId==="APP_STORE_VERSIONS")?.placementPolicies.find((u)=>u.placementType==="APP_SCREENSHOT")?.groupLimits.find((u)=>u.groupIds.includes(c))?.maxCount;if(h===void 0||y.length>h)throw Error(`[pantry] Screenshot count exceeds Apple's limit for ${c}`);let S=l.filter((u)=>u.attributes.placementGroup===c),R=[];for(let u of y){let m=S.find((w)=>w.relationships?.image?.data&&!Array.isArray(w.relationships.image.data)&&w.relationships.image.data.id===u);if(!m)m=(await e.request("/appAssetLibraryPlacements",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacements",attributes:{placementType:"APP_SCREENSHOT",placementGroup:c},relationships:{image:{data:{type:"appAssetLibraryImages",id:u}},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})).data;R.push({type:"appAssetLibraryPlacements",id:m.id})}for(let u of S)if(!R.some((m)=>m.id===u.id))await e.request(`/appAssetLibraryPlacements/${u.id}`,{method:"DELETE"});await e.request("/appAssetLibraryPlacementOrderingRequests",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacementOrderingRequests",attributes:{placementGroup:c},relationships:{orderedPlacements:{data:R},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})}}async function we(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 Pt(e,t.buildId,r.encryptionDeclarationId);return}let i=r.usesNonExemptEncryption??!1,s=await e.request(`/builds/${t.buildId}?fields[builds]=usesNonExemptEncryption`);if(s.data.attributes.usesNonExemptEncryption===void 0||s.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 Pt(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 s=await e.request(`/builds/${encodeURIComponent(t)}?include=app,appEncryptionDeclaration`),n=i.data.relationships?.app?.data,a=s.data.relationships?.app?.data;if(!n||Array.isArray(n)||!a||Array.isArray(a)||n.id!==a.id)throw Error("[pantry] App Store encryption declaration and build must belong to the same app");let o=s.data.relationships?.appEncryptionDeclaration?.data;if(o&&!Array.isArray(o)&&o.id===r)return;if(s.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 U(e,t,r){let i=await e.request(`/apps/${t}/reviewSubmissions?limit=200`),s=[];for(let n of r){let a=B(n.platform),o=i.data.filter((l)=>l.attributes.platform===a&&l.attributes.state!=="COMPLETE"),p;for(let l of o){if(!((await e.request(`/reviewSubmissions/${l.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((y)=>y.type==="appStoreVersions"&&y.id===n.id))continue;if(p=l,l.attributes.state!=="READY_FOR_REVIEW"){s.push(l.id);break}}if(p&&p.attributes.state!=="READY_FOR_REVIEW")continue;if(p??=o.find((l)=>l.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((l)=>l.type==="appStoreVersions"&&l.id===n.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:n.id}}}}})});await e.request(`/reviewSubmissions/${p.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"reviewSubmissions",id:p.id,attributes:{submitted:!0}}})}),s.push(p.id)}return s}async function pe(e,t,r,i,s={}){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 n=s.submit??t.submitForReview??!1;if(n&&!z(t.reviewContact))throw Error("[pantry] Submitting for review requires a review contact with a first name, last name, phone and email");let a=s.cwd??process.cwd(),o=s.screenshotTimeoutMs??600000,p=s.screenshotPollIntervalMs??5000;await fe(e,r,t),await Ae(e,r,t),await me(e,r,t.availableInNewTerritories??!0,t.excludedTerritories);let f=[];for(let A of i){await we(e,A,t);let l=await ge(e,A.id,t);await be(e,A.id,t);let d=he(t.screenshots).filter((c)=>A.platform==="macos"?c.platform==="MAC_APP_STORE":c.platform!=="MAC_APP_STORE");await Re(e,r,l,d,a,o,p),f.push({platform:A.platform,versionId:A.id,localizationId:l})}return{appId:r,versions:f,reviewSubmissionIds:n?await U(e,r,i):[]}}async function Te(e,t){if(!t.bundleId)throw Error("[pantry] App Store submission requires a bundle ID");let r=new P(t),i=await r.findApp(t.bundleId);if(!i)throw Error("[pantry] the App Store Connect app record is missing");let s=t.platforms??["macos"],n=await r.listAppStoreVersions(i.id),a=[],o=[];for(let f of s){let A=n.find((d)=>d.attributes.platform===B(f)&&d.attributes.versionString===t.version);if(!A)throw Error(`[pantry] ${f} App Store version ${t.version} does not exist`);let l=await r.request(`/appStoreVersions/${A.id}/build`);a.push({platform:f,id:A.id,buildId:l.data?.id}),o.push(A.attributes.appStoreState)}if((t.submit??e.submitForReview??!1)&&o.every((f)=>!de.has(f))){let f=await Promise.all(a.map(async(A)=>{let l=await r.request(`/appStoreVersions/${A.id}/appStoreVersionLocalizations?limit=200`);return{platform:A.platform,versionId:A.id,localizationId:l.data[0]?.id??""}}));return{appId:i.id,versions:f,reviewSubmissionIds:await U(r,i.id,a)}}return await pe(r,e,i.id,a,t)}import{execFileSync as Pe}from"node:child_process";import{createReadStream as Ie}from"node:fs";import{createHash as Ce}from"node:crypto";class x extends Error{}async function Oe(e){let t=Ce("sha256");return await new Promise((r,i)=>{let s=Ie(e);s.on("data",(n)=>t.update(n)),s.once("end",r),s.once("error",i)}),t.digest("hex")}async function F(e){return e.json().catch(async()=>({error:await e.text().catch(()=>e.statusText)}))}function xe(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 _a=3600000,Ta=30000,xo=Math.ceil(_a/Ta)+10;function wo(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 J(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 ve(e,t){return e.status===408||e.status===425||e.status===429||t?.retryable===!0||e.status===503&&t?.code==="REGISTRY_DRAINING"||e.status>=500&&!t.code||e.status===404&&t.code==="BINARY_STAGING_NOT_FOUND"}async function Po(e,t,r,i={}){let s=Math.max(1,i.attempts??xo),n=Date.now()+(i.deadlineMs??_a),a=i.fetch??fetch,o=i.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),p=Error("binary upload completion did not run"),f=Date.now(),A=0;for(let l=1;l<=s;l++){A=l;let d=Math.min(Ta,1000*2**Math.min(l-1,5));try{let c=await a(`${e}/api/v1/binaries/uploads/complete`,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({uploadId:t})}),y=await F(c);if(c.ok&&y.success===!0)return y;if(p=wo(c,y),!ve(c,y))throw new x(p.message);d=Math.max(d,J(c,y)??0)}catch(c){if(c instanceof x)throw c;p=c instanceof Error?c:Error(String(c))}if(l>=s||Date.now()>=n)break;if(Date.now()+d>n){p=Error(`${p.message} - registry asked for ${Math.round(d/1000)}s more than the ${Math.round((n-f)/60000)} min completion budget allows`);break}await o(d)}throw Error(`Binary upload completion remained ambiguous after ${A} attempts over ${Math.round((Date.now()-f)/1000)}s: ${p.message}`)}var Uo=4;function Ne(e){return e.status===408||e.status===429||e.status>=500}async function De(e,t,r,i){let s=Math.max(1,i.initiateAttempts??Uo),n=Date.now()+(i.initiateDeadlineMs??_a),a=i.fetch??fetch,o=i.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),p=Error("binary upload initiation did not run"),f=0,A=0;while(f<s){A++;let l=Math.min(Ta,1000*2**Math.min(A-1,5)),d=!1;try{let c=await a(`${e}/api/v1/binaries/uploads`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:r}),y=await F(c);if(c.ok||!Ne(c))return{response:c,initiated:y};p=Error(`${y.code||c.status}: ${y.error||c.statusText}`),d=c.status===503&&y.code==="REGISTRY_DRAINING",l=Math.max(l,J(c,y)??0)}catch(c){p=c instanceof Error?c:Error(String(c))}if(!d)f++;if(f>=s||i.initiateAttempts!==void 0&&A>=s||Date.now()>=n||Date.now()+l>n)break;await o(l)}throw Error(`Could not reach the registry to start the upload after ${A} attempts: ${p.message}`)}async function Va(e){let{registryUrl:t,token:r}=xe(e),i=await Oe(e.filePath),s={Authorization:`Bearer ${r}`},{response:n,initiated:a}=await De(t,s,JSON.stringify({domain:e.domain,version:e.version,platforms:e.platforms,filename:e.filename,size:e.size,sha256:i}),e);if(!n.ok||!a.uploadId||!a.uploadUrl)throw Error(`${a.code||n.status}: ${a.error||n.statusText}`);let o=["-fsS","--connect-timeout","30","--speed-limit","1024","--speed-time","120","--retry","3","--retry-all-errors","-X","PUT"];for(let[f,A]of Object.entries(a.uploadHeaders||{}))o.push("-H",`${f}: ${A}`);o.push("-T",e.filePath,a.uploadUrl),Pe("curl",o,{stdio:["ignore","ignore","inherit"]});let p=await Po(t,a.uploadId,s);if(p.scan?.artifactSha256!==i||p.scan?.verdict!=="clean")throw Error("Registry returned an invalid binary malware-scan attestation");return p}
2
- export{vt,P,ce,le,xt,Ea,Ee,wt,_e,z,Pt,pe,Te,_a,Ta,xo,wo,Po,Uo,Va};
1
+ import T from"node:process";import{spawnSync as L}from"node:child_process";import{createHash as M,createPrivateKey as Y,createPublicKey as K,sign as W,X509Certificate as j}from"node:crypto";import{existsSync as X,readFileSync as Q}from"node:fs";var Z="https://api.appstoreconnect.apple.com/v1";function V(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(...V(i));return t}function N(e){return Buffer.from(JSON.stringify(e)).toString("base64url")}function ee(e){let t={keyId:e.keyId||T.env.APP_STORE_CONNECT_API_KEY_ID||"",issuerId:e.issuerId||T.env.APP_STORE_CONNECT_API_ISSUER_ID||"",keyPath:e.keyPath||T.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||!X(t.keyPath))throw Error("[pantry] APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file");return t}function xt(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"},s=`${N(r)}.${N(i)}`,n;try{n=Y(Q(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=W("sha256",Buffer.from(s),{key:n,dsaEncoding:"ieee-p1363"});return`${s}.${a.toString("base64url")}`}class P{auth;baseUrl;fetcher;now;constructor(e={}){this.auth=ee(e),this.baseUrl=(e.baseUrl??Z).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 ${xt(this.auth,this.now())}`,...t.body?{"Content-Type":"application/json"}:{},...t.headers}});if(!i.ok){let s=await i.json().catch(()=>({})),n=[...new Set(s.errors?.flatMap(V)??[])].join("; ");throw Error(`[pantry] App Store Connect ${t.method??"GET"} ${e} failed (${i.status})${n?`: ${n}`:""}`)}if(i.status===204)return;return await i.json()}async upload(e,t){let r=new Headers(t.headers),i=t.body,s;if(ArrayBuffer.isView(i)){let o=new ArrayBuffer(i.byteLength);s=new Uint8Array(o),s.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),i=o}else if(i instanceof ArrayBuffer)s=new Uint8Array(i);if(s)r.set("Content-Length",String(s.byteLength));let n=await this.fetcher(e,{...t,headers:r,body:i});if(!n.ok)throw Error(`[pantry] App Store Connect asset upload failed (${n.status})`);let a=n.headers.get("etag")?.replaceAll('"',"");if(s&&a&&/^[a-f\d]{32}$/i.test(a)&&M("md5").update(s).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)=>q(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}`),s=new Map((i.included??[]).filter((n)=>n.type==="preReleaseVersions").map((n)=>[n.id,n.attributes]));return i.data.flatMap((n)=>{let a=n.relationships?.preReleaseVersion?.data?.id,o=a?s.get(a):void 0;if(!o)return[];return[{id:n.id,buildNumber:n.attributes.version,version:o.version,platform:o.platform,processingState:n.attributes.processingState}]})}async attachBuild(e,t){await this.request(`/appStoreVersions/${e}/relationships/build`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:t}})})}}var _=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED","INVALID_BINARY"]),D=new Set(["READY_FOR_DISTRIBUTION","READY_FOR_SALE","DEVELOPER_REMOVED_FROM_SALE","REMOVED_FROM_SALE"]);async function ce(e,t,r){let i=await e.listAppStoreVersions(t),s=[],n=new Map(r.map((a)=>[a.platform,a]));for(let{platform:a,version:o}of n.values()){let p=i.find((d)=>d.attributes.platform===a&&d.attributes.versionString===o);if(p){let d=p.attributes.appStoreState,c=_.has(d)?"ready":D.has(d)?"published":"deferred";s.push({platform:a,version:o,created:!1,updated:!1,id:p.id,status:c,appStoreState:d,...c==="deferred"?{reason:`${a} version ${o} is already ${d}`}:{}});continue}let f=i.find((d)=>d.attributes.platform===a&&_.has(d.attributes.appStoreState));if(f){let d=await e.updateAppStoreVersion(f.id,o);f.attributes.versionString=o,s.push({platform:a,version:o,created:!1,updated:!0,id:d.id,status:"ready",appStoreState:d.attributes.appStoreState});continue}let A=i.find((d)=>d.attributes.platform===a&&!D.has(d.attributes.appStoreState));if(A){s.push({platform:a,version:o,created:!1,updated:!1,id:A.id,status:"deferred",appStoreState:A.attributes.appStoreState,reason:`${a} version ${o} is queued behind ${A.attributes.versionString} (${A.attributes.appStoreState})`});continue}let l=await e.createAppStoreVersion(t,a,o);i.push(l),s.push({platform:a,version:o,created:!0,updated:!1,id:l.id,status:"ready",appStoreState:l.attributes.appStoreState})}return s}async function le(e,t,r,i,s={}){let n=s.timeoutMs??1200000,a=s.pollIntervalMs??15000,o=s.now??Date.now,p=s.sleep??((A)=>new Promise((l)=>setTimeout(l,A))),f=o()+n;while(!0){let A=await e.listBuilds(t,i),l=[];for(let d of r){let c=A.find((y)=>y.platform===d.platform&&y.version===d.version);if(!c)continue;if(c.processingState==="FAILED"||c.processingState==="INVALID")throw Error(`[pantry] ${d.platform} build ${i} failed App Store Connect processing (${c.processingState})`);if(c.processingState!=="VALID")continue;l.push({platform:d.platform,versionId:d.id,buildId:c.id,buildNumber:i})}if(l.length===r.length){for(let d of l)await e.attachBuild(d.versionId,d.buildId);return l}if(o()>=f){let d=r.map((c)=>c.platform).join(", ");throw Error(`[pantry] timed out waiting for ${d} build ${i} to finish App Store Connect processing`)}await p(a)}}function O(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 te(e){try{return K(e).export({type:"spki",format:"der"}).toString("base64")}catch{return}}function wt(e){let t=L("openssl",["req","-pubkey","-noout"],{input:e,encoding:"utf8"});if(t.error||t.status!==0)return;return te(t.stdout)}function _a(e){if(!e)return;return M("sha1").update(Buffer.from(e,"base64")).digest("hex").toUpperCase()}function Ee(e=L){if(T.platform!=="darwin")return[];let t=new Set;for(let r of[["find-identity","-v","-p","codesigning"],["find-identity","-v","-p","basic"]]){let i=e("security",r,{encoding:"utf8"});for(let s of String(i.stdout??"").matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s/gm))t.add(s[1])}return[...t]}function Pt(e){if(!e)return;try{return new j(Buffer.from(e,"base64")).publicKey.export({type:"spki",format:"der"}).toString("base64")}catch{return}}function q(e,t){let r=e.relationships?.[t]?.data;if(!r)return[];return(Array.isArray(r)?r:[r]).map((i)=>i.id)}async function _e(e){let t=new P(e),r=e.checkOnly!==!1,i=[],s=await t.ensureBundleId(e.identifier,e.name,{checkOnly:r,platform:"MAC_OS"}),n=s.bundleId;if(!n)i.push(`Register macOS Bundle ID ${e.identifier}`);let a=[],o=[...new Set(e.capabilities??[])].filter(Boolean).sort(),p=n?await t.listBundleIdCapabilities(n.id):[];for(let u of o){if(p.find((w)=>w.attributes.capabilityType===u)){a.push({type:u,enabled:!0,created:!1});continue}if(i.push(`Enable ${u} for ${e.identifier}`),!r&&n)await t.enableBundleIdCapability(n.id,u),a.push({type:u,enabled:!0,created:!0});else a.push({type:u,enabled:!1,created:!1})}let f=[],A=[["MAC_APP_DISTRIBUTION",e.appCertificateCsr],["MAC_INSTALLER_DISTRIBUTION",e.installerCertificateCsr]],l=new Set((e.signingFingerprints??[]).map((u)=>u.toUpperCase()));for(let[u,m]of A){if(!m&&l.size>0){let b=u==="MAC_APP_DISTRIBUTION"?["MAC_APP_DISTRIBUTION","DISTRIBUTION"]:[u],g,C=u;for(let v of b){let H=(await t.listCertificates(v)).filter((G)=>l.has(_a(G.attributes.certificateContent)??""));if(g=O(H),g){C=v;break}}if(g){f.push({type:C,id:g.id,exists:!0,created:!1,expirationDate:g.attributes.expirationDate,certificateContent:g.attributes.certificateContent,localKey:!0});continue}i.push(`No active ${b.join(" or ")} certificate has its private key on this machine; signing here will fail until one is imported or issued from a local CSR`)}let w=await t.listCertificates(u),I=m?wt(m):void 0;if(m&&!I)throw Error(`[pantry] ${u} CSR could not be read; is it a PEM certificate request?`);let E=O(I?w.filter((b)=>Pt(b.attributes.certificateContent)===I):w);if(E){f.push({type:u,id:E.id,exists:!0,created:!1,expirationDate:E.attributes.expirationDate,certificateContent:E.attributes.certificateContent,...l.size>0&&!m?{localKey:l.has(_a(E.attributes.certificateContent)??"")}:{}});continue}if(i.push(I&&O(w)?`Create ${u} certificate (the active ones were issued for a different private key)`:`Create ${u} certificate`),!r){if(!m)throw Error(`[pantry] ${u} certificate is missing; provide its CSR to apply the provisioning plan`);let b=await t.createCertificate(u,m);f.push({type:u,id:b.id,exists:!0,created:!0,expirationDate:b.attributes.expirationDate,certificateContent:b.attributes.certificateContent})}else f.push({type:u,exists:!1,created:!1})}let d=f.find((u)=>u.type==="MAC_APP_DISTRIBUTION"||u.type==="DISTRIBUTION"),c=e.profileName||`${e.name} Mac App Store`,y=n?await t.listProfiles(n.id):[],h=y.find((u)=>u.attributes.profileState==="ACTIVE"&&(!u.attributes.expirationDate||Date.parse(u.attributes.expirationDate)>Date.now())&&(!d?.id||q(u,"certificates").includes(d.id))),S;if(h)S={id:h.id,name:h.attributes.name,exists:!0,created:!1,expirationDate:h.attributes.expirationDate,profileContent:h.attributes.profileContent};else if(i.push(`Create MAC_APP_STORE profile ${c}`),!r){if(!n)throw Error("[pantry] Bundle ID was not created");if(!d?.id)throw Error("[pantry] A MAC_APP_DISTRIBUTION or DISTRIBUTION certificate is required to create the profile");let u=await t.createMacAppStoreProfile(y.some((m)=>m.attributes.name===c)?`${c} ${d.id.slice(0,8)}`:c,n.id,d.id);S={id:u.id,name:u.attributes.name,exists:!0,created:!0,expirationDate:u.attributes.expirationDate,profileContent:u.attributes.profileContent}}else S={name:c,exists:!1,created:!1};let R=await t.findApp(e.identifier);if(!R)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:n?.id,exists:Boolean(n),created:s.created},capabilities:a,certificates:f,profile:S,appRecord:{exists:Boolean(R),id:R?.id,...!R?{manualAction:"Create the app record in App Store Connect; Apple does not expose an app-creation API."}:{}},actions:i}}import{createHash as re}from"node:crypto";import{basename as ie,resolve as se}from"node:path";import{readFile as ne}from"node:fs/promises";var ae=["alcoholTobaccoOrDrugUseOrReferences","contests","gamblingSimulated","gunsOrOtherWeapons","medicalOrTreatmentInformation","profanityOrCrudeHumor","sexualContentGraphicAndNudity","sexualContentOrNudity","horrorOrFearThemes","matureOrSuggestiveThemes","violenceCartoonOrFantasy","violenceRealisticProlongedGraphicOrSadistic","violenceRealistic"],oe=["advertising","gambling","healthOrWellnessTopics","lootBox","messagingAndChat","parentalControls","ageAssurance","socialMedia","socialMediaAgeRestricted","unrestrictedWebAccess","userGeneratedContent"],de=new Set(["PREPARE_FOR_SUBMISSION","DEVELOPER_REJECTED","REJECTED","METADATA_REJECTED"]);function ue(e={}){let t={ageRatingOverrideV2:"NONE",koreaAgeRatingOverride:"NONE"};for(let r of ae)t[r]=e[r]??"NONE";for(let r of oe)t[r]=e[r]??!1;return t}function B(e){return e==="ios"?"IOS":"MAC_OS"}async function fe(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`),s=i.data.find((p)=>p.attributes.appStoreState==="PREPARE_FOR_SUBMISSION")??i.data[0];if(!s)throw Error("[pantry] App Store Connect has no editable app information resource");await e.request(`/appInfos/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appInfos",id:s.id,relationships:{primaryCategory:{data:{type:"appCategories",id:r.primaryCategory}}}}})});let n=await e.request(`/appInfos/${s.id}/appInfoLocalizations?limit=200`),a=r.locale??"en-US",o=n.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/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"ageRatingDeclarations",id:s.id,attributes:ue(r.ageRating)}})}),s.id}async function Ae(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",s=await e.request(`/apps/${t}/appPricePoints?filter[territory]=${encodeURIComponent(i)}&limit=200`),n=Number(r.price),a=s.data.find((p)=>Number(p.attributes.customerPrice)===n);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 me(e,t,r=!0,i=[]){let s=new Set(i.map((o)=>o.toUpperCase()));try{let o=await e.request(`/apps/${t}/appAvailabilityV2`);if(s.size)await ye(e,o.data.id,s);return}catch(o){if(!(o instanceof Error)||!o.message.includes("(404)"))throw o}let a=(await e.request("/territories?limit=200")).data.map((o,p)=>({type:"territoryAvailabilities",id:`\${territory-${p}}`,attributes:{available:!s.has(o.id)},relationships:{territory:{data:{type:"territories",id:o.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:a.map((o)=>({type:o.type,id:o.id}))}}},included:a})})}async function ye(e,t,r){let i=await e.request(`/v2/appAvailabilities/${t}/territoryAvailabilities?include=territory&limit=200`);for(let s of i.data){let n=s.relationships?.territory?.data,a=n&&!Array.isArray(n)?n.id:void 0;if(!a||!r.has(a)||s.attributes.available===!1)continue;await e.request(`/territoryAvailabilities/${s.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"territoryAvailabilities",id:s.id,attributes:{available:!1}}})})}}async function ge(e,t,r){let i=r.locale??"en-US",n=(await e.request(`/appStoreVersions/${t}/appStoreVersionLocalizations?limit=200`)).data.find((p)=>p.attributes.locale===i);if(!n)n=(await e.request("/appStoreVersionLocalizations",{method:"POST",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",attributes:{locale:i},relationships:{appStoreVersion:{data:{type:"appStoreVersions",id:t}}}}})})).data;let a={description:r.description,keywords:r.keywords,supportUrl:r.supportUrl,...r.marketingUrl?{marketingUrl:r.marketingUrl}:{},...r.promotionalText?{promotionalText:r.promotionalText}:{},...r.whatsNew?{whatsNew:r.whatsNew}:{}},o=(p)=>e.request(`/appStoreVersionLocalizations/${n.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreVersionLocalizations",id:n.id,attributes:p}})});try{await o(a)}catch(p){if(!a.whatsNew||!(p instanceof Error)||!/\(409\)/.test(p.message)||!p.message.includes("whatsNew"))throw p;let f={...a};delete f.whatsNew,await o(f)}return n.id}function z(e){return Boolean(e?.firstName&&e.lastName&&e.phone&&e.email)}async function be(e,t,r){let i=r.reviewContact;if(!z(i))return;let s=await e.request(`/appStoreVersions/${t}/appStoreReviewDetail`),n={contactFirstName:i.firstName,contactLastName:i.lastName,contactPhone:i.phone,contactEmail:i.email,demoAccountRequired:!1,...i.notes?{notes:i.notes}:{}};if(s.data){await e.request(`/appStoreReviewDetails/${s.data.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"appStoreReviewDetails",id:s.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 k(e,t){let r=[],i=t;while(i){let s=await e.request(i);r.push(...s.data),i=s.links?.next}return r}async function Se(e,t,r,i){let s=Date.now()+r;while(!0){let{data:n}=await e.request(`/appAssetLibraryImages/${t}`);if(n.attributes.specId&&!["AWAITING_UPLOAD","UPLOAD_COMPLETE","PROCESSING","FAILED","REJECTED","ARCHIVED"].includes(n.attributes.state))return n;if(["FAILED","REJECTED","ARCHIVED"].includes(n.attributes.state))throw Error(`[pantry] App Store image ${n.attributes.fileName} ${n.attributes.state}: ${JSON.stringify(n.attributes.stateDetails)}`);if(Date.now()>=s)throw Error(`[pantry] timed out processing App Store image ${n.attributes.fileName}`);await new Promise((a)=>setTimeout(a,i))}}function he(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 Re(e,t,r,i,s,n,a){if(!i.some((c)=>c.files.length))return;let{data:o}=await e.request(`/apps/${t}/assetLibrary`),{data:p}=await e.request("/appAssetLibraryRefData"),f=p[0]?.attributes;if(!f)throw Error("[pantry] Apple returned no asset specification catalog");let A=await k(e,`/appAssetLibraries/${o.id}/images?limit=200`),l=await k(e,`/appStoreVersionLocalizations/${r}/placements?filter[placementType]=APP_SCREENSHOT&include=image&limit=200`),d=new Map;for(let c of i)for(let y of c.files){let h=se(s,y),S=await ne(h),R=`sha256:${re("sha256").update(S).digest("hex")}`,u=A.find((b)=>b.attributes.referenceName===R);if(u?.attributes.state==="FAILED")await e.request(`/appAssetLibraryImages/${u.id}`,{method:"DELETE"});let m=u?.attributes.state==="FAILED"?void 0:u;if(m&&["REJECTED","ARCHIVED"].includes(m.attributes.state))throw Error(`[pantry] Existing image ${y} is ${m.attributes.state}`);if(!m)m=(await e.request("/appAssetLibraryImages",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryImages",attributes:{fileName:ie(h),fileSize:S.byteLength,category:"APP_SCREENSHOTS_AND_PREVIEWS",referenceName:R},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 b=0;for(let g of m.attributes.uploadOperations??[]){if(g.offset!==b||!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((C)=>[C.name,C.value])),body:S.subarray(g.offset,g.offset+g.length)}),b+=g.length}if(b!==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 Se(e,m.id,n,a),!A.some((b)=>b.id===m.id))A.push(m);let I=(f.placementTypes.find((b)=>b.placementTypeId==="APP_SCREENSHOT")?.specMappings??[]).find((b)=>b.specs.includes(m.attributes.specId)&&f.placementProfileGroups.some((g)=>g.placementProfileGroupId===b.placementGroupId&&g.platform===c.platform))?.placementGroupId;if(!I)throw Error(`[pantry] Image ${y} does not match an Apple screenshot specification for ${c.platform}`);let E=d.get(I)??[];if(!E.includes(m.id))E.push(m.id);d.set(I,E)}for(let[c,y]of d){let h=f.features.find((u)=>u.featureId==="APP_STORE_VERSIONS")?.placementPolicies.find((u)=>u.placementType==="APP_SCREENSHOT")?.groupLimits.find((u)=>u.groupIds.includes(c))?.maxCount;if(h===void 0||y.length>h)throw Error(`[pantry] Screenshot count exceeds Apple's limit for ${c}`);let S=l.filter((u)=>u.attributes.placementGroup===c),R=[];for(let u of y){let m=S.find((w)=>w.relationships?.image?.data&&!Array.isArray(w.relationships.image.data)&&w.relationships.image.data.id===u);if(!m)m=(await e.request("/appAssetLibraryPlacements",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacements",attributes:{placementType:"APP_SCREENSHOT",placementGroup:c},relationships:{image:{data:{type:"appAssetLibraryImages",id:u}},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})).data;R.push({type:"appAssetLibraryPlacements",id:m.id})}for(let u of S)if(!R.some((m)=>m.id===u.id))await e.request(`/appAssetLibraryPlacements/${u.id}`,{method:"DELETE"});await e.request("/appAssetLibraryPlacementOrderingRequests",{method:"POST",body:JSON.stringify({data:{type:"appAssetLibraryPlacementOrderingRequests",attributes:{placementGroup:c},relationships:{orderedPlacements:{data:R},appStoreVersionLocalization:{data:{type:"appStoreVersionLocalizations",id:r}}}}})})}}async function we(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 Ut(e,t.buildId,r.encryptionDeclarationId);return}let i=r.usesNonExemptEncryption??!1,s=await e.request(`/builds/${t.buildId}?fields[builds]=usesNonExemptEncryption`);if(s.data.attributes.usesNonExemptEncryption===void 0||s.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 Ut(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 s=await e.request(`/builds/${encodeURIComponent(t)}?include=app,appEncryptionDeclaration`),n=i.data.relationships?.app?.data,a=s.data.relationships?.app?.data;if(!n||Array.isArray(n)||!a||Array.isArray(a)||n.id!==a.id)throw Error("[pantry] App Store encryption declaration and build must belong to the same app");let o=s.data.relationships?.appEncryptionDeclaration?.data;if(o&&!Array.isArray(o)&&o.id===r)return;if(s.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 U(e,t,r){let i=await e.request(`/apps/${t}/reviewSubmissions?limit=200`),s=[];for(let n of r){let a=B(n.platform),o=i.data.filter((l)=>l.attributes.platform===a&&l.attributes.state!=="COMPLETE"),p;for(let l of o){if(!((await e.request(`/reviewSubmissions/${l.id}/items?include=appStoreVersion&limit=200`)).included??[]).some((y)=>y.type==="appStoreVersions"&&y.id===n.id))continue;if(p=l,l.attributes.state!=="READY_FOR_REVIEW"){s.push(l.id);break}}if(p&&p.attributes.state!=="READY_FOR_REVIEW")continue;if(p??=o.find((l)=>l.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((l)=>l.type==="appStoreVersions"&&l.id===n.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:n.id}}}}})});await e.request(`/reviewSubmissions/${p.id}`,{method:"PATCH",body:JSON.stringify({data:{type:"reviewSubmissions",id:p.id,attributes:{submitted:!0}}})}),s.push(p.id)}return s}async function pe(e,t,r,i,s={}){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 n=s.submit??t.submitForReview??!1;if(n&&!z(t.reviewContact))throw Error("[pantry] Submitting for review requires a review contact with a first name, last name, phone and email");let a=s.cwd??process.cwd(),o=s.screenshotTimeoutMs??600000,p=s.screenshotPollIntervalMs??5000;await fe(e,r,t),await Ae(e,r,t),await me(e,r,t.availableInNewTerritories??!0,t.excludedTerritories);let f=[];for(let A of i){await we(e,A,t);let l=await ge(e,A.id,t);await be(e,A.id,t);let d=he(t.screenshots).filter((c)=>A.platform==="macos"?c.platform==="MAC_APP_STORE":c.platform!=="MAC_APP_STORE");await Re(e,r,l,d,a,o,p),f.push({platform:A.platform,versionId:A.id,localizationId:l})}return{appId:r,versions:f,reviewSubmissionIds:n?await U(e,r,i):[]}}async function Te(e,t){if(!t.bundleId)throw Error("[pantry] App Store submission requires a bundle ID");let r=new P(t),i=await r.findApp(t.bundleId);if(!i)throw Error("[pantry] the App Store Connect app record is missing");let s=t.platforms??["macos"],n=await r.listAppStoreVersions(i.id),a=[],o=[];for(let f of s){let A=n.find((d)=>d.attributes.platform===B(f)&&d.attributes.versionString===t.version);if(!A)throw Error(`[pantry] ${f} App Store version ${t.version} does not exist`);let l=await r.request(`/appStoreVersions/${A.id}/build`);a.push({platform:f,id:A.id,buildId:l.data?.id}),o.push(A.attributes.appStoreState)}if((t.submit??e.submitForReview??!1)&&o.every((f)=>!de.has(f))){let f=await Promise.all(a.map(async(A)=>{let l=await r.request(`/appStoreVersions/${A.id}/appStoreVersionLocalizations?limit=200`);return{platform:A.platform,versionId:A.id,localizationId:l.data[0]?.id??""}}));return{appId:i.id,versions:f,reviewSubmissionIds:await U(r,i.id,a)}}return await pe(r,e,i.id,a,t)}import{execFileSync as Pe}from"node:child_process";import{createReadStream as Ie}from"node:fs";import{createHash as Ce}from"node:crypto";class x extends Error{}async function Oe(e){let t=Ce("sha256");return await new Promise((r,i)=>{let s=Ie(e);s.on("data",(n)=>t.update(n)),s.once("end",r),s.once("error",i)}),t.digest("hex")}async function F(e){return e.json().catch(async()=>({error:await e.text().catch(()=>e.statusText)}))}function xe(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 Ta=3600000,Va=30000,Uo=Math.ceil(Ta/Va)+10;function Co(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 J(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 ve(e,t){return e.status===408||e.status===425||e.status===429||t?.retryable===!0||e.status===503&&t?.code==="REGISTRY_DRAINING"||e.status>=500&&!t.code||e.status===404&&t.code==="BINARY_STAGING_NOT_FOUND"}async function jo(e,t,r,i={}){let s=Math.max(1,i.attempts??Uo),n=Date.now()+(i.deadlineMs??Ta),a=i.fetch??fetch,o=i.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),p=Error("binary upload completion did not run"),f=Date.now(),A=0;for(let l=1;l<=s;l++){A=l;let d=Math.min(Va,1000*2**Math.min(l-1,5));try{let c=await a(`${e}/api/v1/binaries/uploads/complete`,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({uploadId:t})}),y=await F(c);if(c.ok&&y.success===!0)return y;if(p=Co(c,y),!ve(c,y))throw new x(p.message);d=Math.max(d,J(c,y)??0)}catch(c){if(c instanceof x)throw c;p=c instanceof Error?c:Error(String(c))}if(l>=s||Date.now()>=n)break;if(Date.now()+d>n){p=Error(`${p.message} - registry asked for ${Math.round(d/1000)}s more than the ${Math.round((n-f)/60000)} min completion budget allows`);break}await o(d)}throw Error(`Binary upload completion remained ambiguous after ${A} attempts over ${Math.round((Date.now()-f)/1000)}s: ${p.message}`)}var So=4;function Ne(e){return e.status===408||e.status===429||e.status>=500}async function De(e,t,r,i){let s=Math.max(1,i.initiateAttempts??So),n=Date.now()+(i.initiateDeadlineMs??Ta),a=i.fetch??fetch,o=i.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),p=Error("binary upload initiation did not run"),f=0,A=0;while(f<s){A++;let l=Math.min(Va,1000*2**Math.min(A-1,5)),d=!1;try{let c=await a(`${e}/api/v1/binaries/uploads`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:r}),y=await F(c);if(c.ok||!Ne(c))return{response:c,initiated:y};p=Error(`${y.code||c.status}: ${y.error||c.statusText}`),d=c.status===503&&y.code==="REGISTRY_DRAINING",l=Math.max(l,J(c,y)??0)}catch(c){p=c instanceof Error?c:Error(String(c))}if(!d)f++;if(f>=s||i.initiateAttempts!==void 0&&A>=s||Date.now()>=n||Date.now()+l>n)break;await o(l)}throw Error(`Could not reach the registry to start the upload after ${A} attempts: ${p.message}`)}async function Ra(e){let{registryUrl:t,token:r}=xe(e),i=await Oe(e.filePath),s={Authorization:`Bearer ${r}`},{response:n,initiated:a}=await De(t,s,JSON.stringify({domain:e.domain,version:e.version,platforms:e.platforms,filename:e.filename,size:e.size,sha256:i}),e);if(!n.ok||!a.uploadId||!a.uploadUrl)throw Error(`${a.code||n.status}: ${a.error||n.statusText}`);let o=["-fsS","--connect-timeout","30","--speed-limit","1024","--speed-time","120","--retry","3","--retry-all-errors","-X","PUT"];for(let[f,A]of Object.entries(a.uploadHeaders||{}))o.push("-H",`${f}: ${A}`);o.push("-T",e.filePath,a.uploadUrl),Pe("curl",o,{stdio:["ignore","ignore","inherit"]});let p=await jo(t,a.uploadId,s);if(p.scan?.artifactSha256!==i||p.scan?.verdict!=="clean")throw Error("Registry returned an invalid binary malware-scan attestation");return p}
2
+ export{xt,P,ce,le,wt,_a,Ee,Pt,_e,z,Ut,pe,Te,Ta,Va,Uo,Co,jo,So,Ra};