ts-pantry 0.11.190 → 0.11.191
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +1 -1
- package/dist/bin/desktop.js +1 -1
- package/dist/chunk-bfvq09k2.js +2 -0
- package/dist/{chunk-nrt173kn.js → chunk-hxr0vweg.js} +12 -12
- package/dist/src/native/index.js +1 -1
- package/dist/src/native/pipeline.d.ts +1 -1
- package/dist/src/native/release.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5tjgz3sy.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,O,W,ke,ve,n,X,z,u,Z,E,_,L,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-4bgj0csn.js";import{a,C}from"../chunk-9fzxx1pq.js";import"../chunk-y67kbve9.js";import"../chunk-eg5pze25.js";import{Sa}from"../chunk-k5gh5ec6.js";import{d}from"../chunk-
|
|
2
|
+
import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,O,W,ke,ve,n,X,z,u,Z,E,_,L,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-4bgj0csn.js";import{a,C}from"../chunk-9fzxx1pq.js";import"../chunk-y67kbve9.js";import"../chunk-eg5pze25.js";import{Sa}from"../chunk-k5gh5ec6.js";import{d}from"../chunk-bfvq09k2.js";import m from"node:fs";import v from"node:path";import s from"node:process";C();async function ae(t="src/pantry"){if(!m.existsSync(t))throw Error(`Pantry directory not found: ${t}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function o(i,c=""){let g=m.readdirSync(i,{withFileTypes:!0}),p=v.join(i,"package.yml");if(c&&m.existsSync(p))e.push(c);for(let S of g)if(S.isDirectory()&&!S.name.startsWith(".")){let w=c?`${c}/${S.name}`:S.name,x=v.join(i,S.name);o(x,w)}}return o(t),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ce(t=!1){async function e(p){let S=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(S.searchParams.set("list-type","2"),S.searchParams.set("prefix",""),S.searchParams.set("max-keys","1000"),p)S.searchParams.set("continuation-token",p);let w=await fetch(S.toString());if(!w.ok)throw Error(`Failed to fetch S3 listing: ${w.status}`);let x=await w.text(),B=[],J=x.match(/<Key>([^<]+)<\/Key>/g);if(J)for(let G of J){let U=G.replace(/<Key>([^<]+)<\/Key>/,"$1");B.push({Key:U})}let y=x.includes("<IsTruncated>true</IsTruncated>"),F=x.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),h=F?F[1]:void 0;return{IsTruncated:y,NextContinuationToken:h,Contents:B}}console.log("Scraping packages from S3 registry...");let o=new Set,i;do{let p=await e(i);for(let S of p.Contents){let w=S.Key,x=w.split("/");if(x.length===0)continue;if(x[0].startsWith(".")||x[0].includes(" ")||w.match(/\.(md|txt|yml|yaml|json)$/i))continue;let B=["darwin","linux","windows"],J=-1;for(let y=1;y<x.length;y++)if(B.includes(x[y])){J=y;break}if(J>0){let y=x.slice(0,J).join("/");if(y.includes("."))o.add(y)}else if(x.length>=2&&x[0].includes(".")&&!x[1].startsWith("v")&&!x[1].match(/^\d/)){let y=`${x[0]}/${x[1]}`;o.add(y)}else if(x.length>=1&&x[0].includes("."))o.add(x[0])}i=p.NextContinuationToken,console.log(`Found ${o.size} packages so far...`)}while(i);let c=Array.from(o).sort(),g=[];for(let p of c){if(!p.includes(".")||p.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(p.endsWith("/README.rst")||p.endsWith("/README")||p.includes("/docs/"))continue;if(p.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(p))continue;g.push(p)}return console.log(`\uD83D\uDCE6 Found ${g.length} valid packages in registry`),g}async function le(t,e){let i=`/**
|
|
3
3
|
* Constants used throughout the ts-pantry package
|
|
4
4
|
* This file is auto-generated from ${e}. Do not edit manually.
|
|
5
5
|
* Generated on ${new Date().toISOString()}
|
package/dist/bin/desktop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import{q}from"../chunk-7q8as4h2.js";import"../chunk-eg5pze25.js";import"../chunk-g213c227.js";import{G,K,fe,Ye}from"../chunk-02w87xdt.js";import{d}from"../chunk-
|
|
2
|
+
import{q}from"../chunk-7q8as4h2.js";import"../chunk-eg5pze25.js";import"../chunk-g213c227.js";import{G,K,fe,Ye}from"../chunk-02w87xdt.js";import{d}from"../chunk-bfvq09k2.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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function D(t,e,r){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4
4
|
<plist version="1.0"><dict>
|
|
5
5
|
<key>Label</key><string>dev.pantry.desktop</string>
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{Te}from"./chunk-9fzxx1pq.js";import{d}from"./chunk-
|
|
2
|
-
${i.stderr}`.trim());return i}import z from"node:process";import{createHash as
|
|
1
|
+
import{Te}from"./chunk-9fzxx1pq.js";import{d}from"./chunk-bfvq09k2.js";import{existsSync as et,readFileSync as tt}from"node:fs";import{join as rt,resolve as H,sep as it}from"node:path";var ko={revision:"e1d6e40100ae2c35c96f9d96ed826f08ddf1f48b",version:"0.0.367"};function Re(r){let i=r.split(".");return i.length>1&&i.every((o)=>/^[A-Za-z]\w*$/.test(o))}function s(r,i){let o=H(r,i);if(o===H(r)||!o.startsWith(`${H(r)}${it}`))throw Error(`Native output must be inside the project: ${i}`);return o}function p(r,i=!1){let o=rt(r,"pantry.json");if(!et(o)){if(i)throw Error("Native publishing requires pantry.json with a native configuration");return}let n=JSON.parse(tt(o,"utf8")).native;if(!n){if(i)throw Error("pantry.json must declare native app settings");return}if(n.environment!==void 0&&(typeof n.environment!=="string"||!/^[a-z][a-z0-9-]*$/.test(n.environment)))throw Error("Invalid native release environment name");if(n.runtime&&(!/^[a-f0-9]{40}$/.test(n.runtime.revision)||!/^\d+\.\d+\.\d+$/.test(n.runtime.version)))throw Error("Craft requires an immutable 40-character Git revision and an exact version");for(let c of[n.build,...n.checks?.before??[],...n.checks?.after??[]])if(c!==void 0&&(!Array.isArray(c)||!c.length||c.some((a)=>typeof a!=="string"||!a)))throw Error("Native commands must be nonempty argument arrays");if(n.macos?.maxBundleSize!==void 0&&(!Number.isSafeInteger(n.macos.maxBundleSize)||n.macos.maxBundleSize<=0))throw Error("maxBundleSize must be a positive byte count");if(n.registry){if(typeof n.registry.domain!=="string"||!/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i.test(n.registry.domain)||n.registry.domain.includes("..")||n.registry.domain.endsWith("/"))throw Error("Native registry publishing requires an exact package domain");if(n.registry.url){let c=new URL(n.registry.url);if(c.username||c.password||c.search||c.hash||c.protocol!=="https:"&&!(c.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(c.hostname)))throw Error("Native registry URL must use HTTPS, or HTTP on loopback for testing")}if(!n.macos?.notarize)throw Error("Native registry apps require notarized macOS distribution")}if(n.android){if(s(r,n.android.bundle),!Re(n.android.packageName)||!n.android.track||!["draft","completed","inProgress"].includes(n.android.status))throw Error("Android publishing requires a package name, track and explicit release status");let c=n.android.userFraction;if(n.android.status==="inProgress"?!(typeof c==="number"&&c>0&&c<1):c!==void 0)throw Error("Only an inProgress rollout requires userFraction between zero and one")}return n}import nt from"node:process";import{spawn as ot}from"node:child_process";var t=(r,i,o={})=>new Promise((n,c)=>{if(o.timeoutMs!==void 0&&(!Number.isSafeInteger(o.timeoutMs)||o.timeoutMs<=0||o.timeoutMs>2147483647)){c(Error("A native command timeout must be a positive integer no greater than 2147483647ms"));return}let a=ot(r,i,{cwd:o.cwd,env:o.env??nt.env,stdio:o.inherit?"inherit":[o.input===void 0?"ignore":"pipe","pipe","pipe"]}),u="",m="";a.stdout?.on("data",(h)=>{u+=h.toString()}),a.stderr?.on("data",(h)=>{m+=h.toString()});let y,g,f=!1,l=()=>{if(y!==void 0)clearTimeout(y)},v=()=>{a.stdin?.destroy(),a.stdout?.destroy(),a.stderr?.destroy()};if(a.once("error",(h)=>{g=f?Error(g.message,{cause:h}):h,l()}),a.stdin?.once("error",(h)=>{g=f?Error(g.message,{cause:h}):h}),a.once("exit",()=>{if(!f)return;v()}),a.once("close",(h)=>{if(l(),g)c(g);else n({exitCode:h??1,stdout:u,stderr:m})}),o.timeoutMs!==void 0)y=setTimeout(()=>{if(f=!0,g=Error(`Native command timed out after ${o.timeoutMs}ms: ${r}`),a.exitCode!==null||a.signalCode)v();else try{a.kill("SIGKILL")}catch(h){g=Error(g.message,{cause:h})}},o.timeoutMs);if(o.input!==void 0)a.stdin?.end(o.input)});function e(r,i){if(i.exitCode!==0)throw Error(`${r} failed (${i.exitCode}): ${i.stdout}
|
|
2
|
+
${i.stderr}`.trim());return i}import z from"node:process";import{createHash as ct}from"node:crypto";import{existsSync as k,mkdirSync as ut,readFileSync as Q,rmSync as pt,writeFileSync as dt}from"node:fs";import{join as N,resolve as ft}from"node:path";var X="(?:0|[1-9]\\d*)",ce="(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)",pe=`${X}\\.${X}\\.${X}(?:-${ce}(?:\\.${ce})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?`,st=new RegExp(`^${pe}$`),at=new RegExp(`^pantry\\s+(${pe})(?:\\s+\\([^\\r\\n()]+\\))?$`);if(!st.test(d))throw Error("The native SDK requires a valid paired Pantry SDK/CLI version");var Oe=`^${d}`;async function Z(r,i,o){let n=`ts-pantry@${d} native provisioning requires Pantry ${Oe} on PATH in ${i}.`,c="Install or upgrade the Pantry CLI on that PATH before retrying.",a;try{a=await r("pantry",["--version"],{cwd:i,env:o,timeoutMs:1e4})}catch(m){throw Error(`${n} Could not run \`pantry --version\`. Install or upgrade the Pantry CLI on that PATH before retrying.`,{cause:m})}if(a.exitCode!==0)throw Error(`${n} \`pantry --version\` exited ${a.exitCode}. Install or upgrade the Pantry CLI on that PATH before retrying.`);let u=at.exec(a.stdout.trim()||a.stderr.trim())?.[1];if(!u)throw Error(`${n} \`pantry --version\` returned an invalid native CLI version. Install or upgrade the Pantry CLI on that PATH before retrying.`);if(Te(Oe,[u])!==u)throw Error(`${n} Found ${u}. Install or upgrade the Pantry CLI on that PATH before retrying.`)}function Ut(r,i=k){for(let o of[N(r,"bin","zig"),N(r,"zig")])if(i(o))return o;return null}function Ta(r,i,o=z.arch){if(!/^[a-f0-9]{40}$/.test(r))throw Error("Craft revision must be immutable");if(!/^\d+\.\d+(?:\.\d+)?$/.test(i))throw Error("A valid minimum macOS version is required");let n=o==="arm64"?"aarch64":o==="x64"?"x86_64":void 0;if(!n)throw Error(`Unsupported native architecture: ${o}`);return`revision=${r};ReleaseSmall;js-runtime=false;target=${n}-macos.${i}`}function Ct(r,i,o=z.arch){if(!r.runtime)throw Error("No Craft runtime configured");return ct("sha256").update(`${Ta(r.runtime.revision,i,o)};version=${r.runtime.version};schema=1`).digest("hex")}function jt(r){let i=r.workspaces?.[""]?.system?.["ziglang.org"];if(typeof i!=="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(i))throw Error("Craft must lock an exact Zig compiler version");return i}function St(r){if(!k(N(r,"packages/zig/build.zig.zon")))throw Error("Craft dependency manifest is missing");let i=N(r,".github/actions/first-party-zig-deps/pins.env");if(!k(i))return{kind:"manifest"};let o=Q(i,"utf8");return{kind:"legacy-pins",sources:[["zig-js","zig_js"],["zig-regex","zig_regex"],["zig-gc","zig_gc"]].map(([c,a])=>{let u=o.match(new RegExp(`^${a}=([a-f0-9]{40})$`,"m"))?.[1];if(!u)throw Error(`Missing upstream dependency pin: ${a}`);return{repository:`zig-utils/${c}`,revision:u,directory:c}})}}async function Va(r,i,o,n={}){let c=n.env??z.env;if(c.CRAFT_BIN){let w=ft(r,c.CRAFT_BIN);if(!k(w))throw Error(`CRAFT_BIN does not exist: ${w}`);return w}if(!i.runtime)return;if(z.platform!=="darwin")throw Error("The configured macOS Craft runtime must be built on macOS");let a=n.command??t,{revision:u,version:m}=i.runtime,y=Ta(u,o),g=N(r,".pantry/native/runtimes",Ct(i,o)),f=N(g,"Tools/craft"),l=N(f,"packages/zig/zig-out/bin/craft"),v=N(f,".pantry-runtime-profile"),h=()=>!k(l)||!k(v)||Q(v,"utf8")!==y;if(h())await Z(a,k(f)?f:r,c);let E=async(w,I,P=c,x=!1)=>e(w[0],await a(w[0],w.slice(1),{cwd:I,env:P,inherit:x})),b=async(w,I,P)=>{if(!/^[a-f0-9]{40}$/.test(I))throw Error(`Missing immutable dependency pin: ${w}`);if(ut(P,{recursive:!0}),!k(N(P,".git")))await E(["git","init","--quiet"],P),await E(["git","remote","add","origin",`https://github.com/${w}.git`],P),await E(["git","fetch","--quiet","--depth","1","origin",I],P),await E(["git","checkout","--quiet","--detach","FETCH_HEAD"],P);let x=(await E(["git","rev-parse","HEAD"],P)).stdout.trim();if(x!==I)throw Error(`Unexpected source revision in ${P}: ${x}`);if((await E(["git","status","--porcelain","--untracked-files=no"],P)).stdout.trim())throw Error(`Modified runtime source in ${P}`)};await b("craft-native/craft",u,f);let R=St(f);if(R.kind==="legacy-pins")for(let w of R.sources)await b(w.repository,w.revision,N(g,"Libraries",w.directory));if(h()){await Z(a,f,c),pt(v,{force:!0});let w=JSON.parse(Q(N(f,"pantry.lock"),"utf8")),I=jt(w);await E(["pantry","install",`ziglang.org@${I}`,"--no-save","--ignore-scripts"],f,c,!0);let P=N(f,"pantry/ziglang.org",`v${I}`),x=Ut(P);if(!x)throw Error(`Locked Zig compiler is missing under ${P}`);let J={...c,CRAFT_ZIG:x};if(R.kind==="manifest")await E(["bun","scripts/zig.ts","--core","build","--fetch"],f,J,!0);let ae=(await E(["xcrun","--sdk","macosx","--show-sdk-path"],f)).stdout.trim();if(!ae)throw Error("The macOS SDK is required");let Qe=y.split("target=")[1];await E(["bun","scripts/zig.ts","--core","--versioned","build","-Doptimize=ReleaseSmall","-Djs-runtime=false",`-Dtarget=${Qe}`,`-Dmacos-sdk=${ae}`],f,J,!0),dt(v,y)}let se=await E([l,"--version"],f);if(!`${se.stdout}${se.stderr}`.includes(`craft version ${m}`))throw Error(`Craft does not match configured version ${m}`);return l}import lt from"node:process";import{existsSync as fe,mkdirSync as mt,mkdtempSync as yt,readFileSync as gt,rmSync as de,writeFileSync as le}from"node:fs";import{tmpdir as ht}from"node:os";import{join as L,resolve as vt}from"node:path";function ee(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Dt(r){let i=(o)=>typeof o==="boolean"?`<${o}/>`:typeof o==="string"?`<string>${ee(o)}</string>`:Array.isArray(o)&&o.every((n)=>typeof n==="string")?`<array>${o.map((n)=>`<string>${ee(n)}</string>`).join("")}</array>`:(()=>{throw Error("Unsupported entitlement value")})();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
|
-
<plist version="1.0"><dict>${Object.entries(r).map(([o,n])=>`<key>${
|
|
5
|
-
`}async function vo(r,i={}){let o=p(r),n=i.env??
|
|
6
|
-
`)}function Le(r){let i=JSON.parse(
|
|
4
|
+
<plist version="1.0"><dict>${Object.entries(r).map(([o,n])=>`<key>${ee(o)}</key>${i(n)}`).join("")}</dict></plist>
|
|
5
|
+
`}async function vo(r,i={}){let o=p(r),n=i.env??lt.env;if(!o)return{overrides:{},cleanup(){}};let c=await Va(r,o,i.minimumSystemVersion??"13.0",{env:n}),a=n.PANTRY_DISTRIBUTION==="app-store",u=a?o.macos?.entitlements?.appStore:o.macos?.entitlements?.direct,m=n.APPLE_SIGNING_IDENTITY,y=n.APPLE_PROVISIONING_PROFILE_PATH||n.APPLE_PROVISIONING_PROFILE,g=yt(L(ht(),"pantry-native-build-"));try{let f=L(g,"entitlements.plist");if(u)le(f,Dt(u),{mode:384});if(y&&!fe(y))throw Error("APPLE_PROVISIONING_PROFILE must name a local profile file");if(a&&(!m||!y||u?.["com.apple.security.app-sandbox"]!==!0))throw Error("App Store builds require a signing identity, provisioning profile and sandbox entitlement");return{overrides:{...c?{craftPath:c}:{},...a?{output:s(r,".pantry/native/app-store")}:{},...m?{macosSigning:{identity:m,...y?{provisioningProfile:vt(y)}:{},...u?{entitlements:f}:{},hardenedRuntime:!a}}:{}},cleanup(){de(g,{recursive:!0,force:!0})}}}catch(f){throw de(g,{recursive:!0,force:!0}),f}}function xo(r,i){s(r,i.path);let o=L(r,".pantry/native");mt(o,{recursive:!0}),le(L(o,"artifact.json"),`${JSON.stringify(i,null,2)}
|
|
6
|
+
`)}function Le(r){let i=JSON.parse(gt(L(r,".pantry/native/artifact.json"),"utf8"));if(s(r,i.path),!i.name||!i.bundleId||!i.version||!i.buildNumber||!fe(i.path))throw Error("The native build did not produce a complete artifact manifest");return i}import Et from"node:process";import{createHash as wt}from"node:crypto";import{existsSync as O,mkdtempSync as me,readFileSync as ye,rmSync as ge,writeFileSync as ve}from"node:fs";import{tmpdir as Ee}from"node:os";import{basename as Pt,dirname as Nt,join as V}from"node:path";import{setTimeout as _t}from"node:timers/promises";function qa(r=Et.env){if(r.APPLE_NOTARY_KEYCHAIN_PROFILE)return{keychainProfile:r.APPLE_NOTARY_KEYCHAIN_PROFILE};let i=r.APP_STORE_CONNECT_API_KEY_ID,o=r.APP_STORE_CONNECT_ISSUER_ID||r.APP_STORE_CONNECT_API_ISSUER_ID,n=r.APP_STORE_CONNECT_PRIVATE_KEY||(r.APP_STORE_CONNECT_API_KEY_PATH?ye(r.APP_STORE_CONNECT_API_KEY_PATH,"utf8"):void 0);if(i||o||n){if(!i||!o||!n)throw Error("Notarization requires complete App Store Connect API credentials");if(!/^[A-Z0-9]+$/.test(i))throw Error("Invalid App Store Connect API key ID");return{apiKeyId:i,issuerId:o,privateKey:n}}if(r.APPLE_ID&&r.APPLE_APP_SPECIFIC_PASSWORD&&r.APPLE_TEAM_ID)return{appleId:r.APPLE_ID,password:r.APPLE_APP_SPECIFIC_PASSWORD,teamId:r.APPLE_TEAM_ID};throw Error("Notarization requires an existing keychain profile, App Store Connect API key, or Apple ID credentials")}async function Ra(r,i,o=t){if(!O(r)||!r.toLowerCase().endsWith(".dmg")||!i)throw Error("Disk image signing requires an existing DMG and a Developer ID Application identity");e("Sign disk image",await o("codesign",["--force","--sign",i,"--timestamp",r])),e("Disk image signature",await o("codesign",["--verify","--strict",r]));let n=e("Disk image identity",await o("codesign",["-dv","--verbose=4",r])),c=`${n.stdout}
|
|
7
7
|
${n.stderr}`;if(!c.includes("Authority=Developer ID Application:")||!/^Timestamp=/m.test(c))throw Error("Disk image requires a timestamped Developer ID Application signature")}async function Y(r,i=t){let o=r.toLowerCase().endsWith(".dmg")?["--type","open","--context","context:primary-signature"]:r.toLowerCase().endsWith(".app")?["--type","exec"]:r.toLowerCase().endsWith(".pkg")?["--type","install"]:void 0;if(!O(r)||!o)throw Error("Gatekeeper assessment requires an existing app, DMG or PKG");let n=e("Gatekeeper assessment",await i("spctl",["--assess",...o,"--verbose=2",r]));if(!`${n.stdout}
|
|
8
8
|
${n.stderr}`.includes("source=Notarized Developer ID"))throw Error("Gatekeeper did not recognize the notarized Developer ID distribution")}async function B(r,i,o){let n=r==="staple"?"Staple notarization":"Validate notarization";for(let c=0;;c++){let a=await o("xcrun",["stapler",r,i]),u=/NSURLErrorDomain\s+Code=-(?:1001|1003|1004|1005|1009)\b/.test(`${a.stdout}
|
|
9
|
-
${a.stderr}`);if(a.exitCode===0||!u||c===4){e(n,a);return}await
|
|
9
|
+
${a.stderr}`);if(a.exitCode===0||!u||c===4){e(n,a);return}await _t(1000*2**c)}}async function Oa(r,i,o=t){if(!O(r)||!/\.(dmg|pkg|zip)$/i.test(r))throw Error("Notarization requires an existing DMG, PKG or ZIP");let n=me(V(Ee(),"pantry-notary-"));try{let c;if("keychainProfile"in i)c=["--keychain-profile",i.keychainProfile];else if("apiKeyId"in i){let m=V(n,"AuthKey.p8");ve(m,i.privateKey,{mode:384}),c=["--key",m,"--key-id",i.apiKeyId,"--issuer",i.issuerId]}else c=["--apple-id",i.appleId,"--password",i.password,"--team-id",i.teamId];let a=e("Apple notarization",await o("xcrun",["notarytool","submit",r,...c,"--wait","--timeout","30m","--output-format","json"])),u=JSON.parse(a.stdout);if(!u.id||u.status!=="Accepted")throw Error(`Apple did not accept notarization: ${u.status??"unknown status"} (${u.id??"no submission ID"})`);if(!r.toLowerCase().endsWith(".zip"))await B("staple",r,o),await B("validate",r,o);return{schemaVersion:1,file:Pt(r),submissionId:u.id,status:u.status,sha256:wt("sha256").update(ye(r)).digest("hex"),completedAt:new Date().toISOString()}}finally{ge(n,{recursive:!0,force:!0})}}async function La(r,i,o,n=t){if(!r.endsWith(".app")||!O(r)||!i.endsWith(".pkg")||!o)throw Error("App Store packaging requires an app, .pkg output and installer identity");if(O(i))throw Error(`Refusing to overwrite an existing package: ${i}`);if(!O(V(r,"Contents/embedded.provisionprofile")))throw Error("App Store app is missing its provisioning profile");e("App signature",await n("codesign",["--verify","--deep","--strict",r]));let c=e("Read signed entitlements",await n("codesign",["-d","--entitlements",":-",r])),a=me(V(Ee(),"pantry-app-store-package-"));try{let u=V(a,"entitlements.plist");if(ve(u,c.stdout||c.stderr),JSON.parse(e("App sandbox entitlement",await n("plutil",["-convert","json","-o","-",u])).stdout)["com.apple.security.app-sandbox"]!==!0)throw Error("App Store app sandbox must be enabled");if(e("Create signed App Store package",await n("productbuild",["--component",r,"/Applications","--sign",o,i],{cwd:Nt(i)})),e("Installer signature",await n("pkgutil",["--check-signature",i])),!O(i))throw Error("productbuild did not produce the requested package");return i}finally{ge(a,{recursive:!0,force:!0})}}import $t from"node:process";import{existsSync as we,mkdtempSync as bt,renameSync as It,rmSync as Pe,writeFileSync as kt}from"node:fs";import{tmpdir as Tt}from"node:os";import{join as Ae}from"node:path";async function Ma(r,i=$t.env,o=t){if(!r.endsWith(".aab")||!we(r))throw Error("Android signing requires an existing .aab");let n=[i.ANDROID_KEYSTORE_BASE64,i.ANDROID_KEYSTORE_PASSWORD,i.ANDROID_KEY_ALIAS,i.ANDROID_KEY_PASSWORD];if(n.some(Boolean)&&!n.every(Boolean))throw Error("Android signing requires a keystore, alias, store password and key password");let c=bt(Ae(Tt(),"pantry-android-signing-")),a=`${r}.pantry-signed.aab`,u=async(m)=>{let y=e("Android bundle signature",await o("jarsigner",["-J-Duser.language=en","-J-Duser.country=US","-verify",m]));if(!/jar verified\./i.test(y.stdout)||/jar is unsigned/i.test(`${y.stdout}${y.stderr}`))throw Error("Android bundle is not signed")};try{if(n.every(Boolean)){if(we(a))throw Error("A previous Android signing artifact still exists");let m=Ae(c,"release.keystore");kt(m,Buffer.from(i.ANDROID_KEYSTORE_BASE64,"base64"),{mode:384}),e("Android bundle signing",await o("jarsigner",["-J-Duser.language=en","-J-Duser.country=US","-keystore",m,"-storepass:env","PANTRY_ANDROID_STORE_PASSWORD","-keypass:env","PANTRY_ANDROID_KEY_PASSWORD","-signedjar",a,r,i.ANDROID_KEY_ALIAS],{env:{...i,PANTRY_ANDROID_STORE_PASSWORD:i.ANDROID_KEYSTORE_PASSWORD,PANTRY_ANDROID_KEY_PASSWORD:i.ANDROID_KEY_PASSWORD}})),await u(a),It(a,r)}else await u(r)}finally{Pe(a,{force:!0}),Pe(c,{recursive:!0,force:!0})}}import{existsSync as dr,readFileSync as fr}from"node:fs";import{join as lr}from"node:path";import{chmodSync as Pi,existsSync as Ke,readFileSync as De,renameSync as Ni,rmSync as Ai,writeFileSync as _i}from"node:fs";import{basename as Si,dirname as bi,resolve as Ve}from"node:path";import{createCipheriv as ni,createDecipheriv as $e,createHash as te,createPrivateKey as xt,createPublicKey as re,diffieHellman as Ot,generateKeyPairSync as oi,hkdfSync as Rt,randomBytes as si}from"node:crypto";var U="x25519-public:",_e="x25519-private:",Se="encrypted:v2:",be="encrypted:",Kt=Buffer.from("stacks-env:v2","utf8"),Ie="Environment decryption failed: authentication or format error";function Lt(r){if(r.length===32)return r;return te("sha256").update(r).digest()}function Vt(r,i,o,n){try{let c=$e("aes-256-gcm",Lt(i),Buffer.from(o,"hex"));return c.setAuthTag(Buffer.from(n,"hex")),Buffer.concat([c.update(Buffer.from(r,"hex")),c.final()]).toString("utf8")}catch{throw Error("Decryption failed: authentication or format error")}}function ie(r){return r.toString("base64url")}function C(r,i,o){if(typeof r!=="string"||r.length>0&&!/^[A-Za-z0-9_-]+$/.test(r))throw Error(`${i} is not canonical base64url`);let n=Buffer.from(r,"base64url");if(ie(n)!==r)throw Error(`${i} is not canonical base64url`);if(o!==void 0&&n.length!==o)throw Error(`${i} has an invalid length`);return n}function Ft(r){if(!r.startsWith(U))throw Error("Legacy or invalid public key. Run buddy env:rotate before creating new ciphertext.");let i=re({key:C(r.slice(U.length),"public key"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw Error("Public key is not X25519");return i}function F(r){if(typeof r!=="string")return!1;try{let i=Ft(r);return r===`${U}${ie(i.export({format:"der",type:"spki"}))}`}catch{return!1}}function ke(r){if(!r.startsWith(_e))throw Error("Private key is not a version 2 X25519 key");let i=xt({key:C(r.slice(_e.length),"private key"),format:"der",type:"pkcs8"});if(i.asymmetricKeyType!=="x25519")throw Error("Private key is not X25519");return i}function M(r,i){if(!F(r)||typeof i!=="string")return!1;try{let o=re(ke(i));return r===`${U}${ie(o.export({format:"der",type:"spki"}))}`}catch{return!1}}function Bt(r){return Buffer.from(`stacks-env:v2;${r.epk};${r.salt};${r.nonce}`,"utf8")}function Yt(r){let i=C(r.slice(Se.length),"envelope").toString("utf8"),o=JSON.parse(i);if(!o||typeof o!=="object"||Array.isArray(o))throw Error("envelope is not an object");let n=Object.keys(o).sort(),c=["ciphertext","epk","nonce","salt","tag","v"];if(n.length!==c.length||n.some((a,u)=>a!==c[u]))throw Error("envelope fields are invalid");if(o.v!==2)throw Error("envelope version is unsupported");for(let a of["epk","salt","nonce","ciphertext","tag"])if(typeof o[a]!=="string")throw Error(`${a} is invalid`);return o}function Wt(r,i){try{let o=Yt(r),n=ke(i),c=re({key:C(o.epk,"ephemeral public key"),format:"der",type:"spki"});if(c.asymmetricKeyType!=="x25519")throw Error("ephemeral key is not X25519");let a=C(o.salt,"salt",16),u=C(o.nonce,"nonce",12),m=C(o.ciphertext,"ciphertext"),y=C(o.tag,"tag",16),g=Ot({privateKey:n,publicKey:c}),f=Buffer.from(Rt("sha256",g,a,Kt,32));try{let l=$e("aes-256-gcm",f,u);return l.setAAD(Bt(o)),l.setAuthTag(y),Buffer.concat([l.update(m),l.final()]).toString("utf8")}finally{g.fill(0),f.fill(0)}}catch{throw Error(Ie)}}function zt(r,i){try{if(!/^[0-9a-f]{64}$/.test(i))throw Error("invalid legacy private key");let o=Buffer.from(r.slice(be.length),"base64");if(o.length<32)throw Error("invalid legacy payload");let n=te("sha256").update(Buffer.from(i,"hex")).digest(),c=te("sha256").update(n).digest();return Vt(o.subarray(32).toString("hex"),c,o.subarray(0,16).toString("hex"),o.subarray(16,32).toString("hex"))}catch{throw Error(Ie)}}function ne(r,i){if(!r.startsWith(be))return r;return r.startsWith(Se)?Wt(r,i):zt(r,i)}import{spawnSync as Mt}from"node:child_process";import{readFileSync as qt}from"node:fs";import{arch as Gt,hostname as Jt,platform as xe,release as Ht,userInfo as Xt}from"node:os";import{basename as Zt,dirname as Qt,resolve as er}from"node:path";function q(r){return typeof r==="string"&&(r.startsWith("encrypted:")||r.startsWith("enc:"))}function Ce(r,i=Object.keys(r)){let o=i.map((n)=>r[n]).filter((n)=>q(n));return Object.fromEntries(Object.entries(r).filter(([,n])=>n===void 0||!o.some((c)=>n.includes(c))))}function W(r,i={}){let o={},n=[],c=[],a=r.split(`
|
|
10
10
|
`),u=Ce(i.processEnv||process.env);for(let m of a){let y=m.trim();if(!y||y.startsWith("#"))continue;if(y.startsWith("DOTENV_PUBLIC_KEY=")){let v=y.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(v&&v[1]!==void 0)o.DOTENV_PUBLIC_KEY=v[1];continue}let g=y.match(/^([^=]+)=(.*)$/);if(!g||g[1]===void 0||g[2]===void 0)continue;let f=g[1].trim(),l=g[2].trim();if(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'")){if(l=l.slice(1,-1),l.includes("\\n"))l=l.replace(/\\n/g,`
|
|
11
|
-
`)}if(l.startsWith("encrypted:")||l.startsWith("enc:")){if(!i.privateKey){c.push(f);continue}try{let v=l.startsWith("enc:")?`encrypted:${l.slice(4)}`:l;l=
|
|
12
|
-
`);let y=
|
|
13
|
-
`)}function We(r,i={}){let o=i.cwd||process.cwd(),n=Ve(o,i.file||".env");if(!Ke(n))return{success:!1,error:`File not found: ${n}`};try{let c=
|
|
14
|
-
`);break;case"json":default:f=i.prettyPrint?JSON.stringify(g,null,2):JSON.stringify(g);break}return{success:!0,output:f}}catch(c){return{success:!1,error:`Failed to get: ${c instanceof Error?c.message:"Unknown error"}`}}}var
|
|
15
|
-
${i.stderr}`.trim();throw Error(`${r} failed${o?`: ${o}`:` with exit code ${i.exitCode}`}`)}function Ue(r,i,o){let n=K.join(r,i);return T.writeFileSync(n,Buffer.from(o.trim(),"base64"),{mode:384}),n}async function ue(r,i={}){if((i.platform||process.platform)!=="darwin")throw Error("Apple code signing requires a macOS runner");if(!r.applicationCertificate)throw Error("Apple code signing requires an application certificate");if(!r.certificatePassword)throw Error("Apple code signing requires the password protecting the .p12 certificates");let n=i.runCommand||Je,c=T.mkdtempSync(K.join(i.tempDirectory||Ge.tmpdir(),"pantry-signing-")),a=qe.randomBytes(24).toString("base64"),u=K.join(c,"pantry-signing.keychain-db");try{_("Keychain creation",await n("security",["create-keychain","-p",a,u])),_("Keychain configuration",await n("security",["set-keychain-settings","-lut","21600",u])),_("Keychain unlock",await n("security",["unlock-keychain","-p",a,u]));let m=[{name:"application.p12",content:r.applicationCertificate},...r.installerCertificate?[{name:"installer.p12",content:r.installerCertificate}]:[]];for(let b of m){let R=Ue(c,b.name,b.content);_(`Import of ${b.name}`,await n("security",["import",R,"-k",u,"-P",r.certificatePassword,"-T","/usr/bin/codesign","-T","/usr/bin/productbuild","-f","pkcs12","-A"])),T.rmSync(R,{force:!0})}_("Keychain partition list",await n("security",["set-key-partition-list","-S","apple-tool:,apple:,codesign:","-s","-k",a,u]));let y=await n("security",["list-keychains","-d","user"]);_("Keychain search list",y);let g=[...y.stdout.matchAll(/"([^"]+)"/g)].map((b)=>b[1]);_("Keychain search list update",await n("security",["list-keychains","-d","user","-s",u,...g]));let f=await n("security",["find-identity","-v",u]);_("Identity lookup",f);let l=Na(f.stdout),v=Ne(l,"application");if(!v)throw Error(`No application signing identity found in the imported certificates (found: ${l.join(", ")||"none"})`);let h=Ne(l,"installer");if(r.installerCertificate&&!h)throw Error(`No installer signing identity found in the imported certificates (found: ${l.join(", ")})`);let E=r.provisioningProfile?Ue(r.outputDirectory||c,"embedded.provisionprofile",r.provisioningProfile):void 0;return{keychainPath:u,applicationIdentity:v,applicationFingerprint:ze(f.stdout,v),...h?{installerIdentity:h,installerFingerprint:ze(f.stdout,h)}:{},...E?{provisioningProfilePath:E}:{}}}catch(m){try{await n("security",["delete-keychain",u])}catch(y){throw AggregateError([m,y],"Apple signing failed and its temporary keychain could not be removed")}finally{T.rmSync(c,{recursive:!0,force:!0})}throw m}}async function Fe(r,i={}){let o=i.runCommand||Je;try{_("Keychain removal",await o("security",["delete-keychain",r]))}finally{T.rmSync(K.dirname(r),{recursive:!0,force:!0})}}function Fa(r){let i=mr(r);if(i.isSymbolicLink())throw Error(`Native app must not contain symbolic links: ${r}`);return i.isDirectory()?
|
|
16
|
-
`),l.push(E)}if(f?.path.toLowerCase().endsWith(".dmg")){let h=`${f.path}.zip`;if(
|
|
11
|
+
`)}if(l.startsWith("encrypted:")||l.startsWith("enc:")){if(!i.privateKey){c.push(f);continue}try{let v=l.startsWith("enc:")?`encrypted:${l.slice(4)}`:l;l=ne(v,i.privateKey)}catch(v){n.push(`Failed to decrypt ${f}: ${v instanceof Error?v.message:"Unknown error"}`),c.push(f);continue}}l=tr(l,{...u,...o}),l=or(l),o[f]=l}return{parsed:o,errors:n,skippedEncrypted:c}}function tr(r,i){return r.replace(/\$\{([^}]+)\}/g,(o,n)=>{let c=n.match(/^([^:\-+]+)(:-|-)(.+)$/);if(c){let[,u,m,y]=c,g=i[u];if(m===":-")return g||y;else return g!==void 0?g:y}let a=n.match(/^([^:\-+]+)(:?\+)(.+)$/);if(a){let[,u,m,y]=a,g=i[u];if(m===":+")return g?y:"";else return g!==void 0?y:""}return i[n]||""})}var rr=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ir(r){let i=[],o="",n=null,c=!1;for(let a of r.trim()){if(c){o+=a,c=!1;continue}if(a==="\\"&&n!=="'"){c=!0;continue}if(n){if(a===n)n=null;else o+=a;continue}if(a==='"'||a==="'"){n=a;continue}if(/\s/.test(a)){if(o)i.push(o),o="";continue}o+=a}if(c||n)throw Error("Command substitution contains an unterminated escape or quote");if(o)i.push(o);return i}function nr(r){let[i,...o]=r,n=o.some((c)=>c.startsWith("-"));if(i==="echo"&&!n)return o.join(" ");if(i==="printf"&&o.length===1&&!o[0]?.includes("%"))return o[0];if(i==="hostname"&&o.length===0)return Jt();if(i==="whoami"&&o.length===0)return Xt().username;if(i==="pwd"&&o.length===0)return process.cwd();if(i==="basename"&&o.length===1)return Zt(o[0]??"");if(i==="dirname"&&o.length===1)return Qt(o[0]??"");if(i==="cat"&&o.length>0&&!n)return o.map((c)=>qt(er(process.cwd(),c),"utf8")).join("");if(i==="uname"){let c=o[0]??"-s";if(o.length<=1&&c==="-m")return Gt();if(o.length<=1&&c==="-r")return Ht();if(o.length<=1&&c==="-s")return{aix:"AIX",android:"Android",cygwin:"CYGWIN",darwin:"Darwin",freebsd:"FreeBSD",haiku:"Haiku",linux:"Linux",netbsd:"NetBSD",openbsd:"OpenBSD",sunos:"SunOS",win32:"Windows_NT"}[xe()]??xe()}return}function or(r){return r.replace(/\$\(([^)]+)\)/g,(i,o)=>{try{let n=ir(o),c=n[0];if(!c||!rr.has(c))return console.warn(`[env] Blocked command substitution for disallowed command: ${c}`),"";let a=nr(n);if(a!==void 0)return a.trim();let u=Mt(c,n.slice(1),{encoding:"utf8",env:process.env});if(u.status===0)return u.stdout.trim();let m=u.stderr.trim();console.warn(`[env] Command substitution failed (exit code ${u.status??"unknown"}): ${c}${m?`: ${m}`:""}`)}catch(n){console.warn(`[env] Command substitution error: ${n instanceof Error?n.message:String(n)}`)}return""})}function Be(r){let i=((r||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase();return{publicKeyName:i?`DOTENV_PUBLIC_KEY_${i}`:"DOTENV_PUBLIC_KEY",privateKeyName:i?`DOTENV_PRIVATE_KEY_${i}`:"DOTENV_PRIVATE_KEY"}}function sr(r){let{publicKeyName:i}=Be(r);return i==="DOTENV_PUBLIC_KEY"?[i]:[i,"DOTENV_PUBLIC_KEY"]}function Ye(r){let{privateKeyName:i}=Be(r);return i==="DOTENV_PRIVATE_KEY"?[i]:[i,"DOTENV_PRIVATE_KEY"]}function oe(r={}){let i=Ve(r.cwd||process.cwd(),r.keysFile||".env.keys"),o=Ke(i)?W(De(i,"utf8")).parsed:{};for(let n of Ye(r.file)){let c=o[n]||process.env[n];if(c)return c}return}function ar(r,i,o,n){let c=n.file||".env",a=n.keysFile||".env.keys",[u]=Ye(n.file),m=`${r.length===1?"Value":"Values"} that cannot be decrypted: ${r.join(", ")}.`;if(!o)return[`Cannot read ${c}: no private key for it.`,` Expected ${u} in ${a} or the environment, and found neither.`,` ${m}`].join(`
|
|
12
|
+
`);let y=sr(n.file).find((l)=>i[l]),g=y?i[y]:void 0,f=g&&!M(g,o)?` The private key found for it does not match ${y} in the file, so it belongs to a different key pair.`:" The private key found for it did not decrypt them. It may belong to a different key pair, or the values may be damaged.";return[`Cannot read ${c}: its private key does not decrypt it.`,f,` ${m}`].join(`
|
|
13
|
+
`)}function We(r,i={}){let o=i.cwd||process.cwd(),n=Ve(o,i.file||".env");if(!Ke(n))return{success:!1,error:`File not found: ${n}`};try{let c=oe(i),a=De(n,"utf-8"),{parsed:u,skippedEncrypted:m}=W(a,{privateKey:c}),y=r&&!i.all?m.filter((l)=>l===r):m;if(y.length>0)return{success:!1,error:ar(y,u,c,i)};if(r&&!i.all){let l=u[r];if(l===void 0)return{success:!1,error:`Key not found: ${r}`};return{success:!0,output:l}}let g=u,f;switch(i.format){case"shell":f=Object.entries(g).map(([l,v])=>`${l}=${v}`).join(" ");break;case"eval":f=Object.entries(g).map(([l,v])=>`${l}="${v}"`).join(`
|
|
14
|
+
`);break;case"json":default:f=i.prettyPrint?JSON.stringify(g,null,2):JSON.stringify(g);break}return{success:!0,output:f}}catch(c){return{success:!1,error:`Failed to get: ${c instanceof Error?c.message:"Unknown error"}`}}}var cr=/(?:^|_)(?:PASSWORD|PASSWD|SECRET|TOKEN|APIKEY|API_KEY|CREDENTIAL|CREDENTIALS|PRIVATE|SALT|DSN|CERT|CIPHER|SIGNATURE|WEBHOOK)(?:_|$)|(?:^|_)(?:ACCESS|SECRET)_KEY(?:_|$)|_KEY$/,ur=/^DOTENV_(?:PUBLIC|PRIVATE)_KEY/,pr=/^\$\{[^}]+\}$/;function je(r,i={}){let{placeholders:o={},strict:n=!1}=i,c=[];for(let[a,u]of Object.entries(r)){if(n&&a.startsWith("DOTENV_PUBLIC_KEY")){if(!F(u))c.push({key:a,reason:"invalid-public-key"});continue}if(n&&a.startsWith("DOTENV_PRIVATE_KEY")){if(u.trim())c.push({key:a,reason:"private-key-material"});continue}if(!u||u.trim()==="")continue;if(q(u))continue;if(ur.test(a))continue;if(pr.test(u.trim()))continue;let m=cr.test(a),y=Object.prototype.hasOwnProperty.call(o,a)&&o[a]===u;if(m&&!y){c.push({key:a,reason:"plaintext-secret"});continue}if(n)c.push({key:a,reason:"plaintext-value"})}return c}function Me(r,i){if(!/^[a-z][a-z0-9-]*$/.test(i))throw Error("Invalid native release environment name");let o=lr(r,`.env.${i}`);if(!dr(o))throw Error(`Native release environment is missing: .env.${i}`);let{parsed:n,skippedEncrypted:c}=W(fr(o,"utf8"),{processEnv:{}});if([...Object.keys(n),...c].some((m)=>m.startsWith("DOTENV_PRIVATE_KEY")))throw Error("Private decryption keys must never be committed in environment files");let a=je(n,{strict:!0});if(a.length)throw Error(`Native release environment must be Buddy-encrypted: ${a.map((m)=>m.key).join(", ")}`);let u=n[`DOTENV_PUBLIC_KEY_${i.toUpperCase()}`]||n.DOTENV_PUBLIC_KEY;if(!F(u))throw Error("Native release environment requires valid Buddy public-key metadata")}function j(r,i,o=()=>{}){Me(r,i);let n=`.env.${i}`,c=We(void 0,{cwd:r,file:n,all:!0,format:"json"});if(!c.success||!c.output)throw Error(c.error||`Could not read ${n}`);let a=JSON.parse(c.output),u=a[`DOTENV_PUBLIC_KEY_${i.toUpperCase()}`]||a.DOTENV_PUBLIC_KEY;if(!M(u,oe({cwd:r,file:n})))throw Error("Native release environment key does not match its public metadata");for(let[m,y]of Object.entries(a)){if(m.startsWith("DOTENV_PRIVATE_KEY")&&y)throw Error("Private decryption keys must never be committed in environment files");if(!m.startsWith("DOTENV_PUBLIC_KEY")&&y)o(y)}return Object.fromEntries(Object.entries(a).filter(([m])=>!m.startsWith("DOTENV_")))}import Xe from"node:process";import{existsSync as D,lstatSync as mr,mkdtempSync as yr,readdirSync as gr,readFileSync as Ze,rmSync as G,writeFileSync as hr}from"node:fs";import{tmpdir as vr}from"node:os";import{basename as Er,dirname as He,join as A}from"node:path";import*as qe from"node:crypto";import*as T from"node:fs";import*as Ge from"node:os";import*as K from"node:path";function Na(r){return[...r.matchAll(/^\s*\d+\)\s+[0-9A-F]+\s+"([^"]+)"/gim)].map((i)=>i[1])}function ze(r,i){let o=new Set([...r.matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s+"([^"]+)"/gim)].filter((n)=>n[2]===i).map((n)=>n[1].toUpperCase()));if(o.size!==1)throw Error(`Imported signing identity requires a unique certificate fingerprint: ${i}`);return[...o][0]}function Ne(r,i){let o=i==="application"?["3rd Party Mac Developer Application","Apple Distribution","Developer ID Application"]:["3rd Party Mac Developer Installer","Developer ID Installer"];for(let n of o){let c=r.find((a)=>a.startsWith(n));if(c)return c}return}async function Je(r,i){return t(r,i)}function _(r,i){if(i.exitCode===0)return;let o=`${i.stdout}
|
|
15
|
+
${i.stderr}`.trim();throw Error(`${r} failed${o?`: ${o}`:` with exit code ${i.exitCode}`}`)}function Ue(r,i,o){let n=K.join(r,i);return T.writeFileSync(n,Buffer.from(o.trim(),"base64"),{mode:384}),n}async function ue(r,i={}){if((i.platform||process.platform)!=="darwin")throw Error("Apple code signing requires a macOS runner");if(!r.applicationCertificate)throw Error("Apple code signing requires an application certificate");if(!r.certificatePassword)throw Error("Apple code signing requires the password protecting the .p12 certificates");let n=i.runCommand||Je,c=T.mkdtempSync(K.join(i.tempDirectory||Ge.tmpdir(),"pantry-signing-")),a=qe.randomBytes(24).toString("base64"),u=K.join(c,"pantry-signing.keychain-db");try{_("Keychain creation",await n("security",["create-keychain","-p",a,u])),_("Keychain configuration",await n("security",["set-keychain-settings","-lut","21600",u])),_("Keychain unlock",await n("security",["unlock-keychain","-p",a,u]));let m=[{name:"application.p12",content:r.applicationCertificate},...r.installerCertificate?[{name:"installer.p12",content:r.installerCertificate}]:[]];for(let b of m){let R=Ue(c,b.name,b.content);_(`Import of ${b.name}`,await n("security",["import",R,"-k",u,"-P",r.certificatePassword,"-T","/usr/bin/codesign","-T","/usr/bin/productbuild","-f","pkcs12","-A"])),T.rmSync(R,{force:!0})}_("Keychain partition list",await n("security",["set-key-partition-list","-S","apple-tool:,apple:,codesign:","-s","-k",a,u]));let y=await n("security",["list-keychains","-d","user"]);_("Keychain search list",y);let g=[...y.stdout.matchAll(/"([^"]+)"/g)].map((b)=>b[1]);_("Keychain search list update",await n("security",["list-keychains","-d","user","-s",u,...g]));let f=await n("security",["find-identity","-v",u]);_("Identity lookup",f);let l=Na(f.stdout),v=Ne(l,"application");if(!v)throw Error(`No application signing identity found in the imported certificates (found: ${l.join(", ")||"none"})`);let h=Ne(l,"installer");if(r.installerCertificate&&!h)throw Error(`No installer signing identity found in the imported certificates (found: ${l.join(", ")})`);let E=r.provisioningProfile?Ue(r.outputDirectory||c,"embedded.provisionprofile",r.provisioningProfile):void 0;return{keychainPath:u,applicationIdentity:v,applicationFingerprint:ze(f.stdout,v),...h?{installerIdentity:h,installerFingerprint:ze(f.stdout,h)}:{},...E?{provisioningProfilePath:E}:{}}}catch(m){try{await n("security",["delete-keychain",u])}catch(y){throw AggregateError([m,y],"Apple signing failed and its temporary keychain could not be removed")}finally{T.rmSync(c,{recursive:!0,force:!0})}throw m}}async function Fe(r,i={}){let o=i.runCommand||Je;try{_("Keychain removal",await o("security",["delete-keychain",r]))}finally{T.rmSync(K.dirname(r),{recursive:!0,force:!0})}}function Fa(r){let i=mr(r);if(i.isSymbolicLink())throw Error(`Native app must not contain symbolic links: ${r}`);return i.isDirectory()?gr(r).reduce((o,n)=>o+Fa(A(r,n)),0):i.size}function Ya(r){return D(A(r,"Contents/Resources/native-screen.js"))&&D(A(r,"Contents/Resources/craft-app.json"))}async function he(r,i,o=t){let n=r.appPath??r.path;if(!n.endsWith(".app")||!D(n))throw Error("Native build must produce a macOS application bundle");let c=A(n,"Contents/Info.plist"),a=A(n,"Contents/MacOS",r.name),m=Ya(n)?["native-screen.js","craft-app.json"]:["index.html","craft.json"];for(let l of[c,a,...m.map((v)=>A(n,"Contents/Resources",v))])if(!D(l))throw Error(`Native app is incomplete: ${l}`);let y=Ze(a).subarray(0,4).toString("hex");if(!["cffaedfe","cefaedfe","cafebabe","bebafeca","cafebabf","bfbafeca"].includes(y))throw Error("Native app executable must be Mach-O");let g=Fa(n);if(i!==void 0&&g>=i)throw Error(`Native bundle is ${g} bytes; it must be below ${i}`);let f=JSON.parse(e("Read bundle metadata",await o("plutil",["-convert","json","-o","-",c])).stdout);if(f.CFBundleIdentifier!==r.bundleId||f.CFBundleShortVersionString!==r.version||String(f.CFBundleVersion)!==r.buildNumber)throw Error("Built app identity/version does not match the release manifest")}async function At(r,i,o=t,n=Xe.env){await he(r,i,o);let c=A(r.appPath??r.path,"Contents/MacOS",r.name);if(Ya(r.appPath??r.path)){let u=e("Native launch check",await o(c,["--version"]));if(!`${u.stdout}${u.stderr}`.includes("craft native macOS renderer"))throw Error("Native app did not report the AppKit renderer");return}let a=yr(A(vr(),"pantry-native-launch-"));try{let u=e("Native launch check",await o(c,["--benchmark"],{env:{...n,STX_DATA_HOME:a},timeoutMs:30000}));if(!`${u.stdout}${u.stderr}`.includes("ready"))throw Error("Native app did not report ready")}finally{G(a,{recursive:!0})}}async function S(r,i,o={}){let n=p(r,!0),c=o.command??t,a={...o.env??Xe.env};if(n.environment){if(Me(r,n.environment),i==="release"){let f=j(r,n.environment,o.onSecret);Object.assign(a,f,{APP_ENV:n.environment,NODE_ENV:n.environment,DOTENV_ENV:n.environment}),o.onEnvironment?.(f)}}let u=JSON.parse(Ze(A(r,"package.json"),"utf8"));if(!u.version||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(u.version))throw Error("A native release requires a semantic package version");if(a.PANTRY_BUILD_NUMBER=a.PANTRY_BUILD_NUMBER||a.GITHUB_RUN_NUMBER||u.version,i==="release"&&a.GITHUB_REF_TYPE==="tag"&&a.GITHUB_REF_NAME!==`v${u.version}`)throw Error("Release tag must match package.json version");if(i==="release"&&a.CRAFT_BIN)throw Error("Release builds must use the configured immutable runtime; CRAFT_BIN is a development override");let m=i==="release"&&n.macos?.notarize?qa(a):void 0;if(i==="release"&&n.registry&&!(a.PANTRY_REGISTRY_TOKEN||a.PANTRY_TOKEN))throw Error("Native registry publishing requires a Pantry publishing token");if(i==="release"&&n.android&&!a.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON)throw Error("Google Play publishing requires GOOGLE_PLAY_SERVICE_ACCOUNT_JSON");if(i==="release"&&n.macos?.appStore&&(!a.APPLE_APP_STORE_APPLICATION_CERTIFICATE||!a.APPLE_APP_STORE_INSTALLER_CERTIFICATE||!a.APPLE_APP_STORE_PROVISIONING_PROFILE_BASE64||!a.APP_STORE_CONNECT_API_KEY_ID||!a.APP_STORE_CONNECT_ISSUER_ID||!a.APP_STORE_CONNECT_PRIVATE_KEY))throw Error("App Store publishing requires distribution certificates, provisioning profile and App Store Connect credentials");if(i==="release"&&n.macos&&!(a.APPLE_SIGNING_IDENTITY||a.APPLE_APPLICATION_CERTIFICATE))throw Error("Native macOS releases require an application signing identity or certificate");let y=async(f)=>e(f[0],await c(f[0],f.slice(1),{cwd:r,env:a,inherit:!0})),g=[];try{if(i==="release"&&n.macos&&a.APPLE_APPLICATION_CERTIFICATE){let h=await ue({applicationCertificate:a.APPLE_APPLICATION_CERTIFICATE,certificatePassword:a.APPLE_CERTIFICATE_PASSWORD||"",provisioningProfile:a.APPLE_PROVISIONING_PROFILE_BASE64});if(g.push(h.keychainPath),a.APPLE_SIGNING_IDENTITY=h.applicationFingerprint,h.provisioningProfilePath)a.APPLE_PROVISIONING_PROFILE_PATH=h.provisioningProfilePath}await y(["bun","install","--frozen-lockfile"]);for(let h of n.checks?.before??[])await y(h);if(G(A(r,".pantry/native/artifact.json"),{force:!0}),await y(n.build??["bun","run","package"]),i==="release"&&n.android)await Ma(s(r,n.android.bundle),a,c);let f=n.macos?Le(r):void 0;if(f){if(f.version!==u.version)throw Error("Native artifact belongs to a different package version");await At(f,n.macos?.maxBundleSize,c,a)}for(let h of n.checks?.after??[])await y(h);let l=f?[f.path]:n.android?[s(r,n.android.bundle)]:[];if(!l.length||l.some((h)=>!D(h)))throw Error("Native pipeline produced no release files");if(f&&i==="release"){e("Release signature",await c("codesign",["--verify","--deep","--strict",f.appPath??f.path]));let h=e("Release identity",await c("codesign",["-dv","--verbose=4",f.appPath??f.path]));if(!`${h.stdout}${h.stderr}`.includes("Authority=Developer ID Application:"))throw Error("Direct macOS releases require a Developer ID signature");if(f.path.toLowerCase().endsWith(".dmg"))await Ra(f.path,a.APPLE_SIGNING_IDENTITY,c)}if(m){let h=await Oa(l[0],m,c);if(f?.appPath)await Y(f.appPath,c);if(!l[0].toLowerCase().endsWith(".zip"))await Y(l[0],c);let E=A(He(l[0]),"notarization-receipt.json");hr(E,`${JSON.stringify(h,null,2)}
|
|
16
|
+
`),l.push(E)}if(f?.path.toLowerCase().endsWith(".dmg")){let h=`${f.path}.zip`;if(G(h,{force:!0}),e("Archive disk image",await c("ditto",["-c","-k",f.path,h],{cwd:r,env:a})),!D(h))throw Error("Disk image archive was not created");l[0]=h}let v;if(i==="release"&&n.macos?.appStore){let h=await ue({applicationCertificate:a.APPLE_APP_STORE_APPLICATION_CERTIFICATE,installerCertificate:a.APPLE_APP_STORE_INSTALLER_CERTIFICATE,certificatePassword:a.APPLE_CERTIFICATE_PASSWORD||"",provisioningProfile:a.APPLE_APP_STORE_PROVISIONING_PROFILE_BASE64});g.push(h.keychainPath),a.PANTRY_DISTRIBUTION="app-store",a.APPLE_SIGNING_IDENTITY=h.applicationFingerprint,a.APPLE_PROVISIONING_PROFILE_PATH=h.provisioningProfilePath,G(s(r,".pantry/native/app-store"),{recursive:!0,force:!0}),await y(["bun","run","build"]);let E=Le(r);if(await he(E,n.macos.maxBundleSize,c),!f||E.bundleId!==f.bundleId||E.version!==f.version||E.buildNumber!==f.buildNumber)throw Error("App Store bundle must match the qualified direct release identity and version");v=A(He(l[0]),`${Er(E.appPath??E.path,".app")}-${u.version}.pkg`),await La(E.appPath??E.path,v,h.installerFingerprint,c),l.push(v)}return{config:n,version:u.version,files:l,...f?{artifact:f}:{},...v?{appStorePackage:v}:{}}}finally{for(let f of g.reverse())await Fe(f)}}
|
|
17
17
|
export{ko,Re,s,p,t,e,Oe,Ut,Ta,Ct,jt,St,Va,Dt,vo,xo,Le,qa,Ra,Y,B,Oa,La,Ma,Me,j,Na,Ne,ue,Fe,Fa,Ya,he,At,S};
|
package/dist/src/native/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"../../chunk-9fzxx1pq.js";import{ko,Re,s,p,t,e,Oe,Ut,Ta,Ct,jt,St,Va,Dt,vo,xo,Le,qa,Ra,Y,B,Oa,La,Ma,Me,j,Na,Ne,ue,Fe,Fa,Ya,he,At,S}from"../../chunk-
|
|
1
|
+
import"../../chunk-9fzxx1pq.js";import{ko,Re,s,p,t,e,Oe,Ut,Ta,Ct,jt,St,Va,Dt,vo,xo,Le,qa,Ra,Y,B,Oa,La,Ma,Me,j,Na,Ne,ue,Fe,Fa,Ya,he,At,S}from"../../chunk-hxr0vweg.js";import{T,De,Ae,Ie,Da,za}from"../../chunk-k5gh5ec6.js";import{createHash as Z,createSign as Q}from"node:crypto";import{createReadStream as U,existsSync as ee,statSync as te}from"node:fs";import{basename as re}from"node:path";import{finished as ie}from"node:stream/promises";var M="https://androidpublisher.googleapis.com",q="https://oauth2.googleapis.com/token";async function Ke(r,i={}){if(!ee(r.bundle)||!r.bundle.endsWith(".aab"))throw Error("Google Play delivery requires an existing signed .aab");if(!Re(r.packageName)||!r.track||!["draft","completed","inProgress"].includes(r.status))throw Error("Google Play requires a package, track and explicit release status");if(r.status==="inProgress"?!(typeof r.userFraction==="number"&&r.userFraction>0&&r.userFraction<1):r.userFraction!==void 0)throw Error("Only an inProgress release requires userFraction between zero and one");let o=JSON.parse(r.serviceAccount);if(o.type!=="service_account"||!o.client_email||!o.private_key)throw Error("A Google Play service account JSON key is required");let a=i.fetch??fetch,c=Math.floor((i.now?.()??Date.now())/1000),n=(b)=>Buffer.from(JSON.stringify(b)).toString("base64url"),u=`${n({alg:"RS256",typ:"JWT"})}.${n({iss:o.client_email,scope:"https://www.googleapis.com/auth/androidpublisher",aud:q,iat:c,exp:c+3600})}`,v=`${u}.${Q("RSA-SHA256").update(u).sign(o.private_key,"base64url")}`,f=await a(q,{method:"POST",body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:v})});if(!f.ok)throw Error(`Google Play authentication failed (${f.status})`);let d=await f.json();if(!d.access_token)throw Error("Google did not return an access token");let l={Authorization:`Bearer ${d.access_token}`,"Content-Type":"application/json"},g=`/androidpublisher/v3/applications/${encodeURIComponent(r.packageName)}/edits`,m=async(b,R,N)=>{let h=await a(`${M}${b}`,{method:R,headers:l,...N!==void 0?{body:JSON.stringify(N)}:{},signal:AbortSignal.timeout(120000)});if(!h.ok)throw Error(`Google Play ${R} failed (${h.status}): ${await h.text()}`);return h.status===204?{}:await h.json()},w=await m(g,"POST",{});if(typeof w.id!=="string"||!w.id)throw Error("Google Play did not return an edit ID");let A=`${g}/${encodeURIComponent(w.id)}`,C=!1;try{let b=Z("sha256");for await(let E of U(r.bundle))b.update(E);let R=b.digest("hex"),N=U(r.bundle),h=ie(N).then(()=>{return},(E)=>E),P;try{P=await a(`${M}/upload${A}/bundles?uploadType=media`,{method:"POST",headers:{Authorization:l.Authorization,"Content-Type":"application/octet-stream","Content-Length":String(te(r.bundle).size)},body:N,duplex:"half",signal:AbortSignal.timeout(120000)})}finally{N.destroy();let E=await h;if(E&&E.code!=="ERR_STREAM_PREMATURE_CLOSE")throw E}if(!P.ok)throw Error(`Google Play bundle upload failed (${P.status}): ${await P.text()}`);let x=await P.json();if(!Number.isSafeInteger(x.versionCode)||x.versionCode<=0||x.sha256?.toLowerCase()!==R)throw Error("Google Play uploaded bundle does not match the local SHA-256 and version code");if(await m(`${A}/tracks/${encodeURIComponent(r.track)}`,"PUT",{track:r.track,releases:[{status:r.status,versionCodes:[String(x.versionCode)],...r.releaseName?{name:r.releaseName}:{},...r.userFraction!==void 0?{userFraction:r.userFraction}:{},...r.releaseNotes?{releaseNotes:r.releaseNotes}:{}}]}),await m(`${A}:validate`,"POST"),!r.validateOnly){if((await m(`${A}:commit?changesInReviewBehavior=ERROR_IF_IN_REVIEW`,"POST")).id!==w.id)throw Error("Google Play commit did not confirm the edit ID");C=!0}return{schemaVersion:1,bundle:re(r.bundle),packageName:r.packageName,track:r.track,status:r.status,versionCode:x.versionCode,sha256:R,editId:w.id,validated:!0,committed:C,completedAt:new Date().toISOString()}}finally{if(!C)await m(A,"DELETE")}}import{chmodSync as ae,existsSync as G,mkdirSync as ne}from"node:fs";import{dirname as oe,resolve as se}from"node:path";import J from"node:process";var ce=String.raw`
|
|
2
2
|
import Foundation
|
|
3
3
|
import Security
|
|
4
4
|
import CryptoKit
|
|
@@ -7,7 +7,7 @@ export declare function isNativeAppKitBundle(app: string): boolean;
|
|
|
7
7
|
/** Structural validation is shared by locally runnable and Store distribution bundles. */
|
|
8
8
|
export declare function validateNativeMacBundle(artifact: NativeArtifact, maxBytes: number | undefined, command?: NativeCommand): Promise<void>;
|
|
9
9
|
/** Launch only locally runnable builds; Store distribution profiles require Store delivery. */
|
|
10
|
-
export declare function validateNativeMacApp(artifact: NativeArtifact, maxBytes: number | undefined, command?: NativeCommand): Promise<void>;
|
|
10
|
+
export declare function validateNativeMacApp(artifact: NativeArtifact, maxBytes: number | undefined, command?: NativeCommand, env?: NodeJS.ProcessEnv): Promise<void>;
|
|
11
11
|
/** Shared local/CI pipeline. It prepares artifacts; providers deliver only after checks pass. */
|
|
12
12
|
export declare function prepareNativeRelease(root: string, mode: 'check' | 'release', dependencies?: { command?: NativeCommand, env?: NodeJS.ProcessEnv, onSecret?: (value: string) => void, onEnvironment?: (values: Record<string, string>) => void }): Promise<NativePipelineResult>;
|
|
13
13
|
export declare interface NativePipelineResult {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{qe}from"../../chunk-qhf2sgz4.js";import"../../chunk-9fzxx1pq.js";import{t,e,S}from"../../chunk-
|
|
1
|
+
import{qe}from"../../chunk-qhf2sgz4.js";import"../../chunk-9fzxx1pq.js";import{t,e,S}from"../../chunk-hxr0vweg.js";async function se(s,a,o={}){if(!["patch","minor","major"].includes(a.bump))throw Error("Native release bump must be patch, minor or major");let i=o.command??t,r=async(m)=>e("Native release Git check",await i("git",m,{cwd:s})).stdout.trim(),n=await r(["rev-parse","HEAD"]);if(await r(["branch","--show-current"])!=="main")throw Error("Native releases must be cut from main");if(await r(["status","--porcelain","--untracked-files=normal"]))throw Error("Commit native app source before releasing");await S(s,"check",{command:i}),await qe({cwd:s,release:a.bump,expectedSource:n,recursive:!0,commit:!a.dryRun,tag:!a.dryRun,push:!a.dryRun,dryRun:a.dryRun,yes:!0})}export{se as releaseNativeApp};
|
package/package.json
CHANGED
package/dist/chunk-5tjgz3sy.js
DELETED