@stacksjs/buddy 0.75.543 → 0.75.548
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/build.js +1 -1
- package/dist/commands/cloud.js +2 -2
- package/dist/commands/desktop-release.d.ts +20 -0
- package/dist/commands/desktop-release.js +4 -0
- package/dist/commands/dev.js +1 -1
- package/dist/commands/index.d.ts +1 -0
- package/dist/commands/index.js +1 -1
- package/dist/commands/license.d.ts +13 -0
- package/dist/commands/license.js +2 -0
- package/dist/lazy-commands.js +1 -1
- package/package.json +57 -57
package/dist/commands/build.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{intro,log,multiselect,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions/run-action")).runAction;return _runAction(...args)}export function build(buddy){const descriptions={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",libs:"Build every package configured in config/library.ts",desktop:"Build the Desktop Application",mobile:"Build the native iOS and Android applications",android:"Build the native Android application",ios:"Build the native iOS application",dmg:"Package the desktop build as a macOS .app inside a .dmg",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",frontendStatic:"Build the prerendered marketing/public static site (storage/framework/frontend-dist)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("build [type]",descriptions.build).option("-c, --components",descriptions.components).option("-w, --web-components",descriptions.webComponents).option("-e, --elements",descriptions.elements).option("-f, --functions",descriptions.functions).option("-l, --libs",descriptions.libs).option("-k, --desktop",descriptions.desktop).option("-m, --mobile",descriptions.mobile).option("--android",descriptions.android).option("--ios",descriptions.ios).option("-p, --views",descriptions.pages).option("--pages",descriptions.pages).option("-d, --docs",descriptions.docs).option("-b, --buddy",descriptions.buddy,{default:false}).option("-s, --stacks",descriptions.framework,{default:false}).option("--project [project]",descriptions.project,{default:false}).option("--server",descriptions.server,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy build` ...",options);applyBuildTarget(server,options);if(options.mobile){options.android=true;options.ios=true}if(hasNoOptions(options)){if(!isCI&&hasTTY&&process.stdin.isTTY){const answers=await multiselect({message:descriptions.select,choices:[{label:"Frontend (views)",value:"views"},{label:"Components",value:"components"},{label:"Web Components",value:"webComponents"},{label:"Functions",value:"functions"},{label:"All library packages",value:"libs"},{label:"Desktop application",value:"desktop"},{label:"Mobile applications (iOS + Android)",value:"mobile"},{label:"Android application",value:"android"},{label:"iOS application",value:"ios"},{label:"Documentation",value:"docs"},{label:"Stacks framework",value:"stacks"},{label:"Buddy CLI",value:"buddy"},{label:"Server (Docker image)",value:"server"}]});const selected=new Set(answers);if(selected.has("views"))options.views=true;if(selected.has("components"))options.components=true;if(selected.has("webComponents"))options.webComponents=true;if(selected.has("functions"))options.functions=true;if(selected.has("libs"))options.libs=true;if(selected.has("desktop"))options.desktop=true;if(selected.has("mobile")){options.mobile=true;options.android=true;options.ios=true}if(selected.has("android"))options.android=true;if(selected.has("ios"))options.ios=true;if(selected.has("docs"))options.docs=true;if(selected.has("stacks"))options.stacks=true;if(selected.has("buddy"))options.buddy=true;if(selected.has("server"))options.server=true}if(hasNoOptions(options)){options.views=true;log.info("No build target specified, defaulting to the frontend (views). See `buddy build --help` for all targets.")}}let succeeded=true;if(options.docs)succeeded=await runBuildAction(Action.BuildDocs,"documentation",options)&&succeeded;if(options.components)succeeded=await runBuildAction(Action.BuildComponentLibs,"component libraries",options)&&succeeded;if(options.webComponents)succeeded=await runBuildAction(Action.BuildWebComponentLib,"web component library",options)&&succeeded;if(options.functions)succeeded=await runBuildAction(Action.BuildFunctionLib,"function library",options)&&succeeded;if(options.libs)succeeded=await runBuildAction(Action.BuildLibs,"library packages",options)&&succeeded;if(options.desktop)succeeded=await runBuildAction(Action.BuildDesktop,"desktop application",options)&&succeeded;if(options.android)succeeded=await runBuildAction(Action.BuildAndroid,"Android application",options)&&succeeded;if(options.ios)succeeded=await runBuildAction(Action.BuildIos,"iOS application",options)&&succeeded;if(options.views)succeeded=await runBuildAction(Action.BuildViews,"frontend",options)&&succeeded;if(options.stacks)succeeded=await runBuildAction(Action.BuildStacks,"Stacks framework",options)&&succeeded;if(options.buddy)succeeded=await runBuildAction(Action.BuildCli,"Buddy CLI",options)&&succeeded;if(options.server)succeeded=await runBuildAction(Action.BuildServer,"server",options)&&succeeded;if(!succeeded)process.exit(ExitCode.FatalError);process.exit(ExitCode.Success)});buddy.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",descriptions.components,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:components` ...",options);if(!await runBuildAction(Action.BuildComponentLibs,"component libraries",options))process.exit(ExitCode.FatalError)});buddy.command("build:cli",descriptions.cli).alias("prod:cli").option("-b, --buddy",descriptions.buddy,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:cli` ...",options);if(!await runBuildAction(Action.BuildCli,"Buddy CLI",options))process.exit(ExitCode.FatalError)});buddy.command("build:server",descriptions.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:server` ...",options);if(!await runBuildAction(Action.BuildServer,"server",options))process.exit(ExitCode.FatalError)});buddy.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",descriptions.functions,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:functions` ...",options);if(!await runBuildAction(Action.BuildFunctionLib,"function library",options))process.exit(ExitCode.FatalError)});buddy.command("build:libs",descriptions.libs).alias("build:libraries").alias("prod:libs").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:libs` ...",options);if(!await runBuildAction(Action.BuildLibs,"library packages",options))process.exit(ExitCode.FatalError)});buddy.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",descriptions.webComponents,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:web-components` ...",options);if(!await runBuildAction(Action.BuildWebComponentLib,"web component library",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend",descriptions.pages).alias("build:pages").alias("build:views").alias("prod:frontend").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend` ...",options);if(!await runBuildAction(Action.BuildViews,"frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",descriptions.docs,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:docs` ...",options);if(!await runBuildAction(Action.BuildDocs,"documentation",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend-static",descriptions.frontendStatic).alias("build:public").alias("prod:frontend-static").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend-static` ...",options);if(!await runBuildAction(Action.BuildFrontendStatic,"static frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:core` ...",options);const startTime=await intro("buddy build:core");const result=await runAction(Action.BuildCore,options);if(resultFailed(result)){await log.error("Failed to build the Stacks core.",result.error);process.exit(ExitCode.FatalError)}await outro("Core packages built successfully",{startTime,useSeconds:true})});buddy.command("build:desktop",descriptions.desktop).alias("prod:desktop").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:desktop` ...",options);const perf=await intro("buddy build:desktop");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");const result=await runAction(await hasMacosDesktop(projectPath())?Action.BuildDesktopMacos:Action.BuildDesktop,options);if(resultFailed(result)){await outro("While running the build:desktop 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("build:mobile",descriptions.mobile).alias("prod:mobile").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:mobile` ...",options);const perf=await intro("buddy build:mobile");const androidSucceeded=await runBuildAction(Action.BuildAndroid,"Android application",options);const iosSucceeded=await runBuildAction(Action.BuildIos,"iOS application",options);if(!androidSucceeded||!iosSucceeded){await outro("One or more mobile application builds failed",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("iOS and Android applications built",{startTime:perf,useSeconds:true})});buddy.command("build:android",descriptions.android).alias("prod:android").option("-p, --project [project]",descriptions.project,{default:false}).option("--bundle","Build a signed Android App Bundle (.aab) for Google Play (CRAFT_ANDROID_KEYSTORE and friends)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:android` ...",options);if(options.bundle)process.env.STACKS_ANDROID_BUNDLE="1";const perf=await intro("buddy build:android");const result=await runAction(Action.BuildAndroid,options);if(resultFailed(result)){await outro("While building the Android application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Android application built",{startTime:perf,useSeconds:true})});buddy.command("build:ios",descriptions.ios).alias("prod:ios").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:ios` ...",options);const perf=await intro("buddy build:ios");const result=await runAction(Action.BuildIos,options);if(resultFailed(result)){await outro("While building the iOS application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("iOS application built",{startTime:perf,useSeconds:true})});buddy.command("build:dmg",descriptions.dmg).option("--app-name <name>","Bundle display name (or DESKTOP_APP_NAME / APP_NAME)").option("--app-version <version>","Bundle version (or DESKTOP_APP_VERSION; defaults to the project's package.json)").option("--bundle-id <id>","Reverse-DNS bundle identifier (or DESKTOP_BUNDLE_ID)").option("--signing-identity <identity>","Developer ID identity to sign with (or DESKTOP_SIGNING_IDENTITY)").option("--notary-profile <profile>","notarytool keychain profile to notarize and staple with (or DESKTOP_NOTARY_PROFILE)").option("--notarize","Notarize and staple with an App Store Connect API key (or DESKTOP_NOTARIZE)").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_API_ISSUER_ID)").option("--api-key-path <path>","The AuthKey_*.p8 file (or APP_STORE_CONNECT_API_KEY_PATH, or its PEM in APP_STORE_CONNECT_API_KEY)").option("--volume-name <name>","Name the mounted image shows (or DESKTOP_VOLUME_NAME)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:dmg` ...",options);const perf=await intro("buddy build:dmg");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");const result=await runAction(await hasMacosDesktop(projectPath())?Action.BuildDmgMacos:Action.BuildDmg,options);if(resultFailed(result)){await outro("While running the build:dmg 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("build:stacks","Build the Stacks framework.").option("-s, --stacks",descriptions.framework,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:stacks` ...",options);const startTime=await intro("buddy build:stacks");const result=await runAction(Action.BuildStacks,options);if(resultFailed(result)){await log.error("Failed to build Stacks.",result.error);process.exit(ExitCode.FatalError)}await outro("Stacks built successfully",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"build")}function hasNoOptions(options){return!options.components&&!options.webComponents&&!options.elements&&!options.functions&&!options.libs&&!options.desktop&&!options.mobile&&!options.android&&!options.ios&&!options.views&&!options.docs&&!options.stacks&&!options.buddy&&!options.server}export function applyBuildTarget(target,options){switch(target){case"components":options.components=true;break;case"web-components":options.webComponents=true;break;case"functions":options.functions=true;break;case"libs":case"libraries":options.libs=true;break;case"desktop":options.desktop=true;break;case"mobile":options.mobile=true;options.android=true;options.ios=true;break;case"android":options.android=true;break;case"ios":options.ios=true;break;case"views":options.views=true;break;case"docs":options.docs=true;break;case"buddy":case"cli":options.buddy=true;break;case"stacks":options.stacks=true;break;case"server":options.server=true;break}}async function runBuildAction(action,target,options){const result=await runAction(action,options);if(resultFailed(result)){log.error(`Failed to build ${target}.`,result.error);return false}return true}
|
|
1
|
+
import process from"node:process";import{intro,log,multiselect,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions/run-action")).runAction;return _runAction(...args)}export function build(buddy){const descriptions={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",libs:"Build every package configured in config/library.ts",desktop:"Build the Desktop Application",mobile:"Build the native iOS and Android applications",android:"Build the native Android application",ios:"Build the native iOS application",dmg:"Package the desktop build as a macOS .app inside a .dmg",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",frontendStatic:"Build the prerendered marketing/public static site (storage/framework/frontend-dist)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("build [type]",descriptions.build).option("-c, --components",descriptions.components).option("-w, --web-components",descriptions.webComponents).option("-e, --elements",descriptions.elements).option("-f, --functions",descriptions.functions).option("-l, --libs",descriptions.libs).option("-k, --desktop",descriptions.desktop).option("-m, --mobile",descriptions.mobile).option("--android",descriptions.android).option("--ios",descriptions.ios).option("-p, --views",descriptions.pages).option("--pages",descriptions.pages).option("-d, --docs",descriptions.docs).option("-b, --buddy",descriptions.buddy,{default:false}).option("-s, --stacks",descriptions.framework,{default:false}).option("--project [project]",descriptions.project,{default:false}).option("--server",descriptions.server,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy build` ...",options);applyBuildTarget(server,options);if(options.mobile){options.android=true;options.ios=true}if(hasNoOptions(options)){if(!isCI&&hasTTY&&process.stdin.isTTY){const answers=await multiselect({message:descriptions.select,choices:[{label:"Frontend (views)",value:"views"},{label:"Components",value:"components"},{label:"Web Components",value:"webComponents"},{label:"Functions",value:"functions"},{label:"All library packages",value:"libs"},{label:"Desktop application",value:"desktop"},{label:"Mobile applications (iOS + Android)",value:"mobile"},{label:"Android application",value:"android"},{label:"iOS application",value:"ios"},{label:"Documentation",value:"docs"},{label:"Stacks framework",value:"stacks"},{label:"Buddy CLI",value:"buddy"},{label:"Server (Docker image)",value:"server"}]});const selected=new Set(answers);if(selected.has("views"))options.views=true;if(selected.has("components"))options.components=true;if(selected.has("webComponents"))options.webComponents=true;if(selected.has("functions"))options.functions=true;if(selected.has("libs"))options.libs=true;if(selected.has("desktop"))options.desktop=true;if(selected.has("mobile")){options.mobile=true;options.android=true;options.ios=true}if(selected.has("android"))options.android=true;if(selected.has("ios"))options.ios=true;if(selected.has("docs"))options.docs=true;if(selected.has("stacks"))options.stacks=true;if(selected.has("buddy"))options.buddy=true;if(selected.has("server"))options.server=true}if(hasNoOptions(options)){options.views=true;log.info("No build target specified, defaulting to the frontend (views). See `buddy build --help` for all targets.")}}let succeeded=true;if(options.docs)succeeded=await runBuildAction(Action.BuildDocs,"documentation",options)&&succeeded;if(options.components)succeeded=await runBuildAction(Action.BuildComponentLibs,"component libraries",options)&&succeeded;if(options.webComponents)succeeded=await runBuildAction(Action.BuildWebComponentLib,"web component library",options)&&succeeded;if(options.functions)succeeded=await runBuildAction(Action.BuildFunctionLib,"function library",options)&&succeeded;if(options.libs)succeeded=await runBuildAction(Action.BuildLibs,"library packages",options)&&succeeded;if(options.desktop)succeeded=await runBuildAction(Action.BuildDesktop,"desktop application",options)&&succeeded;if(options.android)succeeded=await runBuildAction(Action.BuildAndroid,"Android application",options)&&succeeded;if(options.ios)succeeded=await runBuildAction(Action.BuildIos,"iOS application",options)&&succeeded;if(options.views)succeeded=await runBuildAction(Action.BuildViews,"frontend",options)&&succeeded;if(options.stacks)succeeded=await runBuildAction(Action.BuildStacks,"Stacks framework",options)&&succeeded;if(options.buddy)succeeded=await runBuildAction(Action.BuildCli,"Buddy CLI",options)&&succeeded;if(options.server)succeeded=await runBuildAction(Action.BuildServer,"server",options)&&succeeded;if(!succeeded)process.exit(ExitCode.FatalError);process.exit(ExitCode.Success)});buddy.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",descriptions.components,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:components` ...",options);if(!await runBuildAction(Action.BuildComponentLibs,"component libraries",options))process.exit(ExitCode.FatalError)});buddy.command("build:cli",descriptions.cli).alias("prod:cli").option("-b, --buddy",descriptions.buddy,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:cli` ...",options);if(!await runBuildAction(Action.BuildCli,"Buddy CLI",options))process.exit(ExitCode.FatalError)});buddy.command("build:server",descriptions.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:server` ...",options);if(!await runBuildAction(Action.BuildServer,"server",options))process.exit(ExitCode.FatalError)});buddy.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",descriptions.functions,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:functions` ...",options);if(!await runBuildAction(Action.BuildFunctionLib,"function library",options))process.exit(ExitCode.FatalError)});buddy.command("build:libs",descriptions.libs).alias("build:libraries").alias("prod:libs").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:libs` ...",options);if(!await runBuildAction(Action.BuildLibs,"library packages",options))process.exit(ExitCode.FatalError)});buddy.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",descriptions.webComponents,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:web-components` ...",options);if(!await runBuildAction(Action.BuildWebComponentLib,"web component library",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend",descriptions.pages).alias("build:pages").alias("build:views").alias("prod:frontend").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend` ...",options);if(!await runBuildAction(Action.BuildViews,"frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",descriptions.docs,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:docs` ...",options);if(!await runBuildAction(Action.BuildDocs,"documentation",options))process.exit(ExitCode.FatalError)});buddy.command("build:frontend-static",descriptions.frontendStatic).alias("build:public").alias("prod:frontend-static").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:frontend-static` ...",options);if(!await runBuildAction(Action.BuildFrontendStatic,"static frontend",options))process.exit(ExitCode.FatalError)});buddy.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:core` ...",options);const startTime=await intro("buddy build:core");const result=await runAction(Action.BuildCore,options);if(resultFailed(result)){await log.error("Failed to build the Stacks core.",result.error);process.exit(ExitCode.FatalError)}await outro("Core packages built successfully",{startTime,useSeconds:true})});buddy.command("build:desktop",descriptions.desktop).alias("prod:desktop").option("--target <targets>","Web view app: comma-separated targets (darwin-arm64, linux-x64, win32-x64, ...) or all. Default: this machine").option("--package","Web view app: also make the installers this operating system can make (MSI on Windows; AppImage, deb, rpm on Linux)",{default:false}).option("--native","Build 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)=>{log.debug("Running `buddy build:desktop` ...",options);const perf=await intro("buddy build:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");const webview=!options.native&&await hasWebviewDesktop(projectPath());if(webview){if(options.target)process.env.DESKTOP_TARGETS=options.target;if(options.package)process.env.DESKTOP_PACKAGE="1"}const result=await runAction(webview?Action.BuildDesktopWebview:await hasMacosDesktop(projectPath())?Action.BuildDesktopMacos:Action.BuildDesktop,options);if(resultFailed(result)){await outro("While running the build:desktop 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("build:mobile",descriptions.mobile).alias("prod:mobile").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:mobile` ...",options);const perf=await intro("buddy build:mobile");const androidSucceeded=await runBuildAction(Action.BuildAndroid,"Android application",options);const iosSucceeded=await runBuildAction(Action.BuildIos,"iOS application",options);if(!androidSucceeded||!iosSucceeded){await outro("One or more mobile application builds failed",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("iOS and Android applications built",{startTime:perf,useSeconds:true})});buddy.command("build:android",descriptions.android).alias("prod:android").option("-p, --project [project]",descriptions.project,{default:false}).option("--bundle","Build a signed Android App Bundle (.aab) for Google Play (CRAFT_ANDROID_KEYSTORE and friends)",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:android` ...",options);if(options.bundle)process.env.STACKS_ANDROID_BUNDLE="1";const perf=await intro("buddy build:android");const result=await runAction(Action.BuildAndroid,options);if(resultFailed(result)){await outro("While building the Android application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Android application built",{startTime:perf,useSeconds:true})});buddy.command("build:ios",descriptions.ios).alias("prod:ios").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:ios` ...",options);const perf=await intro("buddy build:ios");const result=await runAction(Action.BuildIos,options);if(resultFailed(result)){await outro("While building the iOS application, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("iOS application built",{startTime:perf,useSeconds:true})});buddy.command("build:dmg",descriptions.dmg).option("--app-name <name>","Bundle display name (or DESKTOP_APP_NAME / APP_NAME)").option("--app-version <version>","Bundle version (or DESKTOP_APP_VERSION; defaults to the project's package.json)").option("--bundle-id <id>","Reverse-DNS bundle identifier (or DESKTOP_BUNDLE_ID)").option("--signing-identity <identity>","Developer ID identity to sign with (or DESKTOP_SIGNING_IDENTITY)").option("--notary-profile <profile>","notarytool keychain profile to notarize and staple with (or DESKTOP_NOTARY_PROFILE)").option("--notarize","Notarize and staple with an App Store Connect API key (or DESKTOP_NOTARIZE)").option("--api-key-id <id>","App Store Connect API key ID (or APP_STORE_CONNECT_API_KEY_ID)").option("--api-issuer-id <id>","App Store Connect API issuer ID (or APP_STORE_CONNECT_API_ISSUER_ID)").option("--api-key-path <path>","The AuthKey_*.p8 file (or APP_STORE_CONNECT_API_KEY_PATH, or its PEM in APP_STORE_CONNECT_API_KEY)").option("--volume-name <name>","Name the mounted image shows (or DESKTOP_VOLUME_NAME)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:dmg` ...",options);const perf=await intro("buddy build:dmg");const{hasMacosDesktop}=await import("@stacksjs/desktop-build");const result=await runAction(await hasMacosDesktop(projectPath())?Action.BuildDmgMacos:Action.BuildDmg,options);if(resultFailed(result)){await outro("While running the build:dmg 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("build:stacks","Build the Stacks framework.").option("-s, --stacks",descriptions.framework,{default:true}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy build:stacks` ...",options);const startTime=await intro("buddy build:stacks");const result=await runAction(Action.BuildStacks,options);if(resultFailed(result)){await log.error("Failed to build Stacks.",result.error);process.exit(ExitCode.FatalError)}await outro("Stacks built successfully",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"build")}function hasNoOptions(options){return!options.components&&!options.webComponents&&!options.elements&&!options.functions&&!options.libs&&!options.desktop&&!options.mobile&&!options.android&&!options.ios&&!options.views&&!options.docs&&!options.stacks&&!options.buddy&&!options.server}export function applyBuildTarget(target,options){switch(target){case"components":options.components=true;break;case"web-components":options.webComponents=true;break;case"functions":options.functions=true;break;case"libs":case"libraries":options.libs=true;break;case"desktop":options.desktop=true;break;case"mobile":options.mobile=true;options.android=true;options.ios=true;break;case"android":options.android=true;break;case"ios":options.ios=true;break;case"views":options.views=true;break;case"docs":options.docs=true;break;case"buddy":case"cli":options.buddy=true;break;case"stacks":options.stacks=true;break;case"server":options.server=true;break}}async function runBuildAction(action,target,options){const result=await runAction(action,options);if(resultFailed(result)){log.error(`Failed to build ${target}.`,result.error);return false}return true}
|
package/dist/commands/cloud.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{existsSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{intro,italic,log,onUnknownSubcommand,outro,prompts,runCommand,text,underline}from"@stacksjs/cli";import{addJumpBox,deleteCdkRemnants,deleteIamUsers,deleteJumpBox,deleteLogGroups,deleteParameterStore,deleteStacksBuckets,deleteStacksFunctions,deleteSubnets,deleteVpcs,cloudEnvironment,diffStackTemplate,getCloudFrontDistributionId,stacksCloudRegion}from"@stacksjs/cloud";import{hasTTY,isCI}from"@stacksjs/env";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";import{isSshPipelineProvider,sshFleetFromConfigAndState}from"./deploy-ssh-target";async function createTemporaryCdkRole(roleName){const{AWSClient}=await import("@stacksjs/ts-cloud");const client=new AWSClient;const trustPolicy={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudformation.amazonaws.com"},Action:"sts:AssumeRole"}]};try{try{const getRoleParams=new URLSearchParams({Action:"GetRole",RoleName:roleName,Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:getRoleParams.toString()});log.debug(`Role ${roleName} already exists`);return}catch(e){if(!e.message?.includes("NoSuchEntity")&&!e.message?.includes("cannot be found")){throw e}}log.info("Creating temporary IAM role to enable stack deletion...");const createRoleParams=new URLSearchParams({Action:"CreateRole",RoleName:roleName,AssumeRolePolicyDocument:JSON.stringify(trustPolicy),Description:"Temporary role to allow CloudFormation to delete stuck stack",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:createRoleParams.toString()});log.success("Created IAM role");log.info("Attaching permissions...");const attachPolicyParams=new URLSearchParams({Action:"AttachRolePolicy",RoleName:roleName,PolicyArn:"arn:aws:iam::aws:policy/AdministratorAccess",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:attachPolicyParams.toString()});log.success("IAM role ready for stack deletion");log.info("Waiting for IAM role to propagate...");await new Promise((resolve)=>setTimeout(resolve,1e4))}catch(error){if(error.message?.includes("EntityAlreadyExists")){log.debug("Role already exists")}else{throw error}}}async function deleteTemporaryCdkRole(roleName){const{AWSClient}=await import("@stacksjs/ts-cloud");const client=new AWSClient;try{const detachPolicyParams=new URLSearchParams({Action:"DetachRolePolicy",RoleName:roleName,PolicyArn:"arn:aws:iam::aws:policy/AdministratorAccess",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:detachPolicyParams.toString()});const deleteRoleParams=new URLSearchParams({Action:"DeleteRole",RoleName:roleName,Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:deleteRoleParams.toString()});log.success("Cleaned up temporary IAM role")}catch(error){log.debug(`Could not clean up temporary role: ${error.message}`)}}function isResultError(result){return resultFailed(result)}function getResultError(result){if(!result||typeof result!=="object")return"Unknown error";return String(result.error||"Unknown error")}function getResultValue(result){if(!result||typeof result!=="object")return;return result.value}async function refuse(...messages){for(const message of messages.slice(0,-1))await log.error(message);return log.exit(messages[messages.length-1],ExitCode.FatalError)}async function driverStatePins(){const{driverStatePath}=await import("@stacksjs/ts-cloud");const dir=join(driverStatePath("probe"),"..");let files;try{files=readdirSync(dir).filter((name)=>name.endsWith(".json"))}catch{return[]}const pins=[];for(const name of files){const file=join(dir,name);try{const state=JSON.parse(readFileSync(file,"utf8"));if(typeof state?.serverName==="string")pins.push({file,state})}catch{}}return pins}function writePinName(file,next){const state=JSON.parse(readFileSync(file,"utf8"));writeFileSync(file,`${JSON.stringify({...state,serverName:next},null,2)}
|
|
2
2
|
`)}export async function renameEffects(tsCloudConfig,servers,current){const taken=servers.map((s)=>String(s?.name)).filter(Boolean);const effects={takenNames:async()=>taken,inventoryName:()=>String(current?.name??""),renameInventory:(next)=>{current.name=next}};const pinned=(await driverStatePins()).filter((pin)=>pin.state.serverName===current?.name);if(pinned.length>0){effects.stateName=async()=>{const stale=(await driverStatePins()).find((pin)=>pin.state.serverName===current?.name);return stale?String(stale.state.serverName):undefined};effects.writeStateName=async(next)=>{for(const pin of pinned)writePinName(pin.file,next)}}const host=current?.ipv4;if(host){const{sshExec,buildSetHostnameScript}=await import("@stacksjs/ts-cloud");const ssh={user:"root",connectTimeoutSec:10};effects.remoteHostname=async()=>{const result=await sshExec(host,"hostname",ssh);if(result.code!==0)throw new Error(result.stderr.trim()||`Could not reach ${host} over SSH.`);return result.stdout.trim()};effects.setRemoteHostname=async(next)=>{const result=await sshExec(host,buildSetHostnameScript(next),ssh);if(result.code!==0)throw new Error(result.stderr.trim()||`Setting the hostname on ${host} failed.`)}}const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(provider!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);const serverId=Number(current?.id);if(!apiToken||!Number.isFinite(serverId))return effects;const client=new HetznerClient({apiToken});effects.providerName=async()=>(await client.getServer(serverId))?.name;effects.renameProvider=async(next)=>{await client.renameServer(serverId,next)};return effects}export function planServerDestroy(name,effects){const steps=[{id:"provider:delete",title:`Delete the server ${name}`,change:{from:name,to:"gone"},destructive:true,satisfied:async()=>!await effects.providerExists(),apply:async()=>await effects.deleteProvider()}];if(effects.pinnedName&&effects.clearPin){steps.push({id:"state:clear",title:"Clear the state pin that names it",change:{from:name,to:"none"},satisfied:async()=>await effects.pinnedName()!==name,apply:async()=>await effects.clearPin()})}return{operation:"server:destroy",target:name,steps}}export async function destroyEffects(tsCloudConfig,current){const pinned=(await driverStatePins()).filter((pin)=>pin.state.serverName===current?.name);const effects={providerExists:async()=>true,deleteProvider:async()=>{throw new Error(`No provider API for this fleet, so ${current?.name} cannot be deleted from here.`)}};if(pinned.length>0){effects.pinnedName=async()=>{const stale=(await driverStatePins()).find((pin)=>pin.state.serverName===current?.name);return stale?String(stale.state.serverName):undefined};effects.clearPin=async()=>{for(const pin of pinned){const{serverId:_id,serverName:_name,...rest}=JSON.parse(readFileSync(pin.file,"utf8"));writeFileSync(pin.file,`${JSON.stringify(rest,null,2)}
|
|
3
3
|
`)}}}const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(provider!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);const serverId=Number(current?.id);if(!apiToken||!Number.isFinite(serverId))return effects;const client=new HetznerClient({apiToken});effects.providerExists=async()=>{try{return Boolean(await client.getServer(serverId))}catch{return false}};effects.deleteProvider=async()=>{await client.deleteServer(serverId)};return effects}export function sitesSharingHostnames(sites,siteName,hostnames,hostsOf){return Object.entries(sites??{}).filter(([name])=>name!==siteName).filter(([name,site])=>hostsOf(name,site).some((host)=>hostnames.includes(host))).map(([name,site])=>`${name} (${String(site?.path??"/")})`).sort()}async function moveEffects(context){const{slug,siteName,rawSite,source,target,tsCloudConfig}=context;const{buildCertificatePackScript,buildCertificateStateScript,buildCertificateUnpackScript,buildRpxConfig,buildRpxFragmentRefreshScript,buildSshArgs,certificatesMatch,DEFAULT_RPX_CERTS_DIR,parseCertificateState,probeHostRoutes,sshExec,sshExecOrThrow}=await import("@stacksjs/ts-cloud");const{reconcileHetznerDns}=await import("./deploy");const ssh={user:"root",connectTimeoutSec:10};const runOnSource=(script)=>sshExecOrThrow(source.ipv4,script,ssh);const runOnTarget=(script)=>sshExecOrThrow(target.ipv4,script,ssh);async function carry(path){const args=buildSshArgs(ssh,"ssh");const reader=Bun.spawn(["ssh",...args,`root@${source.ipv4}`,`cat ${path}`],{stdout:"pipe",stderr:"pipe"});const writer=Bun.spawn(["ssh",...args,`root@${target.ipv4}`,`cat > ${path}`],{stdin:reader.stdout,stdout:"pipe",stderr:"pipe"});const[readCode,writeCode]=await Promise.all([reader.exited,writer.exited]);if(readCode!==0||writeCode!==0){const why=(await new Response(readCode===0?writer.stderr:reader.stderr).text()).trim();throw new Error(why||`Carrying ${path} from ${source.name} to ${target.name} failed.`)}}const staged=async(path)=>(await sshExec(target.ipv4,`test -s ${path} && echo staged`,ssh)).stdout.includes("staged");const{siteMoveArchivePath,siteMoveCertArchivePath}=await import("@stacksjs/ts-cloud");const archive=siteMoveArchivePath(slug,siteName);const effects={runOnSource,runOnTarget,archiveStaged:()=>staged(archive),transferArchive:()=>carry(archive),publishedAddress:async()=>{const host=context.hostnames[0];if(!host)return;try{const{resolve4}=await import("node:dns/promises");return(await resolve4(host))[0]}catch{return}},cutoverDns:async()=>{const warnings=[];const collect=new Proxy(log,{get:(target_,key)=>key==="warn"?(message)=>{warnings.push(String(message))}:target_[key]});await reconcileHetznerDns({[siteName]:rawSite},target.ipv4,collect,target.ipv6,tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww);return warnings},targetRoutesSite:async()=>{const probe=await probeHostRoutes(target,(host,command)=>sshExec(host,command,ssh));if(probe.unavailable)return false;return probe.routes.some((route)=>context.hostnames.includes(String(route.host)))},refreshTargetGateway:async()=>{const rpx=buildRpxConfig(tsCloudConfig?.sites??{},{proxy:tsCloudConfig?.infrastructure?.compute?.proxy??{},slug});await runOnTarget(buildRpxFragmentRefreshScript({config:rpx,slug}).join(`
|
|
4
|
-
`))}};const certArchive=siteMoveCertArchivePath(slug,siteName);effects.certificates={inPlace:async()=>{const read=async(run)=>parseCertificateState(await run(buildCertificateStateScript(DEFAULT_RPX_CERTS_DIR,context.hostnames)));return certificatesMatch(await read(runOnSource),await read(runOnTarget))},carry:async()=>{await runOnSource(buildCertificatePackScript(DEFAULT_RPX_CERTS_DIR,context.hostnames,certArchive));await carry(certArchive);await runOnTarget(buildCertificateUnpackScript(DEFAULT_RPX_CERTS_DIR,certArchive))}};return effects}export async function serverServing(servers,hosts,probe){for(const candidate of servers){if(!candidate?.ipv4)continue;const result=await probe(candidate);if(!result.unavailable&&(result.routes??[]).some((route)=>hosts.includes(String(route.host))))return candidate}return}export async function onBoxDatabase(tsCloudConfig){const{isLocalDatabase,resolveAppDatabase}=await import("@stacksjs/ts-cloud");const database=resolveAppDatabase(tsCloudConfig);if(!database||!isLocalDatabase(database))return;const engine=String(database.engine||database.driver||"");if(engine==="sqlite"||engine==="better-sqlite3")return;const name=String(database.name||"");return name?{name}:undefined}async function assertFleetProvider(tsCloudConfig,command){const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(isSshPipelineProvider(provider))return;await log.info("The on-box half (the rpx gateway registry) is provider-independent; the server listing is not yet.");await log.exit(`\`buddy ${command}\` can list Hetzner and ssh servers, and this project's provider is '${provider}'.`,ExitCode.FatalError)}function readSshStatePins(cwd=process.cwd()){const dir=join(cwd,"storage","cloud","state");if(!existsSync(dir))return[];const pins=[];for(const file of readdirSync(dir)){if(!file.endsWith(".json"))continue;try{pins.push(JSON.parse(readFileSync(join(dir,file),"utf8")))}catch{}}return pins}async function listFleet(tsCloudConfig){if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER)==="ssh"){const servers=sshFleetFromConfigAndState(tsCloudConfig,readSshStatePins());return{servers,problem:servers.length===0?"No ssh hosts are configured. Add one under `ssh.hosts` in config/cloud.ts, or set TS_CLOUD_SSH_HOST.":undefined}}const{HetznerClient,toInventoryServer}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken){return{servers:[],problem:"No Hetzner API token, so no servers were looked up. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts)."}}try{const servers=await new HetznerClient({apiToken}).listServers();return{servers:servers.map((server)=>toInventoryServer(server)).sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const status=Number(error?.status);const where=Number.isFinite(status)&&status>0?`returned HTTP ${status}`:"could not be reached";return{servers:[],problem:`The Hetzner API ${where}, so the server list is incomplete. ${error?.message??String(error)}`+(status===401||status===403?" That is an auth failure, not an empty project: check the token is valid for this Hetzner project.":"")}}}async function declaredSitesFor(tsCloudConfig,slug){const{resolveSiteKind,siteInstallBase}=await import("@stacksjs/ts-cloud");return Object.entries(tsCloudConfig?.sites??{}).map(([name,site])=>{const domain=typeof site?.domain==="string"&&site.domain.trim()?site.domain.trim():undefined;const port=Number(site?.port);return{name,kind:resolveSiteKind(site),domain,path:typeof site?.path==="string"&&site.path.trim()?site.path.trim():"/",port:Number.isFinite(port)&&port>0?port:undefined,installBase:siteInstallBase(slug,name),loopbackOnly:!domain}})}function describeAttachEdits(slug,owner,edit,dryRun){const lines=[" Two edits make the attach real, in two different repositories:",""];if(edit.state==="refused"){lines.push(` 1. config/cloud.ts here: could not edit it (${edit.reason})`);lines.push(` Add \`attachTo: '${owner}'\` to the \`cloud\` block by hand.`)}else if(edit.state==="already-set"){lines.push(` 1. config/cloud.ts here: already sets attachTo: '${owner}'. Nothing to do.`)}else{lines.push(` 1. config/cloud.ts here: ${dryRun?`would set attachTo: '${owner}' (--dry-run, not written)`:`set attachTo: '${owner}'`}`)}lines.push("");lines.push(` 2. In the '${owner}' project's own repository, which this command cannot edit:`);lines.push(` add '${slug}' to the \`tenants\` array in its config/cloud.ts.`);lines.push(` Without it, that project's deploy ships ${slug.toUpperCase()}_* keys from its`);lines.push(" env files into this project's .env instead of dropping them.");lines.push("");lines.push(" Then `buddy deploy` from here puts these sites on that box.");return lines}async function runCloudDiff(){try{const{InfrastructureGenerator}=await import("@stacksjs/ts-cloud");const{tsCloud:cloudConfig}=await import(p.projectPath("config/cloud"));const environment=cloudEnvironment();const template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().toJSON();const result=await diffStackTemplate(template,{config:cloudConfig});if(result.isErr)return result.error.message;const diff=result.value;if(!diff.deployed)log.info(`${diff.stack} is not deployed in ${diff.region}. The whole template (${diff.localBytes} bytes) is new.`);else if(!diff.changed)log.info(`No changes detected against ${diff.stack} (${diff.region}).`);else{log.info(`Changes detected between ${diff.stack} (${diff.region}) and the local template:`);log.info(`Deployed template: ${diff.deployedBytes} bytes`);log.info(`Local template: ${diff.localBytes} bytes`)}return}catch(error){return error instanceof Error?error.message:String(error)}}export function cloud(buddy){buddy.command("cloud:apply","Apply configured server size, persistent volumes and deployment storage").option("--env [env]","Environment to reconcile",{default:"production"}).option("--dry-run","Show the compute plan without changing anything",{default:false}).option("--yes","Apply the displayed plan without prompting",{default:false}).option("-J, --json","Print the plan as JSON",{default:false}).action(async(options)=>{try{const{createCloudDriver}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const config=await loadTsCloudConfig(options.env);if(!config?.project?.slug)throw new Error("config/cloud.ts must declare tsCloud.project.slug");const environment=options.env||"production";const nativeConfig=config;const driver=createCloudDriver({config:nativeConfig});if(!driver.applyComputeChanges)throw new Error("This cloud provider does not support configured compute changes");const plan=await driver.applyComputeChanges({config:nativeConfig,environment,dryRun:true});if(options.json)console.log(JSON.stringify(plan,null,2));else{for(const change of plan.changes)await log.info(`${change.resource}: ${change.action} (${change.detail})`);if(plan.waitingForCapacity)await log.warn(plan.waitingForCapacity)}if(options.dryRun)return;if(!await confirmCloudChange(options,"buddy cloud:apply --yes","Apply these compute changes?","apply compute changes"))return;const applied=await driver.applyComputeChanges({config:nativeConfig,environment});if(applied.waitingForCapacity)await log.warn(applied.waitingForCapacity);await log.success("Configured compute changes applied")}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exitCode=ExitCode.FatalError}});const descriptions={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",dashboard:"Run the local Stacks Cloud management cockpit (servers, sites, deploys)",sites:"List every server and what each one is hosting, across projects",attach:"Attach this project to a server another project owns, after checking it is safe",rename:"Rename a server in place, keeping the provider, state pin, hostname and inventory in step",renameTo:"The new server name",renameEnv:"Environment whose fleet and state pin to rename in",renameJson:"Emit the rename plan as JSON",destroy:"Destroy a drained server, once nothing on it is anyone's rollback",destroyEnv:"Environment whose fleet and state pin the server belongs to",destroyJson:"Emit the teardown plan as JSON",destroyConfirm:"The exact server name, which an irreversible step requires before it runs",destroyDiscardDrained:"Destroy it even though it still holds site trees that are somebody's rollback",move:"Move a deployed site to another server, cutting DNS over once the target serves it",moveTo:"Server to move the site to, by provider name or by owning project slug",moveFrom:"Server the site is on now, when more than one could be serving it",moveEnv:"Environment whose fleet and sites to move within",moveJson:"Emit the move plan as JSON",moveConfirm:"The exact site name, which the irreversible steps require before they run",attachServer:"Server to attach to, by provider name or by owning project slug",dryRun:"Print the plan and change nothing",sitesEnv:"Environment to take the inventory for",remote:"Skip the SSH read of each box's gateway registry (co-tenants are then not listed)",json:"Emit the inventory as JSON",host:"Host to bind the dashboard to",port:"Port to bind the dashboard to",env:"Environment to manage",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("cloud",descriptions.cloud).option("--ssh",descriptions.ssh,{default:false}).option("--connect",descriptions.ssh,{default:false}).option("--invalidate-cache",descriptions.invalidateCache,{default:false}).option("--paths [paths]",descriptions.paths).option("-y, --yes","Invalidate the CDN cache without asking first",{default:false}).option("--diff",descriptions.diff,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud` ...",options);const startTime=performance.now();if(options.ssh||options.connect){const jumpBox=await addJumpBox();if(isResultError(jumpBox)){await outro("Could not find the jump box",{startTime,useSeconds:true},getResultError(jumpBox));process.exit(ExitCode.FatalError)}const{message,state}=getResultValue(jumpBox);if(!state.instanceId){log.info(message);await outro("There is no jump box to connect to",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}const result=await runCommand(["aws","ssm","start-session","--target",state.instanceId,"--region",state.region],{...options,cwd:p.projectPath(),stdin:"inherit",stdout:"inherit"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(options.invalidateCache){const confirm=await confirmInvalidation(options,"buddy cloud --invalidate-cache --yes","Would you like to invalidate the CDN (CloudFront) cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const{AWSCloudFrontClient}=await import("@stacksjs/ts-cloud");const cloudfront=new AWSCloudFrontClient;const distributionId=await getCloudFrontDistributionId();try{const invalidationId=await cloudfront.invalidateAll(distributionId);log.success(`Invalidation created: ${invalidationId}`);log.info(`Status: pending`)}catch(err){log.error(`Failed to invalidate CloudFront cache: ${err.message}`)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(options.diff){const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:add",descriptions.add).option("--jump-box","Check for the jump box, and say how to declare one if the stack has none",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:add` ...",options);const startTime=await intro("buddy cloud:add");if(options.jumpBox){const result=await addJumpBox();if(isResultError(result)){await outro("While running the cloud:add command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No jump box was added.",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has a jump box.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("This functionality is not yet implemented.");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:remove",descriptions.remove).alias("cloud:rm").alias("undeploy").option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:false}).option("-y, --yes","Skip the confirmation prompt",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:remove` ...",options);const startTime=await intro("buddy cloud:remove");const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While removing your jump-box, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("The jump box was not removed.",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has no jump box.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(!options.yes&&(isCI||!hasTTY||!process.stdin.isTTY)){log.syncError(`Refusing to remove the "${environment}" cloud infrastructure from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\` to confirm (e.g. in CI): \`buddy cloud:remove --yes\``);await outro("cloud:remove cancelled.",{startTime,useSeconds:true,type:"warning"});await log.flush();process.exit(ExitCode.FatalError)}if(!options.yes){log.warning(`This will permanently delete the "${environment}" cloud infrastructure (compute, storage, CDN, and DNS managed by Stacks). This cannot be undone.`);const typed=await text({message:`Type the environment name "${environment}" to confirm (blank to cancel):`});if(typed.trim()!==environment){await outro("cloud:remove cancelled - confirmation did not match.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}}console.log("");console.log("Removing cloud infrastructure...");console.log(` ${italic("This typically takes 2-5 minutes.")}`);console.log("");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs");const{projectPath}=await import("@stacksjs/path");const envFiles=[projectPath(`.env.${environment}`),projectPath(".env")];for(const envPath of envFiles){if(existsSync(envPath)){const envContent=readFileSync(envPath,"utf-8");const lines=envContent.split(`
|
|
5
|
-
`);for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").replace(/^["']|["']$/g,"");if(key==="AWS_ACCESS_KEY_ID"||key==="AWS_SECRET_ACCESS_KEY"||key==="AWS_REGION"||key==="AWS_ACCOUNT_ID"){process.env[key]=value}}break}}}delete process.env.AWS_PROFILE;try{const{undeployStack}=await import("@stacksjs/actions/deploy/stack");const region=await stacksCloudRegion(undefined,environment);await undeployStack({environment,region,verbose:options.verbose});await outro("Cloud infrastructure removed",{startTime,useSeconds:true});process.exit(ExitCode.Success)}catch(error){console.log("");console.error("✗ Failed to remove cloud infrastructure");const errorStr=String(error.message||error);if(errorStr.includes("security token")||errorStr.includes("credentials")){console.log("");console.error(" AWS credentials are invalid or expired");console.log(" Check your AWS credentials in .env.production:");console.log(" - AWS_ACCESS_KEY_ID");console.log(" - AWS_SECRET_ACCESS_KEY")}else if(errorStr.includes("region")||errorStr.includes("AWS_REGION")){console.log("");console.error(" AWS Region not configured");console.log(" Add AWS_REGION to your .env.production file")}else if(errorStr.includes("AccessDenied")){console.log("");console.error(" Access denied");console.log(" Your AWS credentials may not have permission to delete stacks")}else{console.error(` ${errorStr}`)}console.log("");console.log("Troubleshooting:");console.log(" ./buddy cloud:cleanup - Clean up resources manually");console.log(" --verbose - Show detailed error information");console.log("");if(options.verbose){console.error("Error details:",error)}await outro("Failed to remove infrastructure",{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}});buddy.command("cloud:optimize-cost",descriptions.optimizeCost).option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:true}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:optimize-cost` ...",options);const startTime=await intro("buddy cloud:optimize-cost");if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While checking your jump-box, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No cost optimization was applied",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}}await outro("No cost optimization was applied",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:cleanup",descriptions.cleanUp).alias("cloud:clean-up").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:cleanup` ...",options);const startTime=await intro("buddy cloud:cleanup");delete process.env.AWS_PROFILE;log.info(`Cleaning up your cloud resources will take a while to complete. Please be patient.`);await new Promise((resolve)=>setTimeout(resolve,2000));const cleanupSteps=[{label:"retained S3 buckets",fn:deleteStacksBuckets},{label:"retained Lambda functions",fn:deleteStacksFunctions,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:deleteLogGroups},{label:"stored parameters",fn:deleteParameterStore},{label:"VPCs",fn:deleteVpcs},{label:"Subnets",fn:deleteSubnets},{label:"CDK remnants",fn:deleteCdkRemnants},{label:"IAM users",fn:deleteIamUsers}];const errors=[];for(const step of cleanupSteps){log.info(`Removing any ${step.label}...`);try{const result=await step.fn();if(isResultError(result)){const errMsg=getResultError(result);if(!step.ignoreErrors?.includes(errMsg)){log.warn(`${step.label} cleanup issue: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}else{const value=getResultValue(result);if(value)log.info(String(value))}}catch(e){const errMsg=e.message||"AWS SDK error";log.warn(`${step.label} cleanup skipped: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}if(errors.length>0){log.warn(`Cleanup completed with ${errors.length} issue(s):`);for(const{label,error}of errors){log.warn(` - ${label}: ${error}`)}}await outro("AWS resources have been removed",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:invalidate-cache",descriptions.invalidateCache).option("--paths [paths]",descriptions.paths,{default:false}).option("-y, --yes","Invalidate without asking first",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:invalidate-cache` ...",options);const startTime=await intro("buddy cloud:invalidate-cache");const confirm=await confirmInvalidation(options,"buddy cloud:invalidate-cache --yes","Would you like to invalidate the CloudFront cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const distributionId=await getCloudFrontDistributionId();if(!distributionId){await outro("Could not resolve CloudFront distribution ID",{startTime,useSeconds:true},"Ensure your cloud stack is deployed before invalidating cache.");process.exit(ExitCode.FatalError)}const paths=options.paths?String(options.paths):"/*";const result=await runCommand(`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths ${paths}`,{...options,cwd:p.projectPath(),stdin:"pipe",stdout:"pipe"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:diff",descriptions.diff).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:diff` ...",options);const startTime=await intro("buddy cloud:diff");const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:dashboard",descriptions.dashboard).alias("cloud:cockpit").option("--host [host]",descriptions.host,{default:"127.0.0.1"}).option("--port [port]",descriptions.port,{default:"7676"}).option("--env [env]",descriptions.env).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:dashboard` ...",options);const startTime=await intro("buddy cloud:dashboard");const tsCloud=await import("@stacksjs/ts-cloud");if(typeof tsCloud.startLocalDashboardServer!=="function"){await outro("The installed @stacksjs/ts-cloud does not provide the local cockpit yet",{startTime,useSeconds:true},"Update your dependencies (requires @stacksjs/ts-cloud >= 0.5.27).");process.exit(ExitCode.FatalError)}try{const server=await tsCloud.startLocalDashboardServer({host:options.host?String(options.host):undefined,port:options.port?Number(options.port):undefined,environment:options.env,verbose:!!options.verbose});log.success(`Stacks Cloud cockpit running at ${underline(server.url)}`);log.info(italic("Manage servers, sites, SSH keys and deploys. Press Ctrl+C to stop."));await new Promise(()=>{})}catch(error){await outro("While starting the cloud dashboard, there was an issue",{startTime,useSeconds:true},error?.message??String(error));process.exit(ExitCode.FatalError)}});buddy.command("cloud:sites",descriptions.sites).option("--env [env]",descriptions.sitesEnv).option("--no-remote",descriptions.remote).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:sites` ...",options);const{formatInventory,probeHostRoutes}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:sites");const listing=await listFleet(tsCloudConfig);if(listing.problem)await log.error(listing.problem);const declared=await declaredSitesFor(tsCloudConfig,slug);const probes=options.remote===false?[]:await probeFleet(listing.servers);const inventory={slug,servers:listing.servers,probes,declared};if(options.json){console.log(JSON.stringify({environment,...inventory},null,2))}else{for(const line of formatInventory(inventory))console.log(line)}process.exit(listing.problem&&listing.servers.length===0?ExitCode.FatalError:ExitCode.Success);async function probeFleet(servers){const{sshExec}=await import("@stacksjs/ts-cloud");const probes=[];for(let index=0;index<servers.length;index+=6){probes.push(...await Promise.all(servers.slice(index,index+6).map((server)=>probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})))))}return probes}});buddy.command("cloud:attach",descriptions.attach).option("--server <server>",descriptions.attachServer).option("--env [env]",descriptions.sitesEnv).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:attach` ...",options);const{attachConflicts,attachIsViable,attachPreconditions,formatAttachPlan,probeHostRoutes,resolveAttachTarget,setAttachToInCloudConfig,sshExec}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");if(!options.server)return await refuse("Which server? Pass --server <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:attach");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const target=resolveAttachTarget(listing.servers,String(options.server),environment);if("problem"in target)return await refuse(`${target.problem} \`buddy cloud:sites\` lists what is there.`);const server=target.server;const preconditions=attachPreconditions(slug,server);if(preconditions.length>0)return await refuse(...preconditions);const declared=await declaredSitesFor(tsCloudConfig,slug);const probe=await probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10}));const plan={slug,owner:server.project,server,declared,conflicts:probe.unavailable?[]:attachConflicts(slug,declared,probe.routes),registryRead:!probe.unavailable,registryProblem:probe.unavailable};const viable=attachIsViable(plan);const edit=viable?await applyAttachToConfig(plan.owner,Boolean(options.dryRun)):undefined;if(options.json){console.log(JSON.stringify({environment,...plan,edit},null,2))}else{for(const line of formatAttachPlan(plan))console.log(line);if(edit)console.log(["",...describeAttachEdits(plan.slug,plan.owner,edit,Boolean(options.dryRun))].join(`
|
|
4
|
+
`))}};const certArchive=siteMoveCertArchivePath(slug,siteName);effects.certificates={inPlace:async()=>{const read=async(run)=>parseCertificateState(await run(buildCertificateStateScript(DEFAULT_RPX_CERTS_DIR,context.hostnames)));return certificatesMatch(await read(runOnSource),await read(runOnTarget))},carry:async()=>{await runOnSource(buildCertificatePackScript(DEFAULT_RPX_CERTS_DIR,context.hostnames,certArchive));await carry(certArchive);await runOnTarget(buildCertificateUnpackScript(DEFAULT_RPX_CERTS_DIR,certArchive))}};return effects}export async function serverServing(servers,hosts,probe){for(const candidate of servers){if(!candidate?.ipv4)continue;const result=await probe(candidate);if(!result.unavailable&&(result.routes??[]).some((route)=>hosts.includes(String(route.host))))return candidate}return}export async function onBoxDatabase(tsCloudConfig){const{isLocalDatabase,resolveAppDatabase}=await import("@stacksjs/ts-cloud");const database=resolveAppDatabase(tsCloudConfig);if(!database||!isLocalDatabase(database))return;const engine=String(database.engine||database.driver||"");if(engine==="sqlite"||engine==="better-sqlite3")return;const name=String(database.name||"");return name?{name}:undefined}async function assertFleetProvider(tsCloudConfig,command){const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(isSshPipelineProvider(provider))return;await log.info("The on-box half (the rpx gateway registry) is provider-independent; the server listing is not yet.");await log.exit(`\`buddy ${command}\` can list Hetzner and ssh servers, and this project's provider is '${provider}'.`,ExitCode.FatalError)}function readSshStatePins(cwd=process.cwd()){const dir=join(cwd,"storage","cloud","state");if(!existsSync(dir))return[];const pins=[];for(const file of readdirSync(dir)){if(!file.endsWith(".json"))continue;try{pins.push(JSON.parse(readFileSync(join(dir,file),"utf8")))}catch{}}return pins}async function listFleet(tsCloudConfig){if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER)==="ssh"){const servers=sshFleetFromConfigAndState(tsCloudConfig,readSshStatePins());return{servers,problem:servers.length===0?"No ssh hosts are configured. Add one under `ssh.hosts` in config/cloud.ts, or set TS_CLOUD_SSH_HOST.":undefined}}const{HetznerClient,toInventoryServer}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken){return{servers:[],problem:"No Hetzner API token, so no servers were looked up. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts)."}}try{const servers=await new HetznerClient({apiToken}).listServers();return{servers:servers.map((server)=>toInventoryServer(server)).sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const status=Number(error?.status);const where=Number.isFinite(status)&&status>0?`returned HTTP ${status}`:"could not be reached";return{servers:[],problem:`The Hetzner API ${where}, so the server list is incomplete. ${error?.message??String(error)}`+(status===401||status===403?" That is an auth failure, not an empty project: check the token is valid for this Hetzner project.":"")}}}async function declaredSitesFor(tsCloudConfig,slug){const{resolveSiteKind,siteInstallBase}=await import("@stacksjs/ts-cloud");return Object.entries(tsCloudConfig?.sites??{}).map(([name,site])=>{const domain=typeof site?.domain==="string"&&site.domain.trim()?site.domain.trim():undefined;const port=Number(site?.port);return{name,kind:resolveSiteKind(site),domain,path:typeof site?.path==="string"&&site.path.trim()?site.path.trim():"/",port:Number.isFinite(port)&&port>0?port:undefined,installBase:siteInstallBase(slug,name),loopbackOnly:!domain}})}function describeAttachEdits(slug,owner,edit,dryRun){const lines=[" Two edits make the attach real, in two different repositories:",""];if(edit.state==="refused"){lines.push(` 1. config/cloud.ts here: could not edit it (${edit.reason})`);lines.push(` Add \`attachTo: '${owner}'\` to the \`cloud\` block by hand.`)}else if(edit.state==="already-set"){lines.push(` 1. config/cloud.ts here: already sets attachTo: '${owner}'. Nothing to do.`)}else{lines.push(` 1. config/cloud.ts here: ${dryRun?`would set attachTo: '${owner}' (--dry-run, not written)`:`set attachTo: '${owner}'`}`)}lines.push("");lines.push(` 2. In the '${owner}' project's own repository, which this command cannot edit:`);lines.push(` add '${slug}' to the \`tenants\` array in its config/cloud.ts.`);lines.push(` Without it, that project's deploy ships ${slug.toUpperCase()}_* keys from its`);lines.push(" env files into this project's .env instead of dropping them.");lines.push("");lines.push(" Then `buddy deploy` from here puts these sites on that box.");return lines}async function runCloudDiff(){try{const{InfrastructureGenerator}=await import("@stacksjs/ts-cloud");const{tsCloud:cloudConfig}=await import(p.projectPath("config/cloud"));const environment=cloudEnvironment();const template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().toJSON();const result=await diffStackTemplate(template,{config:cloudConfig});if(result.isErr)return result.error.message;const diff=result.value;if(!diff.deployed)log.info(`${diff.stack} is not deployed in ${diff.region}. The whole template (${diff.localBytes} bytes) is new.`);else if(!diff.changed)log.info(`No changes detected against ${diff.stack} (${diff.region}).`);else{log.info(`Changes detected between ${diff.stack} (${diff.region}) and the local template:`);log.info(`Deployed template: ${diff.deployedBytes} bytes`);log.info(`Local template: ${diff.localBytes} bytes`)}return}catch(error){return error instanceof Error?error.message:String(error)}}export function cloud(buddy){buddy.command("cloud:apply","Apply configured server size, persistent volumes and deployment storage").option("--env [env]","Environment to reconcile",{default:"production"}).option("--dry-run","Show the compute plan without changing anything",{default:false}).option("--yes","Apply the displayed plan without prompting",{default:false}).option("-J, --json","Print the plan as JSON",{default:false}).action(async(options)=>{try{const{createCloudDriver}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const config=await loadTsCloudConfig(options.env);if(!config?.project?.slug)throw new Error("config/cloud.ts must declare tsCloud.project.slug");const environment=options.env||"production";const nativeConfig=config;const driver=createCloudDriver({config:nativeConfig});if(!driver.applyComputeChanges)throw new Error("This cloud provider does not support configured compute changes");const plan=await driver.applyComputeChanges({config:nativeConfig,environment,dryRun:true});if(options.json)console.log(JSON.stringify(plan,null,2));else{for(const change of plan.changes)await log.info(`${change.resource}: ${change.action} (${change.detail})`);if(plan.waitingForCapacity)await log.warn(plan.waitingForCapacity)}if(options.dryRun)return;if(!await confirmCloudChange(options,"buddy cloud:apply --yes","Apply these compute changes?","apply compute changes"))return;const applied=await driver.applyComputeChanges({config:nativeConfig,environment});if(applied.waitingForCapacity)await log.warn(applied.waitingForCapacity);await log.success("Configured compute changes applied")}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exitCode=ExitCode.FatalError}});const descriptions={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",dashboard:"Run the local Stacks Cloud management cockpit (servers, sites, deploys)",sites:"List every server and what each one is hosting, across projects",targets:"List deployed sites with what a remote session needs: host, SSH user and key, app path and env file",attach:"Attach this project to a server another project owns, after checking it is safe",rename:"Rename a server in place, keeping the provider, state pin, hostname and inventory in step",renameTo:"The new server name",renameEnv:"Environment whose fleet and state pin to rename in",renameJson:"Emit the rename plan as JSON",destroy:"Destroy a drained server, once nothing on it is anyone's rollback",destroyEnv:"Environment whose fleet and state pin the server belongs to",destroyJson:"Emit the teardown plan as JSON",destroyConfirm:"The exact server name, which an irreversible step requires before it runs",destroyDiscardDrained:"Destroy it even though it still holds site trees that are somebody's rollback",move:"Move a deployed site to another server, cutting DNS over once the target serves it",moveTo:"Server to move the site to, by provider name or by owning project slug",moveFrom:"Server the site is on now, when more than one could be serving it",moveEnv:"Environment whose fleet and sites to move within",moveJson:"Emit the move plan as JSON",moveConfirm:"The exact site name, which the irreversible steps require before they run",attachServer:"Server to attach to, by provider name or by owning project slug",dryRun:"Print the plan and change nothing",sitesEnv:"Environment to take the inventory for",remote:"Skip the SSH read of each box's gateway registry (co-tenants are then not listed)",json:"Emit the inventory as JSON",host:"Host to bind the dashboard to",port:"Port to bind the dashboard to",env:"Environment to manage",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("cloud",descriptions.cloud).option("--ssh",descriptions.ssh,{default:false}).option("--connect",descriptions.ssh,{default:false}).option("--invalidate-cache",descriptions.invalidateCache,{default:false}).option("--paths [paths]",descriptions.paths).option("-y, --yes","Invalidate the CDN cache without asking first",{default:false}).option("--diff",descriptions.diff,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud` ...",options);const startTime=performance.now();if(options.ssh||options.connect){const jumpBox=await addJumpBox();if(isResultError(jumpBox)){await outro("Could not find the jump box",{startTime,useSeconds:true},getResultError(jumpBox));process.exit(ExitCode.FatalError)}const{message,state}=getResultValue(jumpBox);if(!state.instanceId){log.info(message);await outro("There is no jump box to connect to",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}const result=await runCommand(["aws","ssm","start-session","--target",state.instanceId,"--region",state.region],{...options,cwd:p.projectPath(),stdin:"inherit",stdout:"inherit"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(options.invalidateCache){const confirm=await confirmInvalidation(options,"buddy cloud --invalidate-cache --yes","Would you like to invalidate the CDN (CloudFront) cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const{AWSCloudFrontClient}=await import("@stacksjs/ts-cloud");const cloudfront=new AWSCloudFrontClient;const distributionId=await getCloudFrontDistributionId();try{const invalidationId=await cloudfront.invalidateAll(distributionId);log.success(`Invalidation created: ${invalidationId}`);log.info(`Status: pending`)}catch(err){log.error(`Failed to invalidate CloudFront cache: ${err.message}`)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(options.diff){const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:add",descriptions.add).option("--jump-box","Check for the jump box, and say how to declare one if the stack has none",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:add` ...",options);const startTime=await intro("buddy cloud:add");if(options.jumpBox){const result=await addJumpBox();if(isResultError(result)){await outro("While running the cloud:add command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No jump box was added.",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has a jump box.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("This functionality is not yet implemented.");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:remove",descriptions.remove).alias("cloud:rm").alias("undeploy").option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:false}).option("-y, --yes","Skip the confirmation prompt",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:remove` ...",options);const startTime=await intro("buddy cloud:remove");const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While removing your jump-box, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("The jump box was not removed.",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has no jump box.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(!options.yes&&(isCI||!hasTTY||!process.stdin.isTTY)){log.syncError(`Refusing to remove the "${environment}" cloud infrastructure from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\` to confirm (e.g. in CI): \`buddy cloud:remove --yes\``);await outro("cloud:remove cancelled.",{startTime,useSeconds:true,type:"warning"});await log.flush();process.exit(ExitCode.FatalError)}if(!options.yes){log.warning(`This will permanently delete the "${environment}" cloud infrastructure (compute, storage, CDN, and DNS managed by Stacks). This cannot be undone.`);const typed=await text({message:`Type the environment name "${environment}" to confirm (blank to cancel):`});if(typed.trim()!==environment){await outro("cloud:remove cancelled - confirmation did not match.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}}console.log("");console.log("Removing cloud infrastructure...");console.log(` ${italic("This typically takes 2-5 minutes.")}`);console.log("");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs");const{projectPath}=await import("@stacksjs/path");const envFiles=[projectPath(`.env.${environment}`),projectPath(".env")];for(const envPath of envFiles){if(existsSync(envPath)){const envContent=readFileSync(envPath,"utf-8");const lines=envContent.split(`
|
|
5
|
+
`);for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").replace(/^["']|["']$/g,"");if(key==="AWS_ACCESS_KEY_ID"||key==="AWS_SECRET_ACCESS_KEY"||key==="AWS_REGION"||key==="AWS_ACCOUNT_ID"){process.env[key]=value}}break}}}delete process.env.AWS_PROFILE;try{const{undeployStack}=await import("@stacksjs/actions/deploy/stack");const region=await stacksCloudRegion(undefined,environment);await undeployStack({environment,region,verbose:options.verbose});await outro("Cloud infrastructure removed",{startTime,useSeconds:true});process.exit(ExitCode.Success)}catch(error){console.log("");console.error("✗ Failed to remove cloud infrastructure");const errorStr=String(error.message||error);if(errorStr.includes("security token")||errorStr.includes("credentials")){console.log("");console.error(" AWS credentials are invalid or expired");console.log(" Check your AWS credentials in .env.production:");console.log(" - AWS_ACCESS_KEY_ID");console.log(" - AWS_SECRET_ACCESS_KEY")}else if(errorStr.includes("region")||errorStr.includes("AWS_REGION")){console.log("");console.error(" AWS Region not configured");console.log(" Add AWS_REGION to your .env.production file")}else if(errorStr.includes("AccessDenied")){console.log("");console.error(" Access denied");console.log(" Your AWS credentials may not have permission to delete stacks")}else{console.error(` ${errorStr}`)}console.log("");console.log("Troubleshooting:");console.log(" ./buddy cloud:cleanup - Clean up resources manually");console.log(" --verbose - Show detailed error information");console.log("");if(options.verbose){console.error("Error details:",error)}await outro("Failed to remove infrastructure",{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}});buddy.command("cloud:optimize-cost",descriptions.optimizeCost).option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:true}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:optimize-cost` ...",options);const startTime=await intro("buddy cloud:optimize-cost");if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While checking your jump-box, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No cost optimization was applied",{startTime,useSeconds:true,type:"warning"});process.exit(ExitCode.FatalError)}}await outro("No cost optimization was applied",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:cleanup",descriptions.cleanUp).alias("cloud:clean-up").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:cleanup` ...",options);const startTime=await intro("buddy cloud:cleanup");delete process.env.AWS_PROFILE;log.info(`Cleaning up your cloud resources will take a while to complete. Please be patient.`);await new Promise((resolve)=>setTimeout(resolve,2000));const cleanupSteps=[{label:"retained S3 buckets",fn:deleteStacksBuckets},{label:"retained Lambda functions",fn:deleteStacksFunctions,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:deleteLogGroups},{label:"stored parameters",fn:deleteParameterStore},{label:"VPCs",fn:deleteVpcs},{label:"Subnets",fn:deleteSubnets},{label:"CDK remnants",fn:deleteCdkRemnants},{label:"IAM users",fn:deleteIamUsers}];const errors=[];for(const step of cleanupSteps){log.info(`Removing any ${step.label}...`);try{const result=await step.fn();if(isResultError(result)){const errMsg=getResultError(result);if(!step.ignoreErrors?.includes(errMsg)){log.warn(`${step.label} cleanup issue: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}else{const value=getResultValue(result);if(value)log.info(String(value))}}catch(e){const errMsg=e.message||"AWS SDK error";log.warn(`${step.label} cleanup skipped: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}if(errors.length>0){log.warn(`Cleanup completed with ${errors.length} issue(s):`);for(const{label,error}of errors){log.warn(` - ${label}: ${error}`)}}await outro("AWS resources have been removed",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:invalidate-cache",descriptions.invalidateCache).option("--paths [paths]",descriptions.paths,{default:false}).option("-y, --yes","Invalidate without asking first",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:invalidate-cache` ...",options);const startTime=await intro("buddy cloud:invalidate-cache");const confirm=await confirmInvalidation(options,"buddy cloud:invalidate-cache --yes","Would you like to invalidate the CloudFront cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const distributionId=await getCloudFrontDistributionId();if(!distributionId){await outro("Could not resolve CloudFront distribution ID",{startTime,useSeconds:true},"Ensure your cloud stack is deployed before invalidating cache.");process.exit(ExitCode.FatalError)}const paths=options.paths?String(options.paths):"/*";const result=await runCommand(`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths ${paths}`,{...options,cwd:p.projectPath(),stdin:"pipe",stdout:"pipe"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:diff",descriptions.diff).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:diff` ...",options);const startTime=await intro("buddy cloud:diff");const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:dashboard",descriptions.dashboard).alias("cloud:cockpit").option("--host [host]",descriptions.host,{default:"127.0.0.1"}).option("--port [port]",descriptions.port,{default:"7676"}).option("--env [env]",descriptions.env).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:dashboard` ...",options);const startTime=await intro("buddy cloud:dashboard");const tsCloud=await import("@stacksjs/ts-cloud");if(typeof tsCloud.startLocalDashboardServer!=="function"){await outro("The installed @stacksjs/ts-cloud does not provide the local cockpit yet",{startTime,useSeconds:true},"Update your dependencies (requires @stacksjs/ts-cloud >= 0.5.27).");process.exit(ExitCode.FatalError)}try{const server=await tsCloud.startLocalDashboardServer({host:options.host?String(options.host):undefined,port:options.port?Number(options.port):undefined,environment:options.env,verbose:!!options.verbose});log.success(`Stacks Cloud cockpit running at ${underline(server.url)}`);log.info(italic("Manage servers, sites, SSH keys and deploys. Press Ctrl+C to stop."));await new Promise(()=>{})}catch(error){await outro("While starting the cloud dashboard, there was an issue",{startTime,useSeconds:true},error?.message??String(error));process.exit(ExitCode.FatalError)}});buddy.command("cloud:sites",descriptions.sites).option("--env [env]",descriptions.sitesEnv).option("--no-remote",descriptions.remote).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:sites` ...",options);const{formatInventory,probeHostRoutes}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:sites");const listing=await listFleet(tsCloudConfig);if(listing.problem)await log.error(listing.problem);const declared=await declaredSitesFor(tsCloudConfig,slug);const probes=options.remote===false?[]:await probeFleet(listing.servers);const inventory={slug,servers:listing.servers,probes,declared};if(options.json){console.log(JSON.stringify({environment,...inventory},null,2))}else{for(const line of formatInventory(inventory))console.log(line)}process.exit(listing.problem&&listing.servers.length===0?ExitCode.FatalError:ExitCode.Success);async function probeFleet(servers){const{sshExec}=await import("@stacksjs/ts-cloud");const probes=[];for(let index=0;index<servers.length;index+=6){probes.push(...await Promise.all(servers.slice(index,index+6).map((server)=>probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})))))}return probes}});buddy.command("cloud:targets",descriptions.targets).option("--env [env]",descriptions.sitesEnv).option("--no-remote",descriptions.remote).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:targets` ...",options);const cloud=await import("@stacksjs/ts-cloud");if(typeof cloud.listDeployedSites!=="function"){await log.error("`buddy cloud:targets` needs @stacksjs/ts-cloud 0.16.126 or newer. Run `buddy upgrade`.");process.exit(ExitCode.FatalError)}const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const inventory=await cloud.listDeployedSites({config:tsCloudConfig,environment,cwd:process.cwd(),...options.remote===false?{listServers:false}:{}});if(options.json){console.log(JSON.stringify(inventory,null,2))}else{if(inventory.sites.length===0)console.log(`No server-deployed sites for ${inventory.slug} (${environment}).`);for(const site of inventory.sites){const host=site.hosts[0];console.log(`${site.name} ${site.ssh.user}@${host?.address??"(no host resolved)"}:${site.ssh.port} ${site.appPath}`);if(site.envFile)console.log(` env ${site.envFile}`)}for(const skipped of inventory.skipped)console.log(`${skipped.name} (${skipped.kind}: ${skipped.reason})`)}for(const warning of inventory.warnings)await log.warn(warning);process.exit(ExitCode.Success)});buddy.command("cloud:attach",descriptions.attach).option("--server <server>",descriptions.attachServer).option("--env [env]",descriptions.sitesEnv).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:attach` ...",options);const{attachConflicts,attachIsViable,attachPreconditions,formatAttachPlan,probeHostRoutes,resolveAttachTarget,setAttachToInCloudConfig,sshExec}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");if(!options.server)return await refuse("Which server? Pass --server <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:attach");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const target=resolveAttachTarget(listing.servers,String(options.server),environment);if("problem"in target)return await refuse(`${target.problem} \`buddy cloud:sites\` lists what is there.`);const server=target.server;const preconditions=attachPreconditions(slug,server);if(preconditions.length>0)return await refuse(...preconditions);const declared=await declaredSitesFor(tsCloudConfig,slug);const probe=await probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10}));const plan={slug,owner:server.project,server,declared,conflicts:probe.unavailable?[]:attachConflicts(slug,declared,probe.routes),registryRead:!probe.unavailable,registryProblem:probe.unavailable};const viable=attachIsViable(plan);const edit=viable?await applyAttachToConfig(plan.owner,Boolean(options.dryRun)):undefined;if(options.json){console.log(JSON.stringify({environment,...plan,edit},null,2))}else{for(const line of formatAttachPlan(plan))console.log(line);if(edit)console.log(["",...describeAttachEdits(plan.slug,plan.owner,edit,Boolean(options.dryRun))].join(`
|
|
6
6
|
`))}process.exit(viable?ExitCode.Success:ExitCode.FatalError);async function applyAttachToConfig(owner,dryRun){const configPath=p.projectPath("config/cloud.ts");const{readFileSync,writeFileSync}=await import("node:fs");const before=readFileSync(configPath,"utf8");try{const after=setAttachToInCloudConfig({configText:before,owner});if(after===before)return{state:"already-set"};if(dryRun)return{state:"would-write"};writeFileSync(configPath,after);return{state:"written"}}catch(error){return{state:"refused",reason:error instanceof Error?error.message:String(error)}}}});buddy.command("cloud:rename <server>",descriptions.rename).option("--to <name>",descriptions.renameTo).option("--env [env]",descriptions.renameEnv).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.renameJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy cloud:rename` ...",options);const{applyPlan,formatPlan,pendingSteps,planServerRename,resolvePlan,validateServerName}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");if(!options.to)return await refuse("Rename it to what? Pass --to <name>.");const next=String(options.to);try{validateServerName(next)}catch(error){return await refuse(error instanceof Error?error.message:String(error))}const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);await assertFleetProvider(tsCloudConfig,"cloud:rename");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const current=listing.servers.find((s)=>s?.name===server);if(!current)return await refuse(`No server named ${server}. \`buddy cloud:sites\` lists what is there.`);if(server===next)return await refuse(`${server} is already called that.`);const plan=await planServerRename(server,next,await renameEffects(tsCloudConfig,listing.servers,current));const resolved=await resolvePlan(plan);const pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,to:next,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`${server} is already named ${next} everywhere. Nothing to do.`);return}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`)});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`Re-run \`buddy cloud:rename ${server} --to ${next}\` to continue: completed steps skip themselves.`)}await log.success(`Renamed ${server} to ${next}`)});buddy.command("cloud:destroy <server>",descriptions.destroy).option("--env [env]",descriptions.destroyEnv).option("--confirm <name>",descriptions.destroyConfirm).option("--discard-drained",descriptions.destroyDiscardDrained,{default:false}).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.destroyJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy cloud:destroy` ...",options);const{applyPlan,buildDrainedSiteScanScript,formatDrainedSiteRefusal,formatPlan,parseDrainedSites,pendingSteps,resolvePlan,sshExec}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);await assertFleetProvider(tsCloudConfig,"cloud:destroy");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const current=listing.servers.find((s)=>s?.name===server);if(!current)return await refuse(`No server named ${server}. \`buddy cloud:sites\` lists what is there.`);const slug=String(tsCloudConfig?.project?.slug||"app");if(current.ipv4&&!options.discardDrained){const scan=await sshExec(current.ipv4,buildDrainedSiteScanScript(slug).join(`
|
|
7
7
|
`),{user:"root",connectTimeoutSec:10});if(scan.code===0){const drained=parseDrainedSites(scan.stdout);if(drained.length>0)return await refuse(formatDrainedSiteRefusal(drained,slug,"--discard-drained"))}else if(!options.dryRun){return await refuse(`Could not scan ${server} for drained sites: ${scan.stderr.trim()||"the box did not answer over SSH."}`,"A box that cannot be scanned may still be holding a rollback. Re-run with --discard-drained if it is not.")}}const plan=planServerDestroy(server,await destroyEffects(tsCloudConfig,current));const resolved=await resolvePlan(plan);const pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`${server} is already gone, and nothing still points at it.`);return}if(options.confirm!==server){return await refuse(`Destroying ${server} cannot be undone.`,`Re-run with \`--confirm ${server}\` to go ahead.`)}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`Re-run \`buddy cloud:destroy ${server} --confirm ${server}\` to continue: completed steps skip themselves.`)}await log.success(`Destroyed ${server}`)});buddy.command("cloud:move <site>",descriptions.move).option("--to <server>",descriptions.moveTo).option("--from <server>",descriptions.moveFrom).option("--env [env]",descriptions.moveEnv).option("--confirm <site>",descriptions.moveConfirm).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.moveJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(site,options)=>{log.debug("Running `buddy cloud:move` ...",options);const{applyPlan,formatPlan,gatewayHostnames,pendingSteps,planSiteMove,probeHostRoutes,resolveAttachTarget,resolvePlan,siteInstallBase,sshExec}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");if(!options.to)return await refuse("Move it where? Pass --to <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const slug=String(tsCloudConfig?.project?.slug||"app");await assertFleetProvider(tsCloudConfig,"cloud:move");const rawSite=(tsCloudConfig?.sites??{})[site];if(!rawSite)return await refuse(`config/cloud.ts declares no site named '${site}'.`);const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const resolvedTarget=resolveAttachTarget(listing.servers,String(options.to),environment);if("problem"in resolvedTarget)return await refuse(`${resolvedTarget.problem} \`buddy cloud:sites\` lists what is there.`);const target=resolvedTarget.server;const hostnames=gatewayHostnames({[site]:rawSite},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)});const shared=sitesSharingHostnames(tsCloudConfig?.sites??{},site,hostnames,(name,declared)=>gatewayHostnames({[name]:declared},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)}));if(shared.length>0){return await refuse(`'${site}' answers on ${hostnames.join(", ")}, and so do ${shared.length} other site(s): ${shared.join(", ")}.`,"A move repoints the hostname, not the path - so this would carry one tree to the target and send every request for the others to a box that does not have them.","Give the site its own hostname first, or move the whole set to the target and deploy once.")}const source=options.from?listing.servers.find((s)=>s?.name===options.from):await serverServing(listing.servers,hostnames,(candidate)=>probeHostRoutes(candidate,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})));if(!source){return await refuse(options.from?`No server named ${options.from}.`:`Could not tell which server serves '${site}'. Pass --from <name> to say.`)}if(source.name===target.name)return await refuse(`'${site}' is already on ${target.name}.`);if(!source.ipv4||!target.ipv4)return await refuse(`A move needs an address for both boxes, and ${(source.ipv4?target:source).name} has none.`);let plan;try{plan=await planSiteMove({slug,siteName:site,appBase:siteInstallBase(slug,site),from:source.name,to:target.name,targetAddress:target.ipv4,port:Number(rawSite?.port)||undefined,database:await onBoxDatabase(tsCloudConfig)},await moveEffects({tsCloudConfig,slug,siteName:site,rawSite,source,target,hostnames}))}catch(error){return await refuse(error instanceof Error?error.message:String(error))}const resolved=await resolvePlan(plan);const pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,from:source.name,to:target.name,hostnames,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`'${site}' is already on ${target.name}, serving and cut over.`);return}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`The source still holds the site's files - that is the rollback. Re-run \`buddy cloud:move ${site} --to ${target.name}\` to continue: completed steps skip themselves.`)}await log.success(`Moved '${site}' from ${source.name} to ${target.name}`)});onUnknownSubcommand(buddy,"cloud")}export async function confirmInvalidation(options,retry,question){return confirmCloudChange(options,retry,question,"invalidate the CDN cache")}export async function confirmCloudChange(options,retry,question,action){if(options.yes)return true;if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError(`Refusing to ${action} from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\`: \`${retry}\``);await log.flush();process.exit(ExitCode.FatalError)}return await prompts.confirm(question)}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CLI } from '@stacksjs/types';
|
|
2
|
+
/**
|
|
3
|
+
* The environment `release:desktop` hands the build and release actions.
|
|
4
|
+
* Flags win over what is already set, so a terminal can override CI secrets
|
|
5
|
+
* for one run; nothing is cleared.
|
|
6
|
+
*/
|
|
7
|
+
export declare function releaseDesktopEnvironment(options: ReleaseDesktopOptions, env?: Record<string, string | undefined>): Record<string, string>;
|
|
8
|
+
export declare function desktopRelease(buddy: CLI): void;
|
|
9
|
+
declare interface ReleaseDesktopOptions {
|
|
10
|
+
target?: string
|
|
11
|
+
identity?: string
|
|
12
|
+
notaryProfile?: string
|
|
13
|
+
channel?: string
|
|
14
|
+
notes?: string
|
|
15
|
+
skipBuild?: boolean
|
|
16
|
+
dryRun?: boolean
|
|
17
|
+
allowDirty?: boolean
|
|
18
|
+
verbose?: boolean
|
|
19
|
+
}
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function releaseDesktopEnvironment(options,env=process.env){const set={};if(options.target)set.DESKTOP_TARGETS=options.target;if(options.identity)set.DESKTOP_SIGNING_IDENTITY=options.identity;if(options.notaryProfile)set.DESKTOP_NOTARY_PROFILE=options.notaryProfile;if(options.channel)set.DESKTOP_RELEASE_CHANNEL=options.channel;if(options.notes)set.DESKTOP_RELEASE_NOTES=options.notes;if(options.dryRun)set.DESKTOP_RELEASE_DRY_RUN="1";if(options.allowDirty)set.DESKTOP_RELEASE_ALLOW_DIRTY="1";if(!env.DESKTOP_PACKAGE)set.DESKTOP_PACKAGE="1";return set}export function desktopRelease(buddy){buddy.command("desktop:update:keypair","Generate the Ed25519 keypair that signs a desktop app's update manifests").option("--key-id <id>","The name the app knows the key by",{default:"main"}).option("--json","Print the keypair as JSON",{default:false}).example("buddy desktop:update:keypair").example("buddy desktop:update:keypair --key-id release-2026").action(async(options)=>{try{const{generateUpdateKeypair}=await import("@stacksjs/desktop-build");const pair=generateUpdateKeypair(options.keyId);if(options.json){process.stdout.write(`${JSON.stringify(pair,null,2)}
|
|
2
|
+
`);return}process.stdout.write(["Public key. Add it to config/desktop.ts, where every build of the app carries it:","",` webview: { updates: { publicKeys: { ${JSON.stringify(pair.keyId)}: ${JSON.stringify(pair.publicKey)} } } }`,"","Private key. It signs every update, so keep it out of the repository (a password manager, a CI secret):","",` DESKTOP_UPDATE_PRIVATE_KEY=${pair.privateKey}`,"","It is shown once. Anyone who holds it can publish an update the app will accept, and an app built with","this public key takes updates from no other key: a lost private key means shipping a new build by hand.",""].join(`
|
|
3
|
+
`))}catch(error){process.stderr.write(`${error instanceof Error?error.message:String(error)}
|
|
4
|
+
`);process.exit(1)}});buddy.command("release:desktop","Build, sign and notarize the web view desktop app, and publish it with signed update manifests").option("--target <targets>","Comma-separated targets (darwin-arm64, linux-x64, win32-x64, ...) or all. Default: this machine").option("--identity <identity>","macOS: Developer ID Application certificate (or DESKTOP_SIGNING_IDENTITY)").option("--notary-profile <profile>","macOS: notarytool keychain profile (or DESKTOP_NOTARY_PROFILE)").option("--channel <channel>","Release channel (default: webview.updates.channel, else stable)").option("--notes <file>","Release notes, shown by the app before it updates").option("--skip-build","Release what `buddy build:desktop` already made (installers built on another machine)",{default:false}).option("--dry-run","Do everything except notarize and upload; write the signed manifests locally",{default:false}).option("--allow-dirty","Release from a working tree with uncommitted changes",{default:false}).option("--verbose","Enable verbose output",{default:false}).example('buddy release:desktop --identity "Developer ID Application: Example (ABCDE12345)" --notary-profile example').example("buddy release:desktop --target linux-x64 --skip-build").action(async(options)=>{const perf=await intro("buddy release:desktop");const{hasWebviewDesktop}=await import("@stacksjs/desktop-build");if(!await hasWebviewDesktop(projectPath())){await log.error("config/desktop.ts has no webview section. `release:desktop` releases a web view desktop app; a Mac App Store app is `desktop:apple:publish`.");process.exit(ExitCode.FatalError)}Object.assign(process.env,releaseDesktopEnvironment(options));for(const action of options.skipBuild?[Action.ReleaseDesktop]:[Action.BuildDesktopWebview,Action.ReleaseDesktop]){const result=await runAction(action,options);if(resultFailed(result)){await outro("While running the release:desktop command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}}await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)})}
|
package/dist/commands/dev.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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("-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}=await import("@stacksjs/desktop-build");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 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.")}
|
|
2
2
|
`);return}if(!createApp){console.log(` ${dim("Native window unavailable. The Craft SDK did not export createApp.")}
|
|
3
3
|
`);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
4
|
`);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")}
|
package/dist/commands/index.d.ts
CHANGED
package/dist/commands/index.js
CHANGED
|
@@ -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"./http";export*from"./install";export*from"./key";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"./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";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CLI } from '@stacksjs/types';
|
|
2
|
+
/**
|
|
3
|
+
* `buddy license:keygen`
|
|
4
|
+
*
|
|
5
|
+
* Generates the Ed25519 keypair that signs offline license tokens
|
|
6
|
+
* (`@stacksjs/commerce` `licensing`). The private half goes in the server's
|
|
7
|
+
* environment; the public half is embedded in the app, which verifies tokens
|
|
8
|
+
* with it and never needs the private one.
|
|
9
|
+
*
|
|
10
|
+
* Prints and writes nothing to disk: the private key is a secret, and where it
|
|
11
|
+
* lives (an encrypted `.env`, a CI secret, a vault) is the operator's call.
|
|
12
|
+
*/
|
|
13
|
+
export declare function license(buddy: CLI): void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import process from"node:process";import{onUnknownSubcommand}from"@stacksjs/cli";export function license(buddy){buddy.command("license:keygen","Generate the Ed25519 keypair that signs software license tokens").option("--key-id <id>","The id apps look the public key up by (defaults to license-<today>)").option("--json","Print the keypair as JSON",{default:false}).example("buddy license:keygen").example("buddy license:keygen --key-id license-2026").action(async(options)=>{const{generateLicenseSigningKeypair}=await import("@stacksjs/commerce/licensing/token");let keypair;try{keypair=generateLicenseSigningKeypair(typeof options.keyId==="string"&&options.keyId?options.keyId:undefined)}catch(error){console.error(error instanceof Error?error.message:String(error));process.exit(1)}if(options.json){console.log(JSON.stringify(keypair,null,2));return}console.log(["","Server environment (secret, shown once; store it encrypted with `buddy env:set`):","",` LICENSE_SIGNING_KEY=${keypair.privateKey}`,` LICENSE_SIGNING_KEY_ID=${keypair.keyId}`,"","App (public, safe to commit; pass as `publicKeys` to createLicenseClient):","",` { '${keypair.keyId}': '${keypair.publicKey}' }`,"","To rotate later, generate a new pair, ship an app build that trusts both","key ids, then switch the server to the new private key.",""].join(`
|
|
2
|
+
`))});onUnknownSubcommand(buddy,"license")}
|
package/dist/lazy-commands.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==undefined)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},screenshot:{path:"./commands/screenshot.js",load:()=>import("./commands/screenshot.js"),exportName:"screenshot"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:style-guide":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}};const commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]};const loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader){return false}let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return true;set.add(key);try{const module=await loader.load();const commandFunction=module[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return true}else{return false}}catch{return false}}export async function loadCommands(commandNames,buddy){const seen=new Set;const unique=[];for(const name of commandNames){const loader=commandRegistry[name];const key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands){await loadCommands(commands,buddy)}}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0];const isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v";const isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h";const isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list"){return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")]}if(commandRegistry[requestedCommand]){return[requestedCommand]}if(commandRegistry[baseCommand]){return[baseCommand]}return Object.keys(commandRegistry)}
|
|
1
|
+
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==undefined)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:update:keypair":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"release:desktop":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},license:{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},"license:keygen":{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},screenshot:{path:"./commands/screenshot.js",load:()=>import("./commands/screenshot.js"),exportName:"screenshot"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:style-guide":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}};const commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]};const loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader){return false}let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return true;set.add(key);try{const module=await loader.load();const commandFunction=module[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return true}else{return false}}catch{return false}}export async function loadCommands(commandNames,buddy){const seen=new Set;const unique=[];for(const name of commandNames){const loader=commandRegistry[name];const key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands){await loadCommands(commands,buddy)}}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0];const isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v";const isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h";const isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list"){return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")]}if(commandRegistry[requestedCommand]){return[requestedCommand]}if(commandRegistry[baseCommand]){return[baseCommand]}return Object.keys(commandRegistry)}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/buddy",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.548",
|
|
6
6
|
"description": "Meet Buddy. The Stacks runtime.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -95,70 +95,70 @@
|
|
|
95
95
|
"prepublishOnly": "bun run build"
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@stacksjs/actions": "0.75.
|
|
99
|
-
"@stacksjs/docs": "0.75.
|
|
100
|
-
"@stacksjs/ai": "0.75.
|
|
101
|
-
"@stacksjs/alias": "0.75.
|
|
102
|
-
"@stacksjs/analytics": "0.75.
|
|
103
|
-
"@stacksjs/api": "0.75.
|
|
104
|
-
"@stacksjs/arrays": "0.75.
|
|
105
|
-
"@stacksjs/auth": "0.75.
|
|
106
|
-
"@stacksjs/browser-extension": "0.75.
|
|
107
|
-
"@stacksjs/build": "0.75.
|
|
98
|
+
"@stacksjs/actions": "0.75.548",
|
|
99
|
+
"@stacksjs/docs": "0.75.548",
|
|
100
|
+
"@stacksjs/ai": "0.75.548",
|
|
101
|
+
"@stacksjs/alias": "0.75.548",
|
|
102
|
+
"@stacksjs/analytics": "0.75.548",
|
|
103
|
+
"@stacksjs/api": "0.75.548",
|
|
104
|
+
"@stacksjs/arrays": "0.75.548",
|
|
105
|
+
"@stacksjs/auth": "0.75.548",
|
|
106
|
+
"@stacksjs/browser-extension": "0.75.548",
|
|
107
|
+
"@stacksjs/build": "0.75.548",
|
|
108
108
|
"@stacksjs/bumpx": "^0.2.26",
|
|
109
|
-
"@stacksjs/cache": "0.75.
|
|
110
|
-
"@stacksjs/chat": "0.75.
|
|
109
|
+
"@stacksjs/cache": "0.75.548",
|
|
110
|
+
"@stacksjs/chat": "0.75.548",
|
|
111
111
|
"@stacksjs/clapp": "^0.2.16",
|
|
112
|
-
"@stacksjs/cli": "0.75.
|
|
113
|
-
"@stacksjs/cloud": "0.75.
|
|
114
|
-
"@stacksjs/cms": "0.75.
|
|
115
|
-
"@stacksjs/collections": "0.75.
|
|
116
|
-
"@stacksjs/commerce": "0.75.
|
|
117
|
-
"@stacksjs/config": "0.75.
|
|
118
|
-
"@stacksjs/database": "0.75.
|
|
119
|
-
"@stacksjs/desktop-build": "0.75.
|
|
120
|
-
"@stacksjs/dns": "0.75.
|
|
112
|
+
"@stacksjs/cli": "0.75.548",
|
|
113
|
+
"@stacksjs/cloud": "0.75.548",
|
|
114
|
+
"@stacksjs/cms": "0.75.548",
|
|
115
|
+
"@stacksjs/collections": "0.75.548",
|
|
116
|
+
"@stacksjs/commerce": "0.75.548",
|
|
117
|
+
"@stacksjs/config": "0.75.548",
|
|
118
|
+
"@stacksjs/database": "0.75.548",
|
|
119
|
+
"@stacksjs/desktop-build": "0.75.548",
|
|
120
|
+
"@stacksjs/dns": "0.75.548",
|
|
121
121
|
"@stacksjs/dnsx": "^0.2.3",
|
|
122
|
-
"@stacksjs/email": "0.75.
|
|
123
|
-
"@stacksjs/enums": "0.75.
|
|
124
|
-
"@stacksjs/env": "0.75.
|
|
125
|
-
"@stacksjs/error-handling": "0.75.
|
|
126
|
-
"@stacksjs/events": "0.75.
|
|
127
|
-
"@stacksjs/features": "0.75.
|
|
128
|
-
"@stacksjs/git": "0.75.
|
|
122
|
+
"@stacksjs/email": "0.75.548",
|
|
123
|
+
"@stacksjs/enums": "0.75.548",
|
|
124
|
+
"@stacksjs/env": "0.75.548",
|
|
125
|
+
"@stacksjs/error-handling": "0.75.548",
|
|
126
|
+
"@stacksjs/events": "0.75.548",
|
|
127
|
+
"@stacksjs/features": "0.75.548",
|
|
128
|
+
"@stacksjs/git": "0.75.548",
|
|
129
129
|
"@stacksjs/gitit": "^0.2.5",
|
|
130
|
-
"@stacksjs/health": "0.75.
|
|
130
|
+
"@stacksjs/health": "0.75.548",
|
|
131
131
|
"@stacksjs/httx": "^0.1.10",
|
|
132
|
-
"@stacksjs/image": "0.75.
|
|
133
|
-
"@stacksjs/lint": "0.75.
|
|
134
|
-
"@stacksjs/logging": "0.75.
|
|
135
|
-
"@stacksjs/notifications": "0.75.
|
|
136
|
-
"@stacksjs/objects": "0.75.
|
|
137
|
-
"@stacksjs/orm": "0.75.
|
|
138
|
-
"@stacksjs/path": "0.75.
|
|
139
|
-
"@stacksjs/payments": "0.75.
|
|
140
|
-
"@stacksjs/realtime": "0.75.
|
|
141
|
-
"@stacksjs/router": "0.75.
|
|
132
|
+
"@stacksjs/image": "0.75.548",
|
|
133
|
+
"@stacksjs/lint": "0.75.548",
|
|
134
|
+
"@stacksjs/logging": "0.75.548",
|
|
135
|
+
"@stacksjs/notifications": "0.75.548",
|
|
136
|
+
"@stacksjs/objects": "0.75.548",
|
|
137
|
+
"@stacksjs/orm": "0.75.548",
|
|
138
|
+
"@stacksjs/path": "0.75.548",
|
|
139
|
+
"@stacksjs/payments": "0.75.548",
|
|
140
|
+
"@stacksjs/realtime": "0.75.548",
|
|
141
|
+
"@stacksjs/router": "0.75.548",
|
|
142
142
|
"@stacksjs/rpx": "^0.11.54",
|
|
143
|
-
"@stacksjs/scheduler": "0.75.
|
|
144
|
-
"@stacksjs/search-engine": "0.75.
|
|
145
|
-
"@stacksjs/security": "0.75.
|
|
146
|
-
"@stacksjs/server": "0.75.
|
|
147
|
-
"@stacksjs/sites": "0.75.
|
|
148
|
-
"@stacksjs/skills": "0.75.
|
|
149
|
-
"@stacksjs/socials": "0.75.
|
|
150
|
-
"@stacksjs/storage": "0.75.
|
|
151
|
-
"@stacksjs/strings": "0.75.
|
|
143
|
+
"@stacksjs/scheduler": "0.75.548",
|
|
144
|
+
"@stacksjs/search-engine": "0.75.548",
|
|
145
|
+
"@stacksjs/security": "0.75.548",
|
|
146
|
+
"@stacksjs/server": "0.75.548",
|
|
147
|
+
"@stacksjs/sites": "0.75.548",
|
|
148
|
+
"@stacksjs/skills": "0.75.548",
|
|
149
|
+
"@stacksjs/socials": "0.75.548",
|
|
150
|
+
"@stacksjs/storage": "0.75.548",
|
|
151
|
+
"@stacksjs/strings": "0.75.548",
|
|
152
152
|
"@stacksjs/stx": "^0.2.842",
|
|
153
|
-
"@stacksjs/testing": "0.75.
|
|
154
|
-
"@stacksjs/tinker": "0.75.
|
|
153
|
+
"@stacksjs/testing": "0.75.548",
|
|
154
|
+
"@stacksjs/tinker": "0.75.548",
|
|
155
155
|
"@stacksjs/tlsx": "^0.13.19",
|
|
156
|
-
"@stacksjs/ts-cloud": "^0.16.
|
|
157
|
-
"@stacksjs/tunnel": "0.75.
|
|
158
|
-
"@stacksjs/types": "0.75.
|
|
159
|
-
"@stacksjs/ui": "0.75.
|
|
160
|
-
"@stacksjs/utils": "0.75.
|
|
161
|
-
"@stacksjs/validation": "0.75.
|
|
156
|
+
"@stacksjs/ts-cloud": "^0.16.126",
|
|
157
|
+
"@stacksjs/tunnel": "0.75.548",
|
|
158
|
+
"@stacksjs/types": "0.75.548",
|
|
159
|
+
"@stacksjs/ui": "0.75.548",
|
|
160
|
+
"@stacksjs/utils": "0.75.548",
|
|
161
|
+
"@stacksjs/validation": "0.75.548",
|
|
162
162
|
"ajv": "^8.20.0",
|
|
163
163
|
"ajv-formats": "^3.0.1",
|
|
164
164
|
"bun-plugin-stx": "^0.2.842",
|