@stacksjs/buddy 0.75.86 → 0.75.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes:!0})){const rel=prefix?`${prefix}/${entry.name}`:entry.name;if(entry.isDirectory())out.push(...filesUnder(join(dir,entry.name),rel));else out.push(rel)}return out}function matchesTemplate(projectFile,templateFile){if(!existsSync(templateFile))return!1;try{return readFileSync(projectFile).equals(readFileSync(templateFile))}catch{return!1}}function pruneEmptyDirs(root,dir){let current=dir;while(current.startsWith(root)&&current!==root){try{if(readdirSync(current).length>0)return;rmdirSync(current)}catch{return}current=join(current,"..")}}export async function deleteFeatureFiles(feature,root=projectPath(),options={}){const source=options.source??frameworkPath("defaults"),force=options.force===!0,dryRun=options.dryRun===!0,remove=async(path,recursive=!1)=>{if(!dryRun)await rm(path,{recursive,force:!0})},removed=[],preserved=[];for(const rel of FEATURE_FILES[feature]){const full=join(root,rel);if(!existsSync(full))continue;if(force){await remove(full,!0);removed.push(rel);continue}const template=join(source,rel);if(!statSync(full).isDirectory()){if(matchesTemplate(full,template)){await remove(full);removed.push(rel)}else preserved.push(rel);continue}let keptAny=!1;for(const child of filesUnder(full)){const projectFile=join(full,child);if(matchesTemplate(projectFile,join(template,child))){await remove(projectFile);removed.push(`${rel}${child}`)}else{keptAny=!0;preserved.push(`${rel}${child}`)}}if(dryRun)continue;pruneEmptyDirs(root,full);if(!keptAny&&existsSync(full))await rm(full,{recursive:!0,force:!0})}return{removed,preserved}}export async function copyFeatureFiles(feature,options={}){const source=options.source??frameworkPath("defaults"),target=options.target??projectPath(),force=options.force===!0,copied=[],skipped=[];for(const rel of FEATURE_FILES[feature]){const sourceFull=join(source,rel);if(!existsSync(sourceFull)){skipped.push(rel);continue}const targetFull=join(target,rel);if(existsSync(targetFull)&&!force){skipped.push(rel);continue}if(options.dryRun!==!0)await cp(sourceFull,targetFull,{recursive:!0,force});copied.push(rel)}return{copied,skipped}}const FEATURE_DESCRIPTIONS={dashboard:"Admin SPA shell + Activity/Log/Request/Deployment/Notification dashboards.",commerce:"Order/Cart/Product/Customer/Coupon/GiftCard/Shipping + storefront API.",cms:"Post/Page/Author/Comment/Tag models + content edit dashboards.",forms:"User-defined forms: builder models, conditional fields, public submit + CSV export.",marketing:"/api/email/subscribe, /api/contact, Campaign/EmailList/SocialPost.",monitoring:"Error model + error-tracking views and actions.",realtime:"WebSocket broadcaster + Websocket model + realtime-stats actions.",queue:"Job + FailedJob models + queue dashboard pages."},STARTER_TEMPLATES={dashboard:`import type { DashboardConfig } from '@stacksjs/types'
1
+ import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes:!0})){const rel=prefix?`${prefix}/${entry.name}`:entry.name;if(entry.isDirectory())out.push(...filesUnder(join(dir,entry.name),rel));else out.push(rel)}return out}function matchesTemplate(projectFile,templateFile){if(!existsSync(templateFile))return!1;try{return readFileSync(projectFile).equals(readFileSync(templateFile))}catch{return!1}}function pruneEmptyDirs(root,dir){let current=dir;while(current.startsWith(root)&&current!==root){try{if(readdirSync(current).length>0)return;rmdirSync(current)}catch{return}current=join(current,"..")}}export async function deleteFeatureFiles(feature,root=projectPath(),options={}){const source=options.source??frameworkPath("defaults"),force=options.force===!0,dryRun=options.dryRun===!0,remove=async(path,recursive=!1)=>{if(!dryRun)await rm(path,{recursive,force:!0})},removed=[],preserved=[];for(const rel of FEATURE_FILES[feature]){const full=join(root,rel);if(!existsSync(full))continue;if(force){await remove(full,!0);removed.push(rel);continue}const template=join(source,rel);if(!statSync(full).isDirectory()){if(matchesTemplate(full,template)){await remove(full);removed.push(rel)}else preserved.push(rel);continue}let keptAny=!1;for(const child of filesUnder(full)){const projectFile=join(full,child);if(matchesTemplate(projectFile,join(template,child))){await remove(projectFile);removed.push(`${rel}${child}`)}else{keptAny=!0;preserved.push(`${rel}${child}`)}}if(dryRun)continue;pruneEmptyDirs(root,full);if(!keptAny&&existsSync(full))await rm(full,{recursive:!0,force:!0})}return{removed,preserved}}export async function copyFeatureFiles(feature,options={}){const source=options.source??frameworkPath("defaults"),target=options.target??projectPath(),force=options.force===!0,copied=[],skipped=[];for(const rel of FEATURE_FILES[feature]){const sourceFull=join(source,rel);if(!existsSync(sourceFull)){skipped.push(rel);continue}const targetFull=join(target,rel);if(existsSync(targetFull)&&!force){skipped.push(rel);continue}if(options.dryRun!==!0)await cp(sourceFull,targetFull,{recursive:!0,force});copied.push(rel)}return{copied,skipped}}const FEATURE_DESCRIPTIONS={dashboard:"Admin SPA shell + Activity/Log/Request/Deployment/Notification dashboards.",commerce:"Order/Cart/Product/Customer/Coupon/GiftCard/Shipping + storefront API.",cms:"Post/Page/Author/Comment/Tag models + content edit dashboards.",forms:"User-defined forms: builder models, conditional fields, public submit + CSV export.",marketing:"/api/email/subscribe, /api/contact, Campaign/EmailList/SocialPost.",monitoring:"Error model + error-tracking views and actions.",realtime:"WebSocket broadcaster + Websocket model + realtime-stats actions.",queue:"Job + FailedJob models + queue dashboard pages."};export const CONFIG_GATES={auth:"Loads the account models (Team, Referral, SocialAccount, Subscriber, Subscription, Site, ...). Auth routes are STACKS_DEFAULT_ROUTES, not this.",email:"Mounts the email provider webhook routes, when STACKS_DEFAULT_ROUTES does not name the bundles."};const STARTER_TEMPLATES={dashboard:`import type { DashboardConfig } from '@stacksjs/types'
2
2
 
3
3
  /**
4
4
  * **Dashboard Configuration**
@@ -127,4 +127,4 @@ export default {
127
127
  },
128
128
  } satisfies QueueConfig
129
129
  `};function withoutComments(src){return src.replace(/\/\*[\s\S]*?\*\//g,(m)=>" ".repeat(m.length)).replace(/\/\/[^\n]*/g,(m)=>" ".repeat(m.length))}function findTopLevelEnabled(src){const scan=withoutComments(src),start=scan.search(/export default\s*\{/);if(start===-1)return null;const open=scan.indexOf("{",start);let depth=0;for(let i=open;i<scan.length;i++){const char=scan[i];if(char==="{"){depth++;continue}if(char==="}"){depth--;if(depth===0)return null;continue}if(depth!==1||char!=="e")continue;const match=/^enabled\s*:\s*(true|false)/.exec(scan.slice(i));if(!match)continue;if(i>0&&/[\w$]/.test(scan[i-1]))continue;return{index:i,length:match[0].length,value:match[1]==="true"}}return null}export function readFeatureFlag(feature,root=projectPath()){const path=join(root,`config/${feature}.ts`);if(!existsSync(path))return"absent";const found=findTopLevelEnabled(readFileSync(path,"utf8"));if(!found)return"unset";return found.value}export function featureMigrationCounts(feature,root=projectPath()){const counts={active:0,hidden:0},base=join(root,"database/migrations");if(!existsSync(base))return counts;const dirs=[base];for(const entry of readdirSync(base,{withFileTypes:!0}))if(entry.isDirectory())dirs.push(join(base,entry.name));for(const dir of dirs)for(const file of readdirSync(dir)){const hidden=file.endsWith(".sql.disabled");if(!hidden&&!file.endsWith(".sql"))continue;const sqlName=hidden?file.slice(0,-9):file;if(migrationFeature(sqlName)!==feature)continue;if(hidden)counts.hidden++;else counts.active++}return counts}export async function setFeatureEnabled(feature,enabled,options){const write=async(target,contents)=>{if(options.dryRun!==!0)await Bun.write(target,contents)},path=options.root?join(options.root,`config/${feature}.ts`):projectPath(`config/${feature}.ts`),file=Bun.file(path);if(!await file.exists()){if(!options.createIfMissing)return"missing";await write(path,STARTER_TEMPLATES[feature]);return"created"}const src=await file.text(),found=findTopLevelEnabled(src);if(found){if(found.value===enabled)return"unchanged";const replaced=src.slice(0,found.index)+`enabled: ${enabled}`+src.slice(found.index+found.length);await write(path,replaced);return"flipped"}const insertRegex=/(export default\s*\{)/;if(!insertRegex.test(src))throw Error(`Could not locate \`export default {\` in ${path} - please add \`enabled: ${enabled}\` manually.`);const next=src.replace(insertRegex,`$1
130
- enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath(),results=[];for(const feature of FEATURE_NAMES){const configOutcome=await setFeatureEnabled(feature,!1,{createIfMissing:!1,root}),{removed:filesRemoved}=await deleteFeatureFiles(feature,root,{force:!0});results.push({feature,configOutcome,filesRemoved})}return results}function isDryRun(options){return options.dryRun===!0||process.argv.includes("--dry-run")}async function offerMigrate(feature){const{active,hidden}=featureMigrationCounts(feature),total=active+hidden;if(total===0)return;console.log(` \u2192 ${feature} owns ${total} ${total===1?"migration":"migrations"}; its tables do not exist until they run.`);const answer=await confirmOrNull({message:"Run ./buddy migrate now?",initial:!1});if(answer!==!0){console.log(answer===null?" \u2192 Not asking (non-interactive). Run ./buddy migrate when ready.":" \u2192 Skipped. Run ./buddy migrate when ready.");return}const result=await runCommand("./buddy migrate",{cwd:projectPath()});if(resultFailed(result)){console.error(`\u2717 ./buddy migrate failed: ${resultError(result)}`);console.error(` \u2192 ${feature} is installed; re-run ./buddy migrate once that is resolved.`);return}console.log("\u2713 Migrated.")}function registerInstallPair(buddy,feature){const desc=FEATURE_DESCRIPTIONS[feature],configRel=`config/${feature}.ts`;buddy.command(`${feature}:install`,`Activate the ${feature} feature bundle. ${desc}`).option("--force",`Overwrite any existing ${feature} files in the project (default skips existing paths so the install is idempotent).`).option("--dry-run",`Say what ${feature}:install would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!0,{createIfMissing:!0,dryRun})){case"created":console.log(dryRun?`${mark} Would create ${configRel} with '${feature}' enabled.`:`${mark} Created ${configRel} with '${feature}' enabled.`);break;case"flipped":console.log(dryRun?`${mark} Would enable '${feature}' in ${configRel}.`:`${mark} Enabled '${feature}' in ${configRel}.`);break;case"unchanged":console.log(`${mark} '${feature}' is already enabled in ${configRel}.`);break}const{copied}=await copyFeatureFiles(feature,{force:options.force===!0,dryRun});if(copied.length>0){console.log(dryRun?`${mark} Would copy ${copied.length} stamped path(s) from framework defaults:`:`${mark} Copied ${copied.length} stamped path(s) from framework defaults:`);for(const path of copied)console.log(` - ${path}`)}else if(featurePathsPresent(feature).length>0)console.log(` \u2192 ${feature} scaffolding already in place - use --force to overwrite.`);if(dryRun){console.log(` \u2192 Dry run: nothing was written. Run it without --dry-run to install ${feature}.`);process.exit(ExitCode.Success)}await offerMigrate(feature);console.log(` \u2192 next ./buddy dev will boot with ${feature} loaded.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to install ${feature}:`,err);process.exit(ExitCode.FatalError)}});buddy.command(`${feature}:uninstall`,`Deactivate the ${feature} feature bundle.`).option("--keep-files",`Don't delete the ${feature} scaffolding (action/model/view files). Flip the flag only.`).option("--force",`Delete the ${feature} scaffolding even where you have edited it. Without this, changed files are kept.`).option("--dry-run",`Say what ${feature}:uninstall would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!1,{createIfMissing:!1,dryRun})){case"missing":console.log(`${mark} '${feature}' is already disabled (${configRel} is absent).`);break;case"flipped":console.log(dryRun?`${mark} Would disable '${feature}' in ${configRel}.`:`${mark} Disabled '${feature}' in ${configRel}. Custom config preserved.`);break;case"unchanged":console.log(`${mark} '${feature}' is already disabled in ${configRel}.`);break;case"created":console.log(`\u2717 Unexpected create on uninstall for ${feature}; please re-run with --force or report this bug.`);break}if(options.keepFiles){const stillPresent=featurePathsPresent(feature);if(stillPresent.length>0)console.log(` \u2192 ${stillPresent.length} stamped path(s) preserved (--keep-files).`)}else{const{removed,preserved}=await deleteFeatureFiles(feature,projectPath(),{force:options.force,dryRun});if(removed.length>0){console.log(dryRun?`${mark} Would remove ${removed.length} stamped path(s):`:`${mark} Removed ${removed.length} stamped path(s):`);for(const path of removed)console.log(` - ${path}`)}if(preserved.length>0){console.log(dryRun?` \u2192 Would keep ${preserved.length} path(s) you have edited (--force would remove them):`:` \u2192 Kept ${preserved.length} path(s) you have edited (re-run with --force to remove):`);for(const path of preserved)console.log(` - ${path}`)}}console.log(dryRun?` \u2192 Dry run: nothing was written or removed. Run it without --dry-run to uninstall ${feature}.`:` \u2192 next ./buddy dev will boot without ${feature}.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to uninstall ${feature}:`,err);process.exit(ExitCode.FatalError)}})}function registerStatus(buddy){buddy.command("features","Show which framework feature bundles are active.").action(async()=>{try{const{feature,overridesReady}=await import("@stacksjs/config");await overridesReady;const rows=FEATURE_NAMES.map((name)=>{const declared=readFeatureFlag(name),active=feature(name),migrations=featureMigrationCounts(name);return{name,declared,active,migrations,scaffolded:featurePathsPresent(name).length}}),enabled=rows.filter((r)=>r.active).length;console.log("");console.log(`Feature bundles (${enabled} of ${rows.length} active)`);console.log("");for(const row of rows){const mark=row.active?"\u2713":"\xB7",declared=row.declared==="absent"?"no config":row.declared==="unset"?"flag unset":`enabled: ${row.declared}`,parts=[`${mark} ${row.name.padEnd(11)}`,declared.padEnd(14)],total=row.migrations.active+row.migrations.hidden,plural=total===1?"migration":"migrations";if(total>0)parts.push(row.migrations.hidden>0?`${total} ${plural} (${row.migrations.hidden} hidden)`:`${total} ${plural}`);else parts.push("");console.log(` ${parts.join(" ")}`);if(row.declared===!0&&!row.active)console.log(` declared on but reading off - check \`env\` in config/${row.name}.ts against config.app.env`);if(row.declared===!1&&row.active)console.log(" declared off but reading on - a runtime override is in play");if(!row.active&&row.scaffolded>0)console.log(` ${row.scaffolded} scaffolded path(s) still present - \`./buddy ${row.name}:uninstall\` removes them`);if(row.active&&row.migrations.hidden>0)console.log(` ${row.migrations.hidden} migration(s) still hidden from a previous run - \`./buddy migrate\` restores them`)}console.log("");console.log(" ./buddy <feature>:install activates one, <feature>:uninstall turns it off.");console.log("");process.exit(ExitCode.Success)}catch(err){console.error("\u2717 Failed to read feature status:",err);process.exit(ExitCode.FatalError)}})}export function features(buddy){registerStatus(buddy);for(const feature of FEATURE_NAMES)registerInstallPair(buddy,feature)}
130
+ enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath(),results=[];for(const feature of FEATURE_NAMES){const configOutcome=await setFeatureEnabled(feature,!1,{createIfMissing:!1,root}),{removed:filesRemoved}=await deleteFeatureFiles(feature,root,{force:!0});results.push({feature,configOutcome,filesRemoved})}return results}function isDryRun(options){return options.dryRun===!0||process.argv.includes("--dry-run")}async function offerMigrate(feature){const{active,hidden}=featureMigrationCounts(feature),total=active+hidden;if(total===0)return;console.log(` \u2192 ${feature} owns ${total} ${total===1?"migration":"migrations"}; its tables do not exist until they run.`);const answer=await confirmOrNull({message:"Run ./buddy migrate now?",initial:!1});if(answer!==!0){console.log(answer===null?" \u2192 Not asking (non-interactive). Run ./buddy migrate when ready.":" \u2192 Skipped. Run ./buddy migrate when ready.");return}const result=await runCommand("./buddy migrate",{cwd:projectPath()});if(resultFailed(result)){console.error(`\u2717 ./buddy migrate failed: ${resultError(result)}`);console.error(` \u2192 ${feature} is installed; re-run ./buddy migrate once that is resolved.`);return}console.log("\u2713 Migrated.")}function registerInstallPair(buddy,feature){const desc=FEATURE_DESCRIPTIONS[feature],configRel=`config/${feature}.ts`;buddy.command(`${feature}:install`,`Activate the ${feature} feature bundle. ${desc}`).option("--force",`Overwrite any existing ${feature} files in the project (default skips existing paths so the install is idempotent).`).option("--dry-run",`Say what ${feature}:install would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!0,{createIfMissing:!0,dryRun})){case"created":console.log(dryRun?`${mark} Would create ${configRel} with '${feature}' enabled.`:`${mark} Created ${configRel} with '${feature}' enabled.`);break;case"flipped":console.log(dryRun?`${mark} Would enable '${feature}' in ${configRel}.`:`${mark} Enabled '${feature}' in ${configRel}.`);break;case"unchanged":console.log(`${mark} '${feature}' is already enabled in ${configRel}.`);break}const{copied}=await copyFeatureFiles(feature,{force:options.force===!0,dryRun});if(copied.length>0){console.log(dryRun?`${mark} Would copy ${copied.length} stamped path(s) from framework defaults:`:`${mark} Copied ${copied.length} stamped path(s) from framework defaults:`);for(const path of copied)console.log(` - ${path}`)}else if(featurePathsPresent(feature).length>0)console.log(` \u2192 ${feature} scaffolding already in place - use --force to overwrite.`);if(dryRun){console.log(` \u2192 Dry run: nothing was written. Run it without --dry-run to install ${feature}.`);process.exit(ExitCode.Success)}await offerMigrate(feature);console.log(` \u2192 next ./buddy dev will boot with ${feature} loaded.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to install ${feature}:`,err);process.exit(ExitCode.FatalError)}});buddy.command(`${feature}:uninstall`,`Deactivate the ${feature} feature bundle.`).option("--keep-files",`Don't delete the ${feature} scaffolding (action/model/view files). Flip the flag only.`).option("--force",`Delete the ${feature} scaffolding even where you have edited it. Without this, changed files are kept.`).option("--dry-run",`Say what ${feature}:uninstall would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!1,{createIfMissing:!1,dryRun})){case"missing":console.log(`${mark} '${feature}' is already disabled (${configRel} is absent).`);break;case"flipped":console.log(dryRun?`${mark} Would disable '${feature}' in ${configRel}.`:`${mark} Disabled '${feature}' in ${configRel}. Custom config preserved.`);break;case"unchanged":console.log(`${mark} '${feature}' is already disabled in ${configRel}.`);break;case"created":console.log(`\u2717 Unexpected create on uninstall for ${feature}; please re-run with --force or report this bug.`);break}if(options.keepFiles){const stillPresent=featurePathsPresent(feature);if(stillPresent.length>0)console.log(` \u2192 ${stillPresent.length} stamped path(s) preserved (--keep-files).`)}else{const{removed,preserved}=await deleteFeatureFiles(feature,projectPath(),{force:options.force,dryRun});if(removed.length>0){console.log(dryRun?`${mark} Would remove ${removed.length} stamped path(s):`:`${mark} Removed ${removed.length} stamped path(s):`);for(const path of removed)console.log(` - ${path}`)}if(preserved.length>0){console.log(dryRun?` \u2192 Would keep ${preserved.length} path(s) you have edited (--force would remove them):`:` \u2192 Kept ${preserved.length} path(s) you have edited (re-run with --force to remove):`);for(const path of preserved)console.log(` - ${path}`)}}console.log(dryRun?` \u2192 Dry run: nothing was written or removed. Run it without --dry-run to uninstall ${feature}.`:` \u2192 next ./buddy dev will boot without ${feature}.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to uninstall ${feature}:`,err);process.exit(ExitCode.FatalError)}})}function registerStatus(buddy){buddy.command("features","Show which framework feature bundles are active.").action(async()=>{try{const{feature,overridesReady}=await import("@stacksjs/config");await overridesReady;const rows=FEATURE_NAMES.map((name)=>{const declared=readFeatureFlag(name),active=feature(name),migrations=featureMigrationCounts(name);return{name,declared,active,migrations,scaffolded:featurePathsPresent(name).length}}),enabled=rows.filter((r)=>r.active).length;console.log("");console.log(`Feature bundles (${enabled} of ${rows.length} active)`);console.log("");for(const row of rows){const mark=row.active?"\u2713":"\xB7",declared=row.declared==="absent"?"no config":row.declared==="unset"?"flag unset":`enabled: ${row.declared}`,parts=[`${mark} ${row.name.padEnd(11)}`,declared.padEnd(14)],total=row.migrations.active+row.migrations.hidden,plural=total===1?"migration":"migrations";if(total>0)parts.push(row.migrations.hidden>0?`${total} ${plural} (${row.migrations.hidden} hidden)`:`${total} ${plural}`);else parts.push("");console.log(` ${parts.join(" ")}`);if(row.declared===!0&&!row.active)console.log(` declared on but reading off - check \`env\` in config/${row.name}.ts against config.app.env`);if(row.declared===!1&&row.active)console.log(" declared off but reading on - a runtime override is in play");if(!row.active&&row.scaffolded>0)console.log(` ${row.scaffolded} scaffolded path(s) still present - \`./buddy ${row.name}:uninstall\` removes them`);if(row.active&&row.migrations.hidden>0)console.log(` ${row.migrations.hidden} migration(s) still hidden from a previous run - \`./buddy migrate\` restores them`)}console.log("");console.log(" ./buddy <feature>:install activates one, <feature>:uninstall turns it off.");console.log("");console.log("Config gates (switched by `enabled` in their config file)");console.log("");for(const[name,description]of Object.entries(CONFIG_GATES)){const declared=readFeatureFlag(name),label=declared==="absent"?"no config":declared==="unset"?"flag unset":`enabled: ${declared}`;console.log(` ${feature(name)?"\u2713":"\xB7"} ${name.padEnd(11)} ${label.padEnd(14)} ${description}`)}console.log("");process.exit(ExitCode.Success)}catch(err){console.error("\u2717 Failed to read feature status:",err);process.exit(ExitCode.FatalError)}})}export function features(buddy){registerStatus(buddy);for(const feature of FEATURE_NAMES)registerInstallPair(buddy,feature)}
@@ -0,0 +1,41 @@
1
+ export declare function assertPreviewName(name: string): string;
2
+ /**
3
+ * The domain previews live under: `cloud.previews.domain` in
4
+ * config/cloud.ts, else `PREVIEW_DOMAIN`. Its DNS has to be managed by a
5
+ * provider the deploy has credentials for, or each preview's record is
6
+ * created by hand.
7
+ */
8
+ export declare function previewDomain(config: any, env: Record<string, string | undefined>): string;
9
+ /** The site a preview deploys: `cloud.previews.site`, else the first site that runs a server. */
10
+ export declare function previewSite(config: any): string;
11
+ export declare function previewTarget(config: any, name: string, domain: string): PreviewTarget;
12
+ /**
13
+ * The app's config, reshaped into the preview's: its own slug, attached to
14
+ * the app's box, serving only the preview site at the preview host on `port`.
15
+ * The site's env strings that name the app's own host are pointed at the
16
+ * preview's, the way an environment's `domainPrefix` rewrites them.
17
+ */
18
+ export declare function derivePreviewConfig(config: any, target: PreviewTarget, port: number): any;
19
+ /**
20
+ * The port a preview runs on: the one it already has when it is being
21
+ * redeployed, else the first free one in the box's range at or above the
22
+ * app site's own.
23
+ */
24
+ export declare function previewPort(owners: ReadonlyMap<number, string>, slug: string, preferred: number, range?: Record<string, unknown>): number;
25
+ /**
26
+ * Remove a preview from the box: stop and delete its units, its gateway
27
+ * fragment and certificate units, and its files, then reload the gateway.
28
+ *
29
+ * Every name is exact - `<slug>-<site>` for the units and the site's tree,
30
+ * `<slug>-shared` for its data - never a wildcard on the slug, because
31
+ * preview `pr-1`'s slug is a prefix of preview `pr-1-docs`'s, and a glob on
32
+ * it would take the other preview down too.
33
+ */
34
+ export declare function buildPreviewTeardownScript(slug: string, site: string): string;
35
+ export declare interface PreviewTarget {
36
+ slug: string
37
+ owner: string
38
+ site: string
39
+ host: string
40
+ url: string
41
+ }
@@ -0,0 +1,2 @@
1
+ const PREVIEW_NAME=/^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])?$/;export function assertPreviewName(name){if(!PREVIEW_NAME.test(name))throw TypeError(`"${name}" is not a usable preview name: lowercase letters, digits and dashes, at most 30 characters, starting and ending with a letter or digit (e.g. pr-123).`);return name}export function previewDomain(config,env){const domain=String(config?.cloud?.previews?.domain??env.PREVIEW_DOMAIN??"").trim().replace(/^\*\./,"").replace(/\.$/,"");if(!domain)throw TypeError("Previews need a domain to live under: set cloud.previews.domain in config/cloud.ts, or PREVIEW_DOMAIN.");if(!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(domain))throw TypeError(`"${domain}" is not a domain previews can live under.`);return domain.toLowerCase()}export function previewSite(config){const sites=config?.sites??{},named=config?.cloud?.previews?.site;if(named){if(!sites[named])throw TypeError(`cloud.previews.site names "${named}", which config/cloud.ts does not declare.`);return named}const serverApp=Object.entries(sites).find(([,site])=>site&&(site.start||site.port!==void 0)&&!site.redirect&&!site.bucket);if(!serverApp)throw TypeError("No site in config/cloud.ts runs a server, so there is nothing to preview. Name one with cloud.previews.site.");return serverApp[0]}export function previewTarget(config,name,domain){assertPreviewName(name);const appSlug=config?.project?.slug;if(!appSlug)throw TypeError("config/cloud.ts declares no project.slug, which a preview's slug is made from.");const slug=`${appSlug}-${name}`;if(slug.length>63)throw TypeError(`The preview slug "${slug}" is longer than 63 characters; use a shorter preview name.`);const site=previewSite(config);for(const appSite of Object.keys(config.sites??{}))if(`${appSlug}-${appSite}`.startsWith(`${slug}-`))throw TypeError(`The preview "${name}" would share unit names with the app's site "${appSite}"; pick another preview name.`);const host=`${name}.${domain}`;return{slug,owner:config?.cloud?.attachTo??appSlug,site,host,url:`https://${host}`}}export function derivePreviewConfig(config,target,port){const derived=structuredClone(config),site=derived.sites[target.site],appHost=typeof site.domain==="string"?site.domain:void 0;derived.project={...derived.project,slug:target.slug};delete derived.project.stackName;derived.cloud={...derived.cloud,attachTo:target.owner};delete derived.cloud.retiredDomains;delete derived.cloud.previews;delete derived.environments;const env={...site.env};if(appHost){for(const[key,value]of Object.entries(env))if(typeof value==="string")env[key]=value.split(`//${appHost}`).join(`//${target.host}`)}env.APP_URL=target.url;derived.sites={[target.site]:{...site,domain:target.host,port,env,aliases:void 0,www:!1}};return derived}export function previewPort(owners,slug,preferred,range={start:3000,end:3999}){for(const[port,owner]of owners)if(owner===slug)return port;for(let candidate=Math.max(preferred,range.start);candidate<=range.end;candidate++)if(!owners.has(candidate))return candidate;throw Error(`No free port between ${range.start} and ${range.end} on the box for a preview.`)}export function buildPreviewTeardownScript(slug,site){if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(slug)||!/^[a-z0-9][a-z0-9_-]*$/i.test(site))throw TypeError(`Refusing to build a teardown for "${slug}" / "${site}".`);const unit=`${slug}-${site}`,units=`^${unit}(@[^.]*)?\\.service$|^${unit}-(liveness\\.(service|timer)|scheduler\\.service|(queue|daemon)-.*\\.service)$`;return["set -eu",`for instance in $(systemctl list-units --all --plain --no-legend '${unit}@*.service' 2>/dev/null | awk '{print $1}'); do`,' systemctl disable --now "$instance" 2>/dev/null || true',"done",`rm -f /etc/systemd/system/*.wants/${unit}@*.service`,`others=$(ls /etc/rpx/sites.d/ 2>/dev/null | sed -n 's/^\\(${slug}-.*\\)\\.json$/\\1/p')`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '${units}' || true); do`," skip=0",' for other in $others; do case "$unit" in "$other"-*) skip=1 ;; esac; done',' [ "$skip" = 1 ] && continue',' systemctl disable --now "$unit" 2>/dev/null || true',' rm -rf "/etc/systemd/system/$unit"',"done",`systemctl disable --now rpx-cert-renew-${slug}.timer 2>/dev/null || true`,`rm -f /etc/systemd/system/rpx-cert-renew-${slug}.timer /etc/systemd/system/rpx-cert-renew-${slug}.service /etc/rpx/renew-certs-${slug}.sh /etc/rpx/sites.d/${slug}.json`,"systemctl daemon-reload","systemctl reload rpx-gateway.service 2>/dev/null || systemctl restart rpx-gateway.service 2>/dev/null || true",`rm -rf /var/www/${unit} /var/www/${slug}-shared /usr/local/sbin/${unit}-liveness`,`echo "removed ${slug}"`].join(`
2
+ `)}
@@ -1,5 +1,5 @@
1
- import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";const log={info:(...args)=>console.log("\u2139",...args),success:(...args)=>console.log("\u2713",...args),warn:(...args)=>console.log("\u26A0",...args),error:(...args)=>console.error("\u2717",...args)},OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":void 0},str=(key)=>{return new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out)?.[1]},num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):void 0};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"}),[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]),whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]),found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:!0});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"])if(Bun.spawnSync(["which",candidate]).exitCode===0)return[candidate,"-dc"];throw Error("No xz decompressor found, and the images are .img.xz.\n Install one with: brew install xz\n Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi(),missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"}),timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts,findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err),unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson)console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2));else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
2
- `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return!1}if(asJson)console.log(JSON.stringify({host:target.host,facts,findings},null,2));else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}return!(typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error"))}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:void 0}).option("--list","List the disks that could be written to, and exit",{default:!1}).option("--dry-run","Say what would happen without writing anything",{default:!1}).option("--yes","Do not ask for confirmation before writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes){if(await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:!1})!==!0){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);if(await Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:void 0}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:void 0}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:void 0}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:void 0}).option("--timezone <tz>","IANA timezone for the board",{default:void 0}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:!1}).action(async(options)=>{const perf=await intro("buddy server:first-boot"),api=await loadSshApi(),{config}=await loadSshProject(options.env),keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?void 0:options.user),os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os",bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:!0});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
1
+ import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";const log={info:(...args)=>console.log("\u2139",...args),success:(...args)=>console.log("\u2713",...args),warn:(...args)=>console.log("\u26A0",...args),error:(...args)=>console.error("\u2717",...args)},OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":void 0},str=(key)=>{return new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out)?.[1]},num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):void 0};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"}),[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]),whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]),found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:!0});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"])if(Bun.spawnSync(["which",candidate]).exitCode===0)return[candidate,"-dc"];throw Error("No xz decompressor found, and the images are .img.xz.\n Install one with: brew install xz\n Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi(),missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"}),timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts,findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err),unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson)console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2));else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
2
+ `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return!1}if(asJson)console.log(JSON.stringify({host:target.host,facts,findings},null,2));else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}return!(typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error"))}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:void 0}).option("--list","List the disks that could be written to, and exit",{default:!1}).option("--dry-run","Say what would happen without writing anything",{default:!1}).option("-y, --yes","Do not ask for confirmation before writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.error("Refusing to erase a disk from a non-interactive shell without confirmation.");log.info(` \u27A1\uFE0F Re-run with \`--yes\`: \`buddy server:flash --device ${info.DeviceNode} --yes\``);process.exit(ExitCode.FatalError)}if(await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:!1})!==!0){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);if(await Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:void 0}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:void 0}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:void 0}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:void 0}).option("--timezone <tz>","IANA timezone for the board",{default:void 0}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:!1}).action(async(options)=>{const perf=await intro("buddy server:first-boot"),api=await loadSshApi(),{config}=await loadSshProject(options.env),keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?void 0:options.user),os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os",bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:!0});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
3
3
  ${bundle.instructions}`);log.info(`Next: eject the card, boot the board, then \`buddy server:doctor ${options.hostname}.local\``);await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:doctor [host]","Check that a host can run this application before deploying to it").option("--env <name>","Environment whose configuration to check against",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--json","Print the findings as JSON",{default:!1}).action(async(host,options)=>{const perf=options.json?void 0:await intro("buddy server:doctor"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target;log.info(`Checking ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const ok=await reportPreflight(api,checked,options.json===!0);if(perf)await outro(ok?"Ready":"Not ready",{startTime:perf,useSeconds:!0});process.exit(ok?ExitCode.Success:ExitCode.FatalError)});buddy.command("server:setup [host]","Adopt a host: check it, then install what the deploy needs").option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--dry-run","Run the checks and stop before changing the host",{default:!1}).action(async(host,options)=>{const perf=await intro("buddy server:setup"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const adopted=host_?{...target,host:host_}:target;log.info(`Adopting ${adopted.user}@${adopted.host}${adopted.port===22?"":`:${adopted.port}`}`);if(!await reportPreflight(api,adopted,!1)){log.error("The host is not ready. Nothing was changed on it.");process.exit(ExitCode.FatalError)}if(options.dryRun){log.info("Dry run: the host passed its checks and was not modified.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const driver=api.createCloudDriver({config,provider:"ssh"});if(!driver.provisionComputeInfrastructure){log.error("This ts-cloud cannot bootstrap an SSH host (update @stacksjs/ts-cloud).");process.exit(ExitCode.FatalError)}buildBootstrapOrExit(api,config,options.env,adopted.user==="root"?void 0:adopted.user);log.info("Installing the runtime, gateway and service units if they are missing...");let outputs;try{outputs=await driver.provisionComputeInfrastructure({config,environment:options.env})}catch(err){log.error("Bootstrapping the host failed.");log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const stackName=config.project?.stackName||`${config.project?.slug||"app"}-${options.env}`,dir=join(process.cwd(),"storage","cloud","state"),statePath=join(dir,`${stackName}.json`);let recorded=null;try{recorded=existsSync(statePath)?JSON.parse(await Bun.file(statePath).text()):null}catch{recorded=null}mkdirSync(dir,{recursive:!0});await Bun.write(statePath,`${JSON.stringify(mergeSshStatePin(recorded,sshStatePin({stackName,target:adopted,deployStoragePath:outputs?.deployStoragePath})),null,2)}
4
4
  `);log.success(`Host adopted. Recorded at storage/cloud/state/${stackName}.json`);log.info("Next: `buddy deploy --prod`");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:trust [host]","Trust the host's own certificate authority on this machine").option("--env <name>","Environment whose configuration names the host",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--ca-path <path>","Where the authority lives on the host",{default:DEFAULT_LAN_CA_PATH}).option("--mobileconfig <path>","Also write an Apple configuration profile for an iPhone or iPad",{default:void 0}).option("--export-only","Save the certificate without changing this machine, and say how to trust it by hand",{default:!1}).option("--json","Print the result as JSON",{default:!1}).action(async(host,options)=>{const asJson=options.json===!0,perf=asJson?void 0:await intro("buddy server:trust"),{target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0&&!asJson)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)if(!asJson)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target,caPath=resolveCaPath(options.caPath),fail=(reason,message,remediation,detail)=>{if(asJson)console.log(JSON.stringify({host:checked.host,caPath,error:reason,message,remediation,...detail?{detail}:{}},null,2));else{log.error(message);log.info(remediation);if(detail)log.info(detail)}process.exit(ExitCode.FatalError)};if(!asJson)log.info(`Reading ${caPath} from ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const read=await readRemoteCa(checked,caPath);if("failure"in read){if(read.failure==="missing")return fail("ca.absent",`There is no certificate authority at ${caPath} on ${checked.host}.`,"That host is not serving LAN HTTPS from its own authority. Set `ssh: { lan: { tls: 'local-ca' } }` in config/cloud.ts and run `buddy deploy --prod`, which is what creates it. Nothing was created on the host. If the authority lives elsewhere, name it with --ca-path.");if(read.failure==="unreadable")return fail("ca.unreadable",`${caPath} on ${checked.host} exists but could not be read as a certificate.`,`Check it by hand with \`ssh ${checked.user}@${checked.host} sudo cat ${caPath}\`. Reading it falls back to \`sudo -n\`, so a host whose sudo asks for a password cannot serve it to this command.`,read.detail||void 0);return fail("ssh.unreachable",`Could not reach ${checked.user}@${checked.host} over SSH.`,"Check the host is powered on and on this network, that SSH is enabled, and that your key is authorised. `buddy server:doctor` reports on all three.",read.detail.split(`
5
5
  `).find((line)=>line.trim())||void 0)}const pem=read.pem,{exportCA,getCertSha256Fingerprint,isCertTrusted,trustInstructions}=await import("@stacksjs/tlsx");let fingerprint;try{fingerprint=getCertSha256Fingerprint(pem)}catch(err){return fail("ca.unparseable",`The file at ${caPath} on ${checked.host} is not a certificate this can read.`,"Point --ca-path at the root certificate rpx writes, which is a PEM.",err instanceof Error?err.message:String(err))}const savedPath=caCopyPath(checked.host);mkdirSync(dirname(savedPath),{recursive:!0});await Bun.write(savedPath,pem.endsWith(`
@@ -16,6 +16,12 @@ import type { CLI } from '@stacksjs/cli';
16
16
  * with a non-zero exit everywhere it is not implemented. A flag that silently
17
17
  * does nothing is worse than one that does not exist, because it is exactly
18
18
  * what a careful operator reaches for first.
19
+ *
20
+ * `--force` is not here either, for the same reason (stacksjs/stacks#2869).
21
+ * It promised "Skip confirmation prompts" on every command, while the
22
+ * commands that confirm skip it with `--yes`: `gdpr:erase --force` was
23
+ * accepted, ignored, and then refused in a non-interactive shell. The 46
24
+ * commands that implement `--force` declare it, each with what it means there.
19
25
  */
20
26
  export declare function registerGlobalOptions(buddy: CLI, options?: GlobalOptionRegistration): void;
21
27
  declare interface GlobalOptionRegistration {
@@ -1 +1 @@
1
- import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){(options.version===!1?buddy:buddy.version(versionDescriptor,"-V, --version")).option("-v, --verbose","Enable verbose output").option("-q, --quiet","Suppress non-essential output").option("--debug","Enable debug output and stack traces").option("--no-interaction","Do not ask interactive questions").option("--env <environment>","Target an environment").option("--force","Skip confirmation prompts").option("--no-emoji","Disable emoji in output").option("--no-cache","Disable command metadata caching")}
1
+ import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){(options.version===!1?buddy:buddy.version(versionDescriptor,"-V, --version")).option("-v, --verbose","Enable verbose output").option("-q, --quiet","Suppress non-essential output").option("--debug","Enable debug output and stack traces").option("--no-interaction","Do not ask interactive questions").option("--env <environment>","Target an environment").option("--no-emoji","Disable emoji in output").option("--no-cache","Disable command metadata caching")}
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.86",
5
+ "version": "0.75.88",
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.86",
99
- "@stacksjs/ai": "^0.75.86",
100
- "@stacksjs/alias": "^0.75.86",
101
- "@stacksjs/analytics": "^0.75.86",
102
- "@stacksjs/api": "^0.75.86",
103
- "@stacksjs/arrays": "^0.75.86",
104
- "@stacksjs/auth": "^0.75.86",
105
- "@stacksjs/browser-extension": "^0.75.86",
106
- "@stacksjs/build": "^0.75.86",
107
- "@stacksjs/cache": "^0.75.86",
108
- "@stacksjs/chat": "^0.75.86",
98
+ "@stacksjs/actions": "^0.75.88",
99
+ "@stacksjs/ai": "^0.75.88",
100
+ "@stacksjs/alias": "^0.75.88",
101
+ "@stacksjs/analytics": "^0.75.88",
102
+ "@stacksjs/api": "^0.75.88",
103
+ "@stacksjs/arrays": "^0.75.88",
104
+ "@stacksjs/auth": "^0.75.88",
105
+ "@stacksjs/browser-extension": "^0.75.88",
106
+ "@stacksjs/build": "^0.75.88",
107
+ "@stacksjs/cache": "^0.75.88",
108
+ "@stacksjs/chat": "^0.75.88",
109
109
  "@stacksjs/clapp": "^0.2.16",
110
- "@stacksjs/cli": "^0.75.86",
111
- "@stacksjs/cloud": "^0.75.86",
112
- "@stacksjs/cms": "^0.75.86",
113
- "@stacksjs/collections": "^0.75.86",
114
- "@stacksjs/commerce": "^0.75.86",
115
- "@stacksjs/config": "^0.75.86",
116
- "@stacksjs/database": "^0.75.86",
117
- "@stacksjs/desktop-build": "^0.75.86",
118
- "@stacksjs/dns": "^0.75.86",
110
+ "@stacksjs/cli": "^0.75.88",
111
+ "@stacksjs/cloud": "^0.75.88",
112
+ "@stacksjs/cms": "^0.75.88",
113
+ "@stacksjs/collections": "^0.75.88",
114
+ "@stacksjs/commerce": "^0.75.88",
115
+ "@stacksjs/config": "^0.75.88",
116
+ "@stacksjs/database": "^0.75.88",
117
+ "@stacksjs/desktop-build": "^0.75.88",
118
+ "@stacksjs/dns": "^0.75.88",
119
119
  "@stacksjs/dnsx": "^0.2.3",
120
- "@stacksjs/email": "^0.75.86",
121
- "@stacksjs/enums": "^0.75.86",
122
- "@stacksjs/env": "^0.75.86",
123
- "@stacksjs/error-handling": "^0.75.86",
124
- "@stacksjs/events": "^0.75.86",
125
- "@stacksjs/features": "^0.75.86",
126
- "@stacksjs/git": "^0.75.86",
120
+ "@stacksjs/email": "^0.75.88",
121
+ "@stacksjs/enums": "^0.75.88",
122
+ "@stacksjs/env": "^0.75.88",
123
+ "@stacksjs/error-handling": "^0.75.88",
124
+ "@stacksjs/events": "^0.75.88",
125
+ "@stacksjs/features": "^0.75.88",
126
+ "@stacksjs/git": "^0.75.88",
127
127
  "@stacksjs/gitit": "^0.2.5",
128
- "@stacksjs/health": "^0.75.86",
128
+ "@stacksjs/health": "^0.75.88",
129
129
  "@stacksjs/httx": "^0.1.10",
130
- "@stacksjs/image": "^0.75.86",
131
- "@stacksjs/lint": "^0.75.86",
132
- "@stacksjs/logging": "^0.75.86",
133
- "@stacksjs/notifications": "^0.75.86",
134
- "@stacksjs/objects": "^0.75.86",
135
- "@stacksjs/orm": "^0.75.86",
136
- "@stacksjs/path": "^0.75.86",
137
- "@stacksjs/payments": "^0.75.86",
138
- "@stacksjs/realtime": "^0.75.86",
139
- "@stacksjs/router": "^0.75.86",
130
+ "@stacksjs/image": "^0.75.88",
131
+ "@stacksjs/lint": "^0.75.88",
132
+ "@stacksjs/logging": "^0.75.88",
133
+ "@stacksjs/notifications": "^0.75.88",
134
+ "@stacksjs/objects": "^0.75.88",
135
+ "@stacksjs/orm": "^0.75.88",
136
+ "@stacksjs/path": "^0.75.88",
137
+ "@stacksjs/payments": "^0.75.88",
138
+ "@stacksjs/realtime": "^0.75.88",
139
+ "@stacksjs/router": "^0.75.88",
140
140
  "@stacksjs/rpx": "^0.11.54",
141
- "@stacksjs/scheduler": "^0.75.86",
142
- "@stacksjs/search-engine": "^0.75.86",
143
- "@stacksjs/security": "^0.75.86",
144
- "@stacksjs/server": "^0.75.86",
145
- "@stacksjs/sites": "^0.75.86",
146
- "@stacksjs/skills": "^0.75.86",
147
- "@stacksjs/storage": "^0.75.86",
148
- "@stacksjs/strings": "^0.75.86",
149
- "@stacksjs/stx": "^0.2.384",
150
- "@stacksjs/testing": "^0.75.86",
151
- "@stacksjs/tinker": "^0.75.86",
141
+ "@stacksjs/scheduler": "^0.75.88",
142
+ "@stacksjs/search-engine": "^0.75.88",
143
+ "@stacksjs/security": "^0.75.88",
144
+ "@stacksjs/server": "^0.75.88",
145
+ "@stacksjs/sites": "^0.75.88",
146
+ "@stacksjs/skills": "^0.75.88",
147
+ "@stacksjs/storage": "^0.75.88",
148
+ "@stacksjs/strings": "^0.75.88",
149
+ "@stacksjs/stx": "^0.2.389",
150
+ "@stacksjs/testing": "^0.75.88",
151
+ "@stacksjs/tinker": "^0.75.88",
152
152
  "@stacksjs/tlsx": "^0.13.19",
153
- "@stacksjs/ts-cloud": "^0.16.42",
154
- "@stacksjs/tunnel": "^0.75.86",
155
- "@stacksjs/types": "^0.75.86",
156
- "@stacksjs/ui": "^0.75.86",
157
- "@stacksjs/utils": "^0.75.86",
158
- "@stacksjs/validation": "^0.75.86",
153
+ "@stacksjs/ts-cloud": "^0.16.47",
154
+ "@stacksjs/tunnel": "^0.75.88",
155
+ "@stacksjs/types": "^0.75.88",
156
+ "@stacksjs/ui": "^0.75.88",
157
+ "@stacksjs/utils": "^0.75.88",
158
+ "@stacksjs/validation": "^0.75.88",
159
159
  "ajv": "^8.20.0",
160
160
  "ajv-formats": "^3.0.1",
161
- "bun-plugin-stx": "^0.2.384",
161
+ "bun-plugin-stx": "^0.2.389",
162
162
  "ts-pantry": "^0.11.69"
163
163
  },
164
164
  "devDependencies": {