@stacksjs/buddy 0.75.245 → 0.75.247

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 +1 @@
1
- import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{ensurePantryDependencies,ensurePantryInstalled,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create [name]").option("-n, --name [name]",descriptions.name,{default:!1}).option("-u, --ui",descriptions.ui,{default:!0}).option("-c, --components",descriptions.components,{default:!0}).option("-w, --web-components",descriptions.webComponents,{default:!0}).option("-p, --views",descriptions.views,{default:!0}).option("-f, --functions",descriptions.functions,{default:!0}).option("-a, --api",descriptions.api,{default:!0}).option("-d, --database",descriptions.database,{default:!0}).option("-ca, --cache",descriptions.cache,{default:!1}).option("-e, --email",descriptions.email,{default:!1}).option("-P, --project [project]",descriptions.project,{default:!1}).option("-m, --minimal",descriptions.minimal,{default:!1}).option("--with-core",descriptions.withCore,{default:!1}).option("--vendor-defaults",descriptions.vendorDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name);isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){await unvendorCore(path,options);trimFrameworkOnlyFiles(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! \u269B\uFE0F"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}function isFolderCheck(path){if(!isFolder(path))return;if(readdirSync(path).filter((entry)=>entry!==".git").length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){if(await isOnline())return;log.info("It appears you are disconnected from the internet.");log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}async function isOnline(){try{return(await fetch("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:!0})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:!0})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:!1}}catch(error){return{isErr:!0,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github"),destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:!0,force:!0});cpSync(source,destination,{recursive:!0});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config"),destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path),changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:!0,force:!0})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"])try{chmodSync(resolve(path,script),493)}catch{}}async function ensureEnv(path,_options){log.info("Ensuring your environment is ready...");await ensurePantryInstalled();await ensurePantryDependencies(path);log.success("Environment is ready")}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example \u2192 .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:!0});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git")))log.info("Existing git repository detected, skipping git init");else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const result=await runCommand("./buddy unpublish:core --all --force",{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:!0})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path),scripts=applyAppPackageScripts(path);applyPackageAppTsconfig(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path});let strippedAny=!1;for(const{feature,configOutcome,filesRemoved}of results)if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=!0;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}if(!strippedAny)log.info(" \u2192 no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
1
+ import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{ensurePantryDependencies,ensurePantryInstalled,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create [name]").option("-n, --name [name]",descriptions.name,{default:!1}).option("-u, --ui",descriptions.ui,{default:!0}).option("-c, --components",descriptions.components,{default:!0}).option("-w, --web-components",descriptions.webComponents,{default:!0}).option("-p, --views",descriptions.views,{default:!0}).option("-f, --functions",descriptions.functions,{default:!0}).option("-a, --api",descriptions.api,{default:!0}).option("-d, --database",descriptions.database,{default:!0}).option("-ca, --cache",descriptions.cache,{default:!1}).option("-e, --email",descriptions.email,{default:!1}).option("-P, --project [project]",descriptions.project,{default:!1}).option("-m, --minimal",descriptions.minimal,{default:!1}).option("--with-core",descriptions.withCore,{default:!1}).option("--vendor-defaults",descriptions.vendorDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name);isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! \u269B\uFE0F"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}function isFolderCheck(path){if(!isFolder(path))return;if(readdirSync(path).filter((entry)=>entry!==".git").length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){if(await isOnline())return;log.info("It appears you are disconnected from the internet.");log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}async function isOnline(){try{return(await fetch("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)})).ok}catch{return!1}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:!0})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:!0})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:!1}}catch(error){return{isErr:!0,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github"),destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:!0,force:!0});cpSync(source,destination,{recursive:!0});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config"),destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path),changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:!0,force:!0})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"])try{chmodSync(resolve(path,script),493)}catch{}}async function ensureEnv(path,_options){log.info("Ensuring your environment is ready...");await ensurePantryInstalled();await ensurePantryDependencies(path);log.success("Environment is ready")}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example \u2192 .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:!0});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git")))log.info("Existing git repository detected, skipping git init");else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const result=await runCommand("./buddy unpublish:core --all --force",{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:!0})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path),scripts=applyAppPackageScripts(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path});let strippedAny=!1;for(const{feature,configOutcome,filesRemoved}of results)if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=!0;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}if(!strippedAny)log.info(" \u2192 no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
@@ -1,3 +1,3 @@
1
- import{lstatSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,path}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now(),ac=new AbortController,timer=setTimeout(()=>ac.abort(),timeoutMs);try{const message=await Promise.race([fn(),new Promise((_,rej)=>ac.signal.addEventListener("abort",()=>rej(Error(`timed out (>${Math.round(timeoutMs/1000)}s)`))))]);checks.push({name,status:"pass",message:`${message} (${Date.now()-start}ms)`})}catch(err){checks.push({name,status:err instanceof ProbeWarning?"warn":"fail",message:err instanceof Error?err.message:String(err)})}finally{clearTimeout(timer)}}async function mailDnsChecks(){const{hasExplicitEmailConfig,declaredDnsProvider,loadTsCloudConfig}=await import("./deploy");if(!hasExplicitEmailConfig())return[{name:"Mail DNS",status:"pass",message:"No config/email.ts (skipped)"}];const{email}=await import("@stacksjs/config"),cfg=email??{};if(cfg.server?.enabled!==!0)return[{name:"Mail DNS",status:"pass",message:"email.server.enabled is off (skipped)"}];const{describeMailDnsProvider,describeMailDnsRecords,describePostmaster,gatherMailDnsFacts,mailDomainFromConfig}=await import("../mail-dns-health"),{envFileForEnvironment,envFileKeys}=await import("../dns-credentials"),domain=mailDomainFromConfig(cfg);if(!domain)return[{name:"Mail DNS",status:"warn",message:"email.server.enabled is on but config/email.ts names no domain (set `domain` or a from-address)"}];const fs=await import("node:fs"),envFile=envFileForEnvironment("production"),envPath=resolve(process.cwd(),envFile),fileKeys=fs.existsSync(envPath)?envFileKeys(fs.readFileSync(envPath,"utf8")):new Set,dkimSelector="mail",[declared,facts]=await Promise.all([loadTsCloudConfig("production").then(declaredDnsProvider).catch(()=>{return}),gatherMailDnsFacts(domain,dkimSelector)]);return[{name:"Mail DNS provider",...describeMailDnsProvider({domain,zone:facts.zone,nameservers:facts.nameservers,declared,fileKeys,envFile})},{name:"Mail DNS records",...describeMailDnsRecords({domain,records:facts.records,dkimSelector,dmarcPolicy:cfg.server?.dmarc?.policy,mxAddresses:facts.mxAddresses})},{name:"Postmaster Tools",...describePostmaster(domain,cfg.server?.postmaster,facts.records.filter((record)=>record.type==="TXT"&&record.name===domain).map((record)=>record.content))}]}export function doctor(buddy){buddy.command("doctor","Run health checks on your Stacks installation").option("--no-fail","Print results but always exit 0 (CI ramp-up)").action(async(options)=>{log.debug("Running `buddy doctor` ...");await intro("buddy doctor");const checks=[],modulesPath=resolve(process.cwd(),"node_modules");try{if(lstatSync(modulesPath).isSymbolicLink()){const target=resolve(process.cwd(),readlinkSync(modulesPath)),insideProject=target.startsWith(`${resolve(process.cwd())}/`);checks.push({name:"Dependency tree",status:insideProject?"warn":"fail",message:insideProject?`node_modules is a symlink to ${target}`:`node_modules is a symlink to ${target}, which belongs to another project - installs here mutate it, and what runs locally is not what the lockfile resolves. Remove the link and run \`bun install\`.`})}else checks.push({name:"Dependency tree",status:"pass",message:"node_modules is this project's own"})}catch{checks.push({name:"Dependency tree",status:"warn",message:"node_modules is missing - run `bun install`"})}await probe(checks,"Framework defaults",async()=>{const{measureDefaultsDrift,summarizeStructureChanges}=await import("@stacksjs/actions"),root=resolve(process.cwd()),skew=inspectDefaultsProvenance(root);if(skew.status==="not-applicable")return"Not a package-managed project (nothing to compare)";const drift=measureDefaultsDrift(root)??[],synced=skew.syncedAt?`, synced ${skew.syncedAt.slice(0,10)}`:"";if(drift.length===0)return`Vendored tree matches @stacksjs/defaults ${skew.installed}${synced}`;const counts=summarizeStructureChanges(drift);if(skew.status==="stale")throw new ProbeWarning(`storage/framework/defaults is from ${skew.vendored} while @stacksjs/defaults ${skew.installed} is installed (${counts}). Boot resolves the package, so the tree on disk is not what runs. Run \`buddy upgrade\` to sync it.`);throw new ProbeWarning(`storage/framework/defaults differs from the installed @stacksjs/defaults ${skew.installed} (${counts}), and carries no record of what it was synced from. The app runs the vendored copy. Run \`buddy upgrade\` to sync it.`)},8000);await probe(checks,"Route actions",async()=>{const{describeDanglingRouteActions,findDanglingRouteActions}=await import("@stacksjs/actions"),dangling=findDanglingRouteActions(resolve(process.cwd()));if(dangling.length===0)return"Every action a route names exists";throw new ProbeWarning(`${describeDanglingRouteActions(dangling).split(`
1
+ import{lstatSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,installedDefaultsVersion,path,usesVendoredDefaults}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now(),ac=new AbortController,timer=setTimeout(()=>ac.abort(),timeoutMs);try{const message=await Promise.race([fn(),new Promise((_,rej)=>ac.signal.addEventListener("abort",()=>rej(Error(`timed out (>${Math.round(timeoutMs/1000)}s)`))))]);checks.push({name,status:"pass",message:`${message} (${Date.now()-start}ms)`})}catch(err){checks.push({name,status:err instanceof ProbeWarning?"warn":"fail",message:err instanceof Error?err.message:String(err)})}finally{clearTimeout(timer)}}async function mailDnsChecks(){const{hasExplicitEmailConfig,declaredDnsProvider,loadTsCloudConfig}=await import("./deploy");if(!hasExplicitEmailConfig())return[{name:"Mail DNS",status:"pass",message:"No config/email.ts (skipped)"}];const{email}=await import("@stacksjs/config"),cfg=email??{};if(cfg.server?.enabled!==!0)return[{name:"Mail DNS",status:"pass",message:"email.server.enabled is off (skipped)"}];const{describeMailDnsProvider,describeMailDnsRecords,describePostmaster,gatherMailDnsFacts,mailDomainFromConfig}=await import("../mail-dns-health"),{envFileForEnvironment,envFileKeys}=await import("../dns-credentials"),domain=mailDomainFromConfig(cfg);if(!domain)return[{name:"Mail DNS",status:"warn",message:"email.server.enabled is on but config/email.ts names no domain (set `domain` or a from-address)"}];const fs=await import("node:fs"),envFile=envFileForEnvironment("production"),envPath=resolve(process.cwd(),envFile),fileKeys=fs.existsSync(envPath)?envFileKeys(fs.readFileSync(envPath,"utf8")):new Set,dkimSelector="mail",[declared,facts]=await Promise.all([loadTsCloudConfig("production").then(declaredDnsProvider).catch(()=>{return}),gatherMailDnsFacts(domain,dkimSelector)]);return[{name:"Mail DNS provider",...describeMailDnsProvider({domain,zone:facts.zone,nameservers:facts.nameservers,declared,fileKeys,envFile})},{name:"Mail DNS records",...describeMailDnsRecords({domain,records:facts.records,dkimSelector,dmarcPolicy:cfg.server?.dmarc?.policy,mxAddresses:facts.mxAddresses})},{name:"Postmaster Tools",...describePostmaster(domain,cfg.server?.postmaster,facts.records.filter((record)=>record.type==="TXT"&&record.name===domain).map((record)=>record.content))}]}export function doctor(buddy){buddy.command("doctor","Run health checks on your Stacks installation").option("--no-fail","Print results but always exit 0 (CI ramp-up)").action(async(options)=>{log.debug("Running `buddy doctor` ...");await intro("buddy doctor");const checks=[],modulesPath=resolve(process.cwd(),"node_modules");try{if(lstatSync(modulesPath).isSymbolicLink()){const target=resolve(process.cwd(),readlinkSync(modulesPath)),insideProject=target.startsWith(`${resolve(process.cwd())}/`);checks.push({name:"Dependency tree",status:insideProject?"warn":"fail",message:insideProject?`node_modules is a symlink to ${target}`:`node_modules is a symlink to ${target}, which belongs to another project - installs here mutate it, and what runs locally is not what the lockfile resolves. Remove the link and run \`bun install\`.`})}else checks.push({name:"Dependency tree",status:"pass",message:"node_modules is this project's own"})}catch{checks.push({name:"Dependency tree",status:"warn",message:"node_modules is missing - run `bun install`"})}await probe(checks,"Framework defaults",async()=>{const{measureDefaultsDrift,summarizeStructureChanges}=await import("@stacksjs/actions"),root=resolve(process.cwd()),skew=inspectDefaultsProvenance(root);if(skew.status==="not-applicable"){if(!usesVendoredDefaults(root)&&installedDefaultsVersion(root))return`Runs @stacksjs/defaults ${installedDefaultsVersion(root)} from node_modules (not vendored)`;return"Not a package-managed project (nothing to compare)"}const drift=measureDefaultsDrift(root)??[],synced=skew.syncedAt?`, synced ${skew.syncedAt.slice(0,10)}`:"";if(drift.length===0)return`Vendored tree matches @stacksjs/defaults ${skew.installed}${synced}. \`buddy unpublish:defaults\` drops the copy from the repository and runs the package instead`;const counts=summarizeStructureChanges(drift);if(skew.status==="stale")throw new ProbeWarning(`storage/framework/defaults is from ${skew.vendored} while @stacksjs/defaults ${skew.installed} is installed (${counts}). Boot resolves the package, so the tree on disk is not what runs. Run \`buddy upgrade\` to sync it.`);throw new ProbeWarning(`storage/framework/defaults differs from the installed @stacksjs/defaults ${skew.installed} (${counts}), and carries no record of what it was synced from. The app runs the vendored copy. Run \`buddy upgrade\` to sync it.`)},8000);await probe(checks,"Route actions",async()=>{const{describeDanglingRouteActions,findDanglingRouteActions}=await import("@stacksjs/actions"),dangling=findDanglingRouteActions(resolve(process.cwd()));if(dangling.length===0)return"Every action a route names exists";throw new ProbeWarning(`${describeDanglingRouteActions(dangling).split(`
2
2
  `).join("; ")}. Point each route at an action that exists, or delete it. \`buddy upgrade\` removes the ones the scaffold wrote.`)});await probe(checks,"Security overrides",async()=>{const{findShadowedSecurityDefaults,frameworkDefaultsDir,SHADOWED_DEFAULT_REVIEW_MARKER}=await import("@stacksjs/server"),defaultsDir=frameworkDefaultsDir("app");if(!defaultsDir)return"No framework defaults to compare against";const shadowed=findShadowedSecurityDefaults(path.appPath(),defaultsDir);if(shadowed.length===0)return"No app/ file shadows a framework security default";const identical=shadowed.filter((entry)=>entry.kind==="identical").map((entry)=>`app/${entry.path}`),modified=shadowed.filter((entry)=>entry.kind==="modified").map((entry)=>`app/${entry.path} (${SHADOWED_DEFAULT_REVIEW_MARKER} ${entry.fingerprint})`);throw new ProbeWarning([identical.length?`Unchanged copies, delete to receive security fixes: ${identical.join(", ")}.`:"",modified.length?`Differ from the current default, review and mark reviewed: ${modified.join(", ")}.`:""].filter(Boolean).join(" "))});const bunVersion=process.versions.bun;if(bunVersion&&isSupportedBunVersion(bunVersion))checks.push({name:"Bun Runtime",status:"pass",message:`v${bunVersion}`});else if(bunVersion)checks.push({name:"Bun Runtime",status:"fail",message:`v${bunVersion} (requires v${minimumBunVersion} or later, run: bun upgrade)`});else checks.push({name:"Bun Runtime",status:"fail",message:"Not found"});try{const pinnedBun=(await storage.readPackageJson("./package.json")).engines?.bun;if(pinnedBun&&bunVersion&&bunVersion!==pinnedBun)checks.push({name:"Pinned Bun",status:"warn",message:`v${bunVersion} is not the pinned v${pinnedBun} (engines.bun). Installing rewrites bun.lock - use \`./pantry/.bin/bun install\`, the pinned toolchain this checkout already carries, and \`git checkout -- bun.lock\` if it already changed.`});else if(pinnedBun&&bunVersion)checks.push({name:"Pinned Bun",status:"pass",message:`v${bunVersion} matches engines.bun`})}catch{}const nodeVersion=process.versions.node;if(nodeVersion)if(Number.parseInt(nodeVersion.split(".")[0]||"0",10)>=18)checks.push({name:"Node.js",status:"pass",message:`v${nodeVersion}`});else checks.push({name:"Node.js",status:"warn",message:`v${nodeVersion} (v18+ recommended)`});try{const pkg=await storage.readPackageJson("./package.json");if(pkg.name)checks.push({name:"package.json",status:"pass",message:`Found: ${pkg.name}`})}catch{checks.push({name:"package.json",status:"fail",message:"Not found in current directory"})}try{await storage.readTextFile(".env");checks.push({name:".env file",status:"pass",message:"Found"})}catch{checks.push({name:".env file",status:"warn",message:"Not found (optional)"})}const appKey=process.env.APP_KEY;if(appKey&&appKey.length>0)checks.push({name:"APP_KEY",status:appKey.length>=32?"pass":"warn",message:appKey.length>=32?"Set (\u226532 chars)":`Set but short (${appKey.length} chars; \u226532 recommended)`});else checks.push({name:"APP_KEY",status:"fail",message:"Not set - features that depend on it (encrypted columns, signed URLs, env decryption) will refuse to run. Run `buddy key:generate`."});await probe(checks,"SQLite Engine",async()=>{const{Database}=await import("bun:sqlite"),memory=new Database(":memory:");let version;try{const row=memory.query("SELECT sqlite_version() AS version").get();if(typeof row?.version==="string")version=row.version}finally{memory.close()}if(!version)throw new ProbeWarning("could not read sqlite_version() (skipped)");if(!isVersionGreaterThanOrEqual(version,minimumSqliteVersion))throw Error(`v${version} is below the required v${minimumSqliteVersion} (system.sqlite in package.json); upgrade Bun for a newer bundled SQLite`);return`v${version}`});await probe(checks,"Database",async()=>{const{db}=await import("@stacksjs/database"),unsafe=db.unsafe;if(typeof unsafe!=="function")throw new ProbeWarning("driver exposes no raw query method (skipped)");const statement=unsafe("SELECT 1");if(!statement||typeof statement.then!=="function"&&typeof statement.execute!=="function")throw new ProbeWarning("driver returned a non-executable statement (skipped)");const result=typeof statement.execute==="function"?await statement.execute():await statement;if(result===void 0||result===null)throw Error("probe query returned no result");if(Array.isArray(result)&&result.length===0)throw Error("probe query returned no rows");return"Reachable"});await probe(checks,"Database FKs",async()=>{const{auditForeignKeys}=await import("@stacksjs/database"),result=await auditForeignKeys();if(result.declared.length===0)return"No belongsTo declarations";const skipped=result.absentTable.length>0?`, ${result.absentTable.length} on tables not migrated`:"";if(result.missing.length===0)return`${result.declared.length} declared FKs all present${skipped}`;const sample=result.missing.slice(0,5).map((fk)=>`${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"";throw Error(`${result.missing.length}/${result.declared.length} declared FKs missing from live schema: ${sample}${more}${skipped}. Run \`buddy migrate:fresh\` (will reset data) or \`buddy migrate\` against a clean DB.`)});await probe(checks,"Unique indexes",async()=>{const{auditUniqueIndexes}=await import("@stacksjs/database"),result=await auditUniqueIndexes();if(!result.supported)return"Dialect not audited (skipped)";const skipped=result.skippedTables.length>0?`, ${result.skippedTables.length} tables skipped (not migrated)`:"";if(result.missing.length===0)return`${result.declared.length} declared unique constraints all indexed${skipped}`;const sample=result.missing.slice(0,5).map((u)=>`${u.table}.${u.columns.join("+")}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"",first=result.missing[0];if(!first)throw Error("Unique-index audit reported missing entries without details");const example=`CREATE UNIQUE INDEX IF NOT EXISTS "${first.table}_${first.columns.join("_")}_unique" ON "${first.table}" ("${first.columns.join('", "')}")`;throw Error(`${result.missing.length}/${result.declared.length} declared unique constraints have no UNIQUE index: ${sample}${more}. Run \`buddy migrate\` (re-queues missing unique-index migrations, #1952) - dedupe duplicate rows first or migrate hard-fails; if no migration file exists run \`buddy generate:migrations\`, or create manually: ${example}`)},1e4);await probe(checks,"Migration ledger",async()=>{const{auditMigrationLedger}=await import("@stacksjs/database"),result=await auditMigrationLedger();if(!result.supported)return"Dialect not audited (skipped)";if(result.entries.length===0)return"No migration files";const{counts,orphans}=result;if(!result.drift)return`${result.entries.length} migrations, ledger consistent with the schema`;const parts=[];if(counts.stranded>0)parts.push(`${counts.stranded} applied but unrecorded (would re-run)`);if(counts.partial>0)parts.push(`${counts.partial} half-applied`);if(counts.reverted>0)parts.push(`${counts.reverted} recorded but missing from the schema`);if(orphans.length>0)parts.push(`${orphans.length} ledger row(s) with no file on disk`);const needsReapply=counts.reverted+counts.partial,repair=needsReapply>0?`\`buddy migrate:status --reconcile\` cannot repair ${needsReapply} of these - it never runs migration SQL, so it skips anything the schema is missing. Those need re-applying: \`buddy migrate:fresh\` (rebuilds from the corpus, RESETS DATA), or restore the database and re-run the missing files by hand.`:"Repair with `buddy migrate:status --reconcile`.";throw Error(`Migration ledger has drifted: ${parts.join(", ")}. Inspect with \`buddy migrate:status\`. ${repair}`)},1e4);await probe(checks,"FK orphans",async()=>{const{findFkOrphans}=await import("@stacksjs/database"),result=await findFkOrphans();if(!result.supported)return"Dialect not audited (skipped)";if(result.total===0)return"No orphan rows (PRAGMA foreign_key_check clean)";const sample=result.orphans.slice(0,5).map((o)=>`${o.table}.${o.column} \u2192 ${o.parent} (${o.count})`).join(", "),more=result.orphans.length>5?` (+${result.orphans.length-5} more)`:"",first=result.orphans[0];if(!first)throw Error("Foreign-key audit reported orphan rows without details");throw Error(`${result.total} orphan rows violate FKs: ${sample}${more}. Legacy rows written under foreign_keys=OFF (#1951). Review and clean manually, e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}) - doctor never deletes data.`)},1e4);await probe(checks,"Cache",async()=>{const{cache}=await import("@stacksjs/cache"),k=`__doctor_${Date.now()}`;await cache.set(k,1,5);const v=await cache.get(k);await cache.del(k);if(v!==1)throw Error("round-trip failed");return"Round-trip ok"});await probe(checks,"Queue driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.queue?.default??"sync"}`});await probe(checks,"Mail driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.email?.default??"log"}`});{const budget=new Promise((resolve)=>setTimeout(()=>resolve([{name:"Mail DNS",status:"warn",message:"DNS lookups timed out (>6s) (skipped)"}]),6000).unref?.());checks.push(...await Promise.race([mailDnsChecks(),budget]).catch((err)=>[{name:"Mail DNS",status:"warn",message:`Could not audit mail DNS: ${err instanceof Error?err.message:String(err)}`}]))}{const{ensureRuntimeDirectories,projectPath}=await import("@stacksjs/path"),leftover=ensureRuntimeDirectories().filter((entry)=>!entry.cleared);checks.push(leftover.length===0?{name:"Runtime directories",status:"pass",message:"All under storage/"}:{name:"Runtime directories",status:"warn",message:`Still in the project root: ${leftover.map((entry)=>entry.legacy.slice(projectPath().length+1)).join(", ")} - remove them so state stays under storage/`})}const hasAwsCreds=Boolean(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY),hasAwsRole=Boolean(process.env.AWS_PROFILE)||Boolean(process.env.AWS_ROLE_ARN);if(hasAwsCreds||hasAwsRole)checks.push({name:"AWS credentials",status:"pass",message:hasAwsCreds?"Static keys in env":"IAM role configured"});else checks.push({name:"AWS credentials",status:"warn",message:"Not configured (cloud / SES / S3 commands will fail)"});await probe(checks,"Database backups",async()=>{const fs=await import("node:fs"),cloudConfig=resolve(process.cwd(),"config/cloud.ts");if(!fs.existsSync(cloudConfig))return"No config/cloud.ts (skipped)";const{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}=await import("../unbacked-data");let tsCloud;try{tsCloud=(await import(cloudConfig)).tsCloud}catch{throw new ProbeWarning("could not read config/cloud.ts (skipped)")}const unbacked=findUnbackedManagedServices(tsCloud,await hasOffsiteBackupDestination());if(unbacked.length===0)return"No unbacked managed data services";throw new ProbeWarning(unbackedDataMessage(unbacked))});await probe(checks,".env decryption",async()=>{const fs=await import("node:fs");if(!fs.existsSync(".env"))return"No .env (skipped)";const content=fs.readFileSync(".env","utf8");if(!/(?:^|=)(?:enc|encrypted):/m.test(content))return"No encrypted values";const privateKey=process.env.DOTENV_PRIVATE_KEY;if(!privateKey)throw Error("Encrypted values present but DOTENV_PRIVATE_KEY is unset");const{parse}=await import("@stacksjs/env"),{errors}=parse(content,{privateKey});if(errors.length>0)throw Error(errors.join("; "));return"All encrypted values decrypt cleanly"});try{const{filesystems}=await import("@stacksjs/config"),driver=filesystems.driver??"local";if(driver==="s3"){const bucket=process.env.S3_BUCKET??filesystems.s3?.bucket,accessKeyId=process.env.AWS_ACCESS_KEY_ID,secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY,missing=[];if(!bucket)missing.push("S3_BUCKET");if(!accessKeyId)missing.push("AWS_ACCESS_KEY_ID");if(!secretAccessKey)missing.push("AWS_SECRET_ACCESS_KEY");if(missing.length>0)checks.push({name:"Storage credentials",status:"warn",message:`Default disk is 's3' but missing: ${missing.join(", ")}. Uploads will throw on first use.`});else checks.push({name:"Storage credentials",status:"pass",message:"s3 default disk has bucket + AWS credentials"})}else checks.push({name:"Storage credentials",status:"pass",message:`Default disk is '${driver}' (no remote credentials required)`})}catch(err){checks.push({name:"Storage credentials",status:"warn",message:`Could not audit storage config: ${err instanceof Error?err.message:String(err)}`})}try{if(process.platform!=="darwin")checks.push({name:"Dev domains (rpx)",status:"pass",message:"Not macOS (skipped)"});else{const fs=await import("node:fs"),os=await import("node:os"),path=await import("node:path"),isAlive=(pid)=>{try{process.kill(pid,0);return!0}catch(err){return err.code==="EPERM"}},registryDir=path.join(os.homedir(),".stacks","rpx","registry.d"),registered=new Set,deadRegistryFiles=[];if(fs.existsSync(registryDir))for(const file of fs.readdirSync(registryDir)){if(!file.endsWith(".json"))continue;try{const entry=JSON.parse(fs.readFileSync(path.join(registryDir,file),"utf8"));if(entry.to&&(entry.pid===void 0||isAlive(entry.pid)))registered.add(entry.to.toLowerCase());if(typeof entry.pid==="number"&&!isAlive(entry.pid))deadRegistryFiles.push(file)}catch{}}const staleHosts=new Set,staleResolvers=[],hostsPath="/etc/hosts",hostsLines=fs.existsSync(hostsPath)?fs.readFileSync(hostsPath,"utf8").split(`
3
3
  `):[];for(let i=0;i<hostsLines.length;i++){const line=hostsLines[i];if(line.trim()==="# Added by rpx"){for(let j=i+1;j<hostsLines.length;j++){const blockLine=hostsLines[j].trim();if(blockLine===""||blockLine.startsWith("#"))break;const names=blockLine.split("#")[0]?.trim().split(/\s+/).slice(1)??[];for(const name of names)if(!registered.has(name.toLowerCase()))staleHosts.add(name)}continue}const hash=line.indexOf("#");if(hash===-1)continue;const marker=/^rpx(?::pid=(\d+))?$/.exec(line.slice(hash+1).trim());if(!marker)continue;const names=line.slice(0,hash).trim().split(/\s+/).slice(1),pid=marker[1]?Number.parseInt(marker[1],10):null;if(pid!==null?!isAlive(pid):names.every((n)=>!registered.has(n.toLowerCase())))for(const name of names)staleHosts.add(name)}const resolverDir="/etc/resolver";if(fs.existsSync(resolverDir))for(const file of fs.readdirSync(resolverDir))try{const content=fs.readFileSync(path.join(resolverDir,file),"utf8");if(!content.includes("127.0.0.1")||!content.includes("15353"))continue;const domain=file.toLowerCase();if(![...registered].some((host)=>host===domain||host.endsWith(`.${domain}`)))staleResolvers.push(file)}catch{}if(staleHosts.size>0||staleResolvers.length>0||deadRegistryFiles.length>0){const parts=[];if(staleHosts.size>0)parts.push(`hosts(${[...staleHosts].join(", ")})`);if(staleResolvers.length>0)parts.push(`resolver(${staleResolvers.join(", ")})`);if(deadRegistryFiles.length>0)parts.push(`registry(${deadRegistryFiles.join(", ")})`);checks.push({name:"Dev domains (rpx)",status:"warn",message:`Stale loopback overrides from dead dev sessions: ${parts.join(" ")}. These keep pointing the domain at 127.0.0.1. Remove with: sudo nano /etc/hosts; sudo rm /etc/resolver/<name>; rm ~/.stacks/rpx/registry.d/<file>. Updating @stacksjs/rpx lets the daemon sweep pid-stamped entries automatically.`})}else checks.push({name:"Dev domains (rpx)",status:"pass",message:"No stale dev-domain overrides"})}}catch(err){checks.push({name:"Dev domains (rpx)",status:"warn",message:`Could not audit dev-domain overrides: ${err instanceof Error?err.message:String(err)}`})}await probe(checks,"Dev ports",async()=>{const net=await import("node:net"),{config}=await import("@stacksjs/config"),configured=config.ports??{},targets=[{name:"frontend",key:"frontend",envVar:"PORT",fallback:3000},{name:"api",key:"api",envVar:"PORT_API",fallback:3008},{name:"docs",key:"docs",envVar:"PORT_DOCS",fallback:3006},{name:"dashboard",key:"admin",envVar:"PORT_ADMIN",fallback:3002}].map((t)=>({...t,port:Number(configured[t.key])||t.fallback})),canConnect=(port,host)=>new Promise((resolve)=>{const socket=net.createConnection({port,host});socket.setTimeout(400);const done=(occupied)=>{socket.destroy();resolve(occupied)};socket.once("connect",()=>done(!0));socket.once("timeout",()=>done(!1));socket.once("error",()=>done(!1))}),occupied=new Set;await Promise.all([...new Set(targets.map((t)=>t.port))].map(async(port)=>{if(await canConnect(port,"127.0.0.1")||await canConnect(port,"::1"))occupied.add(port)}));const busy=targets.filter((t)=>occupied.has(t.port));if(busy.length>0){const list=busy.map((t)=>`${t.name} :${t.port} (${t.envVar})`).join(", ");throw new ProbeWarning(`in use: ${list}. buddy dev will fail to bind; stop the process holding the port or set the override env var`)}return`All free: ${targets.map((t)=>`${t.name} :${t.port}`).join(", ")}`});try{const orphans=[];for(const name of FEATURE_NAMES){if(feature(name))continue;const present=featurePathsPresent(name);if(present.length>0)orphans.push({feature:name,count:present.length})}if(orphans.length>0){const summary=orphans.map((o)=>`${o.feature} (${o.count} path${o.count===1?"":"s"})`).join(", ");checks.push({name:"Feature scaffolding",status:"warn",message:`Stamped files remain for disabled features: ${summary}. Run \`./buddy <feature>:uninstall\` to remove or \`<feature>:install\` to re-enable.`})}else checks.push({name:"Feature scaffolding",status:"pass",message:"No orphan files for disabled features"})}catch(err){checks.push({name:"Feature scaffolding",status:"warn",message:`Could not audit feature scaffolding: ${err instanceof Error?err.message:String(err)}`})}log.info("");log.info(bold("Health Check Results:"));log.info(dim("\u2500".repeat(60)));log.info("");let hasFailures=!1,hasWarnings=!1;for(const check of checks){let statusIcon="",statusColor=(text)=>text;if(check.status==="pass"){statusIcon="\u2713";statusColor=green}else if(check.status==="warn"){statusIcon="\u26A0";statusColor=yellow;hasWarnings=!0}else{statusIcon="\u2717";statusColor=red;hasFailures=!0}log.info(`${statusColor(statusIcon)} ${bold(check.name.padEnd(20))} ${dim(check.message)}`)}log.info("");log.info(dim("\u2500".repeat(60)));log.info("");if(hasFailures){log.error("Some critical checks failed. Please address the issues above.");if(options?.fail!==!1){await log.flush();process.exit(1)}}else if(hasWarnings)log.info(yellow("Some checks have warnings. Your system should work but may have issues."));else log.success(green("All checks passed! Your Stacks installation looks healthy."));log.info("")});onUnknownSubcommand(buddy,"doctor")}
@@ -1,7 +1,7 @@
1
- import{existsSync,lstatSync,mkdirSync,realpathSync,unlinkSync}from"node:fs";import{cp,readdir,stat}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";import process from"node:process";import{italic,log,onUnknownSubcommand}from"@stacksjs/cli";import{syncPackageProjectFiles}from"@stacksjs/actions/upgrade/package-project";import{installedDefaultsVersion,linkPackagedDefaults,packagedDefaultsRoot,path,usesVendoredDefaults}from"@stacksjs/path";import{fs,globSync}from"@stacksjs/storage";import{pruneVendoredCoreFromWorkflows,splitFrameworkTypecheckScript}from"../workflow-prune";import{detectInstaller,findCoreReferences,INSTALL_RETRY_DELAYS_MS,installWithRetry,isDanglingLink,rewriteCoreCommandPaths,rewriteCoreSourceImports,rewriteSurvivingFrameworkManifests}from"../unvendor-rewrite";import{fetchPublishedVersions}from"../registry";import{adoptPackagedDefaults,unignoreDefaults,VENDORED_DEFAULTS}from"../scaffold-package-app";import{ExitCode}from"@stacksjs/types";export function publish(buddy){const descriptions={command:"Publish a Stacks default into your userland (app/) directory so you can customize it",model:"Publish a default model from storage/framework/defaults/app/Models/ to app/Models/",controller:"Publish a default controller from storage/framework/defaults/app/Controllers/ to app/Controllers/",middleware:"Publish a default middleware from storage/framework/defaults/app/Middleware/ to app/Middleware/",action:"Publish a default action from storage/framework/defaults/app/Actions/ to app/Actions/",core:"Publish a framework package source from node_modules/@stacksjs/<pkg>/ into storage/framework/core/<pkg>/ for editing",unpublishCore:"Drop a vendored storage/framework/core/<pkg>/ and go back to the installed @stacksjs/<pkg>",all:"Unvendor the whole framework: remove storage/framework/core and resolve every @stacksjs package from the `stacks` dependency in package.json",publishAll:"Vendor the whole framework: copy storage/framework/core out of a local Stacks checkout and wire it up as a Bun workspace",frameworkPath:"The Stacks checkout to vendor from (defaults to $STACKS_FRAMEWORK_PATH, ../stacks, then ~/Code/stacks)",coreStatus:"Report whether this project runs on a vendored storage/framework/core or on the published packages",publishDefaults:"Commit a copy of the framework defaults in storage/framework/defaults instead of linking it to node_modules/@stacksjs/defaults",unpublishDefaults:"Drop the vendored storage/framework/defaults and run the installed @stacksjs/defaults through a gitignored link",forceDefaults:"Drop the vendored tree even where it differs from the installed package",name:"The name of the resource to publish (e.g. Cart, User)",pkg:"The name of the framework package (e.g. router, orm, faker - without @stacksjs/ prefix)",force:"Overwrite an existing userland file",forceUnpublish:"Delete the vendored source even when it has uncommitted changes",verbose:"Enable verbose output"};buddy.command("publish:model <name>",descriptions.model).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force})});buddy.command("publish:controller <name>",descriptions.controller).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force})});buddy.command("publish:middleware <name>",descriptions.middleware).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force})});buddy.command("publish:action <name>",descriptions.action).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force})});buddy.command("publish:core [pkg]",descriptions.core).option("--all",descriptions.publishAll,{default:!1}).option("--path <path>",descriptions.frameworkPath).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:core router").example("buddy publish:core --all").example("buddy publish:core --all --path ../stacks").action(async(pkg,options)=>{if(options.all){await vendorFramework(options.path,!!options.force);return}if(!pkg){await log.error("Usage: buddy publish:core <pkg> (or --all to vendor the whole framework as a workspace)");process.exit(ExitCode.FatalError)}await publishCorePackage(pkg,!!options.force)});buddy.command("core:status",descriptions.coreStatus).alias("publish:core:status").option("--verbose",descriptions.verbose,{default:!1}).example("buddy core:status").action(async()=>{await reportCoreStatus()});buddy.command("unpublish:core [pkg]",descriptions.unpublishCore).option("--all",descriptions.all,{default:!1}).option("--force",descriptions.forceUnpublish,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(pkg,options)=>{if(options.all){await unvendorFramework(!!options.force);return}if(!pkg){await log.error("Usage: buddy unpublish:core <pkg> (or --all to move the whole framework to node_modules)");process.exit(ExitCode.FatalError)}await unpublishCorePackage(pkg,!!options.force)});buddy.command("publish:defaults",descriptions.publishDefaults).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:defaults").action(async()=>{await vendorDefaults()});buddy.command("unpublish:defaults",descriptions.unpublishDefaults).option("--force",descriptions.forceDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy unpublish:defaults").action(async(options)=>{await unvendorDefaults(!!options.force)});buddy.command("publish [resource] [name]",descriptions.command).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(resource,name,options)=>{if(!resource||!name){await log.error("Usage: buddy publish:<resource> <Name> (e.g. buddy publish:model Cart)");process.exit(ExitCode.FatalError)}const handler={model:()=>publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force}),controller:()=>publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force}),middleware:()=>publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force}),action:()=>publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force}),core:()=>publishCorePackage(name,!!options.force)}[resource.toLowerCase()];if(!handler){await log.error(`Unknown publishable resource: ${italic(resource)}`);log.info("Available: model, controller, middleware, action, core");await log.flush();process.exit(ExitCode.FatalError)}await handler()});onUnknownSubcommand(buddy,"publish")}async function publishCorePackage(pkg,force){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,""),fail=(msg,hint)=>{process.stderr.write(`${msg}
1
+ import{existsSync,lstatSync,mkdirSync,realpathSync,unlinkSync}from"node:fs";import{cp,readdir,stat}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";import process from"node:process";import{italic,log,onUnknownSubcommand}from"@stacksjs/cli";import{syncPackageProjectFiles,vendorDefaultsTree}from"@stacksjs/actions/upgrade/package-project";import{installedDefaultsVersion,linkPackagedDefaults,packagedDefaultsRoot,path,usesVendoredDefaults}from"@stacksjs/path";import{fs,globSync}from"@stacksjs/storage";import{pruneVendoredCoreFromWorkflows,splitFrameworkTypecheckScript}from"../workflow-prune";import{detectInstaller,findCoreReferences,INSTALL_RETRY_DELAYS_MS,installWithRetry,isDanglingLink,rewriteCoreCommandPaths,rewriteCoreSourceImports,rewriteSurvivingFrameworkManifests}from"../unvendor-rewrite";import{fetchPublishedVersions}from"../registry";import{adoptPackagedDefaults,unignoreDefaults,VENDORED_DEFAULTS}from"../scaffold-package-app";import{ExitCode}from"@stacksjs/types";export function publish(buddy){const descriptions={command:"Publish a Stacks default into your userland (app/) directory so you can customize it",model:"Publish a default model from storage/framework/defaults/app/Models/ to app/Models/",controller:"Publish a default controller from storage/framework/defaults/app/Controllers/ to app/Controllers/",middleware:"Publish a default middleware from storage/framework/defaults/app/Middleware/ to app/Middleware/",action:"Publish a default action from storage/framework/defaults/app/Actions/ to app/Actions/",core:"Publish a framework package source from node_modules/@stacksjs/<pkg>/ into storage/framework/core/<pkg>/ for editing",unpublishCore:"Drop a vendored storage/framework/core/<pkg>/ and go back to the installed @stacksjs/<pkg>",all:"Unvendor the whole framework: remove storage/framework/core and resolve every @stacksjs package from the `stacks` dependency in package.json",publishAll:"Vendor the whole framework: copy storage/framework/core out of a local Stacks checkout and wire it up as a Bun workspace",frameworkPath:"The Stacks checkout to vendor from (defaults to $STACKS_FRAMEWORK_PATH, ../stacks, then ~/Code/stacks)",coreStatus:"Report whether this project runs on a vendored storage/framework/core or on the published packages",publishDefaults:"Commit a copy of the framework defaults in storage/framework/defaults instead of linking it to node_modules/@stacksjs/defaults",unpublishDefaults:"Drop the vendored storage/framework/defaults and run the installed @stacksjs/defaults through a gitignored link",forceDefaults:"Drop the vendored tree even where it differs from the installed package",name:"The name of the resource to publish (e.g. Cart, User)",pkg:"The name of the framework package (e.g. router, orm, faker - without @stacksjs/ prefix)",force:"Overwrite an existing userland file",forceUnpublish:"Delete the vendored source even when it has uncommitted changes",verbose:"Enable verbose output"};buddy.command("publish:model <name>",descriptions.model).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force})});buddy.command("publish:controller <name>",descriptions.controller).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force})});buddy.command("publish:middleware <name>",descriptions.middleware).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force})});buddy.command("publish:action <name>",descriptions.action).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force})});buddy.command("publish:core [pkg]",descriptions.core).option("--all",descriptions.publishAll,{default:!1}).option("--path <path>",descriptions.frameworkPath).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:core router").example("buddy publish:core --all").example("buddy publish:core --all --path ../stacks").action(async(pkg,options)=>{if(options.all){await vendorFramework(options.path,!!options.force);return}if(!pkg){await log.error("Usage: buddy publish:core <pkg> (or --all to vendor the whole framework as a workspace)");process.exit(ExitCode.FatalError)}await publishCorePackage(pkg,!!options.force)});buddy.command("core:status",descriptions.coreStatus).alias("publish:core:status").option("--verbose",descriptions.verbose,{default:!1}).example("buddy core:status").action(async()=>{await reportCoreStatus()});buddy.command("unpublish:core [pkg]",descriptions.unpublishCore).option("--all",descriptions.all,{default:!1}).option("--force",descriptions.forceUnpublish,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(pkg,options)=>{if(options.all){await unvendorFramework(!!options.force);return}if(!pkg){await log.error("Usage: buddy unpublish:core <pkg> (or --all to move the whole framework to node_modules)");process.exit(ExitCode.FatalError)}await unpublishCorePackage(pkg,!!options.force)});buddy.command("publish:defaults",descriptions.publishDefaults).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:defaults").action(async()=>{await vendorDefaults()});buddy.command("unpublish:defaults",descriptions.unpublishDefaults).option("--force",descriptions.forceDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy unpublish:defaults").action(async(options)=>{await unvendorDefaults(!!options.force)});buddy.command("publish [resource] [name]",descriptions.command).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(resource,name,options)=>{if(!resource||!name){await log.error("Usage: buddy publish:<resource> <Name> (e.g. buddy publish:model Cart)");process.exit(ExitCode.FatalError)}const handler={model:()=>publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force}),controller:()=>publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force}),middleware:()=>publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force}),action:()=>publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force}),core:()=>publishCorePackage(name,!!options.force)}[resource.toLowerCase()];if(!handler){await log.error(`Unknown publishable resource: ${italic(resource)}`);log.info("Available: model, controller, middleware, action, core");await log.flush();process.exit(ExitCode.FatalError)}await handler()});onUnknownSubcommand(buddy,"publish")}async function publishCorePackage(pkg,force){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,""),fail=(msg,hint)=>{process.stderr.write(`${msg}
2
2
  `);if(hint)process.stderr.write(` ${hint}
3
3
  `);process.exit(ExitCode.FatalError)};if(!shortName||shortName.includes("/")||shortName.includes(".."))fail(`Invalid package name: ${pkg}`,"Use a short name like `router` or the fully qualified `@stacksjs/router`.");const sourceDir=resolve(process.cwd(),"node_modules","@stacksjs",shortName),targetDir=path.frameworkPath(`core/${shortName}`);try{if(!(await stat(sourceDir)).isDirectory())fail(`${sourceDir} is not a directory.`)}catch{fail(`Could not find @stacksjs/${shortName} in node_modules.`,"Run `bun install` first, or check the package name.")}if(existsSync(targetDir)&&!force)fail(`Already published: ${targetDir.replace(`${process.cwd()}/`,"")}`,"Pass --force to overwrite.");mkdirSync(dirname(targetDir),{recursive:!0});const SKIP=new Set(["node_modules","dist",".bun",".cache","tsconfig.tsbuildinfo"]);let copied=0;await copyTreeFiltered(sourceDir,targetDir,SKIP,()=>copied++);log.success(`Published @stacksjs/${shortName} \u2192 ${italic(targetDir.replace(`${process.cwd()}/`,""))} (${copied} files)`);log.info("Edit freely - local changes win over the installed package.")}async function copyTreeFiltered(sourceDir,targetDir,skip,onFile){mkdirSync(targetDir,{recursive:!0});const entries=await readdir(sourceDir,{withFileTypes:!0});for(const entry of entries){if(skip.has(entry.name))continue;const src=`${sourceDir}/${entry.name}`,dst=`${targetDir}/${entry.name}`;if(entry.isDirectory()){await copyTreeFiltered(src,dst,skip,onFile);continue}await cp(src,dst,{force:!0,dereference:!0});onFile()}}async function publishResource(ctx){const{kind,name,defaultsDir,userDir,force}=ctx,fileName=name.endsWith(".ts")?name:`${name}.ts`,matches=globSync([`${defaultsDir}/**/${fileName}`],{absolute:!0});if(!matches.length){await log.error(`Could not find default ${kind}: ${italic(fileName)}`);log.info(`Looked under: ${italic(defaultsDir)}`);await log.flush();process.exit(ExitCode.FatalError)}if(matches.length>1){log.warn(`Multiple defaults match ${italic(fileName)}; using the first:`);for(const m of matches)log.info(` ${m}`)}const sourcePath=matches[0];if(!sourcePath)throw Error(`Could not resolve default ${kind}: ${fileName}`);const targetPath=`${userDir.replace(/\/$/,"")}/${fileName}`;if(existsSync(targetPath)&&!force){await log.error(`Already exists: ${italic(targetPath)}`);log.info("Pass --force to overwrite.");await log.flush();process.exit(ExitCode.FatalError)}mkdirSync(dirname(targetPath),{recursive:!0});await fs.promises.copyFile(sourcePath,targetPath);const carried=await carryRelativeImports(sourcePath,targetPath);log.success(`Published ${kind} ${italic(name)} \u2192 ${italic(targetPath.replace(`${process.cwd()}/`,""))}`);for(const file of carried)log.info(` + ${italic(file.replace(`${process.cwd()}/`,""))} (imported by it)`)}export async function carryRelativeImports(sourcePath,targetPath,seen=new Set){if(seen.has(sourcePath))return[];seen.add(sourcePath);const source=await fs.promises.readFile(sourcePath,"utf-8"),written=[],root=realpathSync(process.cwd()),targetDir=realpathSync(dirname(targetPath)),specifiers=[...source.matchAll(/from\s+['"](\.[^'"]+)['"]/g)].map((match)=>match[1]);for(const specifier of new Set(specifiers)){if(!specifier)continue;const candidates=specifier.endsWith(".ts")?[specifier]:[`${specifier}.ts`,`${specifier}/index.ts`];for(const candidate of candidates){const from=resolve(dirname(sourcePath),candidate),to=resolve(targetDir,candidate);if(!existsSync(from))continue;if(!to.startsWith(`${root}/`))break;if(!existsSync(to)){mkdirSync(dirname(to),{recursive:!0});await fs.promises.copyFile(from,to);written.push(to)}written.push(...await carryRelativeImports(from,to,seen));break}}return written}async function vendorFramework(explicitPath,force){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(existsSync(coreDir)&&!force){log.info(`Already vendored: ${italic(rel(coreDir))}`);log.info("Pass --force to replace it with a fresh copy of the checkout.");return}const framework=resolveFrameworkCheckout(explicitPath);if(!framework){await log.error("No Stacks checkout found to vendor from.");log.info("Pass one with `--path <dir>`, or set STACKS_FRAMEWORK_PATH.");log.info("A checkout is required: the published packages ship `dist` only, so a copy of them would not be editable.");await log.flush();process.exit(ExitCode.FatalError)}const sourceCore=join(framework,"storage/framework/core"),corePkgPath=resolve(sourceCore,"package.json");if(!existsSync(corePkgPath)){await log.error(`${sourceCore} has no package.json - that does not look like a Stacks checkout.`);process.exit(ExitCode.FatalError)}const depName=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")).name??"stacks";log.info(`Vendoring the framework from ${italic(framework)}...`);if(existsSync(coreDir))await fs.promises.rm(coreDir,{recursive:!0,force:!0});const SKIP=new Set(["node_modules",".bun",".cache","tsconfig.tsbuildinfo"]);let copied=0;await copyTreeFiltered(sourceCore,coreDir,SKIP,()=>copied++);const rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")),provided=new Set([depName]);for(const entry of await readdir(coreDir,{withFileTypes:!0})){if(!entry.isDirectory())continue;if(existsSync(resolve(coreDir,entry.name,"package.json")))provided.add(`@stacksjs/${entry.name}`)}let repointed=0;for(const field of["dependencies","devDependencies"]){const deps=rootPkg[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!provided.has(name)||deps[name].startsWith("workspace:"))continue;deps[name]="workspace:*";repointed++}}if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:"workspace:*"};const workspaces=rootPkg.workspaces??[];let addedGlobs=0;for(const glob of["storage/framework/core","storage/framework/core/*"]){if(workspaces.some((existing)=>existing.replace(/^\.\//,"").replace(/\/$/,"")===glob))continue;workspaces.push(glob);addedGlobs++}rootPkg.workspaces=workspaces;await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
4
- `);const bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),next=bunfig.replace(/(["'])@stacksjs\/([\w-]+)\/([^"']+?)\.js\1/g,(match,quote,pkgName,subpath)=>{if(!provided.has(`@stacksjs/${pkgName}`))return match;rewrittenPreloads++;return`${quote}./storage/framework/core/${pkgName}/${subpath}.ts${quote}`});if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/tsconfig\.app\.json"/,'"extends": "./storage/framework/core/tsconfig.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}log.success(`Vendored ${copied} files into ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@workspace:*`);if(repointed>0)log.info(`Repointed ${repointed} version range${repointed===1?"":"s"} to workspace:*`);if(addedGlobs>0)log.info(`Added ${addedGlobs} workspace glob${addedGlobs===1?"":"s"} for the vendored packages`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to the vendored source`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/core/tsconfig.json");log.info("Linking the workspace...");if(await Bun.spawn(["bun","install"],{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited!==0){await log.error("`bun install` failed. The files are in place; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}log.success("This project now runs on the vendored framework - edits under storage/framework/core are live.");log.info("Go back to the published packages any time with `buddy unpublish:core --all`.")}function resolveFrameworkCheckout(explicit){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(process.cwd(),"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(candidate);if(full===resolve(process.cwd()))continue;if(existsSync(join(full,"storage/framework/core/package.json")))return full}return null}async function reportCoreStatus(){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,""),vendored=existsSync(resolve(coreDir,"package.json")),rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=existsSync(rootPkgPath)?JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")):{},declared=rootPkg.dependencies?.stacks??rootPkg.devDependencies?.stacks;if(vendored){const corePkg=JSON.parse(await fs.promises.readFile(resolve(coreDir,"package.json"),"utf-8")),packages=(await readdir(coreDir,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()&&existsSync(resolve(coreDir,entry.name,"package.json")));log.info(`Layout: vendored - ${italic(rel(coreDir))} (${packages.length} packages, v${corePkg.version??"unknown"})`);log.info(`Declared: stacks@${declared??"(not declared)"}`);if(declared&&!declared.startsWith("workspace:"))log.warn(`The vendored copy is not linked: stacks is declared as ${declared}, not workspace:*. Run \`buddy publish:core --all --force\` to relink, or \`buddy unpublish:core --all\` to remove it.`);log.info("Move to the published packages with `buddy unpublish:core --all`.");return}const installed=resolve(process.cwd(),"node_modules/@stacksjs/buddy/package.json"),installedVersion=existsSync(installed)?JSON.parse(await fs.promises.readFile(installed,"utf-8")).version:void 0;log.info("Layout: published packages - no storage/framework/core in this project");log.info(`Declared: stacks@${declared??"(not declared)"}`);log.info(`Installed: ${installedVersion?`v${installedVersion}`:"(run bun install)"}`);log.info("Vendor the framework for local development with `buddy publish:core --all`.")}async function unpublishCorePackage(pkg,force){const shortName=normalizeCoreName(pkg),targetDir=path.frameworkPath(`core/${shortName}`),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(targetDir)){log.info(`Not vendored: ${italic(rel(targetDir))} - nothing to do.`);return}const installed=resolve(process.cwd(),"node_modules","@stacksjs",shortName);if(!existsSync(installed)&&!force){await log.error(`@stacksjs/${shortName} is not installed, so removing the vendored copy would leave nothing to resolve.`);log.info(`Run \`bun add @stacksjs/${shortName}\` first, or pass --force to remove it anyway.`);await log.flush();process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(targetDir,force);await fs.promises.rm(targetDir,{recursive:!0,force:!0});log.success(`Unpublished ${italic(rel(targetDir))} - @stacksjs/${shortName} now resolves from node_modules.`)}export function packagesPreloadFilesFallBackTo(source){const found=new Set;for(const match of source.matchAll(/'@stacksjs\/'\s*\+\s*'([a-z0-9-]+)'/g))found.add(`@stacksjs/${match[1]}`);return found}export function rewriteBunfigPreloads(bunfig){const packages=new Set;let rewritten=0;return{next:bunfig.replace(/(["'])\.?\/?storage\/framework\/core\/([\w-]+)\/([^"']+?)\.ts\1/g,(_match,quote,pkgName,subpath)=>{rewritten++;packages.add(`@stacksjs/${pkgName}`);return`${quote}@stacksjs/${pkgName}/${subpath}.js${quote}`}),packages,rewritten}}async function vendorDefaults(){const root=path.projectPath();if(usesVendoredDefaults(root)){log.info(`${VENDORED_DEFAULTS} is already a vendored copy.`);return}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to copy. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const tree=resolve(root,VENDORED_DEFAULTS);try{if(lstatSync(tree).isSymbolicLink())unlinkSync(tree)}catch{}mkdirSync(tree,{recursive:!0});const changes=syncPackageProjectFiles(root,packageRoot,{vendorDefaults:!0});unignoreDefaults(root);log.success(`Copied @stacksjs/defaults ${installedDefaultsVersion(root)??""} into ${VENDORED_DEFAULTS} (${changes.length} files). Commit it; \`buddy upgrade\` keeps it current.`);log.info("Go back to the link any time with `buddy unpublish:defaults`.")}async function unvendorDefaults(force){const root=path.projectPath();if(!usesVendoredDefaults(root)){linkPackagedDefaults(root);log.info(`${VENDORED_DEFAULTS} already runs from node_modules/@stacksjs/defaults.`);return}if(existsSync(resolve(root,"storage/framework/core/buddy/package.json"))){await log.error("This project vendors the framework itself (storage/framework/core), and its defaults tree is the source the package is built from. Run `buddy unpublish:core --all` first.");process.exit(ExitCode.FatalError)}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to run the defaults from. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const differs=syncPackageProjectFiles(root,packageRoot,{dryRun:!0,vendorDefaults:!0}).filter((change)=>change.path.startsWith(`${VENDORED_DEFAULTS}/`));if(differs.length>0&&!force){await log.error(`${VENDORED_DEFAULTS} differs from the installed @stacksjs/defaults ${installedDefaultsVersion(root)??""} in ${differs.length} place${differs.length===1?"":"s"}:`);for(const change of differs.slice(0,15))log.error(` ${change.action==="add"?"missing":change.action==="remove"?"extra ":"changed"} ${change.path}`);if(differs.length>15)log.error(` ... and ${differs.length-15} more`);log.info("A tree from another release: run `buddy upgrade` first. A file you edited: move it to the same path under app/, which wins over the defaults. Then run this again, or pass --force to drop the differences.");await log.flush();process.exit(ExitCode.FatalError)}const adopted=adoptPackagedDefaults(root);log.success(`Removed ${VENDORED_DEFAULTS}; it now links to ${adopted.packageRoot.replace(`${root}/`,"")} and is gitignored.`);for(const file of[...adopted.rewrittenImports,...adopted.rewrittenModulePaths])log.info(` repointed ${file} at @stacksjs/defaults`);log.info("Commit the removal. Go back to a vendored copy any time with `buddy publish:defaults`.")}async function unvendorFramework(force){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(coreDir)){log.info("No storage/framework/core in this project - already on the installed packages.");return}const corePkgPath=resolve(coreDir,"package.json");if(!existsSync(corePkgPath)){await log.error(`${rel(coreDir)} has no package.json, so its version cannot be determined.`);log.info("Unvendor the packages individually with `buddy unpublish:core <pkg>` instead.");await log.flush();process.exit(ExitCode.FatalError)}const corePkg=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")),version=corePkg.version;if(!version){await log.error(`${rel(corePkgPath)} has no version field.`);process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(coreDir,force);const depName=corePkg.name??"stacks",range=`^${await resolvePublishedVersion(depName,version)}`,rootPkgPath=resolve(process.cwd(),"package.json"),rootPkgRaw=await fs.promises.readFile(rootPkgPath,"utf-8"),rootPkg=JSON.parse(rootPkgRaw),provided=new Set([depName,...Object.keys(corePkg.dependencies??{}).filter((name)=>name.startsWith("@stacksjs/"))]);for(const entry of await readdir(coreDir,{withFileTypes:!0}))if(entry.isDirectory())provided.add(`@stacksjs/${entry.name}`);let repointed=0;const repointWorkspaceRanges=(pkg)=>{let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;deps[name]=range;touched=!0;repointed++}}return touched};repointWorkspaceRanges(rootPkg);if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:range};let rewrittenScripts=0;for(const[name,script]of Object.entries(rootPkg.scripts??{})){if(!/storage\/framework\/core\/buddy\/src\/cli\.ts/.test(script))continue;rootPkg.scripts[name]=script.replace(/\bbunx?\s+(?:--bun\s+)?\.?\/?storage\/framework\/core\/buddy\/src\/cli\.ts/g,"./buddy");rewrittenScripts++}if(Array.isArray(rootPkg.workspaces)){rootPkg.workspaces=rootPkg.workspaces.filter((glob)=>!isCoreWorkspaceGlob(glob));if(rootPkg.workspaces.length===0)delete rootPkg.workspaces}await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
4
+ `);const bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),next=bunfig.replace(/(["'])@stacksjs\/([\w-]+)\/([^"']+?)\.js\1/g,(match,quote,pkgName,subpath)=>{if(!provided.has(`@stacksjs/${pkgName}`))return match;rewrittenPreloads++;return`${quote}./storage/framework/core/${pkgName}/${subpath}.ts${quote}`});if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/tsconfig\.app\.json"/,'"extends": "./storage/framework/core/tsconfig.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}log.success(`Vendored ${copied} files into ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@workspace:*`);if(repointed>0)log.info(`Repointed ${repointed} version range${repointed===1?"":"s"} to workspace:*`);if(addedGlobs>0)log.info(`Added ${addedGlobs} workspace glob${addedGlobs===1?"":"s"} for the vendored packages`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to the vendored source`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/core/tsconfig.json");log.info("Linking the workspace...");if(await Bun.spawn(["bun","install"],{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited!==0){await log.error("`bun install` failed. The files are in place; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}log.success("This project now runs on the vendored framework - edits under storage/framework/core are live.");log.info("Go back to the published packages any time with `buddy unpublish:core --all`.")}function resolveFrameworkCheckout(explicit){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(process.cwd(),"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(candidate);if(full===resolve(process.cwd()))continue;if(existsSync(join(full,"storage/framework/core/package.json")))return full}return null}async function reportCoreStatus(){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,""),vendored=existsSync(resolve(coreDir,"package.json")),rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=existsSync(rootPkgPath)?JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")):{},declared=rootPkg.dependencies?.stacks??rootPkg.devDependencies?.stacks;if(vendored){const corePkg=JSON.parse(await fs.promises.readFile(resolve(coreDir,"package.json"),"utf-8")),packages=(await readdir(coreDir,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()&&existsSync(resolve(coreDir,entry.name,"package.json")));log.info(`Layout: vendored - ${italic(rel(coreDir))} (${packages.length} packages, v${corePkg.version??"unknown"})`);log.info(`Declared: stacks@${declared??"(not declared)"}`);if(declared&&!declared.startsWith("workspace:"))log.warn(`The vendored copy is not linked: stacks is declared as ${declared}, not workspace:*. Run \`buddy publish:core --all --force\` to relink, or \`buddy unpublish:core --all\` to remove it.`);log.info("Move to the published packages with `buddy unpublish:core --all`.");return}const installed=resolve(process.cwd(),"node_modules/@stacksjs/buddy/package.json"),installedVersion=existsSync(installed)?JSON.parse(await fs.promises.readFile(installed,"utf-8")).version:void 0;log.info("Layout: published packages - no storage/framework/core in this project");log.info(`Declared: stacks@${declared??"(not declared)"}`);log.info(`Installed: ${installedVersion?`v${installedVersion}`:"(run bun install)"}`);log.info("Vendor the framework for local development with `buddy publish:core --all`.")}async function unpublishCorePackage(pkg,force){const shortName=normalizeCoreName(pkg),targetDir=path.frameworkPath(`core/${shortName}`),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(targetDir)){log.info(`Not vendored: ${italic(rel(targetDir))} - nothing to do.`);return}const installed=resolve(process.cwd(),"node_modules","@stacksjs",shortName);if(!existsSync(installed)&&!force){await log.error(`@stacksjs/${shortName} is not installed, so removing the vendored copy would leave nothing to resolve.`);log.info(`Run \`bun add @stacksjs/${shortName}\` first, or pass --force to remove it anyway.`);await log.flush();process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(targetDir,force);await fs.promises.rm(targetDir,{recursive:!0,force:!0});log.success(`Unpublished ${italic(rel(targetDir))} - @stacksjs/${shortName} now resolves from node_modules.`)}export function packagesPreloadFilesFallBackTo(source){const found=new Set;for(const match of source.matchAll(/'@stacksjs\/'\s*\+\s*'([a-z0-9-]+)'/g))found.add(`@stacksjs/${match[1]}`);return found}export function rewriteBunfigPreloads(bunfig){const packages=new Set;let rewritten=0;return{next:bunfig.replace(/(["'])\.?\/?storage\/framework\/core\/([\w-]+)\/([^"']+?)\.ts\1/g,(_match,quote,pkgName,subpath)=>{rewritten++;packages.add(`@stacksjs/${pkgName}`);return`${quote}@stacksjs/${pkgName}/${subpath}.js${quote}`}),packages,rewritten}}async function vendorDefaults(){const root=path.projectPath();if(usesVendoredDefaults(root)){log.info(`${VENDORED_DEFAULTS} is already a vendored copy.`);return}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to copy. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const tree=resolve(root,VENDORED_DEFAULTS);try{if(lstatSync(tree).isSymbolicLink())unlinkSync(tree)}catch{}mkdirSync(tree,{recursive:!0});const changes=vendorDefaultsTree(root,packageRoot);unignoreDefaults(root);log.success(`Copied @stacksjs/defaults ${installedDefaultsVersion(root)??""} into ${VENDORED_DEFAULTS} (${changes.length} files). Commit it; \`buddy upgrade\` keeps it current.`);log.info("Go back to the link any time with `buddy unpublish:defaults`.")}async function unvendorDefaults(force){const root=path.projectPath();if(!usesVendoredDefaults(root)){linkPackagedDefaults(root);log.info(`${VENDORED_DEFAULTS} already runs from node_modules/@stacksjs/defaults.`);return}if(existsSync(resolve(root,"storage/framework/core/buddy/package.json"))){await log.error("This project vendors the framework itself (storage/framework/core), and its defaults tree is the source the package is built from. Run `buddy unpublish:core --all` first.");process.exit(ExitCode.FatalError)}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to run the defaults from. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const differs=syncPackageProjectFiles(root,packageRoot,{dryRun:!0,vendorDefaults:!0}).filter((change)=>change.path.startsWith(`${VENDORED_DEFAULTS}/`)&&change.action!=="add");if(differs.length>0&&!force){await log.error(`${VENDORED_DEFAULTS} differs from the installed @stacksjs/defaults ${installedDefaultsVersion(root)??""} in ${differs.length} place${differs.length===1?"":"s"}:`);for(const change of differs.slice(0,15))log.error(` ${change.action==="remove"?"only here":"changed "} ${change.path}`);if(differs.length>15)log.error(` ... and ${differs.length-15} more`);log.info("A tree from another release: run `buddy upgrade` first. A file you edited: move it to the same path under app/, which wins over the defaults. Then run this again, or pass --force to drop the differences.");await log.flush();process.exit(ExitCode.FatalError)}const adopted=adoptPackagedDefaults(root);log.success(`Removed ${VENDORED_DEFAULTS}; it now links to ${adopted.packageRoot.replace(`${root}/`,"")} and is gitignored.`);for(const file of[...adopted.rewrittenImports,...adopted.rewrittenModulePaths])log.info(` repointed ${file} at @stacksjs/defaults`);log.info("Commit the removal. Go back to a vendored copy any time with `buddy publish:defaults`.")}async function unvendorFramework(force){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(coreDir)){log.info("No storage/framework/core in this project - already on the installed packages.");return}const corePkgPath=resolve(coreDir,"package.json");if(!existsSync(corePkgPath)){await log.error(`${rel(coreDir)} has no package.json, so its version cannot be determined.`);log.info("Unvendor the packages individually with `buddy unpublish:core <pkg>` instead.");await log.flush();process.exit(ExitCode.FatalError)}const corePkg=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")),version=corePkg.version;if(!version){await log.error(`${rel(corePkgPath)} has no version field.`);process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(coreDir,force);const depName=corePkg.name??"stacks",range=`^${await resolvePublishedVersion(depName,version)}`,rootPkgPath=resolve(process.cwd(),"package.json"),rootPkgRaw=await fs.promises.readFile(rootPkgPath,"utf-8"),rootPkg=JSON.parse(rootPkgRaw),provided=new Set([depName,...Object.keys(corePkg.dependencies??{}).filter((name)=>name.startsWith("@stacksjs/"))]);for(const entry of await readdir(coreDir,{withFileTypes:!0}))if(entry.isDirectory())provided.add(`@stacksjs/${entry.name}`);let repointed=0;const repointWorkspaceRanges=(pkg)=>{let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;deps[name]=range;touched=!0;repointed++}}return touched};repointWorkspaceRanges(rootPkg);if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:range};let rewrittenScripts=0;for(const[name,script]of Object.entries(rootPkg.scripts??{})){if(!/storage\/framework\/core\/buddy\/src\/cli\.ts/.test(script))continue;rootPkg.scripts[name]=script.replace(/\bbunx?\s+(?:--bun\s+)?\.?\/?storage\/framework\/core\/buddy\/src\/cli\.ts/g,"./buddy");rewrittenScripts++}if(Array.isArray(rootPkg.workspaces)){rootPkg.workspaces=rootPkg.workspaces.filter((glob)=>!isCoreWorkspaceGlob(glob));if(rootPkg.workspaces.length===0)delete rootPkg.workspaces}await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
5
5
  `);for(const glob of rootPkg.workspaces??[])for(const memberPkgPath of globSync(`${glob.replace(/\/$/,"")}/package.json`,{cwd:process.cwd(),absolute:!0})){const raw=await fs.promises.readFile(memberPkgPath,"utf-8"),memberPkg=JSON.parse(raw);if(repointWorkspaceRanges(memberPkg))await fs.promises.writeFile(memberPkgPath,`${JSON.stringify(memberPkg,null,2)}
6
6
  `)}const survivingManifests=await rewriteSurvivingFrameworkManifests(process.cwd(),provided,range),bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),{next,packages:preloadedPackages,rewritten}=rewriteBunfigPreloads(bunfig);rewrittenPreloads+=rewritten;if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next);for(const match of next.matchAll(/["'](\.\/[^"']+\.ts)["']/g)){const preloadPath=resolve(process.cwd(),match[1]);if(!existsSync(preloadPath))continue;for(const pkgName of packagesPreloadFilesFallBackTo(await fs.promises.readFile(preloadPath,"utf-8")))preloadedPackages.add(pkgName)}let declaredForPreload=0;for(const pkgName of preloadedPackages){if(rootPkg.dependencies?.[pkgName]||rootPkg.devDependencies?.[pkgName])continue;rootPkg.dependencies={...rootPkg.dependencies,[pkgName]:range};declaredForPreload++}if(declaredForPreload>0)await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
7
7
  `)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1,rewroteTypecheck=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/core\/tsconfig\.json"/,'"extends": "./storage/framework/tsconfig.app.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}const splitTypecheck=splitFrameworkTypecheckScript(rootPkg.scripts??{});if(splitTypecheck){rootPkg.scripts=splitTypecheck;rewroteTypecheck=!0;await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
@@ -34,6 +34,13 @@ export declare function appPackageValues(identity: AppIdentity): Record<string,
34
34
  * engines, git hooks) in their original order. Returns the keys it changed.
35
35
  */
36
36
  export declare function applyAppPackageTemplate(root: string, identity: AppIdentity): string[];
37
+ /**
38
+ * Drop the framework's LICENSE.md: "MIT License, Copyright (c) 2023 Open Web
39
+ * Foundation", which every app then claimed as its own terms and copyright
40
+ * holder. Only that file - an app that already has its own licence keeps it.
41
+ * Returns whether it was removed.
42
+ */
43
+ export declare function removeFrameworkLicense(root: string): boolean;
37
44
  /**
38
45
  * Replace the framework's CHANGELOG.md with an empty one for the app.
39
46
  *
@@ -1,5 +1,5 @@
1
- import{existsSync,readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";export function appIdentity(path){const slug=path.replace(/\/+$/,"").split("/").pop()||"stacks-app",words=slug.split(/[^a-z0-9]+/i).filter(Boolean),displayName=words.map((word)=>`${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(" ")||"My App",kebab=words.join("-").toLowerCase().replace(/^[^a-z]+/,"")||"app";return{slug,displayName,kebab,snake:kebab.replaceAll("-","_"),bundleId:`com.example.${kebab}`}}export function templatePlaceholders(identity){return{__APP_NAME__:identity.displayName,__APP_SLUG__:identity.slug,__APP_TAG_PREFIX__:identity.kebab,__APP_BUNDLE_ID__:identity.bundleId}}export function renderTemplate(source,identity){let rendered=source;for(const[placeholder,value]of Object.entries(templatePlaceholders(identity)))rendered=rendered.replaceAll(placeholder,value);return rendered}export function appEnvValues(identity){return{APP_NAME:`"${identity.displayName.replaceAll('"',"")}"`,APP_URL:`${identity.kebab}.localhost`,DB_DATABASE:identity.snake,MAIL_FROM_ADDRESS:`"no-reply@${identity.kebab}.localhost"`,QUEUE_PREFIX:`${identity.snake}:queue`,PREDICTHQ_DB_PASSWORD:null}}export function applyAppEnvTemplate(root,identity){const file=join(root,".env.example");if(!existsSync(file))return[];const values=appEnvValues(identity),changed=[],lines=readFileSync(file,"utf8").split(`
1
+ import{existsSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";export function appIdentity(path){const slug=path.replace(/\/+$/,"").split("/").pop()||"stacks-app",words=slug.split(/[^a-z0-9]+/i).filter(Boolean),displayName=words.map((word)=>`${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(" ")||"My App",kebab=words.join("-").toLowerCase().replace(/^[^a-z]+/,"")||"app";return{slug,displayName,kebab,snake:kebab.replaceAll("-","_"),bundleId:`com.example.${kebab}`}}export function templatePlaceholders(identity){return{__APP_NAME__:identity.displayName,__APP_SLUG__:identity.slug,__APP_TAG_PREFIX__:identity.kebab,__APP_BUNDLE_ID__:identity.bundleId}}export function renderTemplate(source,identity){let rendered=source;for(const[placeholder,value]of Object.entries(templatePlaceholders(identity)))rendered=rendered.replaceAll(placeholder,value);return rendered}export function appEnvValues(identity){return{APP_NAME:`"${identity.displayName.replaceAll('"',"")}"`,APP_URL:`${identity.kebab}.localhost`,DB_DATABASE:identity.snake,MAIL_FROM_ADDRESS:`"no-reply@${identity.kebab}.localhost"`,QUEUE_PREFIX:`${identity.snake}:queue`,PREDICTHQ_DB_PASSWORD:null}}export function applyAppEnvTemplate(root,identity){const file=join(root,".env.example");if(!existsSync(file))return[];const values=appEnvValues(identity),changed=[],lines=readFileSync(file,"utf8").split(`
2
2
  `).flatMap((line)=>{const key=/^([A-Z0-9_]+)=/.exec(line)?.[1];if(!key||!(key in values))return[line];changed.push(key);const value=values[key];return value===null?[]:[`${key}=${value}`]});writeFileSync(file,lines.join(`
3
- `));return changed}export function appPackageValues(identity){return{name:identity.kebab,version:"0.0.0",description:identity.displayName,author:void 0,contributors:void 0,funding:void 0,homepage:void 0,repository:void 0,bugs:void 0}}export function applyAppPackageTemplate(root,identity){const file=join(root,"package.json");if(!existsSync(file))return[];const pkg=JSON.parse(readFileSync(file,"utf8")),changed=[];for(const[key,value]of Object.entries(appPackageValues(identity)))if(value===void 0){if(key in pkg){delete pkg[key];changed.push(key)}}else if(pkg[key]!==value){pkg[key]=value;changed.push(key)}writeFileSync(file,`${JSON.stringify(pkg,null,2)}
4
- `);return changed}export function applyAppChangelogTemplate(root,identity){const file=join(root,"CHANGELOG.md");if(!existsSync(file))return!1;writeFileSync(file,`# ${identity.displayName} Changelog
3
+ `));return changed}export function appPackageValues(identity){return{name:identity.kebab,version:"0.0.0",description:identity.displayName,author:void 0,contributors:void 0,funding:void 0,homepage:void 0,repository:void 0,bugs:void 0,license:void 0}}export function applyAppPackageTemplate(root,identity){const file=join(root,"package.json");if(!existsSync(file))return[];const pkg=JSON.parse(readFileSync(file,"utf8")),changed=[];for(const[key,value]of Object.entries(appPackageValues(identity)))if(value===void 0){if(key in pkg){delete pkg[key];changed.push(key)}}else if(pkg[key]!==value){pkg[key]=value;changed.push(key)}writeFileSync(file,`${JSON.stringify(pkg,null,2)}
4
+ `);return changed}export function removeFrameworkLicense(root){const file=join(root,"LICENSE.md");if(!existsSync(file)||!readFileSync(file,"utf8").includes("Open Web Foundation"))return!1;rmSync(file);return!0}export function applyAppChangelogTemplate(root,identity){const file=join(root,"CHANGELOG.md");if(!existsSync(file))return!1;writeFileSync(file,`# ${identity.displayName} Changelog
5
5
  `);return!0}
@@ -6,6 +6,16 @@ export declare function appPackageScripts(scripts: Record<string, string>): Scri
6
6
  * scripts in `storage/framework/package.json` that publish the framework.
7
7
  */
8
8
  export declare function applyAppPackageScripts(root: string): ScriptChanges;
9
+ /**
10
+ * Strip the framework's author, sponsor link and repository from the
11
+ * workspace manifests an app keeps under `storage/framework` (the root one,
12
+ * `server/`, `cloud/`, `orm/`, `api/` and the library entries). The root
13
+ * package.json already loses them (`appPackageValues`); these said
14
+ * `"funding": "https://github.com/sponsors/chrisbbreuer"` in every app.
15
+ * Returns the manifests it changed.
16
+ */
17
+ export declare function stripFrameworkManifestCredits(root: string): string[];
18
+ export declare function rewriteCoreContentPaths(root: string): string[];
9
19
  /*\/src`, which a new app does not have. The package
10
20
  * variant is what `buddy upgrade` installs anyway (it ships in
11
21
  * `@stacksjs/defaults` as `project/storage/framework/tsconfig.app.json`); this
@@ -1,6 +1,7 @@
1
1
  import{appendFileSync,cpSync,existsSync,lstatSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{extname,join,relative}from"node:path";import{linkPackagedDefaults,packagedDefaultsRoot}from"@stacksjs/path";export const VENDORED_DEFAULTS="storage/framework/defaults",FRAMEWORK_ONLY_PATHS=["bench","logsmith.config.ts","storage/framework/tsconfig.framework.json","storage/framework/tsconfig.defaults.json","storage/framework/tsconfig.type-tests.json","storage/framework/docs","storage/framework/scripts/fresh","storage/framework/scripts/generate-changelog","storage/framework/scripts/install","storage/framework/scripts/link","storage/framework/scripts/lint","storage/framework/scripts/move-built-src-files.ts","storage/framework/scripts/move-dts-files.ts","storage/framework/scripts/normalize-workspace-deps-for-publish","storage/framework/scripts/publish","storage/framework/scripts/publish-commit","storage/framework/scripts/publish-dummy-libs"];export function pruneFrameworkOnlyFiles(root){const removed=[];for(const path of FRAMEWORK_ONLY_PATHS){const full=join(root,path);if(!existsSync(full))continue;rmSync(full,{recursive:!0,force:!0});removed.push(path)}return removed}const FRAMEWORK_ONLY_SCRIPTS=[/^bench(?::|$)/,/^test:bench$/,/^typecheck:(?:bench|framework|type-tests)$/,/^docs:/,/^declarations:check$/,/^deps:lockfile:check$/],APP_SCRIPTS={buddy:"./buddy",typecheck:"bun run typecheck:app","typecheck:app":"bun x --bun tsc --noEmit -p tsconfig.json --pretty false","typecheck:views":"bun x --bun stx typecheck --lib storage/framework/types/request-context.d.ts --lib storage/framework/types/browser-composables.d.ts 'resources/**/*.stx'","build:reset":"rm -rf node_modules && pantry install && ./buddy generate:types && ./buddy lint:fix"};export function appPackageScripts(scripts){const next={},removed=[],rewritten=[];for(const[name,command]of Object.entries(scripts)){if(FRAMEWORK_ONLY_SCRIPTS.some((pattern)=>pattern.test(name))){removed.push(name);continue}const replacement=APP_SCRIPTS[name];if(replacement!==void 0&&replacement!==command){next[name]=replacement;rewritten.push(name);continue}next[name]=command}return{scripts:next,removed,rewritten}}export function applyAppPackageScripts(root){const file=join(root,"package.json"),empty={scripts:{},removed:[],rewritten:[]};if(!existsSync(file))return empty;const pkg=JSON.parse(readFileSync(file,"utf8")),changes=appPackageScripts(pkg.scripts??{});if(changes.removed.length>0||changes.rewritten.length>0){pkg.scripts=changes.scripts;writeFileSync(file,`${JSON.stringify(pkg,null,2)}
2
2
  `)}const frameworkFile=join(root,"storage/framework/package.json");if(existsSync(frameworkFile)){const framework=JSON.parse(readFileSync(frameworkFile,"utf8"));let touched=!1;for(const[name,command]of Object.entries(framework.scripts??{})){if(!/\.\/scripts\/publish|\.\/core\b/.test(command))continue;delete framework.scripts[name];touched=!0}if(touched)writeFileSync(frameworkFile,`${JSON.stringify(framework,null,2)}
3
- `)}return changes}export function applyPackageAppTsconfig(root){const source=join(root,"storage/framework/tsconfig.package-app.json");if(!existsSync(source))return!1;cpSync(source,join(root,"storage/framework/tsconfig.app.json"));rmSync(source);return!0}const SKIPPED_DIRECTORIES=new Set(["node_modules","pantry","dist","storage","public",".git",".cache",".stx","coverage"]),SCANNED_EXTENSIONS=new Set([".ts",".tsx",".js",".mjs",".cjs",".stx"]);function projectSources(dir){let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return[]}return entries.flatMap((entry)=>{const full=join(dir,entry.name);if(entry.isDirectory())return SKIPPED_DIRECTORIES.has(entry.name)?[]:projectSources(full);return entry.isFile()&&SCANNED_EXTENSIONS.has(extname(entry.name))?[full]:[]})}const DEFAULTS_IMPORT=/(\bfrom\s+|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)(['"])(?:~\/|(?:\.{1,2}\/)+)storage\/framework\/defaults\/([^'"]+)\2/gm;export function defaultsSpecifier(rest,hasFile=()=>!1){if(!extname(rest)&&hasFile(`${rest}.ts`))return`@stacksjs/defaults/${rest}.ts`;return`@stacksjs/defaults/${rest}`}export function rewriteDefaultsImports(root,hasFile){const touched=[];for(const file of projectSources(root)){const raw=readFileSync(file,"utf8");if(!raw.includes("storage/framework/defaults/"))continue;const next=raw.replace(DEFAULTS_IMPORT,(_match,lead,quote,rest)=>`${lead}${quote}${defaultsSpecifier(rest,hasFile)}${quote}`);if(next!==raw){writeFileSync(file,next);touched.push(relative(root,file))}}return touched}const DEFAULTS_MODULE_PATHS=[{file:"bunfig.toml",from:'"./storage/framework/defaults/resources/plugins/preloader.js"',to:'"@stacksjs/defaults/resources/plugins/preloader"'},{file:"config/ui.ts",from:"'./storage/framework/defaults/stx-components-plugin.js'",to:"'@stacksjs/defaults/stx-components-plugin.ts'"}];export function rewriteDefaultsModulePaths(root){const touched=[];for(const{file,from,to}of DEFAULTS_MODULE_PATHS){const full=join(root,file);if(!existsSync(full))continue;const raw=readFileSync(full,"utf8");if(!raw.includes(from))continue;writeFileSync(full,raw.replaceAll(from,to));touched.push(file)}return touched}const GITIGNORE_ENTRY=`/${VENDORED_DEFAULTS}`,GITIGNORE_BLOCK=`
3
+ `)}return changes}const FRAMEWORK_CREDIT_KEYS=["author","contributors","funding","homepage","repository","bugs"];export function stripFrameworkManifestCredits(root){const framework=join(root,"storage/framework"),manifests=[],walk=(dir)=>{let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return}for(const entry of entries){const full=join(dir,entry.name);if(entry.isDirectory()&&!["core","defaults","node_modules","dist"].includes(entry.name))walk(full);else if(entry.isFile()&&entry.name==="package.json")manifests.push(full)}};walk(framework);const touched=[];for(const file of manifests){const pkg=JSON.parse(readFileSync(file,"utf8")),present=FRAMEWORK_CREDIT_KEYS.filter((key)=>(key in pkg));if(present.length===0)continue;for(const key of present)delete pkg[key];writeFileSync(file,`${JSON.stringify(pkg,null,2)}
4
+ `);touched.push(relative(root,file))}return touched}const CORE_CONTENT_PATHS=[{file:"config/css.ts",from:"'./storage/framework/core/error-handling/src/views/**/*.{stx,html}'",to:"'./node_modules/@stacksjs/error-handling/dist/views/**/*.{stx,html}'"}];export function rewriteCoreContentPaths(root){const touched=[];for(const{file,from,to}of CORE_CONTENT_PATHS){const full=join(root,file);if(!existsSync(full))continue;const raw=readFileSync(full,"utf8");if(!raw.includes(from))continue;writeFileSync(full,raw.replaceAll(from,to));touched.push(file)}return touched}export function applyPackageAppTsconfig(root){const source=join(root,"storage/framework/tsconfig.package-app.json");if(!existsSync(source))return!1;cpSync(source,join(root,"storage/framework/tsconfig.app.json"));rmSync(source);return!0}const SKIPPED_DIRECTORIES=new Set(["node_modules","pantry","dist","storage","public",".git",".cache",".stx","coverage"]),SCANNED_EXTENSIONS=new Set([".ts",".tsx",".js",".mjs",".cjs",".stx"]);function projectSources(dir){let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return[]}return entries.flatMap((entry)=>{const full=join(dir,entry.name);if(entry.isDirectory())return SKIPPED_DIRECTORIES.has(entry.name)?[]:projectSources(full);return entry.isFile()&&SCANNED_EXTENSIONS.has(extname(entry.name))?[full]:[]})}const DEFAULTS_IMPORT=/(\bfrom\s+|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)(['"])(?:~\/|(?:\.{1,2}\/)+)storage\/framework\/defaults\/([^'"]+)\2/gm;export function defaultsSpecifier(rest,hasFile=()=>!1){if(!extname(rest)&&hasFile(`${rest}.ts`))return`@stacksjs/defaults/${rest}.ts`;return`@stacksjs/defaults/${rest}`}export function rewriteDefaultsImports(root,hasFile){const touched=[];for(const file of projectSources(root)){const raw=readFileSync(file,"utf8");if(!raw.includes("storage/framework/defaults/"))continue;const fileExists=file.endsWith(".stx")?()=>!1:hasFile,next=raw.replace(DEFAULTS_IMPORT,(_match,lead,quote,rest)=>`${lead}${quote}${defaultsSpecifier(rest,fileExists)}${quote}`);if(next!==raw){writeFileSync(file,next);touched.push(relative(root,file))}}return touched}const TS=".ts",DEFAULTS_MODULE_PATHS=[{file:"bunfig.toml",from:`"./storage/framework/defaults/resources/plugins/preloader${TS}"`,to:'"@stacksjs/defaults/resources/plugins/preloader"'},{file:"config/ui.ts",from:`'./storage/framework/defaults/stx-components-plugin${TS}'`,to:`'@stacksjs/defaults/stx-components-plugin${TS}'`}];export function rewriteDefaultsModulePaths(root){const touched=[];for(const{file,from,to}of DEFAULTS_MODULE_PATHS){const full=join(root,file);if(!existsSync(full))continue;const raw=readFileSync(full,"utf8");if(!raw.includes(from))continue;writeFileSync(full,raw.replaceAll(from,to));touched.push(file)}return touched}const GITIGNORE_ENTRY=`/${VENDORED_DEFAULTS}`,GITIGNORE_BLOCK=`
4
5
  # The framework defaults: a link to node_modules/@stacksjs/defaults, made on
5
6
  # boot. \`buddy publish:defaults\` replaces it with a copy you commit instead.
6
7
  ${GITIGNORE_ENTRY}
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.245",
5
+ "version": "0.75.247",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -96,68 +96,68 @@
96
96
  },
97
97
  "dependencies": {
98
98
  "@stacksjs/bumpx": "^0.2.25",
99
- "@stacksjs/actions": "0.75.245",
100
- "@stacksjs/ai": "0.75.245",
101
- "@stacksjs/alias": "0.75.245",
102
- "@stacksjs/analytics": "0.75.245",
103
- "@stacksjs/api": "0.75.245",
104
- "@stacksjs/arrays": "0.75.245",
105
- "@stacksjs/auth": "0.75.245",
106
- "@stacksjs/browser-extension": "0.75.245",
107
- "@stacksjs/build": "0.75.245",
108
- "@stacksjs/cache": "0.75.245",
109
- "@stacksjs/chat": "0.75.245",
99
+ "@stacksjs/actions": "0.75.247",
100
+ "@stacksjs/ai": "0.75.247",
101
+ "@stacksjs/alias": "0.75.247",
102
+ "@stacksjs/analytics": "0.75.247",
103
+ "@stacksjs/api": "0.75.247",
104
+ "@stacksjs/arrays": "0.75.247",
105
+ "@stacksjs/auth": "0.75.247",
106
+ "@stacksjs/browser-extension": "0.75.247",
107
+ "@stacksjs/build": "0.75.247",
108
+ "@stacksjs/cache": "0.75.247",
109
+ "@stacksjs/chat": "0.75.247",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.245",
112
- "@stacksjs/cloud": "0.75.245",
113
- "@stacksjs/cms": "0.75.245",
114
- "@stacksjs/collections": "0.75.245",
115
- "@stacksjs/commerce": "0.75.245",
116
- "@stacksjs/config": "0.75.245",
117
- "@stacksjs/database": "0.75.245",
118
- "@stacksjs/desktop-build": "0.75.245",
119
- "@stacksjs/dns": "0.75.245",
111
+ "@stacksjs/cli": "0.75.247",
112
+ "@stacksjs/cloud": "0.75.247",
113
+ "@stacksjs/cms": "0.75.247",
114
+ "@stacksjs/collections": "0.75.247",
115
+ "@stacksjs/commerce": "0.75.247",
116
+ "@stacksjs/config": "0.75.247",
117
+ "@stacksjs/database": "0.75.247",
118
+ "@stacksjs/desktop-build": "0.75.247",
119
+ "@stacksjs/dns": "0.75.247",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.245",
122
- "@stacksjs/enums": "0.75.245",
123
- "@stacksjs/env": "0.75.245",
124
- "@stacksjs/error-handling": "0.75.245",
125
- "@stacksjs/events": "0.75.245",
126
- "@stacksjs/features": "0.75.245",
127
- "@stacksjs/git": "0.75.245",
121
+ "@stacksjs/email": "0.75.247",
122
+ "@stacksjs/enums": "0.75.247",
123
+ "@stacksjs/env": "0.75.247",
124
+ "@stacksjs/error-handling": "0.75.247",
125
+ "@stacksjs/events": "0.75.247",
126
+ "@stacksjs/features": "0.75.247",
127
+ "@stacksjs/git": "0.75.247",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.245",
129
+ "@stacksjs/health": "0.75.247",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.245",
132
- "@stacksjs/lint": "0.75.245",
133
- "@stacksjs/logging": "0.75.245",
134
- "@stacksjs/notifications": "0.75.245",
135
- "@stacksjs/objects": "0.75.245",
136
- "@stacksjs/orm": "0.75.245",
137
- "@stacksjs/path": "0.75.245",
138
- "@stacksjs/payments": "0.75.245",
139
- "@stacksjs/realtime": "0.75.245",
140
- "@stacksjs/router": "0.75.245",
131
+ "@stacksjs/image": "0.75.247",
132
+ "@stacksjs/lint": "0.75.247",
133
+ "@stacksjs/logging": "0.75.247",
134
+ "@stacksjs/notifications": "0.75.247",
135
+ "@stacksjs/objects": "0.75.247",
136
+ "@stacksjs/orm": "0.75.247",
137
+ "@stacksjs/path": "0.75.247",
138
+ "@stacksjs/payments": "0.75.247",
139
+ "@stacksjs/realtime": "0.75.247",
140
+ "@stacksjs/router": "0.75.247",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.245",
143
- "@stacksjs/search-engine": "0.75.245",
144
- "@stacksjs/security": "0.75.245",
145
- "@stacksjs/server": "0.75.245",
146
- "@stacksjs/sites": "0.75.245",
147
- "@stacksjs/skills": "0.75.245",
148
- "@stacksjs/socials": "0.75.245",
149
- "@stacksjs/storage": "0.75.245",
150
- "@stacksjs/strings": "0.75.245",
142
+ "@stacksjs/scheduler": "0.75.247",
143
+ "@stacksjs/search-engine": "0.75.247",
144
+ "@stacksjs/security": "0.75.247",
145
+ "@stacksjs/server": "0.75.247",
146
+ "@stacksjs/sites": "0.75.247",
147
+ "@stacksjs/skills": "0.75.247",
148
+ "@stacksjs/socials": "0.75.247",
149
+ "@stacksjs/storage": "0.75.247",
150
+ "@stacksjs/strings": "0.75.247",
151
151
  "@stacksjs/stx": "^0.2.607",
152
- "@stacksjs/testing": "0.75.245",
153
- "@stacksjs/tinker": "0.75.245",
152
+ "@stacksjs/testing": "0.75.247",
153
+ "@stacksjs/tinker": "0.75.247",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
155
  "@stacksjs/ts-cloud": "^0.16.58",
156
- "@stacksjs/tunnel": "0.75.245",
157
- "@stacksjs/types": "0.75.245",
158
- "@stacksjs/ui": "0.75.245",
159
- "@stacksjs/utils": "0.75.245",
160
- "@stacksjs/validation": "0.75.245",
156
+ "@stacksjs/tunnel": "0.75.247",
157
+ "@stacksjs/types": "0.75.247",
158
+ "@stacksjs/ui": "0.75.247",
159
+ "@stacksjs/utils": "0.75.247",
160
+ "@stacksjs/validation": "0.75.247",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
163
  "bun-plugin-stx": "^0.2.607",