@stacksjs/buddy 0.75.226 → 0.75.230

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,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}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(`
2
- `).join("; ")}. Point each route at an action that exists, or delete it. \`buddy upgrade\` removes the ones the scaffold wrote.`)});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(`
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(`
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 +1,2 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function test(buddy){const descriptions={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("test",descriptions.command).option("-f, --feature",descriptions.feature,{default:!1}).option("-u, --unit",descriptions.unit,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!0}).action(async(options)=>{const perf=await intro("buddy test");if(options.feature&&options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(options.feature&&!options.unit){log.info("Running Feature tests...");const result=await runAction(Action.TestFeature,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&options.unit){log.info("Running Unit tests...");const result=await runAction(Action.TestUnit,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&!options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}await outro("Finished running tests",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("test:unit",descriptions.unit).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:unit"),result=await runAction(Action.TestUnit,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:unit`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running unit tests",{startTime:perf,useSeconds:!0})});buddy.command("test:feature",descriptions.feature).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:feature"),result=await runAction(Action.TestFeature,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:feature`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running feature tests",{startTime:perf,useSeconds:!0})});buddy.command("test:ui",descriptions.command).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:ui"),result=await runAction(Action.TestUi,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:ui`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running tests in the browser",{startTime:perf,useSeconds:!0})});buddy.command("test:types",descriptions.types).alias("typecheck").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:types"),result=await runAction(Action.Typecheck,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:types`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running typecheck",{startTime:perf,useSeconds:!0})});onUnknownSubcommand(buddy,"test")}
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function test(buddy){const descriptions={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("test",descriptions.command).option("-f, --feature",descriptions.feature,{default:!1}).option("-u, --unit",descriptions.unit,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!0}).action(async(options)=>{const perf=await intro("buddy test");if(options.feature&&options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(options.feature&&!options.unit){log.info("Running Feature tests...");const result=await runAction(Action.TestFeature,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&options.unit){log.info("Running Unit tests...");const result=await runAction(Action.TestUnit,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&!options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}await outro("Finished running tests",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("test:unit",descriptions.unit).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:unit"),result=await runAction(Action.TestUnit,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:unit`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running unit tests",{startTime:perf,useSeconds:!0})});buddy.command("test:feature",descriptions.feature).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:feature"),result=await runAction(Action.TestFeature,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:feature`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running feature tests",{startTime:perf,useSeconds:!0})});buddy.command("test:ui",descriptions.command).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:ui"),result=await runAction(Action.TestUi,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:ui`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running tests in the browser",{startTime:perf,useSeconds:!0})});buddy.command("test:types",descriptions.types).alias("typecheck").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:types"),result=await runAction(Action.Typecheck,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:types`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running typecheck",{startTime:perf,useSeconds:!0})});buddy.command("test:page-audit","Loads pages in headless Chrome and reports duplicate API requests, failed requests and console errors").option("--url <urls>","Page URLs to audit, comma-separated (paths resolve against --base)").option("--base [base]","Origin that paths in --url resolve against",{default:"http://localhost:3000"}).option("--quiet-ms [ms]","How long the network must stay quiet before a page counts as loaded",{default:1000}).option("--timeout [ms]","Give up waiting for a page to settle after this long",{default:15000}).option("--mobile","Audit at a 390px phone viewport instead of 1440px",{default:!1}).option("--json","Print the reports as JSON",{default:!1}).example("buddy test:page-audit --url /,/dashboard --base http://localhost:3000").example("buddy test:page-audit --url http://localhost:3000/pricing --json").action(async(options)=>{const targets=String(options.url??"").split(",").map((url)=>url.trim()).filter(Boolean);if(!targets.length){await log.error("Pass the pages to audit with --url (comma-separated URLs or paths)");process.exit(ExitCode.InvalidArgument)}const{auditPage,formatPageAudit,launch,pageAuditClean}=await import("@stacksjs/testing/browser"),viewport=options.mobile?{width:390,height:844,mobile:!0,deviceScaleFactor:2}:{width:1440,height:900},{cdp,close}=await launch({viewport}),reports=[];try{for(const target of targets){const url=new URL(target,options.base||"http://localhost:3000").href,report=await auditPage(url,{cdp,quietMs:Number(options.quietMs)||1000,timeoutMs:Number(options.timeout)||15000});reports.push(report);if(!options.json)await log.info(formatPageAudit(report))}}finally{await close()}if(options.json)process.stdout.write(`${JSON.stringify(reports,null,2)}
2
+ `);process.exit(reports.every(pageAuditClean)?ExitCode.Success:ExitCode.FatalError)});onUnknownSubcommand(buddy,"test")}
@@ -1 +1 @@
1
- const APP_KEY_OPTIONAL_COMMANDS=["env","build","lint","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
1
+ const APP_KEY_OPTIONAL_COMMANDS=["env","build","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
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.226",
5
+ "version": "0.75.230",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -96,71 +96,71 @@
96
96
  },
97
97
  "dependencies": {
98
98
  "@stacksjs/bumpx": "^0.2.21",
99
- "@stacksjs/actions": "0.75.226",
100
- "@stacksjs/ai": "0.75.226",
101
- "@stacksjs/alias": "0.75.226",
102
- "@stacksjs/analytics": "0.75.226",
103
- "@stacksjs/api": "0.75.226",
104
- "@stacksjs/arrays": "0.75.226",
105
- "@stacksjs/auth": "0.75.226",
106
- "@stacksjs/browser-extension": "0.75.226",
107
- "@stacksjs/build": "0.75.226",
108
- "@stacksjs/cache": "0.75.226",
109
- "@stacksjs/chat": "0.75.226",
99
+ "@stacksjs/actions": "0.75.230",
100
+ "@stacksjs/ai": "0.75.230",
101
+ "@stacksjs/alias": "0.75.230",
102
+ "@stacksjs/analytics": "0.75.230",
103
+ "@stacksjs/api": "0.75.230",
104
+ "@stacksjs/arrays": "0.75.230",
105
+ "@stacksjs/auth": "0.75.230",
106
+ "@stacksjs/browser-extension": "0.75.230",
107
+ "@stacksjs/build": "0.75.230",
108
+ "@stacksjs/cache": "0.75.230",
109
+ "@stacksjs/chat": "0.75.230",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.226",
112
- "@stacksjs/cloud": "0.75.226",
113
- "@stacksjs/cms": "0.75.226",
114
- "@stacksjs/collections": "0.75.226",
115
- "@stacksjs/commerce": "0.75.226",
116
- "@stacksjs/config": "0.75.226",
117
- "@stacksjs/database": "0.75.226",
118
- "@stacksjs/desktop-build": "0.75.226",
119
- "@stacksjs/dns": "0.75.226",
111
+ "@stacksjs/cli": "0.75.230",
112
+ "@stacksjs/cloud": "0.75.230",
113
+ "@stacksjs/cms": "0.75.230",
114
+ "@stacksjs/collections": "0.75.230",
115
+ "@stacksjs/commerce": "0.75.230",
116
+ "@stacksjs/config": "0.75.230",
117
+ "@stacksjs/database": "0.75.230",
118
+ "@stacksjs/desktop-build": "0.75.230",
119
+ "@stacksjs/dns": "0.75.230",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.226",
122
- "@stacksjs/enums": "0.75.226",
123
- "@stacksjs/env": "0.75.226",
124
- "@stacksjs/error-handling": "0.75.226",
125
- "@stacksjs/events": "0.75.226",
126
- "@stacksjs/features": "0.75.226",
127
- "@stacksjs/git": "0.75.226",
121
+ "@stacksjs/email": "0.75.230",
122
+ "@stacksjs/enums": "0.75.230",
123
+ "@stacksjs/env": "0.75.230",
124
+ "@stacksjs/error-handling": "0.75.230",
125
+ "@stacksjs/events": "0.75.230",
126
+ "@stacksjs/features": "0.75.230",
127
+ "@stacksjs/git": "0.75.230",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.226",
129
+ "@stacksjs/health": "0.75.230",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.226",
132
- "@stacksjs/lint": "0.75.226",
133
- "@stacksjs/logging": "0.75.226",
134
- "@stacksjs/notifications": "0.75.226",
135
- "@stacksjs/objects": "0.75.226",
136
- "@stacksjs/orm": "0.75.226",
137
- "@stacksjs/path": "0.75.226",
138
- "@stacksjs/payments": "0.75.226",
139
- "@stacksjs/realtime": "0.75.226",
140
- "@stacksjs/router": "0.75.226",
131
+ "@stacksjs/image": "0.75.230",
132
+ "@stacksjs/lint": "0.75.230",
133
+ "@stacksjs/logging": "0.75.230",
134
+ "@stacksjs/notifications": "0.75.230",
135
+ "@stacksjs/objects": "0.75.230",
136
+ "@stacksjs/orm": "0.75.230",
137
+ "@stacksjs/path": "0.75.230",
138
+ "@stacksjs/payments": "0.75.230",
139
+ "@stacksjs/realtime": "0.75.230",
140
+ "@stacksjs/router": "0.75.230",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.226",
143
- "@stacksjs/search-engine": "0.75.226",
144
- "@stacksjs/security": "0.75.226",
145
- "@stacksjs/server": "0.75.226",
146
- "@stacksjs/sites": "0.75.226",
147
- "@stacksjs/skills": "0.75.226",
148
- "@stacksjs/socials": "0.75.226",
149
- "@stacksjs/storage": "0.75.226",
150
- "@stacksjs/strings": "0.75.226",
151
- "@stacksjs/stx": "^0.2.567",
152
- "@stacksjs/testing": "0.75.226",
153
- "@stacksjs/tinker": "0.75.226",
142
+ "@stacksjs/scheduler": "0.75.230",
143
+ "@stacksjs/search-engine": "0.75.230",
144
+ "@stacksjs/security": "0.75.230",
145
+ "@stacksjs/server": "0.75.230",
146
+ "@stacksjs/sites": "0.75.230",
147
+ "@stacksjs/skills": "0.75.230",
148
+ "@stacksjs/socials": "0.75.230",
149
+ "@stacksjs/storage": "0.75.230",
150
+ "@stacksjs/strings": "0.75.230",
151
+ "@stacksjs/stx": "^0.2.574",
152
+ "@stacksjs/testing": "0.75.230",
153
+ "@stacksjs/tinker": "0.75.230",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
155
  "@stacksjs/ts-cloud": "^0.16.58",
156
- "@stacksjs/tunnel": "0.75.226",
157
- "@stacksjs/types": "0.75.226",
158
- "@stacksjs/ui": "0.75.226",
159
- "@stacksjs/utils": "0.75.226",
160
- "@stacksjs/validation": "0.75.226",
156
+ "@stacksjs/tunnel": "0.75.230",
157
+ "@stacksjs/types": "0.75.230",
158
+ "@stacksjs/ui": "0.75.230",
159
+ "@stacksjs/utils": "0.75.230",
160
+ "@stacksjs/validation": "0.75.230",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
- "bun-plugin-stx": "^0.2.567",
163
+ "bun-plugin-stx": "^0.2.574",
164
164
  "ts-pantry": "^0.11.69"
165
165
  },
166
166
  "devDependencies": {