@stacksjs/buddy 0.75.600 → 0.75.604

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.
@@ -1,6 +1,7 @@
1
- import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=false){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", ");const line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){const candidates=[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")];return candidates.find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale"){throw new Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`)}try{const{measureDefaultsDrift}=await actions();const drift=measureDefaultsDrift(projectPath(),{shallow:true});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return false;await runners[selection]();return true}export function resolvePrettyDevDomain(appUrl,nativeMode=false){if(!appUrl||nativeMode)return null;try{const url=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`);const hostname=url.hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"];const SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");return source.match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");const value=source.match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:undefined}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path)){try{return readFileSync(path,"utf8")}catch{return""}}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return false;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath();const configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==undefined||viewSource(root,"auth/login")!==undefined;const candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==undefined);const appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:undefined);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{const subprocess=Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});subprocess.unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return true;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:false})}catch{return false}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:false}).option("-l, --with-localhost",descriptions.withLocalhost,{default:false}).option("--browser",descriptions.browser,{default:false}).option("--site",descriptions.site,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("--detach",descriptions.detach,{default:false}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":undefined)||(options.api?"api":undefined)||(options.components?"components":undefined)||(options.dashboard?"dashboard":undefined)||(options.desktop?"desktop":undefined)||(options.native?"native":undefined)||(options.systemTray||options["system-tray"]?"system-tray":undefined)||(options.docs?"docs":undefined);if(target){const serverOptions={...options};const a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))});const a=await actions();const handled=await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:true},perf),native:()=>startDevelopmentServer({...options,native:true},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)});if(!handled){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else{await startDevelopmentServer(options,perf)}outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components");const result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs");const result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:desktop",descriptions.desktop).option("--native","Run the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");if(!options.native&&await hasWebviewDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopWebview,options);if(resultFailed(result)){await outro("While running the desktop app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("The desktop app was closed",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:false}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==false){a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)})}await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:false}).option("--site",descriptions.site,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await(await actions()).runFrontendDevServer(options)});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options;const startedAt=_startTime;const appUrl=process.env.APP_URL??"stacks.localhost";const nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native";const entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1";const preferredFrontendPort=Number(process.env.PORT)||3000;const preferredApiPort=Number(process.env.PORT_API)||3008;const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1"){await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort])}const portShifts=[];const claimPort=async(label,preferred)=>{if(proxyManagedExternally)return preferred;const port=await findAvailablePort(preferred);if(port!==preferred)portShifts.push(`${label} :${preferred} → :${port}`);return port};const frontendPort=await claimPort("Frontend",preferredFrontendPort);const apiPort=await claimPort("API",preferredApiPort);const docsPort=await claimPort("Docs",preferredDocsPort);const dashboardPort=await claimPort("Dashboard",preferredDashboardPort);process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1";const domain=resolvePrettyDevDomain(appUrl,nativeMode);const appLooksCustom=domain!==null;const localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1";const prettyUrlsRequested=appLooksCustom&&!localhostOnly;const systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?true:await canStartPrettyDevProxy();const usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized});const prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls;const hasCustomDomain=usePrettyUrls&&!proxyManagedExternally;const displayedDomain=usePrettyUrls?domain:null;const dashboardDomain=displayedDomain?`dashboard.${displayedDomain}`:null;const frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`;const frontendUrl=developmentUrl(frontendBaseUrl,entryPath);const apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`;const docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`;const dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://localhost:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("⚠")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("⚠")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting…")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,includeDashboard,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=false;let closeNativeApp;const SHUTDOWN_GRACE_MS=1500;const cleanup=(signal)=>{if(isExiting)return;isExiting=true;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false)}catch{}})();const teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:true};const a=await actions();const ports=[{name:"API",port:apiPort}];const readinessTimeoutMs=30000;let readyAnnounced=false;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath);const nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve();const waitingOn=new Set(ports);const bootStartedMs=Date.now();let progressLines=0;let nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=true;let proxyReachable=false;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("⚠")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?true:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1"){await printRegisteredRoutes(apiPort).catch(()=>{})}}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Frontend: ${error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return true;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return false}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return false}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input;const verbose=options.verbose??false;const useProxy=hasCustomDomain&&proxyReachable;const feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);const feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`;const apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`;const dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`;const dbUrl=useProxy?dashboardUrl:`http://localhost:${dashboardPort}`;const blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("➜")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("➜")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("➜")} ${bold("Native")}: ${cyan(`Craft → ${feUrl}`)}`);console.log(` ${green("➜")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("➜")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("➜")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`http://localhost:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("●")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} → ${domain}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api → localhost:${apiPort}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs → localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} → ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts");const routesLabel=relative(projectPath(),routesFile);const hasCssEngine=["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config)));if(hasCssEngine)console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile)){try{const source=readFileSync(routesFile,"utf8");const routeCount=(source.match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes → ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest → ${routesLabel}`)}`)}}}async function launchNativeAppWindow(url,options){let createApp;try{const craft=await importCraftSdk();createApp=craft.createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
1
+ import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=false){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", ");const line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){const candidates=[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")];return candidates.find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale"){throw new Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`)}try{const{measureDefaultsDrift}=await actions();const drift=measureDefaultsDrift(projectPath(),{shallow:true});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return false;await runners[selection]();return true}export function resolvePrettyDevDomain(appUrl,nativeMode=false){if(!appUrl||nativeMode)return null;try{const url=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`);const hostname=url.hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"];const SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");return source.match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");const value=source.match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:undefined}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path)){try{return readFileSync(path,"utf8")}catch{return""}}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return false;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath();const configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==undefined||viewSource(root,"auth/login")!==undefined;const candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==undefined);const appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:undefined);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{const subprocess=Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});subprocess.unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return true;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:false})}catch{return false}}export async function claimDevPorts(servers,isFree,attempts=20){const preferred=new Set(servers.map((server)=>server.preferred));const taken=new Set;const ports=[];const shifts=[];for(const server of servers){let port=server.preferred;if(taken.has(port)||!await isFree(port)){for(let candidate=server.preferred+1;candidate<server.preferred+attempts;candidate++){if(taken.has(candidate)||preferred.has(candidate)||!await isFree(candidate))continue;port=candidate;break}}if(port!==server.preferred)shifts.push(`${server.label} :${server.preferred} → :${port}`);taken.add(port);ports.push(port)}return{ports,shifts}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:false}).option("-l, --with-localhost",descriptions.withLocalhost,{default:false}).option("--browser",descriptions.browser,{default:false}).option("--site",descriptions.site,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("--detach",descriptions.detach,{default:false}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":undefined)||(options.api?"api":undefined)||(options.components?"components":undefined)||(options.dashboard?"dashboard":undefined)||(options.desktop?"desktop":undefined)||(options.native?"native":undefined)||(options.systemTray||options["system-tray"]?"system-tray":undefined)||(options.docs?"docs":undefined);if(target){const serverOptions={...options};const a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))});const a=await actions();const handled=await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:true},perf),native:()=>startDevelopmentServer({...options,native:true},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)});if(!handled){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else{await startDevelopmentServer(options,perf)}outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components");const result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs");const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const{ports:[docsPort=preferredDocsPort],shifts}=process.env.STACKS_PROXY_MANAGED==="1"?{ports:[preferredDocsPort],shifts:[]}:await claimDevPorts([{label:"Docs",preferred:preferredDocsPort}],portIsFree);process.env.PORT_DOCS=String(docsPort);if(shifts.length>0)console.log(` ${yellow("⚠")} ${yellow("Port in use by another process")} ${dim(`- ${shifts.join(", ")}`)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(`http://localhost:${docsPort}`)}
2
+ `);const result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:desktop",descriptions.desktop).option("--native","Run the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");if(!options.native&&await hasWebviewDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopWebview,options);if(resultFailed(result)){await outro("While running the desktop app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("The desktop app was closed",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:false}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==false){a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)})}await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:false}).option("--site",descriptions.site,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});try{await(await actions()).runFrontendDevServer(options)}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options;const startedAt=_startTime;const appUrl=process.env.APP_URL??"stacks.localhost";const nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native";const entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1";const preferredFrontendPort=Number(process.env.PORT)||3000;const preferredApiPort=Number(process.env.PORT_API)||3008;const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1"){await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort])}const claimed=await claimDevPorts([{label:"Frontend",preferred:preferredFrontendPort},{label:"API",preferred:preferredApiPort},{label:"Docs",preferred:preferredDocsPort},{label:"Dashboard",preferred:preferredDashboardPort}],proxyManagedExternally?async()=>true:portIsFree);const portShifts=claimed.shifts;const[frontendPort,apiPort,docsPort,dashboardPort]=claimed.ports;process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1";const domain=resolvePrettyDevDomain(appUrl,nativeMode);const appLooksCustom=domain!==null;const localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1";const prettyUrlsRequested=appLooksCustom&&!localhostOnly;const systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?true:await canStartPrettyDevProxy();const usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized});const prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls;const hasCustomDomain=usePrettyUrls&&!proxyManagedExternally;const displayedDomain=usePrettyUrls?domain:null;const dashboardDomain=displayedDomain?`dashboard.${displayedDomain}`:null;const frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`;const frontendUrl=developmentUrl(frontendBaseUrl,entryPath);const apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`;const docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`;const dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://localhost:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("⚠")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("⚠")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting…")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,includeDashboard,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=false;let closeNativeApp;const SHUTDOWN_GRACE_MS=1500;const cleanup=(signal)=>{if(isExiting)return;isExiting=true;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false)}catch{}})();const teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:true};const a=await actions();const ports=[{name:"API",port:apiPort}];const readinessTimeoutMs=30000;let readyAnnounced=false;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath);const nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve();const waitingOn=new Set(ports);const bootStartedMs=Date.now();let progressLines=0;let nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=true;let proxyReachable=false;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("⚠")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?true:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1"){await printRegisteredRoutes(apiPort).catch(()=>{})}}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{log.error(`Frontend: ${error instanceof Error?error.message:error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return true;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return false}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return false}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input;const verbose=options.verbose??false;const useProxy=hasCustomDomain&&proxyReachable;const feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);const feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`;const apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`;const dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`;const dbUrl=useProxy?dashboardUrl:`http://localhost:${dashboardPort}`;const blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("➜")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("➜")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("➜")} ${bold("Native")}: ${cyan(`Craft → ${feUrl}`)}`);console.log(` ${green("➜")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("➜")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("➜")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`http://localhost:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("●")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} → ${domain}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api → localhost:${apiPort}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs → localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} → ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts");const routesLabel=relative(projectPath(),routesFile);const hasCssEngine=["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config)));if(hasCssEngine)console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile)){try{const source=readFileSync(routesFile,"utf8");const routeCount=(source.match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes → ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest → ${routesLabel}`)}`)}}}async function launchNativeAppWindow(url,options){let createApp;try{const craft=await importCraftSdk();createApp=craft.createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
2
3
  `);return}if(!createApp){console.log(` ${dim("Native window unavailable. The Craft SDK did not export createApp.")}
3
4
  `);return}const craftBinaryPath=resolveCraftBinaryPath();if(!craftBinaryPath){console.log(` ${dim("Native window unavailable. Set CRAFT_BIN to a Craft binary, or install Craft in ~/Code/Tools/craft.")}
4
5
  `);return}const appIconPath=resolveNativeAppIconPath();const app=createApp({url,quiet:!options.verbose,craftPath:craftBinaryPath,window:{title:await resolveNativeAppTitle(),width:1280,height:860,titlebarHidden:true,webSidebarMaterial:true,webSidebarWidth:286,webSidebarMaterialOpacity:0.78,...appIconPath&&{icon:appIconPath}}});app.show().catch((error)=>{if(options.verbose)log.warn(`Native window exited: ${error}`)});return()=>app.close()}async function importCraftSdk(){const localCraftSdk=process.env.HOME?`${process.env.HOME}/Code/Tools/craft/packages/typescript/src/index.ts`:undefined;if(localCraftSdk&&existsSync(localCraftSdk))return await import(localCraftSdk);const packageNames=["craft-native","@craft-native/craft","@stacksjs/ts-craft"];let primaryError;for(const packageName of packageNames){try{return await import(packageName)}catch(error){primaryError??=error}}throw primaryError}async function cleanupStaleDevProcesses(ports){const projectRoot=projectPath();const actionDevPath=projectPath("storage/framework/core/actions/src/dev/");const pids=new Set;for(const port of ports){for(const pid of await listenerPids(port)){if(pid===process.pid)continue;const command=await commandForPid(pid);if(!command.includes(projectRoot))continue;const isStacksDevProcess=command.includes("storage/framework/core/buddy/src/cli.ts dev")||command.includes("storage/framework/core/actions/src/dev/")||command.includes(actionDevPath);if(isStacksDevProcess)pids.add(pid)}}if(pids.size===0)return;for(const pid of pids){try{process.kill(pid,"SIGTERM")}catch{}}await new Promise((r)=>setTimeout(r,250));for(const pid of pids){try{process.kill(pid,"SIGKILL")}catch{}}await new Promise((r)=>setTimeout(r,150))}async function listenerPids(port){try{const proc=Bun.spawn(["lsof","-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.split(/\s+/).map((value)=>Number(value)).filter((pid)=>Number.isInteger(pid)&&pid>0)}catch{return[]}}async function commandForPid(pid){try{const proc=Bun.spawn(["ps","-p",String(pid),"-o","command="],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.trim()}catch{return""}}function resolveCraftBinaryPath(){const home=process.env.HOME;const candidates=[process.env.CRAFT_BIN,home?`${home}/Code/Tools/craft/craft`:undefined,home?`${home}/Code/Tools/craft/bin/craft`:undefined,home?`${home}/Code/Tools/craft/packages/zig/zig-out/bin/craft`:undefined,home?`${home}/Documents/Projects/craft/packages/zig/zig-out/bin/craft`:undefined].filter((candidate)=>Boolean(candidate));return candidates.find((candidate)=>existsSync(candidate))}function resolveNativeAppIconPath(){const candidates=[projectPath("resources/assets/images/app-icon.png"),projectPath("resources/assets/images/icon.png"),projectPath("public/icon.png")];return candidates.find((candidate)=>existsSync(candidate))}async function resolveNativeAppTitle(){try{const pkg=await Bun.file(projectPath("package.json")).json();const name=typeof pkg.productName==="string"?pkg.productName:pkg.name;if(typeof name==="string"&&name.length>0){return name.split(/[-_\s]+/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}}catch{}return"Stacks App"}const METHOD_COLORS={GET:cyan,POST:green,PUT:cyan,PATCH:cyan,DELETE:cyan,OPTIONS:dim};async function printRegisteredRoutes(apiPort){try{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),1500);const res=await fetch(`http://127.0.0.1:${apiPort}/__routes`,{signal:ac.signal}).catch(()=>null);clearTimeout(t);if(!res||!res.ok)return;const routes=await res.json();if(!Array.isArray(routes)||routes.length===0)return;const sorted=[...routes].sort((a,b)=>a.path.localeCompare(b.path)||a.method.localeCompare(b.method));const longestPath=Math.max(...sorted.map((r)=>r.path.length));console.log(` ${dim("Registered routes")}
5
- `);for(const r of sorted){const color=METHOD_COLORS[r.method.toUpperCase()]??dim;const method=color(r.method.toUpperCase().padEnd(6));const path=r.path.padEnd(longestPath);const named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"]){const ok=await new Promise((resolve)=>{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(true)}).catch(()=>{clearTimeout(t);resolve(false)})});if(ok)return true}return false}async function findAvailablePort(preferred,attempts=20){for(let port=preferred;port<preferred+attempts;port++){if(await portIsFree(port))return port}return preferred}async function portIsFree(port){for(const host of["127.0.0.1","::1"]){if(await someoneIsListening(port,host))return false}let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:false,fetch:()=>new Response})}catch{return false}server.stop(true);return true}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host});const finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(false));socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return true;await new Promise((r)=>setTimeout(r,50))}return false}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net");const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const ok=await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"});const finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));setTimeout(()=>finish(false),800).unref?.()});if(ok)return true;await new Promise((r)=>setTimeout(r,200))}return false}const RPX_SSL_DIR=join(homedir(),".stacks","ssl");const RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt");const RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate=true){const verbose=options.verbose??false;const{buildRegistryTlsProxyOptions,certIncludesSanHostnames,checkExistingCertificates,clearSslConfigCache,forceTrustCertificate,generateCertificate,getRegistryDir,isDaemonRunning,isRootCaTrustedForSsl,readAll,readCertCommonName,stopDaemon,trustRootCaForBrowsers,verifyHttpsChain}=await importDevelopmentRpx();const hostnames=buildDevelopmentTlsHostnames(domain,includeDashboard);const entries=await readAll(getRegistryDir(),false).catch(()=>[]);for(const entry of entries){const host=entry.to?.trim();if(host&&!hostnames.includes(host))hostnames.push(host)}const tlsOptions=buildRegistryTlsProxyOptions(hostnames,domain,verbose);const hostnameInCert=certIncludesSanHostnames(RPX_HOST_CERT_PATH,hostnames);const cnMatchesApp=readCertCommonName(RPX_HOST_CERT_PATH)===domain;let certRegenerated=false;const existing=await checkExistingCertificates(tlsOptions);if(!existing||!hostnameInCert||!cnMatchesApp){clearSslConfigCache();await generateCertificate({...tlsOptions,forceRegenerate:true});certRegenerated=true}let trusted=isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(!trusted&&trustCertificate){trusted=trustRootCaForBrowsers(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||await forceTrustCertificate(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(trusted)console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local CA trusted - reload the browser if you still see a warning")}`);else console.log(` ${yellow("⚠")} ${yellow("HTTPS")}: ${yellow(`Local CA not trusted — run: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}else if(verbose){console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local certificate trusted for SSL")}`)}const chainOk=existsSync(RPX_ROOT_CA_PATH)?await verifyHttpsChain(domain,RPX_ROOT_CA_PATH):false;if((certRegenerated||!hostnameInCert||!cnMatchesApp)&&await isDaemonRunning()){await stopDaemon({timeoutMs:8000}).catch(()=>{});if(verbose)log.info("Restarting rpx daemon to load TLS certificates for this app")}else if(!chainOk&&verbose){console.log(` ${dim(" ")}${dim("HTTPS chain not yet valid on :443 - daemon will (re)start after backends are ready")}`)}}function resolveRpxDaemonSpawnCwd(){const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return dirname(fromEnv);const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return dirname(bootstrap);return homedir()}async function resolveRpxDaemonSpawnCommand(){const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return[process.execPath,bootstrap];const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return[fromEnv,"daemon:start"];const pkgUrl=import.meta.resolve("@stacksjs/rpx/package.json");const cli=join(dirname(fileURLToPath(pkgUrl)),"dist/bin/cli.js");return[process.execPath,cli,"daemon:start"]}function buildRpxProxySpecs(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard}=input;const dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...includeDashboard?[{id:`${domain}-dashboard`,from:`localhost:${dashboardPort}`,to:dashboardDomain}]:[]]}async function unregisterRpxProxies(ids){if(ids.length===0)return;try{const{removeEntry}=await importDevelopmentRpx();for(const id of ids)await removeEntry(id).catch(()=>{})}catch{}}async function removeStalePublicDomainOverrides(domain,includeDashboard,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx();const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];const present=await checkHosts(hosts,verbose).catch(()=>hosts.map(()=>false));const staleHosts=hosts.filter((_,i)=>present[i]===true);if(staleHosts.length>0){await removeHosts(staleHosts,verbose).catch(()=>{});const remaining=await checkHosts(staleHosts,verbose).catch(()=>staleHosts.map(()=>true));if(remaining.some(Boolean))log.warn(`Stale /etc/hosts entries still point ${staleHosts.join(", ")} at loopback. Remove them with: sudo nano /etc/hosts`);else log.info(`Removed stale /etc/hosts entries for ${staleHosts.join(", ")} (left by a previous dev session)`)}if(process.platform!=="darwin")return;const labels=domain.split(".");const basename=labels.length>=2?labels.slice(-2).join("."):domain;const resolverPath=resolverFilePath(basename);let isRpxManaged=false;try{isRpxManaged=contentLooksLikeRpxResolver(readFileSync(resolverPath,"utf8"))}catch{}if(!isRpxManaged)return;const quotedPath=`'${resolverPath.replace(/'/g,`'\\''`)}'`;const rm=process.env.SUDO_PASSWORD?`printf '%s
6
+ `);for(const r of sorted){const color=METHOD_COLORS[r.method.toUpperCase()]??dim;const method=color(r.method.toUpperCase().padEnd(6));const path=r.path.padEnd(longestPath);const named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"]){const ok=await new Promise((resolve)=>{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(true)}).catch(()=>{clearTimeout(t);resolve(false)})});if(ok)return true}return false}async function portIsFree(port){for(const host of["127.0.0.1","::1"]){if(await someoneIsListening(port,host))return false}let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:false,fetch:()=>new Response})}catch{return false}server.stop(true);return true}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host});const finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(false));socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return true;await new Promise((r)=>setTimeout(r,50))}return false}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net");const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const ok=await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"});const finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));setTimeout(()=>finish(false),800).unref?.()});if(ok)return true;await new Promise((r)=>setTimeout(r,200))}return false}const RPX_SSL_DIR=join(homedir(),".stacks","ssl");const RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt");const RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate=true){const verbose=options.verbose??false;const{buildRegistryTlsProxyOptions,certIncludesSanHostnames,checkExistingCertificates,clearSslConfigCache,forceTrustCertificate,generateCertificate,getRegistryDir,isDaemonRunning,isRootCaTrustedForSsl,readAll,readCertCommonName,stopDaemon,trustRootCaForBrowsers,verifyHttpsChain}=await importDevelopmentRpx();const hostnames=buildDevelopmentTlsHostnames(domain,includeDashboard);const entries=await readAll(getRegistryDir(),false).catch(()=>[]);for(const entry of entries){const host=entry.to?.trim();if(host&&!hostnames.includes(host))hostnames.push(host)}const tlsOptions=buildRegistryTlsProxyOptions(hostnames,domain,verbose);const hostnameInCert=certIncludesSanHostnames(RPX_HOST_CERT_PATH,hostnames);const cnMatchesApp=readCertCommonName(RPX_HOST_CERT_PATH)===domain;let certRegenerated=false;const existing=await checkExistingCertificates(tlsOptions);if(!existing||!hostnameInCert||!cnMatchesApp){clearSslConfigCache();await generateCertificate({...tlsOptions,forceRegenerate:true});certRegenerated=true}let trusted=isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(!trusted&&trustCertificate){trusted=trustRootCaForBrowsers(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||await forceTrustCertificate(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(trusted)console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local CA trusted - reload the browser if you still see a warning")}`);else console.log(` ${yellow("⚠")} ${yellow("HTTPS")}: ${yellow(`Local CA not trusted — run: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}else if(verbose){console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local certificate trusted for SSL")}`)}const chainOk=existsSync(RPX_ROOT_CA_PATH)?await verifyHttpsChain(domain,RPX_ROOT_CA_PATH):false;if((certRegenerated||!hostnameInCert||!cnMatchesApp)&&await isDaemonRunning()){await stopDaemon({timeoutMs:8000}).catch(()=>{});if(verbose)log.info("Restarting rpx daemon to load TLS certificates for this app")}else if(!chainOk&&verbose){console.log(` ${dim(" ")}${dim("HTTPS chain not yet valid on :443 - daemon will (re)start after backends are ready")}`)}}function resolveRpxDaemonSpawnCwd(){const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return dirname(fromEnv);const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return dirname(bootstrap);return homedir()}async function resolveRpxDaemonSpawnCommand(){const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return[process.execPath,bootstrap];const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return[fromEnv,"daemon:start"];const pkgUrl=import.meta.resolve("@stacksjs/rpx/package.json");const cli=join(dirname(fileURLToPath(pkgUrl)),"dist/bin/cli.js");return[process.execPath,cli,"daemon:start"]}function buildRpxProxySpecs(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard}=input;const dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...includeDashboard?[{id:`${domain}-dashboard`,from:`localhost:${dashboardPort}`,to:dashboardDomain}]:[]]}async function unregisterRpxProxies(ids){if(ids.length===0)return;try{const{removeEntry}=await importDevelopmentRpx();for(const id of ids)await removeEntry(id).catch(()=>{})}catch{}}async function removeStalePublicDomainOverrides(domain,includeDashboard,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx();const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];const present=await checkHosts(hosts,verbose).catch(()=>hosts.map(()=>false));const staleHosts=hosts.filter((_,i)=>present[i]===true);if(staleHosts.length>0){await removeHosts(staleHosts,verbose).catch(()=>{});const remaining=await checkHosts(staleHosts,verbose).catch(()=>staleHosts.map(()=>true));if(remaining.some(Boolean))log.warn(`Stale /etc/hosts entries still point ${staleHosts.join(", ")} at loopback. Remove them with: sudo nano /etc/hosts`);else log.info(`Removed stale /etc/hosts entries for ${staleHosts.join(", ")} (left by a previous dev session)`)}if(process.platform!=="darwin")return;const labels=domain.split(".");const basename=labels.length>=2?labels.slice(-2).join("."):domain;const resolverPath=resolverFilePath(basename);let isRpxManaged=false;try{isRpxManaged=contentLooksLikeRpxResolver(readFileSync(resolverPath,"utf8"))}catch{}if(!isRpxManaged)return;const quotedPath=`'${resolverPath.replace(/'/g,`'\\''`)}'`;const rm=process.env.SUDO_PASSWORD?`printf '%s
6
7
  ' "$SUDO_PASSWORD" | sudo -S rm -f ${quotedPath}`:`sudo -n rm -f ${quotedPath}`;try{execSync(rm,{stdio:["pipe","ignore","ignore"]});log.info(`Removed stale rpx DNS resolver ${resolverPath} (left by a previous dev session)`);execSync("sudo -n dscacheutil -flushcache; sudo -n killall -HUP mDNSResponder; true",{stdio:["pipe","ignore","ignore"]})}catch{log.warn(`A stale rpx DNS resolver still hijacks ${domain}. Remove it with: sudo rm ${resolverPath}`)}}async function prepareRpxTlsForDev(input){const{domain,includeDashboard,options,skipHosts=false,trustCertificate=true}=input;const verbose=options.verbose??false;const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];const hostsNeedingFile=hosts.filter((host)=>{const h=host.trim().toLowerCase();return h!=="localhost"&&!h.endsWith(".localhost")&&!h.endsWith(".localhost.")});const{addHosts,setupDevelopmentDns}=await importDevelopmentRpx();const dnsDomains=!skipHosts&&hostsNeedingFile.length>0?hosts:[];if(dnsDomains.length>0){const dnsReady=await setupDevelopmentDns({domains:dnsDomains,verbose}).catch(()=>false);if(!dnsReady&&verbose)log.warn(`Dev DNS not configured for ${dnsDomains.join(", ")} - falling back to /etc/hosts`)}if(!skipHosts&&hostsNeedingFile.length>0){await addHosts(hostsNeedingFile,verbose).catch((err)=>{log.warn(`Could not update /etc/hosts for ${hostsNeedingFile.join(", ")}: ${err.message}`);log.warn("Add 127.0.0.1 entries manually or set SUDO_PASSWORD in .env")})}await ensureRpxDevelopmentHttps(domain,options,includeDashboard,trustCertificate)}export async function setupPrettyDevEnvironment(input){const domain=resolvePrettyDevDomain(input.domain??process.env.APP_URL??"stacks.localhost");if(!domain){log.info("APP_URL already uses localhost; no pretty URL setup is needed");return true}const rpx=await importDevelopmentRpx();if(!rpx.authorizeSystemAccess({interactive:process.stdin.isTTY===true&&process.stdout.isTTY===true})){log.error("Pretty URL setup needs administrator authorization to bind ports 80 and 443 and trust the local CA");return false}await prepareRpxTlsForDev({domain,includeDashboard:process.env.STACKS_DEV_DASHBOARD==="1",options:{verbose:input.verbose},skipHosts:input.skipHosts,trustCertificate:!input.skipTrust});const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(input.verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;await startRpxDaemonIfNeeded({spawnCommand:await resolveRpxDaemonSpawnCommand(),spawnEnv,verbose:input.verbose??false,stopRpx:rpx.stopDaemon});const ready=await waitForHttpsProxy(443,5000);if(ready)log.success(`Pretty URLs are ready at https://${domain}`);else log.error("rpx did not become reachable on port 443");return ready}async function startRpxDaemonIfNeeded(input){const{ensureDaemonRunning,isDaemonRunning:isRpxUp}=await importDevelopmentRpx();if(await isRpxUp()){if(await waitForHttpsProxy(443,1500))return;await input.stopRpx({timeoutMs:5000}).catch(()=>{})}const spawnOpts={spawnCommand:input.spawnCommand,spawnCwd:resolveRpxDaemonSpawnCwd(),startupTimeoutMs:45000,spawnEnv:input.spawnEnv,verbose:input.verbose};try{await ensureDaemonRunning(spawnOpts)}catch(firstError){await input.stopRpx({timeoutMs:5000}).catch(()=>{});await ensureDaemonRunning(spawnOpts).catch(()=>{throw firstError})}}async function registerRpxProxiesForDomain(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options}=input;const verbose=options.verbose??false;const proxies=buildRpxProxySpecs({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard});await unregisterRpxProxies([`${domain}-api`,`${domain}-docs`]);const{getRegistryDir,readAll,stopDaemon:stopRpx,syncDevelopmentDnsFromRegistry,writeEntry}=await importDevelopmentRpx();const spawnCommand=await resolveRpxDaemonSpawnCommand();const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;try{await startRpxDaemonIfNeeded({spawnCommand,spawnEnv,verbose,stopRpx})}catch(error){const{isDaemonRunning}=await importDevelopmentRpx();if(!await isDaemonRunning())throw error;if(verbose){const message=error instanceof Error?error.message:String(error);console.log(` ${dim(" ")}${dim(`rpx daemon spawn skipped (${message}); reusing existing daemon`)}`)}}const createdAt=new Date().toISOString();for(const proxy of proxies){await writeEntry({id:proxy.id,from:proxy.from,to:proxy.to,cwd:process.cwd(),createdAt,pid:process.pid,pathRewrites:proxy.pathRewrites},undefined,verbose);if(!activeRpxRegistryIds.includes(proxy.id))activeRpxRegistryIds.push(proxy.id);if(verbose)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`https://${proxy.to} → ${proxy.from}`)}`)}const registryDir=getRegistryDir();const entries=await readAll(registryDir,verbose).catch(()=>[]);await syncDevelopmentDnsFromRegistry(entries,{verbose,ownerPid:process.pid}).catch((err)=>{if(verbose){const message=err instanceof Error?err.message:String(err);console.log(` ${dim(" ")}${dim(`Dev DNS sync: ${message}`)}`)}})}function wantsInteractive(options){return options.interactive}
@@ -1 +1 @@
1
- import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:false}).option("-t, --pretty",descriptions.pretty,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:false}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==undefined){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===undefined){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:false}).option("--dry-run",descriptions.rotateDryRun,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli");const{storage}=await import("@stacksjs/storage");const{existsSync}=await import("node:fs");const{resolve}=await import("node:path");await intro("buddy env:check");const checks=[];const envFile=resolveEnvFile(options.file,options.env)||".env";const envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath);const contentStr=typeof envContent==="string"?envContent:envContent.data;const values=parseEnvAssignments(contentStr);const keys=Object.keys(values);const varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});const hasAppKey="APP_KEY"in values;if(hasAppKey){const appKeyValue=values.APP_KEY??"";if(appKeyValue.length>0){checks.push({name:"APP_KEY",status:"pass",message:"Set"})}else{checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}}else{checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"})}const{publicKeyName,privateKeyName}=envKeyNames(envFile);const privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"];const publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY;const hasPublicKey=Boolean(publicKey);const privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean);const hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey)){checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`})}if(hasPublicKey&&hasPrivateKey){checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"})}else if(hasPublicKey||hasPrivateKey){checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"})}else{checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0){checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"})}else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants));const isShipped=/^\.env\.[a-z]+$/.test(envFile);const total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0){checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`})}else if(!isShipped){checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`})}else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign){checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");const tracked=trackedEnvFiles(gitLsFiles());if(!tracked.includes(envFile)){checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`})}else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict});const metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material");const leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length){checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`})}if(leaked.length===0){checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`})}else{checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else{checks.push({name:`${envFile} file`,status:"fail",message:"Not found"})}const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath)){checks.push({name:".env.keys file",status:"pass",message:"Found"})}else{checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"})}console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("─".repeat(60)));console.log("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("─".repeat(60)));console.log("");if(hasFailures){console.log(red("✗ Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("⚠ Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("✓ All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config");const cloud=config.cloud;const app=config.app;return{self:app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={};const assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i;const lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:undefined;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else{raw=raw.replace(/\s+#.*$/,"").trim()}values[key]=raw}return values}
1
+ import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:false}).option("-t, --pretty",descriptions.pretty,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:false}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==undefined){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===undefined){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:false}).option("--dry-run",descriptions.rotateDryRun,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli");const{storage}=await import("@stacksjs/storage");const{existsSync}=await import("node:fs");const{resolve}=await import("node:path");await intro("buddy env:check");const checks=[];const envFile=resolveEnvFile(options.file,options.env)||".env";const envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath);const contentStr=typeof envContent==="string"?envContent:envContent.data;const values=parseEnvAssignments(contentStr);const keys=Object.keys(values);const varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});const hasAppKey="APP_KEY"in values;if(hasAppKey){const appKeyValue=values.APP_KEY??"";if(appKeyValue.length>0){checks.push({name:"APP_KEY",status:"pass",message:"Set"})}else{checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}}else{checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"})}const{publicKeyName,privateKeyName}=envKeyNames(envFile);const privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"];const publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY;const hasPublicKey=Boolean(publicKey);const privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean);const hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey)){checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`})}if(hasPublicKey&&hasPrivateKey){checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"})}else if(hasPublicKey||hasPrivateKey){checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"})}else{checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0){checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"})}else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const{HQ_CONNECTION_ENV_KEYS}=await import("../hq");const foreign=foreignTenantKeys(partitionTenantEnv(values,{...declaredTenants,shared:HQ_CONNECTION_ENV_KEYS}));const isShipped=/^\.env\.[a-z]+$/.test(envFile);const total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0){checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`})}else if(!isShipped){checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`})}else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign){checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");const tracked=trackedEnvFiles(gitLsFiles());if(!tracked.includes(envFile)){checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`})}else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict});const metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material");const leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length){checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`})}if(leaked.length===0){checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`})}else{checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else{checks.push({name:`${envFile} file`,status:"fail",message:"Not found"})}const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath)){checks.push({name:".env.keys file",status:"pass",message:"Found"})}else{checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"})}console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("─".repeat(60)));console.log("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("─".repeat(60)));console.log("");if(hasFailures){console.log(red("✗ Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("⚠ Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("✓ All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config");const cloud=config.cloud;const app=config.app;return{self:app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={};const assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i;const lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:undefined;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else{raw=raw.replace(/\s+#.*$/,"").trim()}values[key]=raw}return values}
@@ -68,3 +68,4 @@ export * from './tinker';
68
68
  export * from './types';
69
69
  export * from './upgrade';
70
70
  export * from './version';
71
+ export * from './workflow';
@@ -1 +1 @@
1
- export*from"./about";export*from"./auth";export*from"./build";export*from"./cd";export*from"./changelog";export*from"./clean";export*from"./cloud";export*from"./comments";export*from"./commerce-import";export*from"./commit";export*from"./completion";export*from"./config-migrate";export*from"./configure";export*from"./create";export*from"./db";export*from"./storage-backup";export*from"./deploy";export*from"./deploy-preview";export*from"./dev";export*from"./dns";export*from"./docs";export*from"./doctor";export*from"./domains";export*from"./email";export*from"./env";export*from"./features";export*from"./feedback";export*from"./fresh";export*from"./gdpr";export*from"./generate";export*from"./hq";export*from"./http";export*from"./install";export*from"./key";export*from"./license";export*from"./libs";export*from"./lint";export*from"./list";export*from"./mail";export*from"./make";export*from"./migrate";export*from"./migrate-project";export*from"./outdated";export*from"./phone";export*from"./ports";export*from"./server";export*from"./link";export*from"./user";export*from"./prepublish";export*from"./projects";export*from"./publish";export*from"./queue";export*from"./release";export*from"./route";export*from"./saas";export*from"./schedule";export*from"./search";export*from"./screenshot";export*from"./seed";export*from"./security";export*from"./serve";export*from"./setup";export*from"./sms";export*from"./socials";export*from"./telemetry";export*from"./test";export*from"./tinker";export*from"./types";export*from"./upgrade";export*from"./version";
1
+ export*from"./about";export*from"./auth";export*from"./build";export*from"./cd";export*from"./changelog";export*from"./clean";export*from"./cloud";export*from"./comments";export*from"./commerce-import";export*from"./commit";export*from"./completion";export*from"./config-migrate";export*from"./configure";export*from"./create";export*from"./db";export*from"./storage-backup";export*from"./deploy";export*from"./deploy-preview";export*from"./dev";export*from"./dns";export*from"./docs";export*from"./doctor";export*from"./domains";export*from"./email";export*from"./env";export*from"./features";export*from"./feedback";export*from"./fresh";export*from"./gdpr";export*from"./generate";export*from"./hq";export*from"./http";export*from"./install";export*from"./key";export*from"./license";export*from"./libs";export*from"./lint";export*from"./list";export*from"./mail";export*from"./make";export*from"./migrate";export*from"./migrate-project";export*from"./outdated";export*from"./phone";export*from"./ports";export*from"./server";export*from"./link";export*from"./user";export*from"./prepublish";export*from"./projects";export*from"./publish";export*from"./queue";export*from"./release";export*from"./route";export*from"./saas";export*from"./schedule";export*from"./search";export*from"./screenshot";export*from"./seed";export*from"./security";export*from"./serve";export*from"./setup";export*from"./sms";export*from"./socials";export*from"./telemetry";export*from"./test";export*from"./tinker";export*from"./types";export*from"./upgrade";export*from"./version";export*from"./workflow";
@@ -4,7 +4,7 @@ export declare function waitMinutes(value: IosReleaseOptions['wait']): number |
4
4
  export declare function retainedBuildCount(value: number | string | undefined): number;
5
5
  export declare function release(buddy: CLI): void;
6
6
  export declare function resolveGitHubActionsUrl(remoteUrl?: string, repository?: unknown, serverUrl?: unknown): string;
7
- declare interface IosReleaseOptions {
7
+ export declare interface IosReleaseOptions {
8
8
  bump?: string
9
9
  dryRun?: boolean
10
10
  keepBuilds?: number | string
@@ -13,4 +13,3 @@ declare interface IosReleaseOptions {
13
13
  notesFile?: string
14
14
  wait?: boolean | number | string
15
15
  }
16
- export {};
@@ -2,12 +2,12 @@ import{releaseLibrary}from"./release-library";import{execFileSync}from"node:chil
2
2
 
3
3
  ## What to Test
4
4
 
5
- ${notes.trim()}`}function git(...args){return execFileSync("git",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}async function releaseIos(options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const configPath=join(root,"config/mobile.ts");if(!existsSync(configPath))throw new Error("config/mobile.ts not found: run this in a Stacks app with a mobile config");const xcodegen=await resolveXcodegen(root);log.info(`xcodegen ${xcodegen.version} from Pantry (${xcodegen.path})`);const branch=git("rev-parse","--abbrev-ref","HEAD");if(branch!=="main")throw new Error(`releases are cut from main; this is ${branch}`);if(git("status","--porcelain","--untracked-files=no"))throw new Error("commit or stash your changes first, so the release is exactly what is on main");if(!options.dryRun){git("pull","--quiet","--rebase","origin","main");git("fetch","--quiet","--tags","origin");await assertPublicationAllowed({cwd:root,channel:"ios"})}const source=readFileSync(configPath,"utf8");const current=iosVersionIn(source);if(!current)throw new Error("config/mobile.ts declares no iOS `version`");const version=options.bump?bumpedVersion(current,options.bump):current;const existingTags=git("tag","--list",`v${version}-build.*`).split(`
5
+ ${notes.trim()}`}function git(...args){return execFileSync("git",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}async function releaseIos(options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const configPath=join(root,"config/mobile.ts");if(!existsSync(configPath))throw new Error("config/mobile.ts not found: run this in a Stacks app with a mobile config");if(existsSync(join(root,"config/workflows.ts"))){const{loadWorkflowConfig}=await import("../workflow-project");const config=await loadWorkflowConfig(root);if(config.release){const{releaseWorkflowIos}=await import("../workflow-release-ios");return releaseWorkflowIos(root,config,options)}}const xcodegen=await resolveXcodegen(root);log.info(`xcodegen ${xcodegen.version} from Pantry (${xcodegen.path})`);const branch=git("rev-parse","--abbrev-ref","HEAD");if(branch!=="main")throw new Error(`releases are cut from main; this is ${branch}`);if(git("status","--porcelain","--untracked-files=no"))throw new Error("commit or stash your changes first, so the release is exactly what is on main");if(!options.dryRun){git("pull","--quiet","--rebase","origin","main");git("fetch","--quiet","--tags","origin");await assertPublicationAllowed({cwd:root,channel:"ios"})}const source=readFileSync(configPath,"utf8");const current=iosVersionIn(source);if(!current)throw new Error("config/mobile.ts declares no iOS `version`");const version=options.bump?bumpedVersion(current,options.bump):current;const existingTags=git("tag","--list",`v${version}-build.*`).split(`
6
6
  `).filter(Boolean);let tag=nextBuildTag(version,existingTags);const wait=waitMinutes(options.wait);const mobile=await loadMobileConfig(configPath);const credentials=appStoreConnectCredentials();let store=null;let numberedByXcodeCloud=false;if(credentials){const bundleId=mobile.ios?.bundleId;if(!bundleId)throw new Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);store={api,appId:await api.appId(bundleId)};const latestRun=await api.latestXcodeCloudRun(store.appId);if(latestRun!==null){tag=nextBuildTag(version,existingTags,latestRun);numberedByXcodeCloud=true}}else{log.warn("No App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH): the tag counts releases, not the build number TestFlight will show, and older builds stay listed.")}log.info(`Releasing ${tag}${version===current?"":` (version ${current} → ${version})`}`);const keep=retainedBuildCount(options.keepBuilds);const groups=mobile.ios?.testFlightGroups??[];if(!Array.isArray(groups))throw new Error("ios.testFlightGroups must be an array of existing internal group names");if(groups.length&&!store)throw new Error("ios.testFlightGroups requires an App Store Connect API key");if(store)await store.api.internalTestFlightGroups(store.appId,groups);const summary=iosReleaseSummary(tag,{numberedByXcodeCloud});const releaseConfig=mobile.release??{};const previous=previousMobileTag(root,"HEAD");const commits=commitsBetween(root,previous,"HEAD");const generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes};const notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>testerNotes(commits,generateOptions)});const githubNotes=notes.source==="generated"?testerNotes(commits,{...generateOptions,markdown:true})||NO_VISIBLE_CHANGES:notes.text;const locales=notesLocales(mobile);const origin=notes.source==="generated"?`${commits.length} commits since ${previous??"the first commit"}`:{flag:"--notes",env:"RELEASE_NOTES",config:"config/mobile.ts release.notes"}[notes.source];if(wait!==null&&!numberedByXcodeCloud)log.warn("--wait needs an App Store Connect API key and an Xcode Cloud product to know the TestFlight build; Xcode Cloud still reads the What to Test file.");if(options.dryRun){log.info(`What to Test (${origin}; ${locales.map((locale)=>`TestFlight/WhatToTest.${locale}.txt`).join(", ")}):
7
7
 
8
8
  ${fitNotes(notes.text,XCODE_CLOUD_NOTES_LIMIT)}`);if(store){const retiring=buildsToExpire(await store.api.builds(store.appId),keep);log.info(retiring.length?`After the new build is available to its testers, would expire TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`:"No TestFlight builds to expire")}if(!options.skipGithubRelease){const preview=await publishGitHubRelease({cwd:root,tag,ref:"HEAD",name:summary.name,summary:githubSummary(summary.body,githubNotes),dryRun:true});log.info(preview.draft?`Would create the GitHub release ${tag} (${preview.draft.name}):
9
9
 
10
- ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}const devOverrides=["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"];for(const key of devOverrides)delete process.env[key];const result=await runAction(Action.BuildIos,{env:{...withholdEnv(devOverrides),NODE_ENV:"production"}});if(resultFailed(result))throw result.error??new Error("the iOS build failed");const craftConfigPath=join(root,IOS_PROJECT_DIR,"craft.config.json");if(existsSync(craftConfigPath)){const problem=unreleasableSite(JSON.parse(readFileSync(craftConfigPath,"utf8")));if(problem)throw new Error(`${problem}. Set ios.url in config/mobile.ts to the production site. Nothing was committed, tagged or pushed; restore the build output and any version bump with \`git checkout -- ${paths.join(" ")}\`.`)}const written=writeWhatToTest(root,IOS_PROJECT_DIR,notes.text,locales);log.info(`What to Test from ${origin}: ${written.join(", ")}`);git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);pushIosReleaseTag(root,tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:githubSummary(summary.body,githubNotes)});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store){if(wait!==null&&numberedByXcodeCloud){if(!await deliverTestFlight(store,tag,notes.text,locales,wait,groups,keep))process.exitCode=ExitCode.FatalError}else log.info(`Older TestFlight builds are retained. Complete tester delivery with \`buddy release:testflight ${tag} --wait\`.`)}return tag}function notesForTag(root,tag,mobile,options){const releaseConfig=mobile.release??{};const generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes};const from=options.from||previousMobileTag(root,`${tag}^`);const commits=commitsBetween(root,from,tag);const plainGenerated=testerNotes(commits,generateOptions)||NO_VISIBLE_CHANGES;const committed=options.from?null:committedWhatToTest(root,tag,IOS_PROJECT_DIR);const handWritten=committed&&committed.trim()!==fitNotes(plainGenerated,XCODE_CLOUD_NOTES_LIMIT)?committed.trim():null;const notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>handWritten??plainGenerated});if(notes.source!=="generated"||handWritten)return{text:notes.text,plain:notes.text};return{text:options.markdown?testerNotes(commits,{...generateOptions,markdown:true})||NO_VISIBLE_CHANGES:plainGenerated,plain:plainGenerated}}async function releaseNotesCommand(tagArgument,options){const root=process.cwd();const configPath=join(root,"config/mobile.ts");const mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};const tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw new Error(tagArgument?`there is no tag ${tagArgument}`:"there is no mobile release tag (v*-build.*) yet");const notes=notesForTag(root,tag,mobile,options);if(options.testflight){const credentials=appStoreConnectCredentials();if(!credentials)throw new Error("--testflight needs an App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH)");const bundleId=mobile.ios?.bundleId;if(!bundleId)throw new Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);const store={api,appId:await api.appId(bundleId)};if(!await applyWhatToTest(store,tag,notes.plain,notesLocales(mobile),waitMinutes(options.wait)??0))process.exitCode=ExitCode.FatalError;return}const limit=options.play?PLAY_NOTES_LIMIT:options.markdown?Number.POSITIVE_INFINITY:TESTFLIGHT_NOTES_LIMIT;await printAsync(Number.isFinite(limit)?fitNotes(notes.text,limit):notes.text)}async function releaseTestFlightCommand(tagArgument,options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const mobile=await loadMobileConfig(join(root,"config/mobile.ts"));const tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw new Error("Select an existing mobile release tag");buildNumberOf(tag);const credentials=appStoreConnectCredentials();if(!credentials||!mobile.ios?.bundleId)throw new Error("TestFlight delivery needs an App Store Connect API key and ios.bundleId");const api=await AppStoreConnect.connect(credentials);const store={api,appId:await api.appId(mobile.ios.bundleId)};const groups=mobile.ios.testFlightGroups??[];await api.internalTestFlightGroups(store.appId,groups);const keep=retainedBuildCount(options.keepBuilds);if(options.dryRun){log.info(`Would deliver ${tag}${groups.length?` to ${groups.join(", ")}`:" using its existing internal tester access"}, confirm IN_BETA_TESTING, then retain ${keep} older builds. Nothing was distributed or expired.`);return}if(!await deliverTestFlight(store,tag,undefined,notesLocales(mobile),waitMinutes(options.wait)??DEFAULT_WAIT_MINUTES,groups,keep))process.exitCode=ExitCode.FatalError}export function release(buddy){releaseLibrary(buddy);buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease version identifier, for example beta or rc (registry channel is library.release.distTag)").option("--skip-github-release",descriptions.skipGithubRelease,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release");const result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:true});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","Older TestFlight builds to retain after the replacement is available to testers (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:false}).option("--notes <text>","What to Test for this build, instead of the notes generated from the commits since the previous build").option("--notes-file <path>","Read What to Test from a file (also RELEASE_NOTES / RELEASE_NOTES_FILE, or release.notes in config/mobile.ts)").option("--wait [minutes]","Wait for processing, notes and configured internal TestFlight group delivery (default 60 minutes; needs an App Store Connect API key)").option("--dry-run",descriptions.dryRun,{default:false}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:process.exitCode?`Published ${tag}; TestFlight delivery is incomplete`:`Released ${tag}`,{startTime,useSeconds:true});if(!options.dryRun)log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:testflight [tag]","Complete internal tester delivery for an existing iOS release tag").option("--wait [minutes]","Wait for processing and tester availability (default 60 minutes)").option("--keep-builds <n>","Older builds to retain after tester delivery succeeds",{default:1}).option("--dry-run",descriptions.dryRun,{default:false}).action(async(tag,options)=>{try{await releaseTestFlightCommand(tag,options)}catch(error){await log.error("Failed to deliver the TestFlight build",error);process.exit(ExitCode.FatalError)}});buddy.command("release:notes [tag]","Print the tester notes of a mobile release tag (default: the newest v*-build.* tag), or set them as its TestFlight What to Test").option("--from <ref>","Generate from the commits since this ref instead of the previous build tag").option("--play","Fit the notes to Google Play's 500-character What's new",{default:false}).option("--markdown","Markdown, as the GitHub release shows the notes",{default:false}).option("--testflight","Set the notes as the TestFlight build's What to Test through App Store Connect",{default:false}).option("--wait [minutes]","With --testflight: wait this long for the build to appear (default 60)").option("--notes <text>","Use this text instead").option("--notes-file <path>","Read the text from a file instead").action(async(tag,options)=>{try{await releaseNotesCommand(tag,options)}catch(error){await log.error("Failed to produce the release notes",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--assets <paths>","Attach comma-separated immutable native JSON receipts to the release").option("--dry-run","Print the release instead of creating it",{default:false}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{if(!options.dryRun)await assertPublicationAllowed({cwd:process.cwd(),channel:"github-release"});const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw new Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null;let summary=ios?.body;if(ios){const configPath=join(process.cwd(),"config/mobile.ts");const mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};summary=githubSummary(ios.body,notesForTag(process.cwd(),target,mobile,{markdown:true}).text)}const result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary,dryRun:options.dryRun});if(result.status==="failed")throw new Error(describeGitHubRelease(target,result));if(options.assets&&!options.dryRun){const{attachGitHubReleaseAssets}=await import("@stacksjs/actions/github-release-assets");for(const link of await attachGitHubReleaseAssets({cwd:process.cwd(),tag:target,files:options.assets.split(",")}))log.info(link)}log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
10
+ ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}const devOverrides=["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"];for(const key of devOverrides)delete process.env[key];const result=await runAction(Action.BuildIos,{env:{...withholdEnv(devOverrides),NODE_ENV:"production"}});if(resultFailed(result))throw result.error??new Error("the iOS build failed");const craftConfigPath=join(root,IOS_PROJECT_DIR,"craft.config.json");if(existsSync(craftConfigPath)){const problem=unreleasableSite(JSON.parse(readFileSync(craftConfigPath,"utf8")));if(problem)throw new Error(`${problem}. Set ios.url in config/mobile.ts to the production site. Nothing was committed, tagged or pushed; restore the build output and any version bump with \`git checkout -- ${paths.join(" ")}\`.`)}const written=writeWhatToTest(root,IOS_PROJECT_DIR,notes.text,locales);log.info(`What to Test from ${origin}: ${written.join(", ")}`);git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);pushIosReleaseTag(root,tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:githubSummary(summary.body,githubNotes)});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store){if(wait!==null&&numberedByXcodeCloud){if(!await deliverTestFlight(store,tag,notes.text,locales,wait,groups,keep))process.exitCode=ExitCode.FatalError}else log.info(`Older TestFlight builds are retained. Complete tester delivery with \`buddy release:testflight ${tag} --wait\`.`)}return tag}function notesForTag(root,tag,mobile,options){const releaseConfig=mobile.release??{};const generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes};const from=options.from||previousMobileTag(root,`${tag}^`);const commits=commitsBetween(root,from,tag);const plainGenerated=testerNotes(commits,generateOptions)||NO_VISIBLE_CHANGES;const committed=options.from?null:committedWhatToTest(root,tag,IOS_PROJECT_DIR);const handWritten=committed&&committed.trim()!==fitNotes(plainGenerated,XCODE_CLOUD_NOTES_LIMIT)?committed.trim():null;const notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>handWritten??plainGenerated});if(notes.source!=="generated"||handWritten)return{text:notes.text,plain:notes.text};return{text:options.markdown?testerNotes(commits,{...generateOptions,markdown:true})||NO_VISIBLE_CHANGES:plainGenerated,plain:plainGenerated}}async function releaseNotesCommand(tagArgument,options){const root=process.cwd();const configPath=join(root,"config/mobile.ts");const mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};const tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw new Error(tagArgument?`there is no tag ${tagArgument}`:"there is no mobile release tag (v*-build.*) yet");const notes=notesForTag(root,tag,mobile,options);if(options.testflight){const credentials=appStoreConnectCredentials();if(!credentials)throw new Error("--testflight needs an App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH)");const bundleId=mobile.ios?.bundleId;if(!bundleId)throw new Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);const store={api,appId:await api.appId(bundleId)};if(!await applyWhatToTest(store,tag,notes.plain,notesLocales(mobile),waitMinutes(options.wait)??0))process.exitCode=ExitCode.FatalError;return}const limit=options.play?PLAY_NOTES_LIMIT:options.markdown?Number.POSITIVE_INFINITY:TESTFLIGHT_NOTES_LIMIT;await printAsync(Number.isFinite(limit)?fitNotes(notes.text,limit):notes.text)}async function releaseTestFlightCommand(tagArgument,options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const mobile=await loadMobileConfig(join(root,"config/mobile.ts"));const tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw new Error("Select an existing mobile release tag");buildNumberOf(tag);const credentials=appStoreConnectCredentials();if(!credentials||!mobile.ios?.bundleId)throw new Error("TestFlight delivery needs an App Store Connect API key and ios.bundleId");const api=await AppStoreConnect.connect(credentials);const store={api,appId:await api.appId(mobile.ios.bundleId)};const groups=mobile.ios.testFlightGroups??[];await api.internalTestFlightGroups(store.appId,groups);const keep=retainedBuildCount(options.keepBuilds);if(options.dryRun){log.info(`Would deliver ${tag}${groups.length?` to ${groups.join(", ")}`:" using its existing internal tester access"}, confirm IN_BETA_TESTING, then retain ${keep} older builds. Nothing was distributed or expired.`);return}if(!await deliverTestFlight(store,tag,undefined,notesLocales(mobile),waitMinutes(options.wait)??DEFAULT_WAIT_MINUTES,groups,keep))process.exitCode=ExitCode.FatalError}export function release(buddy){releaseLibrary(buddy);buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease version identifier, for example beta or rc (registry channel is library.release.distTag)").option("--skip-github-release",descriptions.skipGithubRelease,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release");const result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:true});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","Older TestFlight builds to retain after the replacement is available to testers (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:false}).option("--notes <text>","What to Test for this build, instead of the notes generated from the commits since the previous build").option("--notes-file <path>","Read What to Test from a file (also RELEASE_NOTES / RELEASE_NOTES_FILE, or release.notes in config/mobile.ts)").option("--wait [minutes]","Wait for processing, notes and configured internal TestFlight group delivery (default 60 minutes; needs an App Store Connect API key)").option("--dry-run",descriptions.dryRun,{default:false}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:process.exitCode?`Published ${tag}; TestFlight delivery is incomplete`:`Released ${tag}`,{startTime,useSeconds:true});if(!options.dryRun&&!existsSync(join(process.cwd(),"config/workflows.ts")))log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:testflight [tag]","Complete internal tester delivery for an existing iOS release tag").option("--wait [minutes]","Wait for processing and tester availability (default 60 minutes)").option("--keep-builds <n>","Older builds to retain after tester delivery succeeds",{default:1}).option("--dry-run",descriptions.dryRun,{default:false}).action(async(tag,options)=>{try{await releaseTestFlightCommand(tag,options)}catch(error){await log.error("Failed to deliver the TestFlight build",error);process.exit(ExitCode.FatalError)}});buddy.command("release:notes [tag]","Print the tester notes of a mobile release tag (default: the newest v*-build.* tag), or set them as its TestFlight What to Test").option("--from <ref>","Generate from the commits since this ref instead of the previous build tag").option("--play","Fit the notes to Google Play's 500-character What's new",{default:false}).option("--markdown","Markdown, as the GitHub release shows the notes",{default:false}).option("--testflight","Set the notes as the TestFlight build's What to Test through App Store Connect",{default:false}).option("--wait [minutes]","With --testflight: wait this long for the build to appear (default 60)").option("--notes <text>","Use this text instead").option("--notes-file <path>","Read the text from a file instead").action(async(tag,options)=>{try{await releaseNotesCommand(tag,options)}catch(error){await log.error("Failed to produce the release notes",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--assets <paths>","Attach comma-separated immutable native JSON receipts to the release").option("--dry-run","Print the release instead of creating it",{default:false}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{if(!options.dryRun)await assertPublicationAllowed({cwd:process.cwd(),channel:"github-release"});const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw new Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null;let summary=ios?.body;if(ios){const configPath=join(process.cwd(),"config/mobile.ts");const mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};summary=githubSummary(ios.body,notesForTag(process.cwd(),target,mobile,{markdown:true}).text)}const result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary,dryRun:options.dryRun});if(result.status==="failed")throw new Error(describeGitHubRelease(target,result));if(options.assets&&!options.dryRun){const{attachGitHubReleaseAssets}=await import("@stacksjs/actions/github-release-assets");for(const link of await attachGitHubReleaseAssets({cwd:process.cwd(),tag:target,files:options.assets.split(",")}))log.info(link)}log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
11
11
 
12
12
  ${result.draft.body}`:describeGitHubRelease(target,result));await outro(options.dryRun?"Dry run complete. Nothing was created.":`GitHub release for ${target}`,{startTime,useSeconds:true})}catch(error){await log.error("Failed to create the GitHub release",error);process.exit(ExitCode.FatalError)}});buddy.command("release:verify <plan>","Verify exact source gates, published archives and installed consumer checks").option("--output <path>","Save the successful verification receipt as JSON").action(async(planPath,options)=>{let temporary;try{const plan=JSON.parse(readFileSync(planPath,"utf8"));validateReleaseEvidencePlan(plan);const receipt=await verifyReleaseEvidence(plan,{cwd:process.cwd(),token:resolveGitHubToken()??undefined});const json=`${JSON.stringify(receipt,null,2)}
13
13
  `;if(options.output){temporary=`${options.output}.${crypto.randomUUID()}.tmp`;writeFileSync(temporary,json,{flag:"wx",mode:384});renameSync(temporary,options.output);temporary=undefined;await printAsync(`Verified release evidence saved to ${options.output}`)}else{await printAsync(json.trimEnd())}}catch(error){if(temporary)rmSync(temporary,{force:true});await log.error("Release verification failed",error);process.exitCode=ExitCode.FatalError}});onUnknownSubcommand(buddy,"release")}export function resolveGitHubActionsUrl(remoteUrl,repository=process.env.GITHUB_REPOSITORY,serverUrl=process.env.GITHUB_SERVER_URL??"https://github.com"){const repo=repository?.trim()||remoteUrl?.trim().match(/github\.com[/:]([^/\s]+\/[^/\s]+?)(?:\.git)?$/)?.[1];return repo?`${serverUrl.replace(/\/$/,"")}/${repo}/actions`:"https://github.com/stacksjs/stacks/actions"}function readOriginRemote(){try{return execFileSync("git",["config","--get","remote.origin.url"],{encoding:"utf8"}).trim()}catch{return}}
@@ -0,0 +1,2 @@
1
+ import type { CLI } from '@stacksjs/types';
2
+ export declare function workflow(buddy: CLI): void;
@@ -0,0 +1 @@
1
+ import{existsSync,readFileSync}from"node:fs";import{join}from"node:path";import{projectWorkflowClient}from"../workflow-client";import{loadWorkflowConfig,runWorkflowStep,writeProjectWorkflow,writeWorkflowReleaseState}from"../workflow-project";export function workflow(buddy){buddy.command("workflow:setup","Generate the normal Stacks workflow from config/workflows.ts").option("--force","Replace a reviewed existing custom workflow",{default:false}).option("--check","Verify committed workflow bytes without changing them",{default:false}).action(async(options)=>{const root=process.cwd();const config=await loadWorkflowConfig(root);if(options.check){const{renderReviewOsWorkflow}=await import("../workflow-template");const file=join(root,".reviewos/workflows/ci.yml");if(!existsSync(file)||readFileSync(file,"utf8")!==renderReviewOsWorkflow(config))throw new Error("Regenerate the workflow with buddy workflow:setup")}else console.log(writeProjectWorkflow(root,config,options.force))});buddy.command("workflow:step <step>","Run one declared application step through Stacks").action(async(step)=>{await runWorkflowStep(process.cwd(),step)});buddy.command("workflow:release-state","Verify the committed release identity and set its upload output").action(async()=>{await writeWorkflowReleaseState(process.cwd())});buddy.command("workflow:runs [file]","Read the exact-source workflow run history").option("--sha <sha>","Filter by the full source commit").action(async(file,options)=>{const config=await loadWorkflowConfig(process.cwd());console.log(JSON.stringify(await projectWorkflowClient(config).runs(file??"ci.yml",{branch:config.branch??"main",sha:options.sha})))});buddy.command("workflow:show <number>","Read actual workflow job and step execution").action(async(number)=>{console.log(JSON.stringify(await projectWorkflowClient(await loadWorkflowConfig(process.cwd())).run(Number(number))))});buddy.command("workflow:run [file]","Start a configured workflow using its normal API").option("--ref <ref>","Source branch or revision").option("--inputs <json>","Workflow input values as JSON, without credentials").action(async(file,options)=>{const config=await loadWorkflowConfig(process.cwd());const inputs=options.inputs?JSON.parse(options.inputs):{};console.log(JSON.stringify(await projectWorkflowClient(config).dispatch(file??"ci.yml",options.ref??config.branch??"main",inputs)))});buddy.command("workflow:artifacts <number>","Read retained artifact identities and digests").action(async(number)=>{console.log(JSON.stringify(await projectWorkflowClient(await loadWorkflowConfig(process.cwd())).artifacts(Number(number))))})}
@@ -0,0 +1,4 @@
1
+ /** A CI key belongs to this deploy, never to the shared runner's ~/.ssh. */
2
+ export declare function withDeploymentIdentity<T>(key: string | undefined, run: (identity?: DeploymentIdentity) => Promise<T>): Promise<T>;
3
+ export declare function deploymentIdentityConfig<T extends { hetzner?: Record<string, unknown> }>(config: T, identity?: DeploymentIdentity): T;
4
+ export declare interface DeploymentIdentity { privateKeyPath: string, publicKeyPath: string }
@@ -0,0 +1,5 @@
1
+ import{execFileSync}from"node:child_process";import{chmodSync,mkdtempSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";export async function withDeploymentIdentity(key,run){if(!key)return run();if(Buffer.byteLength(key)>65536)throw new Error("The deployment SSH key exceeds its size limit");const directory=mkdtempSync(join(process.env.RUNNER_TEMP||tmpdir(),"stacks-deploy-identity-"));chmodSync(directory,448);const privateKeyPath=join(directory,"identity"),publicKeyPath=`${privateKeyPath}.pub`;const previous=process.env.TS_CLOUD_SSH_KEY;let disposed=false;const cleanup=()=>{if(disposed)return;disposed=true;if(previous===undefined)delete process.env.TS_CLOUD_SSH_KEY;else process.env.TS_CLOUD_SSH_KEY=previous;rmSync(directory,{recursive:true,force:true})};const interrupt=()=>{cleanup();process.exit(130)};const terminate=()=>{cleanup();process.exit(143)};process.once("exit",cleanup);process.once("SIGINT",interrupt);process.once("SIGTERM",terminate);try{if(process.platform==="win32"){try{const user=execFileSync("whoami.exe",["/user","/fo","csv","/nh"],{encoding:"utf8",timeout:1e4});const sid=/"(S-1-\d+(?:-\d+)+)"/.exec(user)?.[1];if(!sid)throw new Error("No current user SID");execFileSync("icacls.exe",[directory,"/inheritance:r","/grant:r",`*${sid}:(OI)(CI)F`],{stdio:"pipe",timeout:1e4})}catch{throw new Error("Cannot restrict the deployment identity directory to the current Windows user")}}writeFileSync(privateKeyPath,key.replaceAll(`\r
2
+ `,`
3
+ `).trimEnd()+`
4
+ `,{mode:384,flag:"wx"});let publicKey;try{publicKey=execFileSync("ssh-keygen",["-y","-P","","-f",privateKeyPath],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1e4}).trim()}catch{throw new Error("DEPLOY_SSH_KEY must contain a valid unencrypted deployment private key")}writeFileSync(publicKeyPath,`${publicKey}
5
+ `,{mode:384,flag:"wx"});process.env.TS_CLOUD_SSH_KEY=privateKeyPath;return await run({privateKeyPath,publicKeyPath})}finally{process.off("exit",cleanup);process.off("SIGINT",interrupt);process.off("SIGTERM",terminate);cleanup()}}export function deploymentIdentityConfig(config,identity){return identity?{...config,hetzner:{...config.hetzner,sshPrivateKeyPath:identity.privateKeyPath,sshPublicKeyPath:identity.publicKeyPath}}:config}
@@ -0,0 +1 @@
1
+ export declare function missingQueueWorkerProblem(sites: Record<string, any> | undefined, queueDriver: string | undefined): string | undefined;
@@ -0,0 +1 @@
1
+ const QUEUE_WORKER_COMMAND=/queue[:-]work|queue-worker/;export function missingQueueWorkerProblem(sites,queueDriver){const all=Object.values(sites??{}).filter(Boolean);const served=all.filter((site)=>site.start||site.port);if(served.length===0)return;if(served.every((site)=>site.env?.STACKS_DEFAULT_ROUTES==="none"))return;const worked=all.some((site)=>Array.isArray(site.queues)&&site.queues.length>0||QUEUE_WORKER_COMMAND.test(String(site.start??""))||Array.isArray(site.daemons)&&site.daemons.some((daemon)=>QUEUE_WORKER_COMMAND.test(String(daemon?.command??""))));if(worked)return;const driver=queueDriver==="redis"?"redis":"database";return`No site declares a queue worker, and in production jobs are queued (to ${driver==="redis"?"redis":"the database"}): anything the app dispatches, password reset and other framework emails included, will be accepted and never run. `+`Add \`queues: [{ connection: '${driver}', queue: 'emails,default' }]\` to a site in config/cloud.ts${driver==="database"?", and `buddy queue:table` after `migrate` in its preStart.":"."}`}
package/dist/hq.d.ts CHANGED
@@ -59,6 +59,16 @@ export declare function runSupportDoctor(config: HqServicesConfig, deps: Pick<Hq
59
59
  */
60
60
  export declare const HQ_SERVICES: Record<HqServiceName, HqServiceDescriptor>;
61
61
  export declare const HQ_SERVICE_NAMES: HqServiceName[];
62
+ /**
63
+ * Every env key that is an app's connection to an HQ service: the keys
64
+ * `hq:connect` writes, and the settings config/services.ts, config/logging.ts
65
+ * and config/monitoring.ts read beside them.
66
+ *
67
+ * They are the app's own, even on a box where the service is a tenant too. A
68
+ * deploy keeps a tenant's prefixed keys out of other projects' sites, and
69
+ * without this list it took an app's `BUGHQ_KEY` for BugHQ's own secret.
70
+ */
71
+ export declare const HQ_CONNECTION_ENV_KEYS: readonly string[];
62
72
  /** The services `hq:connect` asks when none is named: the two that have shipped the contract. */
63
73
  export declare const HQ_DEFAULT_SERVICES: HqServiceName[];
64
74
  /**
package/dist/hq.js CHANGED
@@ -1 +1 @@
1
- import{createHqClient}from"@stacksjs/hq/client";export const HQ_SERVICES={bughq:{label:"BugHQ",env:{key:"BUGHQ_KEY",readKey:"BUGHQ_READ_KEY",project:"BUGHQ_PROJECT_ID"},verify:"error"},loghq:{label:"LogHQ",env:{key:"LOGHQ_KEY",readKey:"LOGHQ_READ_KEY",project:"LOGHQ_PROJECT_ID"},verify:"log"},analyticshq:{label:"AnalyticsHQ",env:{readKey:"ANALYTICSHQ_READ_KEY",project:"ANALYTICSHQ_SITE_ID"}},statushq:{label:"StatusHQ",env:{key:"STATUSHQ_KEY",readKey:"STATUSHQ_READ_KEY"}},supporthq:{label:"HQ.support",env:{key:"SUPPORTHQ_KEY",readKey:"SUPPORTHQ_READ_KEY",project:"SUPPORTHQ_PROJECT_ID"},verify:"support"},commshq:{label:"CommsHQ",env:{key:"COMMSHQ_KEY",readKey:"COMMSHQ_READ_KEY"}},reportshq:{label:"ReportsHQ",env:{license:"REPORTSHQ_LICENSE"}}};export const HQ_SERVICE_NAMES=Object.keys(HQ_SERVICES);export const HQ_DEFAULT_SERVICES=["bughq","loghq"];const REQUEST_TIMEOUT_MS=1e4;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function origin(url){return url.replace(/\/+$/,"")}function httpUrl(value,base){if(typeof value!=="string"||!value)return null;try{const url=new URL(value,base);return url.protocol==="https:"||url.protocol==="http:"?url.toString():null}catch{return null}}function toGrant(body,base,licensed){const project=body.project;if(!isRecord(project)||project.id==null)return null;if(licensed){if(typeof body.licenseKey!=="string"||!body.licenseKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:"",readKey:"",licenseKey:body.licenseKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}if(typeof body.ingestKey!=="string"||typeof body.readKey!=="string")return null;if(!body.ingestKey||!body.readKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:body.ingestKey,readKey:body.readKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}async function request(deps,url,init={}){const signals=[AbortSignal.timeout(REQUEST_TIMEOUT_MS),...deps.signal?[deps.signal]:[]];try{return await deps.fetch(url,{...init,signal:AbortSignal.any(signals)})}catch{return null}}function retryAfterMs(response,fallback){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:fallback}export function resolveHqServices(requested,fallback=HQ_DEFAULT_SERVICES){const names=requested.map((name)=>name.trim().toLowerCase()).filter(Boolean);if(!names.length)return{services:[...fallback]};const unknown=names.filter((name)=>!(name in HQ_SERVICES));if(unknown.length)return{error:`Unknown service: ${unknown.join(", ")}. Choose from ${HQ_SERVICE_NAMES.join(", ")}.`};return{services:[...new Set(names)]}}async function connectOne(service,url,options,deps){const{label}=HQ_SERVICES[service];const base=origin(url);const outcome=(status,detail)=>({outcome:{service,status,detail,send:"skipped",read:"skipped"}});const started=await request(deps,`${base}/api/cli/connect`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({app:options.app})});if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(!started)return outcome("unreachable",`could not reach ${base}`);if(started.status===404||started.status===405)return outcome("unavailable","not available yet");if(started.status===429)return outcome("failed","too many requests, try again in a minute");if(!started.ok)return outcome("failed",`the service answered ${started.status}`);const body=await started.json().catch(()=>null);const code=isRecord(body)&&typeof body.code==="string"&&/^[\w-]{16,128}$/.test(body.code)?body.code:null;const approveUrl=isRecord(body)?httpUrl(body.approveUrl,base):null;if(!code||!approveUrl)return outcome("failed","the service answered something that is not a connect code");const confirmCode=isRecord(body)&&typeof body.confirmCode==="string"&&/^[\w-]{1,32}$/.test(body.confirmCode)?body.confirmCode:null;deps.print("");deps.print(`${label}: approve this connection in your browser`);deps.print(` ${approveUrl}`);if(confirmCode)deps.print(` Confirmation code: ${confirmCode} (type it on that page)`);deps.print(" If the page asks you to sign in, sign in and open the link again.");deps.print(" Waiting for approval. Press Ctrl+C to cancel.");if(options.open!==false){try{await deps.open(approveUrl)}catch{}}const interval=options.pollIntervalMs??2000;const deadline=deps.now()+(options.timeoutMs??10*60*1000);const pollUrl=`${base}/api/cli/connect/${encodeURIComponent(code)}`;while(true){if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(deps.now()>=deadline)return outcome("timeout","nobody approved it in time");await deps.sleep(Math.min(interval,Math.max(0,deadline-deps.now())),deps.signal);if(deps.signal?.aborted)return outcome("cancelled","cancelled");const polled=await request(deps,pollUrl,{headers:{Accept:"application/json"}});if(!polled)continue;if(polled.status===429){await deps.sleep(retryAfterMs(polled,interval),deps.signal);continue}if(polled.status===404)return outcome("expired","the request expired, run the command again");if(!polled.ok)return outcome("failed",`the service answered ${polled.status}`);const answer=await polled.json().catch(()=>null);if(!isRecord(answer)||answer.status==="pending")continue;if(answer.status==="expired")return outcome("expired","the request expired, run the command again");const grant=toGrant(answer,base,Boolean(HQ_SERVICES[service].env.license));if(!grant)return outcome("failed","the service approved the request without sending keys");return{grant,outcome:{service,status:"connected",project:grant.project.name,dashboardUrl:grant.dashboardUrl||undefined,send:"skipped",read:"skipped"}}}}function envEntries(service,grant){const names=HQ_SERVICES[service].env;const entries={};if(names.license&&grant.licenseKey)return{[names.license]:grant.licenseKey};if(names.key)entries[names.key]=grant.ingestKey;if(names.readKey)entries[names.readKey]=grant.readKey;if(names.project)entries[names.project]=grant.project.id;return entries}async function verify(service,url,grant,options,deps){const kind=HQ_SERVICES[service].verify;if(!kind)return{send:"skipped",read:"skipped"};const base=origin(url);if(kind==="support"){const client=createHqClient({services:{supporthq:{url:base,readKey:grant.readKey,project:grant.project.id}},fetch:deps.fetch});const result=await client.support.conversations({limit:1});return result.ok?{send:"skipped",read:"pass"}:{send:"skipped",read:"fail",detail:describeUnavailable(result)}}const marker=`hq-connect-${crypto.randomUUID().slice(0,8)}`;const message=`buddy hq:connect test ${marker}`;const timestamp=new Date(deps.now()).toISOString();const sent=kind==="log"?await request(deps,`${base}/logs`,{method:"POST",headers:{"Content-Type":"application/json","X-LogHQ-Key":grant.ingestKey},body:JSON.stringify({logs:[{level:"info",message,timestamp,context:{source:"buddy hq:connect"}}]})}):await request(deps,`${base}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:grant.ingestKey,type:"HqConnectTest",message,level:"info",environment:"hq-connect",timestamp,sdk:{name:"buddy.hq-connect"}})});if(!sent?.ok)return{send:"fail",read:"skipped",detail:sent?`sending the test ${kind} answered ${sent.status}`:`sending the test ${kind} did not get through`};const receipt=await sent.json().catch(()=>null);if(isRecord(receipt)&&(receipt.sampled===true||receipt.stored===0))return{send:"pass",read:"skipped",detail:`the plan allowance is used up, so the test ${kind} was not kept`};const client=createHqClient({services:{[service]:{url:base,readKey:grant.readKey,project:grant.project.id}},timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});let reason=`the test ${kind} was accepted but did not show up`;const attempts=options.readAttempts??5;for(let attempt=0;attempt<attempts;attempt++){if(attempt>0)await deps.sleep(1000,deps.signal);if(deps.signal?.aborted)return{send:"pass",read:"fail",detail:"cancelled"};if(kind==="log"){const page=await client.logs.list({search:marker,limit:5});if(page.ok&&page.data.logs.some((log)=>log.message.includes(marker)))return{send:"pass",read:"pass"};if(!page.ok)reason=describeUnavailable(page)}else{const list=await client.issues.list();if(list.ok&&list.data.some((issue)=>issue.title.includes(marker)))return{send:"pass",read:"pass"};if(!list.ok)reason=describeUnavailable(list)}}return{send:"pass",read:"fail",detail:reason}}export function describeUnavailable(result){switch(result.reason){case"not_configured":return"not connected";case"unauthorized":return"the read key was refused";case"timeout":return"the service did not answer in time";case"network":return"the service could not be reached";case"http":return result.status===404?"not available yet":`the service answered ${result.status}`;case"bad_response":return"the service answered something unexpected"}}export function renderTable(headers,rows){const widths=headers.map((header,column)=>Math.max(header.length,...rows.map((row)=>(row[column]??"").length)));const line=(cells)=>cells.map((cell,column)=>(cell??"").padEnd(widths[column])).join(" ").trimEnd();return[line(headers),line(widths.map((width)=>"-".repeat(width))),...rows.map(line)]}const CONNECT_WORDS={connected:"pass",unavailable:"not available yet",unreachable:"fail",expired:"fail",timeout:"fail",cancelled:"cancelled",failed:"fail"};const CHECK_WORDS={pass:"pass",fail:"fail",skipped:"-"};export function connectTable(outcomes){return renderTable(["Service","Connect","Send","Read back","Note"],outcomes.map((outcome)=>[HQ_SERVICES[outcome.service].label,CONNECT_WORDS[outcome.status],CHECK_WORDS[outcome.send],CHECK_WORDS[outcome.read],outcome.status==="unavailable"?"":outcome.detail??""]))}export async function runHqConnect(services,config,options,deps){const outcomes=[];for(const service of services){const{label}=HQ_SERVICES[service];if(deps.signal?.aborted){outcomes.push({service,status:"cancelled",detail:"cancelled",send:"skipped",read:"skipped"});continue}const url=config[service]?.url;if(!url){outcomes.push({service,status:"failed",detail:"no URL is configured in config/services.ts",send:"skipped",read:"skipped"});continue}const{outcome,grant}=await connectOne(service,url,options,deps);if(!grant){if(outcome.status==="unavailable")deps.print(`${label}: not available yet`);else if(outcome.status!=="cancelled")deps.print(`${label}: not connected (${outcome.detail})`);outcomes.push(outcome);continue}try{await deps.writeEnv(envEntries(service,grant))}catch(error){const why=error instanceof Error?error.message:"unknown error";deps.print(`${label}: approved, but the keys could not be written to .env (${why})`);outcomes.push({...outcome,status:"failed",detail:"the keys could not be written to .env"});continue}deps.print(grant.licenseKey?`${label}: licensed "${grant.project.name}". Licence written to .env.`:`${label}: connected to project "${grant.project.name}". Keys written to .env.`);if(grant.dashboardUrl)deps.print(` Dashboard: ${grant.dashboardUrl}`);if(options.verify===false){outcomes.push(outcome);continue}outcomes.push({...outcome,...await verify(service,url,grant,options,deps)})}if(deps.signal?.aborted)deps.print("Cancelled. Services already connected keep their keys.");deps.print("");for(const line of connectTable(outcomes))deps.print(line);const ok=outcomes.every((outcome)=>outcome.status==="unavailable"||outcome.status==="connected"&&outcome.send!=="fail"&&outcome.read!=="fail");return{outcomes,ok}}const count=(value)=>value.toLocaleString("en-US");const REPORTSHQ_LICENSE=/^rhq_lic_[0-9a-f]{32}$/;export function describeReportsHqLicense(license){if(!license)return"unlicensed. Reports work in full; set REPORTSHQ_LICENSE to remove the notice";return REPORTSHQ_LICENSE.test(license)?"licensed (checked offline, nothing is metered)":"the licence key is not in the expected format. Reports are unaffected"}export async function runHqStatus(config,deps,services=HQ_SERVICE_NAMES){const connected=services.filter((service)=>config[service]?.url&&config[service]?.readKey);const license=services.includes("reportshq")?config.reportshq?.license:undefined;if(!connected.length&&!license){deps.print("No HQ service is connected yet. Run `buddy hq:connect` to connect one.");return[]}const client=createHqClient({services:Object.fromEntries(connected.map((service)=>[service,{url:config[service].url,readKey:config[service].readKey}])),timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});const rows=[];for(const[index,usage]of(await Promise.all(connected.map((service)=>client.getUsage(service)))).entries()){const service=connected[index];if(!usage.ok){rows.push({service,unavailable:describeUnavailable(usage)});continue}if(!usage.data.length)rows.push({service,unavailable:"no meters reported"});for(const report of usage.data){const over=report.limit!==null&&report.limit>0&&report.used/report.limit>=0.8;rows.push({service,meter:report.meter,used:report.used,limit:report.limit,period:report.period,state:report.state,...over?{upgradeUrl:report.upgradeUrl}:{}})}}if(license)rows.push({service:"reportshq",unavailable:describeReportsHqLicense(license)});const table=renderTable(["Service","Meter","Used","Limit","Period","State"],rows.map((row)=>row.unavailable?[HQ_SERVICES[row.service].label,row.unavailable]:[HQ_SERVICES[row.service].label,row.meter,count(row.used),row.limit===null?"unlimited":count(row.limit),row.period,row.state]));for(const line of table)deps.print(line);const upgrades=rows.filter((row)=>row.upgradeUrl);if(upgrades.length)deps.print("");for(const row of upgrades){const percent=Math.round(row.used/row.limit*100);deps.print(`${HQ_SERVICES[row.service].label} ${row.meter} is at ${percent}% of its allowance. Upgrade: ${row.upgradeUrl}`)}return rows}export async function runSupportDoctor(config,deps,options={}){const service=config.supporthq;const configured=Boolean(service?.url&&service.key&&service.readKey&&service.project);const checks=[{name:"configuration",ok:configured,detail:configured?"server key, read key and project configured":"missing configuration; run `buddy support:install`"}];if(configured){const client=createHqClient({services:{supporthq:{url:service.url,readKey:service.readKey,project:service.project}},fetch:deps.fetch});const usage=await client.getUsage("supporthq");checks.push({name:"usage",ok:usage.ok,detail:usage.ok?`${usage.data.length} usage meters readable`:describeUnavailable(usage)});const conversations=await client.support.conversations({limit:1});checks.push({name:"conversations",ok:conversations.ok,detail:conversations.ok?"project summaries readable":describeUnavailable(conversations)});if(service?.enabled===true){try{const target=new URL(service.url);if(target.username||target.password||target.search||target.hash||target.pathname!=="/"||target.protocol!=="https:"&&!(target.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(target.hostname)))throw new Error("Invalid support origin");const base=target.origin;const probe=await deps.fetch(`${base}/api/v1/projects/${encodeURIComponent(service.project)}/installation`,{headers:{Authorization:`Bearer ${service.key}`},redirect:"error",signal:AbortSignal.timeout(1e4)});const body=probe.ok?await probe.json():null;const current=new URL(options.origin||"").origin;const accepted=isRecord(body)&&body.service==="supporthq"&&body.protocol===1&&body.project===service.project&&body.buddyConnected===true&&Array.isArray(body.allowedOrigins)&&body.allowedOrigins.includes(current);checks.push({name:"installation",ok:accepted,detail:accepted?"approved project and exact app origin; no customer probe was created":"native installation or app origin is not approved"})}catch{checks.push({name:"installation",ok:false,detail:"native installation could not be read"})}if(service.messenger?.enabled){try{const loader=new URL(service.messenger.loaderUrl||"https://hq.support/support.js");if(loader.username||loader.password||loader.search||loader.hash||loader.protocol!=="https:"&&!(loader.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(loader.hostname)))throw new Error("Invalid loader");const response=await deps.fetch(new URL("/widgets/manifest.json",loader).href,{redirect:"error",signal:AbortSignal.timeout(1e4)});const manifest=response.ok?await response.json():null;const published=isRecord(manifest)&&manifest.schemaVersion===1&&Array.isArray(manifest.files)&&manifest.files.some((file)=>isRecord(file)&&typeof file.path==="string"&&file.path.endsWith("/bundle.js")&&typeof file.sha256==="string"&&/^[a-f0-9]{64}$/.test(file.sha256)&&typeof file.gzipBytes==="number"&&file.gzipBytes>0&&file.gzipBytes<=1e5);checks.push({name:"widget",ok:published,detail:published?"published manifest reports a versioned widget within the initial code budget":"published widget manifest or size budget is unavailable"})}catch{checks.push({name:"widget",ok:false,detail:"published widget could not be checked"})}}}}for(const check of checks)deps.print(`HQ.support ${check.name}: ${check.ok?"pass":"fail"} (${check.detail})`);return{ok:checks.every((check)=>check.ok),checks}}
1
+ import{createHqClient}from"@stacksjs/hq/client";export const HQ_SERVICES={bughq:{label:"BugHQ",env:{key:"BUGHQ_KEY",readKey:"BUGHQ_READ_KEY",project:"BUGHQ_PROJECT_ID"},verify:"error"},loghq:{label:"LogHQ",env:{key:"LOGHQ_KEY",readKey:"LOGHQ_READ_KEY",project:"LOGHQ_PROJECT_ID"},verify:"log"},analyticshq:{label:"AnalyticsHQ",env:{readKey:"ANALYTICSHQ_READ_KEY",project:"ANALYTICSHQ_SITE_ID"}},statushq:{label:"StatusHQ",env:{key:"STATUSHQ_KEY",readKey:"STATUSHQ_READ_KEY"}},supporthq:{label:"HQ.support",env:{key:"SUPPORTHQ_KEY",readKey:"SUPPORTHQ_READ_KEY",project:"SUPPORTHQ_PROJECT_ID"},verify:"support"},commshq:{label:"CommsHQ",env:{key:"COMMSHQ_KEY",readKey:"COMMSHQ_READ_KEY"}},reportshq:{label:"ReportsHQ",env:{license:"REPORTSHQ_LICENSE"}}};export const HQ_SERVICE_NAMES=Object.keys(HQ_SERVICES);export const HQ_CONNECTION_ENV_KEYS=[...new Set([...Object.values(HQ_SERVICES).flatMap((service)=>Object.values(service.env)),"BUGHQ_HOST","BUGHQ_DSN","BUGHQ_PROJECT","BUGHQ_RELEASE","LOGHQ_BASE_URL","LOGHQ_PROJECT","ANALYTICSHQ_URL","STATUSHQ_URL","SUPPORTHQ_URL","COMMSHQ_URL","REPORTSHQ_URL"])];export const HQ_DEFAULT_SERVICES=["bughq","loghq"];const REQUEST_TIMEOUT_MS=1e4;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function origin(url){return url.replace(/\/+$/,"")}function httpUrl(value,base){if(typeof value!=="string"||!value)return null;try{const url=new URL(value,base);return url.protocol==="https:"||url.protocol==="http:"?url.toString():null}catch{return null}}function toGrant(body,base,licensed){const project=body.project;if(!isRecord(project)||project.id==null)return null;if(licensed){if(typeof body.licenseKey!=="string"||!body.licenseKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:"",readKey:"",licenseKey:body.licenseKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}if(typeof body.ingestKey!=="string"||typeof body.readKey!=="string")return null;if(!body.ingestKey||!body.readKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:body.ingestKey,readKey:body.readKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}async function request(deps,url,init={}){const signals=[AbortSignal.timeout(REQUEST_TIMEOUT_MS),...deps.signal?[deps.signal]:[]];try{return await deps.fetch(url,{...init,signal:AbortSignal.any(signals)})}catch{return null}}function retryAfterMs(response,fallback){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:fallback}export function resolveHqServices(requested,fallback=HQ_DEFAULT_SERVICES){const names=requested.map((name)=>name.trim().toLowerCase()).filter(Boolean);if(!names.length)return{services:[...fallback]};const unknown=names.filter((name)=>!(name in HQ_SERVICES));if(unknown.length)return{error:`Unknown service: ${unknown.join(", ")}. Choose from ${HQ_SERVICE_NAMES.join(", ")}.`};return{services:[...new Set(names)]}}async function connectOne(service,url,options,deps){const{label}=HQ_SERVICES[service];const base=origin(url);const outcome=(status,detail)=>({outcome:{service,status,detail,send:"skipped",read:"skipped"}});const started=await request(deps,`${base}/api/cli/connect`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({app:options.app})});if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(!started)return outcome("unreachable",`could not reach ${base}`);if(started.status===404||started.status===405)return outcome("unavailable","not available yet");if(started.status===429)return outcome("failed","too many requests, try again in a minute");if(!started.ok)return outcome("failed",`the service answered ${started.status}`);const body=await started.json().catch(()=>null);const code=isRecord(body)&&typeof body.code==="string"&&/^[\w-]{16,128}$/.test(body.code)?body.code:null;const approveUrl=isRecord(body)?httpUrl(body.approveUrl,base):null;if(!code||!approveUrl)return outcome("failed","the service answered something that is not a connect code");const confirmCode=isRecord(body)&&typeof body.confirmCode==="string"&&/^[\w-]{1,32}$/.test(body.confirmCode)?body.confirmCode:null;deps.print("");deps.print(`${label}: approve this connection in your browser`);deps.print(` ${approveUrl}`);if(confirmCode)deps.print(` Confirmation code: ${confirmCode} (type it on that page)`);deps.print(" If the page asks you to sign in, sign in and open the link again.");deps.print(" Waiting for approval. Press Ctrl+C to cancel.");if(options.open!==false){try{await deps.open(approveUrl)}catch{}}const interval=options.pollIntervalMs??2000;const deadline=deps.now()+(options.timeoutMs??10*60*1000);const pollUrl=`${base}/api/cli/connect/${encodeURIComponent(code)}`;while(true){if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(deps.now()>=deadline)return outcome("timeout","nobody approved it in time");await deps.sleep(Math.min(interval,Math.max(0,deadline-deps.now())),deps.signal);if(deps.signal?.aborted)return outcome("cancelled","cancelled");const polled=await request(deps,pollUrl,{headers:{Accept:"application/json"}});if(!polled)continue;if(polled.status===429){await deps.sleep(retryAfterMs(polled,interval),deps.signal);continue}if(polled.status===404)return outcome("expired","the request expired, run the command again");if(!polled.ok)return outcome("failed",`the service answered ${polled.status}`);const answer=await polled.json().catch(()=>null);if(!isRecord(answer)||answer.status==="pending")continue;if(answer.status==="expired")return outcome("expired","the request expired, run the command again");const grant=toGrant(answer,base,Boolean(HQ_SERVICES[service].env.license));if(!grant)return outcome("failed","the service approved the request without sending keys");return{grant,outcome:{service,status:"connected",project:grant.project.name,dashboardUrl:grant.dashboardUrl||undefined,send:"skipped",read:"skipped"}}}}function envEntries(service,grant){const names=HQ_SERVICES[service].env;const entries={};if(names.license&&grant.licenseKey)return{[names.license]:grant.licenseKey};if(names.key)entries[names.key]=grant.ingestKey;if(names.readKey)entries[names.readKey]=grant.readKey;if(names.project)entries[names.project]=grant.project.id;return entries}async function verify(service,url,grant,options,deps){const kind=HQ_SERVICES[service].verify;if(!kind)return{send:"skipped",read:"skipped"};const base=origin(url);if(kind==="support"){const client=createHqClient({services:{supporthq:{url:base,readKey:grant.readKey,project:grant.project.id}},fetch:deps.fetch});const result=await client.support.conversations({limit:1});return result.ok?{send:"skipped",read:"pass"}:{send:"skipped",read:"fail",detail:describeUnavailable(result)}}const marker=`hq-connect-${crypto.randomUUID().slice(0,8)}`;const message=`buddy hq:connect test ${marker}`;const timestamp=new Date(deps.now()).toISOString();const sent=kind==="log"?await request(deps,`${base}/logs`,{method:"POST",headers:{"Content-Type":"application/json","X-LogHQ-Key":grant.ingestKey},body:JSON.stringify({logs:[{level:"info",message,timestamp,context:{source:"buddy hq:connect"}}]})}):await request(deps,`${base}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:grant.ingestKey,type:"HqConnectTest",message,level:"info",environment:"hq-connect",timestamp,sdk:{name:"buddy.hq-connect"}})});if(!sent?.ok)return{send:"fail",read:"skipped",detail:sent?`sending the test ${kind} answered ${sent.status}`:`sending the test ${kind} did not get through`};const receipt=await sent.json().catch(()=>null);if(isRecord(receipt)&&(receipt.sampled===true||receipt.stored===0))return{send:"pass",read:"skipped",detail:`the plan allowance is used up, so the test ${kind} was not kept`};const client=createHqClient({services:{[service]:{url:base,readKey:grant.readKey,project:grant.project.id}},timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});let reason=`the test ${kind} was accepted but did not show up`;const attempts=options.readAttempts??5;for(let attempt=0;attempt<attempts;attempt++){if(attempt>0)await deps.sleep(1000,deps.signal);if(deps.signal?.aborted)return{send:"pass",read:"fail",detail:"cancelled"};if(kind==="log"){const page=await client.logs.list({search:marker,limit:5});if(page.ok&&page.data.logs.some((log)=>log.message.includes(marker)))return{send:"pass",read:"pass"};if(!page.ok)reason=describeUnavailable(page)}else{const list=await client.issues.list();if(list.ok&&list.data.some((issue)=>issue.title.includes(marker)))return{send:"pass",read:"pass"};if(!list.ok)reason=describeUnavailable(list)}}return{send:"pass",read:"fail",detail:reason}}export function describeUnavailable(result){switch(result.reason){case"not_configured":return"not connected";case"unauthorized":return"the read key was refused";case"timeout":return"the service did not answer in time";case"network":return"the service could not be reached";case"http":return result.status===404?"not available yet":`the service answered ${result.status}`;case"bad_response":return"the service answered something unexpected"}}export function renderTable(headers,rows){const widths=headers.map((header,column)=>Math.max(header.length,...rows.map((row)=>(row[column]??"").length)));const line=(cells)=>cells.map((cell,column)=>(cell??"").padEnd(widths[column])).join(" ").trimEnd();return[line(headers),line(widths.map((width)=>"-".repeat(width))),...rows.map(line)]}const CONNECT_WORDS={connected:"pass",unavailable:"not available yet",unreachable:"fail",expired:"fail",timeout:"fail",cancelled:"cancelled",failed:"fail"};const CHECK_WORDS={pass:"pass",fail:"fail",skipped:"-"};export function connectTable(outcomes){return renderTable(["Service","Connect","Send","Read back","Note"],outcomes.map((outcome)=>[HQ_SERVICES[outcome.service].label,CONNECT_WORDS[outcome.status],CHECK_WORDS[outcome.send],CHECK_WORDS[outcome.read],outcome.status==="unavailable"?"":outcome.detail??""]))}export async function runHqConnect(services,config,options,deps){const outcomes=[];for(const service of services){const{label}=HQ_SERVICES[service];if(deps.signal?.aborted){outcomes.push({service,status:"cancelled",detail:"cancelled",send:"skipped",read:"skipped"});continue}const url=config[service]?.url;if(!url){outcomes.push({service,status:"failed",detail:"no URL is configured in config/services.ts",send:"skipped",read:"skipped"});continue}const{outcome,grant}=await connectOne(service,url,options,deps);if(!grant){if(outcome.status==="unavailable")deps.print(`${label}: not available yet`);else if(outcome.status!=="cancelled")deps.print(`${label}: not connected (${outcome.detail})`);outcomes.push(outcome);continue}try{await deps.writeEnv(envEntries(service,grant))}catch(error){const why=error instanceof Error?error.message:"unknown error";deps.print(`${label}: approved, but the keys could not be written to .env (${why})`);outcomes.push({...outcome,status:"failed",detail:"the keys could not be written to .env"});continue}deps.print(grant.licenseKey?`${label}: licensed "${grant.project.name}". Licence written to .env.`:`${label}: connected to project "${grant.project.name}". Keys written to .env.`);if(grant.dashboardUrl)deps.print(` Dashboard: ${grant.dashboardUrl}`);if(options.verify===false){outcomes.push(outcome);continue}outcomes.push({...outcome,...await verify(service,url,grant,options,deps)})}if(deps.signal?.aborted)deps.print("Cancelled. Services already connected keep their keys.");deps.print("");for(const line of connectTable(outcomes))deps.print(line);const ok=outcomes.every((outcome)=>outcome.status==="unavailable"||outcome.status==="connected"&&outcome.send!=="fail"&&outcome.read!=="fail");return{outcomes,ok}}const count=(value)=>value.toLocaleString("en-US");const REPORTSHQ_LICENSE=/^rhq_lic_[0-9a-f]{32}$/;export function describeReportsHqLicense(license){if(!license)return"unlicensed. Reports work in full; set REPORTSHQ_LICENSE to remove the notice";return REPORTSHQ_LICENSE.test(license)?"licensed (checked offline, nothing is metered)":"the licence key is not in the expected format. Reports are unaffected"}export async function runHqStatus(config,deps,services=HQ_SERVICE_NAMES){const connected=services.filter((service)=>config[service]?.url&&config[service]?.readKey);const license=services.includes("reportshq")?config.reportshq?.license:undefined;if(!connected.length&&!license){deps.print("No HQ service is connected yet. Run `buddy hq:connect` to connect one.");return[]}const client=createHqClient({services:Object.fromEntries(connected.map((service)=>[service,{url:config[service].url,readKey:config[service].readKey}])),timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});const rows=[];for(const[index,usage]of(await Promise.all(connected.map((service)=>client.getUsage(service)))).entries()){const service=connected[index];if(!usage.ok){rows.push({service,unavailable:describeUnavailable(usage)});continue}if(!usage.data.length)rows.push({service,unavailable:"no meters reported"});for(const report of usage.data){const over=report.limit!==null&&report.limit>0&&report.used/report.limit>=0.8;rows.push({service,meter:report.meter,used:report.used,limit:report.limit,period:report.period,state:report.state,...over?{upgradeUrl:report.upgradeUrl}:{}})}}if(license)rows.push({service:"reportshq",unavailable:describeReportsHqLicense(license)});const table=renderTable(["Service","Meter","Used","Limit","Period","State"],rows.map((row)=>row.unavailable?[HQ_SERVICES[row.service].label,row.unavailable]:[HQ_SERVICES[row.service].label,row.meter,count(row.used),row.limit===null?"unlimited":count(row.limit),row.period,row.state]));for(const line of table)deps.print(line);const upgrades=rows.filter((row)=>row.upgradeUrl);if(upgrades.length)deps.print("");for(const row of upgrades){const percent=Math.round(row.used/row.limit*100);deps.print(`${HQ_SERVICES[row.service].label} ${row.meter} is at ${percent}% of its allowance. Upgrade: ${row.upgradeUrl}`)}return rows}export async function runSupportDoctor(config,deps,options={}){const service=config.supporthq;const configured=Boolean(service?.url&&service.key&&service.readKey&&service.project);const checks=[{name:"configuration",ok:configured,detail:configured?"server key, read key and project configured":"missing configuration; run `buddy support:install`"}];if(configured){const client=createHqClient({services:{supporthq:{url:service.url,readKey:service.readKey,project:service.project}},fetch:deps.fetch});const usage=await client.getUsage("supporthq");checks.push({name:"usage",ok:usage.ok,detail:usage.ok?`${usage.data.length} usage meters readable`:describeUnavailable(usage)});const conversations=await client.support.conversations({limit:1});checks.push({name:"conversations",ok:conversations.ok,detail:conversations.ok?"project summaries readable":describeUnavailable(conversations)});if(service?.enabled===true){try{const target=new URL(service.url);if(target.username||target.password||target.search||target.hash||target.pathname!=="/"||target.protocol!=="https:"&&!(target.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(target.hostname)))throw new Error("Invalid support origin");const base=target.origin;const probe=await deps.fetch(`${base}/api/v1/projects/${encodeURIComponent(service.project)}/installation`,{headers:{Authorization:`Bearer ${service.key}`},redirect:"error",signal:AbortSignal.timeout(1e4)});const body=probe.ok?await probe.json():null;const current=new URL(options.origin||"").origin;const accepted=isRecord(body)&&body.service==="supporthq"&&body.protocol===1&&body.project===service.project&&body.buddyConnected===true&&Array.isArray(body.allowedOrigins)&&body.allowedOrigins.includes(current);checks.push({name:"installation",ok:accepted,detail:accepted?"approved project and exact app origin; no customer probe was created":"native installation or app origin is not approved"})}catch{checks.push({name:"installation",ok:false,detail:"native installation could not be read"})}if(service.messenger?.enabled){try{const loader=new URL(service.messenger.loaderUrl||"https://hq.support/support.js");if(loader.username||loader.password||loader.search||loader.hash||loader.protocol!=="https:"&&!(loader.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(loader.hostname)))throw new Error("Invalid loader");const response=await deps.fetch(new URL("/widgets/manifest.json",loader).href,{redirect:"error",signal:AbortSignal.timeout(1e4)});const manifest=response.ok?await response.json():null;const published=isRecord(manifest)&&manifest.schemaVersion===1&&Array.isArray(manifest.files)&&manifest.files.some((file)=>isRecord(file)&&typeof file.path==="string"&&file.path.endsWith("/bundle.js")&&typeof file.sha256==="string"&&/^[a-f0-9]{64}$/.test(file.sha256)&&typeof file.gzipBytes==="number"&&file.gzipBytes>0&&file.gzipBytes<=1e5);checks.push({name:"widget",ok:published,detail:published?"published manifest reports a versioned widget within the initial code budget":"published widget manifest or size budget is unavailable"})}catch{checks.push({name:"widget",ok:false,detail:"published widget could not be checked"})}}}}for(const check of checks)deps.print(`HQ.support ${check.name}: ${check.ok?"pass":"fail"} (${check.detail})`);return{ok:checks.every((check)=>check.ok),checks}}