@stacksjs/buddy 0.75.299 → 0.75.301

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import process from"node:process";import{generateComponentMeta,generateCoreSymlink,generateIdeHelpers,generateLibEntries,generateOpenApiSpec,generatePantryConfig,generateProjectImages,generateTypes,generateVsCodeCustomData,generateWebTypes,invoke as startGenerationProcess,watchTypes}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{reportFailure,resultFailed}from"../result";export async function runTypeGeneration(options){await generateTypes(options);try{const{buildDatabaseSchema}=await import("@stacksjs/orm");await buildDatabaseSchema()}catch(err){log.warn(`[generate:db-types] skipped: ${err.message}`)}if(options.watch)await watchTypes(options)}export function generate(buddy){const descriptions={command:"Automagically build any of your libraries/packages for production use. Select any of the following packages",types:"Generate your TypeScript types",entries:"Generate your function & Component Library Entry Points",webTypes:"Generate web-types.json for IDEs",customData:"Generate VS Code custom data (custom-elements.json) for IDEs",ideHelpers:"Generate IDE helpers",componentMeta:"Generate component meta information",coreSymlink:"Generate symlink of the core framework to the project root",pantry:"Generate the pantry configuration file",openApi:"Generate the OpenAPI specification",images:"Generate every image declared in config/images.ts",og:"Generate the social cards used by link previews",appStore:"Generate the App Store screenshot set",appIcons:"Generate the app icon and favicon sets",select:"What are you trying to generate?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("generate",descriptions.command).option("-t, --types",descriptions.types).option("-e, --entries",descriptions.entries).option("-w, --web-types",descriptions.webTypes).option("-d, --custom-data",descriptions.customData).option("-i, --ide-helpers",descriptions.ideHelpers).option("-c, --component-meta",descriptions.componentMeta).option("-r, --pantry",descriptions.pantry).option("-o, --openapi",descriptions.openApi).option("--images",descriptions.images).option("-p, --project [project]",descriptions.project,{default:!1}).option("--core-symlink",descriptions.coreSymlink).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate` ...",options);await startGenerationProcess(options);process.exit(ExitCode.Success)});buddy.command("generate:types",descriptions.types).option("-p, --project [project]",descriptions.project,{default:!1}).option("-w, --watch","Re-run on changes to models/ and config/",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:types` ...",options);await runTypeGeneration(options)});buddy.command("generate:db-types","Refresh database/types.d.ts for db.selectFrom autocomplete (stacksjs/stacks#1923)").option("--dry-run","Print the would-be file content without writing",{default:!1}).option("--framework","Write the framework's own FrameworkSchema instead of the app's DatabaseSchema",{default:!1}).action(async(options)=>{const{buildDatabaseSchema}=await import("@stacksjs/orm"),result=await buildDatabaseSchema(options.framework?{dryRun:options.dryRun,target:"framework",outFile:frameworkPath("core/database/src/framework-schema.ts"),migrationsDir:projectPath("database/migrations")}:{dryRun:options.dryRun});if(options.dryRun)console.log(result.content);for(const e of result.errors)log.warn(`[generate:db-types] ${e.file}: ${e.error}`);log.info(`[generate:db-types] resolved ${result.tables.length} table(s)`)});buddy.command("generate:vschema","Derive a Vitess VSchema from your models (writes database/vschema.json)").option("--dry-run","Print the VSchema without writing it",{default:!1}).option("--out [path]","Where to write the VSchema",{default:"database/vschema.json"}).action(async(options)=>{const{generateVSchema}=await import("@stacksjs/actions"),result=await generateVSchema({dryRun:options.dryRun,out:options.out});if(!result.ok){console.error(`
1
+ import process from"node:process";import{generateComponentMeta,generateCoreSymlink,generateIdeHelpers,generateLibEntries,generateOpenApiSpec,generatePantryConfig,generateProjectImages,generateTypes,generateVsCodeCustomData,generateWebTypes,invoke as startGenerationProcess,watchTypes}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{reportFailure,resultFailed}from"../result";export async function runTypeGeneration(options){await generateTypes(options);try{const{buildDatabaseSchema}=await import("@stacksjs/orm");await buildDatabaseSchema()}catch(err){log.warn(`[generate:db-types] skipped: ${err.message}`)}if(options.watch)await watchTypes(options)}export function generate(buddy){const descriptions={command:"Automagically build any of your libraries/packages for production use. Select any of the following packages",types:"Generate your TypeScript types",entries:"Generate your function & Component Library Entry Points",webTypes:"Generate web-types.json for IDEs",customData:"Generate VS Code custom data (custom-elements.json) for IDEs",ideHelpers:"Generate IDE helpers",componentMeta:"Generate component meta information",coreSymlink:"Generate symlink of the core framework to the project root",pantry:"Generate the pantry configuration file",openApi:"Generate the OpenAPI specification",images:"Generate every image declared in config/images.ts",og:"Generate the social cards used by link previews",appStore:"Generate the App Store screenshot set",appIcons:"Generate the app icon and favicon sets",select:"What are you trying to generate?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("generate",descriptions.command).option("-t, --types",descriptions.types).option("-e, --entries",descriptions.entries).option("-w, --web-types",descriptions.webTypes).option("-d, --custom-data",descriptions.customData).option("-i, --ide-helpers",descriptions.ideHelpers).option("-c, --component-meta",descriptions.componentMeta).option("-r, --pantry",descriptions.pantry).option("-o, --openapi",descriptions.openApi).option("--images",descriptions.images).option("-p, --project [project]",descriptions.project,{default:!1}).option("--core-symlink",descriptions.coreSymlink).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate` ...",options);await startGenerationProcess(options);process.exit(ExitCode.Success)});buddy.command("generate:types",descriptions.types).option("-p, --project [project]",descriptions.project,{default:!1}).option("-w, --watch","Re-run on changes to models/ and config/",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:types` ...",options);await runTypeGeneration(options)});buddy.command("generate:db-types","Refresh database/types.d.ts for db.selectFrom autocomplete (stacksjs/stacks#1923)").option("--dry-run","Print the would-be file content without writing",{default:!1}).option("--framework","Write the framework's own FrameworkSchema instead of the app's DatabaseSchema",{default:!1}).option("--dialect <dialect>","Raw column dialect: sqlite, mysql, or postgres").action(async(options)=>{if(options.dialect&&!["sqlite","mysql","postgres"].includes(options.dialect))throw Error("Database types require dialect sqlite, mysql, or postgres");const{buildDatabaseSchema}=await import("@stacksjs/orm"),result=await buildDatabaseSchema(options.framework?{dryRun:options.dryRun,target:"framework",dialect:options.dialect,outFile:frameworkPath("core/database/src/framework-schema.ts"),migrationsDir:projectPath("database/migrations")}:{dryRun:options.dryRun,dialect:options.dialect});if(options.dryRun)console.log(result.content);for(const e of result.errors)log.warn(`[generate:db-types] ${e.file}: ${e.error}`);log.info(`[generate:db-types] resolved ${result.tables.length} table(s)`)});buddy.command("generate:vschema","Derive a Vitess VSchema from your models (writes database/vschema.json)").option("--dry-run","Print the VSchema without writing it",{default:!1}).option("--out [path]","Where to write the VSchema",{default:"database/vschema.json"}).action(async(options)=>{const{generateVSchema}=await import("@stacksjs/actions"),result=await generateVSchema({dryRun:options.dryRun,out:options.out});if(!result.ok){console.error(`
2
2
  \u274C ${result.error}
3
3
  `);process.exit(ExitCode.FatalError)}console.log(result.report);if(options.dryRun)console.log(JSON.stringify(result.vschema,null,2));else log.success(`Wrote ${result.path} (${result.tableCount} tables)`)});buddy.command("generate:erd-diagram","Derive an entity-relationship diagram from your models (writes docs/erd.md)").alias("generate:erd").option("--dry-run","Print the diagram without writing it",{default:!1}).option("--out [path]","Where to write the diagram; a .md target gets a fenced mermaid block",{default:"docs/erd.md"}).option("--no-columns","Relationships only, without the column lists",{default:!0}).option("--only [tables]","Comma-separated tables or model names to include",{default:""}).action(async(options)=>{const{generateErd}=await import("@stacksjs/actions"),only=(options.only??"").split(",").map((entry)=>entry.trim()).filter(Boolean),result=await generateErd({dryRun:options.dryRun,out:options.out,noColumns:options.columns===!1,only});if(!result.ok){console.error(`
4
4
  \u274C ${result.error}
@@ -16,7 +16,7 @@ These were written under the old \`foreign_keys = OFF\` default (#1951). Review
16
16
  \u274C Error: ${validation.error}
17
17
  `);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=void 0}const dialectCheck=validateMigrationDialect(process.cwd(),{only:willRun});if(!dialectCheck.valid){console.error(`
18
18
  \u274C Error: ${dialectCheck.error}
19
- `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===!1?!1:void 0;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===!1)process.env.STACKS_MIGRATE_NO_RENAME="1";const generate=generatesMigrations(options.generate,hasTTY&&!isCI);if(!generate)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.generate===void 0&&!generate)log.info("Applying committed migrations only: this run is not interactive, so nothing is generated from your models. Run `./buddy generate:migrations` and commit the result, or pass --generate.");if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=!1,files=[];try{files=await pendingMigrationFiles()}catch(error){failed=!0;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` \u2022 ${file}`);if(files.length>10)log.info(` \u2022 \u2026 +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=!0;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` \u2022 ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift(),modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});if((await resolveMigrationGuards()).confirmMigrate&&!options.force)if(isCI||!hasTTY)log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.");else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();if(!await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:!0})){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(generate){if(!await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames})){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`)}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result))log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.");if(options.auth!==!1)try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`);const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success)log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`);const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success)log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}catch(error){log.error("Failed to migrate notification/RBAC/trait tables:",error)}if(resultFailed(result)){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(options.auth!==!1)try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift(),tablesPresent=await reportMissingRecordedTables(),schemaMatches=modelsMatch&&tablesPresent,allCommittable=await reportIgnoredMigrations(),allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){console.error(`
19
+ `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===!1?!1:void 0;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===!1)process.env.STACKS_MIGRATE_NO_RENAME="1";const generate=generatesMigrations(options.generate,hasTTY&&!isCI);if(!generate)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.generate===void 0&&!generate)log.info("Applying committed migrations only: this run is not interactive, so nothing is generated from your models. Run `./buddy generate:migrations` and commit the result, or pass --generate.");if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=!1,files=[];try{files=await pendingMigrationFiles()}catch(error){failed=!0;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` \u2022 ${file}`);if(files.length>10)log.info(` \u2022 \u2026 +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=!0;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` \u2022 ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift(),modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});if((await resolveMigrationGuards()).confirmMigrate&&!options.force)if(isCI||!hasTTY)log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.");else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();if(!await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:!0})){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(generate){if(!await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames})){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`)}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result))log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.");let traitMigrationError;if(options.auth!==!1)try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success)log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`);const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success)log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}catch(error){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate notification/RBAC/trait tables:",error)}if(resultFailed(result)||traitMigrationError){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:!0},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}if(options.auth!==!1)try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift(),tablesPresent=await reportMissingRecordedTables(),schemaMatches=modelsMatch&&tablesPresent,allCommittable=await reportIgnoredMigrations(),allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){console.error(`
20
20
  \u274C --strict: ${!allCommittable?"a migration is git-ignored":!allGenerated?"a migration was written by hand rather than generated from the models":"the live schema does not match the models"} (see above).
21
21
  `);process.exit(ExitCode.FatalError)}await reportFkOrphans();const APP_ENV=process.env.APP_ENV||"local",marker=readMigrateMarker(),authSuffix=options.auth!==!1?" (including auth tables)":"",applied=marker==null?`Migrated your ${APP_ENV} database.${authSuffix}`:marker.appliedCount===0?schemaMatches?`Nothing to migrate - your ${APP_ENV} database is already up to date.${authSuffix}`:`Nothing to migrate${authSuffix}.`:`Applied ${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} to your ${APP_ENV} database.${authSuffix}`,outroMessage=schemaMatches?applied:`${applied} The database is still not in the state its migrations and models describe - see above.`;if(!schemaMatches)logDriftRemedy();await outro(outroMessage,{startTime:perf,useSeconds:!0,type:schemaMatches?"success":"warning"});process.exit(ExitCode.Success)});buddy.command("migrate:fresh",descriptions.fresh).alias("db:fresh").option("-d, --diff","Show what would be dropped and replayed, and change nothing",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("--dry-run","Same as --diff: preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-s, --seed","Run database seeders after migration",{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("-f, --force",'Skip the drop-database confirmation (only honored when the migrateFresh guard is "allow")',{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate:fresh` ...",options);const perf=await intro("buddy migrate:fresh"),validation=validateModelsExist();if(!validation.valid){console.error(`
22
22
  \u274C Error: ${validation.error}
@@ -25,7 +25,7 @@ These were written under the old \`foreign_keys = OFF\` default (#1951). Review
25
25
  `);process.exit(ExitCode.FatalError)}if(isMigratePreview(options)){let files=0;try{const dir=resolveMigrationDirectory(String(process.env.DB_CONNECTION||"sqlite").toLowerCase());files=readdirSync(dir).filter((file)=>file.endsWith(".sql")).length}catch{}log.info(`Would drop every table in the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}" and replay ${files} migration file${files===1?"":"s"}${options.seed?", then seed it":""}.`);await outro("Dry run - nothing was dropped or migrated.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const guards=await resolveMigrationGuards(),dbLabel=currentDatabaseLabel(),APP_ENV=process.env.APP_ENV||"local";if(guards.migrateFresh==="disabled"){await log.error(`\`buddy migrate:fresh\` is disabled by your migration safety guards (it DROPS every table).
26
26
  Target: ${APP_ENV} database "${dbLabel}"
27
27
  To allow it, set database.safety.migrateFresh to 'allow' in config/database.ts,
28
- or run once with: DB_MIGRATE_FRESH=allow ./buddy migrate:fresh`);await outro('migrate:fresh refused - the migrateFresh guard is set to "disabled".',{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(!(guards.migrateFresh==="allow"&&options.force===!0)){if(isCI||!hasTTY){const hint=guards.migrateFresh==="confirm"?'Guard is "confirm": migrate:fresh must be run interactively.':"Re-run with --force to drop the database non-interactively.";await log.error(`Refusing to drop the ${APP_ENV} database "${dbLabel}" in a non-interactive environment. ${hint}`);await outro("migrate:fresh cancelled.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}log.warn(`This will DROP ALL TABLES in the ${APP_ENV} database "${dbLabel}" and rebuild them from scratch. All data will be lost.`);await log.flush();if((await text({message:`Type the database name "${dbLabel}" to confirm (blank to cancel):`})).trim()!==dbLabel){await outro("migrate:fresh cancelled - confirmation did not match.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate:fresh"});await ensureDatabaseOrExit();const result=await runAction(Action.MigrateFresh,options);if(resultFailed(result))log.error("Model migrations failed - applying auth/notification/RBAC table guarantees before exiting.");if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`);const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`)}catch(error){log.error("Failed to migrate auth/notification/RBAC/trait tables:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}if(resultFailed(result)){await outro("While running the migrate:fresh command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await reportMissingForeignKeys();await reportSchemaDrift();if(options.seed){log.info("Running database seeders...");try{const{runApplicationSeeders,seed}=await loadSeeders(),seedResult=await seed({verbose:options.verbose,fresh:!0}),applicationSeedResult=await runApplicationSeeders({verbose:options.verbose}),failures=seedResult.failed+applicationSeedResult.failed;if(failures>0){log.warn(`Seeding completed with ${failures} failure(s)`);for(const r of applicationSeedResult.results)if(!r.success)log.error(` - ${r.seeder}: ${r.error}`)}else log.success(`Seeded ${seedResult.successful} model(s) and ran ${applicationSeedResult.successful} application seeder(s)`)}catch(error){log.error("Failed to run seeders:",error)}}const parts=[];if(options.auth!==!1)parts.push("auth tables");if(options.seed)parts.push("seeded");const suffix=parts.length>0?` & ${parts.join(" & ")}`:"",marker=readMigrateMarker(),countPhrase=marker==null?"":marker.appliedCount===0?" (0 applied - no migration files found?)":` (${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} applied)`;await outro(`All tables dropped successfully & migrated successfully${countPhrase}${suffix}`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:switch <driver>","Pre-flight check + plan for switching DB_CONNECTION between sqlite / mysql / vitess / postgres").action(async(driver)=>{log.debug(`Running \`buddy migrate:switch ${driver}\` ...`);const perf=await intro("buddy migrate:switch"),target=driver.toLowerCase();if(!new Set(["sqlite","mysql","vitess","postgres"]).has(target)){console.log(`
28
+ or run once with: DB_MIGRATE_FRESH=allow ./buddy migrate:fresh`);await outro('migrate:fresh refused - the migrateFresh guard is set to "disabled".',{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(!(guards.migrateFresh==="allow"&&options.force===!0)){if(isCI||!hasTTY){const hint=guards.migrateFresh==="confirm"?'Guard is "confirm": migrate:fresh must be run interactively.':"Re-run with --force to drop the database non-interactively.";await log.error(`Refusing to drop the ${APP_ENV} database "${dbLabel}" in a non-interactive environment. ${hint}`);await outro("migrate:fresh cancelled.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}log.warn(`This will DROP ALL TABLES in the ${APP_ENV} database "${dbLabel}" and rebuild them from scratch. All data will be lost.`);await log.flush();if((await text({message:`Type the database name "${dbLabel}" to confirm (blank to cancel):`})).trim()!==dbLabel){await outro("migrate:fresh cancelled - confirmation did not match.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate:fresh"});await ensureDatabaseOrExit();const result=await runAction(Action.MigrateFresh,{...options,env:{...options.env,STACKS_MIGRATE_NO_AUTH:options.auth===!1?"1":"0"}});if(resultFailed(result))log.error("Model migrations failed - applying auth/notification/RBAC table guarantees before exiting.");let traitMigrationError;if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`);const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}}catch(error){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate auth/notification/RBAC/trait tables:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}if(resultFailed(result)||traitMigrationError){await outro("While running the migrate:fresh command, there was an issue",{startTime:perf,useSeconds:!0},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}await reportMissingForeignKeys();await reportSchemaDrift();if(options.seed){log.info("Running database seeders...");try{const{runApplicationSeeders,seed}=await loadSeeders(),seedResult=await seed({verbose:options.verbose,fresh:!0}),applicationSeedResult=await runApplicationSeeders({verbose:options.verbose}),failures=seedResult.failed+applicationSeedResult.failed;if(failures>0){log.warn(`Seeding completed with ${failures} failure(s)`);for(const r of applicationSeedResult.results)if(!r.success)log.error(` - ${r.seeder}: ${r.error}`)}else log.success(`Seeded ${seedResult.successful} model(s) and ran ${applicationSeedResult.successful} application seeder(s)`)}catch(error){log.error("Failed to run seeders:",error)}}const parts=[];if(options.auth!==!1)parts.push("auth tables");if(options.seed)parts.push("seeded");const suffix=parts.length>0?` & ${parts.join(" & ")}`:"",marker=readMigrateMarker(),countPhrase=marker==null?"":marker.appliedCount===0?" (0 applied - no migration files found?)":` (${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} applied)`;await outro(`All tables dropped successfully & migrated successfully${countPhrase}${suffix}`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:switch <driver>","Pre-flight check + plan for switching DB_CONNECTION between sqlite / mysql / vitess / postgres").action(async(driver)=>{log.debug(`Running \`buddy migrate:switch ${driver}\` ...`);const perf=await intro("buddy migrate:switch"),target=driver.toLowerCase();if(!new Set(["sqlite","mysql","vitess","postgres"]).has(target)){console.log(`
29
29
  Unknown target driver "${driver}". Allowed: sqlite, mysql, vitess, postgres.
30
30
  `);await outro("Aborted.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}const current=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(current===target){console.log(`
31
31
  DB_CONNECTION is already "${target}". Nothing to switch.
@@ -95,8 +95,8 @@ ${unrebuildable.map((t)=>` ${t}`).join(`
95
95
  \u2022 ${removed.length} existing file(s) will be removed${obsoleteBlock}${dataOnlyBlock}${dataBlock}${protectedHistoryBlock}${outOfScopeBlock}${unrebuildableBlock}
96
96
  \u2022 These files are tracked in git, so review with \`git diff\` afterwards
97
97
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
98
- `);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();if(!await confirm({message:`Replace ${removed.length} migration file(s) with ${files.length} generated for ${target}?`,initial:!1})){await outro("Cancelled. Nothing was written.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}const result=await regenerateMigrationCorpus({dialect:target,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(result)){log.syncError(result.error.message);process.exit(ExitCode.FatalError)}log.success(`Wrote ${result.value.files.length} ${target} migration file(s) to database/migrations.`);if((applied>0?applied:await countAppliedMigrations().catch(()=>0))>0){const{reconcileMigrationLedger}=await import("@stacksjs/database"),fixed=await reconcileMigrationLedger({regenerated:{removed:result.value.removed,written:result.value.files.map((file)=>file.name)}});if(fixed.remapped.length>0)log.info(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.recorded.length>0)log.info(`Recorded ${fixed.recorded.length} regenerated migration(s) whose every table, index and type the schema already has - they will not run.`);if(fixed.retired.length>0)log.info(`Retired ${fixed.retired.length} ledger row(s) for migrations the regenerated corpus replaced.`);if(fixed.pruned.length>0)log.info(`Pruned ${fixed.pruned.length} duplicate ledger row(s).`);if(fixed.skipped.length>0){log.warn(`${fixed.skipped.length} ledger entr(ies) need a look:`);for(const entry of fixed.skipped.slice(0,10))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>10)log.info(` \u2026 +${fixed.skipped.length-10} more - run \`./buddy migrate:status\``)}log.info("This database has history. Before `./buddy migrate`, bring its schema in line with the models:");log.info(" ./buddy migrate:align # what differs, and what can be repaired safely");log.info(" ./buddy migrate:align --apply # rename legacy indexes, add missing indexes and foreign keys");log.info(" ./buddy migrate:status --reconcile # record the regenerated files the schema now satisfies")}log.info("Review the change with `git diff`, then run `./buddy migrate`.");await outro("Regenerated.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:align","Repair a live database that drifted from the models, without writing migrations (PostgreSQL)").option("--apply","Run the safe repairs, in one transaction",{default:!1}).option("--widen-integers","Also widen integer columns the models declare as bigint (rewrites those tables)",{default:!1}).option("-f, --force","With --apply, skip the confirmation",{default:!1}).option("--json","Emit the plan as JSON",{default:!1}).action(async(options)=>{const perf=options.json?void 0:await intro("buddy migrate:align"),{alignSchema}=await import("@stacksjs/database");let planned;try{planned=await alignSchema({widenIntegers:options.widenIntegers})}catch(error){log.syncError(`Could not compare the database with the models: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}if(options.json){console.log(JSON.stringify(planned,null,2));process.exit(ExitCode.Success)}if(!planned.supported){await log.info(`migrate:align is not supported for "${planned.dialect}" yet - only PostgreSQL. Nothing was compared.`);await outro("Skipped.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const{actions,reports,refused}=planned.plan,report=["",` Align plan: ${planned.dialect}`," \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];if(actions.length>0){report.push(` ${actions.length} safe repair(s)${options.apply?"":" - run with --apply to make them, in one transaction"}:`);for(const action of actions)report.push(` \u2022 ${action.detail}`,` ${action.sql};`);report.push("")}if(refused.length>0){report.push(` ${refused.length} repair(s) REFUSED - the data would violate them:`);for(const action of refused)report.push(` \u2022 ${action.detail}: ${action.reason}`);report.push("")}if(reports.length>0){report.push(` ${reports.length} difference(s) left for you to decide - destructive or ambiguous, never applied:`);for(const item of reports.slice(0,40))report.push(` \u2022 [${item.kind}] ${item.detail}`);if(reports.length>40)report.push(` \u2026 +${reports.length-40} more (--json lists all)`);report.push("")}if(actions.length===0&&refused.length===0&&reports.length===0)report.push(" The database matches the models.","");console.log(report.join(`
99
- `));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds:!0});process.exit(refused.length>0?ExitCode.FatalError:ExitCode.Success)}if(!options.force&&!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();if(!await confirm({message:`Apply ${actions.length} repair(s) to the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}"?`,initial:!1})){await outro("Cancelled. Nothing was changed.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}try{const applied=await alignSchema({apply:!0,widenIntegers:options.widenIntegers});await log.success(`Applied ${applied.applied.length} repair(s).`);for(const action of applied.plan.refused)await log.warn(`Refused: ${action.detail}: ${action.reason}`)}catch(error){log.syncError(`Nothing was changed - the repairs run as one transaction and it failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}await log.info("Migrations whose every table, index and type now exists can be recorded without running:");await log.info(" ./buddy migrate:status --reconcile");await outro("Aligned.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:status","Compare database/migrations, the migrations ledger, and the live schema").option("--reconcile","Repair the ledger where the schema proves what happened",{default:!1}).option("--include-partial","With --reconcile, also record half-applied migrations",{default:!1}).option("--requeue-reverted","With --reconcile, un-record the migrations of a table that is missing so the next migrate rebuilds it",{default:!1}).option("--json","Emit the audit as JSON",{default:!1}).option("--strict","Also fail when a migration was written by hand rather than generated from the models",{default:!1}).action(async(options)=>{const perf=options.json?void 0:await intro("buddy migrate:status"),{auditMigrationLedger,handWrittenMigrations,reconcileMigrationLedger}=await import("@stacksjs/database"),audit=await auditMigrationLedger(),handWritten=(await handWrittenMigrations()).files,strict=strictMode(options),handWrittenFails=strict&&handWritten.length>0;if(options.json){console.log(JSON.stringify({...audit,handWritten},(_k,v)=>v instanceof Set?[...v]:v,2));process.exit(audit.drift||handWrittenFails?ExitCode.FatalError:ExitCode.Success)}if(!audit.supported){log.info(`Dialect "${audit.dialect}" is not audited. Nothing to compare.`);await outro("Skipped.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const{counts,entries,orphans}=audit,list=(status)=>entries.filter((e)=>e.status===status).map((e)=>e.file),report=[],section=(heading,files)=>{if(files.length===0)return;if(heading)report.push(` ${heading}`);for(const file of files.slice(0,8))report.push(` ${file}`);if(files.length>8)report.push(` \u2026 +${files.length-8} more`);report.push("")};report.push("");report.push(` Migration status: ${audit.dialect}`);report.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");report.push(` ${entries.length+audit.gated.length} file(s) on disk \xB7 ${audit.recordedCount} recorded in the ledger`);report.push("");if(counts.applied>0)report.push(` ${counts.applied} applied - recorded, and present in the schema.`,"");if(counts.unverifiable>0)report.push(` ${counts.unverifiable} unverifiable - data migrations with no schema trace to check.`,"");if(audit.gated.length>0)report.push(` ${audit.gated.length} skipped - owned by a disabled feature, so \`buddy migrate\` does not run them until it is enabled.`,"");section(`${counts.pending} pending - not applied yet, will run on the next \`buddy migrate\`:`,list("pending"));if(counts.stranded>0){report.push(` ${counts.stranded} STRANDED - already applied to the schema, but missing from the ledger.`);report.push(" These re-run on the next `buddy migrate`, which is unsafe for anything not idempotent.");section("",list("stranded"))}section(`${counts.partial} PARTIAL - some effects present, some missing. Needs a human:`,list("partial"));section(`${counts.reverted} REVERTED - recorded as applied, but the effects are gone from the schema:`,list("reverted"));if(orphans.length>0)section(`${orphans.length} orphaned ledger row(s) - recorded, but no such file on disk:`,orphans.map((o)=>{if(o.renamedTo)return`${o.migration} -> renumbered to ${o.renamedTo}`;if(audit.remapPlan.superseded.includes(o.migration))return`${o.migration} (duplicate; already recorded under its current name)`;return`${o.migration} (no counterpart; migration deleted?)`}));if(handWritten.length>0){section(`${handWritten.length} hand-written - no \`-- qb:generated\` marker, so no model describes ${handWritten.length===1?"it":"them"}${strict?" (fails --strict)":""}:`,handWritten);report.push(" Move each change into app/Models and regenerate, or allow the file in");report.push(" database.safety.allowHandWrittenMigrations (reference data no model can describe).","")}console.log(report.join(`
98
+ `);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();if(!await confirm({message:`Replace ${removed.length} migration file(s) with ${files.length} generated for ${target}?`,initial:!1})){await outro("Cancelled. Nothing was written.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}const result=await regenerateMigrationCorpus({dialect:target,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(result)){log.syncError(result.error.message);process.exit(ExitCode.FatalError)}log.success(`Wrote ${result.value.files.length} ${target} migration file(s) to database/migrations.`);if((applied>0?applied:await countAppliedMigrations().catch(()=>0))>0){const{reconcileMigrationLedger}=await import("@stacksjs/database"),fixed=await reconcileMigrationLedger({regenerated:{removed:result.value.removed,written:result.value.files.map((file)=>file.name)}});if(fixed.remapped.length>0)log.info(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.recorded.length>0)log.info(`Recorded ${fixed.recorded.length} regenerated migration(s) whose every table, index and type the schema already has - they will not run.`);if(fixed.retired.length>0)log.info(`Retired ${fixed.retired.length} ledger row(s) for migrations the regenerated corpus replaced.`);if(fixed.pruned.length>0)log.info(`Pruned ${fixed.pruned.length} duplicate ledger row(s).`);if(fixed.skipped.length>0){log.warn(`${fixed.skipped.length} ledger entr(ies) need a look:`);for(const entry of fixed.skipped.slice(0,10))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>10)log.info(` \u2026 +${fixed.skipped.length-10} more - run \`./buddy migrate:status\``)}log.info("This database has history. Before `./buddy migrate`, bring its schema in line with the models:");log.info(" ./buddy migrate:align # what differs, and what can be repaired safely");log.info(" ./buddy migrate:align --apply # rename legacy indexes, add missing indexes and foreign keys");log.info(" ./buddy migrate:status --reconcile # record the regenerated files the schema now satisfies")}log.info("Review the change with `git diff`, then run `./buddy migrate`.");await outro("Regenerated.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:align","Repair a live database that drifted from the models, without writing migrations (PostgreSQL)").option("--apply","Run the safe repairs, in one transaction",{default:!1}).option("--widen-integers","Also widen integer columns the models declare as bigint (rewrites those tables)",{default:!1}).option("--relax-constraints","Also remove obsolete NOT NULL constraints, polymorphic foreign keys, and conflicting keys with an enforced model reference",{default:!1}).option("-f, --force","With --apply, skip the confirmation",{default:!1}).option("--json","Emit the plan as JSON",{default:!1}).action(async(options)=>{const perf=options.json?void 0:await intro("buddy migrate:align"),{alignSchema}=await import("@stacksjs/database");let planned;try{planned=await alignSchema({widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints})}catch(error){log.syncError(`Could not compare the database with the models: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}if(options.json){console.log(JSON.stringify(planned,null,2));process.exit(ExitCode.Success)}if(!planned.supported){await log.info(`migrate:align is not supported for "${planned.dialect}" yet - only PostgreSQL. Nothing was compared.`);await outro("Skipped.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const{actions,reports,refused}=planned.plan,report=["",` Align plan: ${planned.dialect}`," \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];if(actions.length>0){report.push(` ${actions.length} safe repair(s)${options.apply?"":" - run with --apply to make them, in one transaction"}:`);for(const action of actions)report.push(` \u2022 ${action.detail}`,` ${action.sql};`);report.push("")}if(refused.length>0){report.push(` ${refused.length} repair(s) REFUSED - the data would violate them:`);for(const action of refused)report.push(` \u2022 ${action.detail}: ${action.reason}`);report.push("")}if(reports.length>0){report.push(` ${reports.length} difference(s) left for you to decide - destructive or ambiguous, never applied:`);for(const item of reports.slice(0,40))report.push(` \u2022 [${item.kind}] ${item.detail}`);if(reports.length>40)report.push(` \u2026 +${reports.length-40} more (--json lists all)`);report.push("")}if(actions.length===0&&refused.length===0&&reports.length===0)report.push(" The database matches the models.","");console.log(report.join(`
99
+ `));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds:!0});process.exit(refused.length>0?ExitCode.FatalError:ExitCode.Success)}if(!options.force&&!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();if(!await confirm({message:`Apply ${actions.length} repair(s) to the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}"?`,initial:!1})){await outro("Cancelled. Nothing was changed.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}try{const applied=await alignSchema({apply:!0,widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints});await log.success(`Applied ${applied.applied.length} repair(s).`);for(const action of applied.plan.refused)await log.warn(`Refused: ${action.detail}: ${action.reason}`)}catch(error){log.syncError(`Nothing was changed - the repairs run as one transaction and it failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}await log.info("Migrations whose every table, index and type now exists can be recorded without running:");await log.info(" ./buddy migrate:status --reconcile");await outro("Aligned.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:status","Compare database/migrations, the migrations ledger, and the live schema").option("--reconcile","Repair the ledger where the schema proves what happened",{default:!1}).option("--include-partial","With --reconcile, also record half-applied migrations",{default:!1}).option("--requeue-reverted","With --reconcile, un-record the migrations of a table that is missing so the next migrate rebuilds it",{default:!1}).option("--json","Emit the audit as JSON",{default:!1}).option("--strict","Also fail when a migration was written by hand rather than generated from the models",{default:!1}).action(async(options)=>{const perf=options.json?void 0:await intro("buddy migrate:status"),{auditMigrationLedger,handWrittenMigrations,reconcileMigrationLedger}=await import("@stacksjs/database"),audit=await auditMigrationLedger(),handWritten=(await handWrittenMigrations()).files,strict=strictMode(options),handWrittenFails=strict&&handWritten.length>0;if(options.json){console.log(JSON.stringify({...audit,handWritten},(_k,v)=>v instanceof Set?[...v]:v,2));process.exit(audit.drift||handWrittenFails?ExitCode.FatalError:ExitCode.Success)}if(!audit.supported){log.info(`Dialect "${audit.dialect}" is not audited. Nothing to compare.`);await outro("Skipped.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const{counts,entries,orphans}=audit,list=(status)=>entries.filter((e)=>e.status===status).map((e)=>e.file),report=[],section=(heading,files)=>{if(files.length===0)return;if(heading)report.push(` ${heading}`);for(const file of files.slice(0,8))report.push(` ${file}`);if(files.length>8)report.push(` \u2026 +${files.length-8} more`);report.push("")};report.push("");report.push(` Migration status: ${audit.dialect}`);report.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");report.push(` ${entries.length+audit.gated.length} file(s) on disk \xB7 ${audit.recordedCount} recorded in the ledger`);report.push("");if(counts.applied>0)report.push(` ${counts.applied} applied - recorded, and present in the schema.`,"");if(counts.unverifiable>0)report.push(` ${counts.unverifiable} unverifiable - data migrations with no schema trace to check.`,"");if(audit.gated.length>0)report.push(` ${audit.gated.length} skipped - owned by a disabled feature, so \`buddy migrate\` does not run them until it is enabled.`,"");section(`${counts.pending} pending - not applied yet, will run on the next \`buddy migrate\`:`,list("pending"));if(counts.stranded>0){report.push(` ${counts.stranded} STRANDED - already applied to the schema, but missing from the ledger.`);report.push(" These re-run on the next `buddy migrate`, which is unsafe for anything not idempotent.");section("",list("stranded"))}section(`${counts.partial} PARTIAL - some effects present, some missing. Needs a human:`,list("partial"));section(`${counts.reverted} REVERTED - recorded as applied, but the effects are gone from the schema:`,list("reverted"));if(orphans.length>0)section(`${orphans.length} orphaned ledger row(s) - recorded, but no such file on disk:`,orphans.map((o)=>{if(o.renamedTo)return`${o.migration} -> renumbered to ${o.renamedTo}`;if(audit.remapPlan.superseded.includes(o.migration))return`${o.migration} (duplicate; already recorded under its current name)`;return`${o.migration} (no counterpart; migration deleted?)`}));if(handWritten.length>0){section(`${handWritten.length} hand-written - no \`-- qb:generated\` marker, so no model describes ${handWritten.length===1?"it":"them"}${strict?" (fails --strict)":""}:`,handWritten);report.push(" Move each change into app/Models and regenerate, or allow the file in");report.push(" database.safety.allowHandWrittenMigrations (reference data no model can describe).","")}console.log(report.join(`
100
100
  `));if(!audit.drift){if(handWrittenFails){await outro("--strict: hand-written migrations (see above).",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro("Ledger matches the corpus and the schema.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.reconcile){console.log(`
101
101
  Repair with: ./buddy migrate:status --reconcile
102
102
  That repoints renumbered ledger rows and records migrations the schema
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.299",
5
+ "version": "0.75.301",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,69 +95,69 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.299",
99
- "@stacksjs/ai": "0.75.299",
100
- "@stacksjs/alias": "0.75.299",
101
- "@stacksjs/analytics": "0.75.299",
102
- "@stacksjs/api": "0.75.299",
103
- "@stacksjs/arrays": "0.75.299",
104
- "@stacksjs/auth": "0.75.299",
105
- "@stacksjs/browser-extension": "0.75.299",
106
- "@stacksjs/build": "0.75.299",
98
+ "@stacksjs/actions": "0.75.301",
99
+ "@stacksjs/ai": "0.75.301",
100
+ "@stacksjs/alias": "0.75.301",
101
+ "@stacksjs/analytics": "0.75.301",
102
+ "@stacksjs/api": "0.75.301",
103
+ "@stacksjs/arrays": "0.75.301",
104
+ "@stacksjs/auth": "0.75.301",
105
+ "@stacksjs/browser-extension": "0.75.301",
106
+ "@stacksjs/build": "0.75.301",
107
107
  "@stacksjs/bumpx": "^0.2.26",
108
- "@stacksjs/cache": "0.75.299",
109
- "@stacksjs/chat": "0.75.299",
108
+ "@stacksjs/cache": "0.75.301",
109
+ "@stacksjs/chat": "0.75.301",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.299",
112
- "@stacksjs/cloud": "0.75.299",
113
- "@stacksjs/cms": "0.75.299",
114
- "@stacksjs/collections": "0.75.299",
115
- "@stacksjs/commerce": "0.75.299",
116
- "@stacksjs/config": "0.75.299",
117
- "@stacksjs/database": "0.75.299",
118
- "@stacksjs/desktop-build": "0.75.299",
119
- "@stacksjs/dns": "0.75.299",
111
+ "@stacksjs/cli": "0.75.301",
112
+ "@stacksjs/cloud": "0.75.301",
113
+ "@stacksjs/cms": "0.75.301",
114
+ "@stacksjs/collections": "0.75.301",
115
+ "@stacksjs/commerce": "0.75.301",
116
+ "@stacksjs/config": "0.75.301",
117
+ "@stacksjs/database": "0.75.301",
118
+ "@stacksjs/desktop-build": "0.75.301",
119
+ "@stacksjs/dns": "0.75.301",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.299",
122
- "@stacksjs/enums": "0.75.299",
123
- "@stacksjs/env": "0.75.299",
124
- "@stacksjs/error-handling": "0.75.299",
125
- "@stacksjs/events": "0.75.299",
126
- "@stacksjs/features": "0.75.299",
127
- "@stacksjs/git": "0.75.299",
121
+ "@stacksjs/email": "0.75.301",
122
+ "@stacksjs/enums": "0.75.301",
123
+ "@stacksjs/env": "0.75.301",
124
+ "@stacksjs/error-handling": "0.75.301",
125
+ "@stacksjs/events": "0.75.301",
126
+ "@stacksjs/features": "0.75.301",
127
+ "@stacksjs/git": "0.75.301",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.299",
129
+ "@stacksjs/health": "0.75.301",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.299",
132
- "@stacksjs/lint": "0.75.299",
133
- "@stacksjs/logging": "0.75.299",
134
- "@stacksjs/notifications": "0.75.299",
135
- "@stacksjs/objects": "0.75.299",
136
- "@stacksjs/orm": "0.75.299",
137
- "@stacksjs/path": "0.75.299",
138
- "@stacksjs/payments": "0.75.299",
139
- "@stacksjs/realtime": "0.75.299",
140
- "@stacksjs/router": "0.75.299",
131
+ "@stacksjs/image": "0.75.301",
132
+ "@stacksjs/lint": "0.75.301",
133
+ "@stacksjs/logging": "0.75.301",
134
+ "@stacksjs/notifications": "0.75.301",
135
+ "@stacksjs/objects": "0.75.301",
136
+ "@stacksjs/orm": "0.75.301",
137
+ "@stacksjs/path": "0.75.301",
138
+ "@stacksjs/payments": "0.75.301",
139
+ "@stacksjs/realtime": "0.75.301",
140
+ "@stacksjs/router": "0.75.301",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.299",
143
- "@stacksjs/search-engine": "0.75.299",
144
- "@stacksjs/security": "0.75.299",
145
- "@stacksjs/server": "0.75.299",
146
- "@stacksjs/sites": "0.75.299",
147
- "@stacksjs/skills": "0.75.299",
148
- "@stacksjs/socials": "0.75.299",
149
- "@stacksjs/storage": "0.75.299",
150
- "@stacksjs/strings": "0.75.299",
142
+ "@stacksjs/scheduler": "0.75.301",
143
+ "@stacksjs/search-engine": "0.75.301",
144
+ "@stacksjs/security": "0.75.301",
145
+ "@stacksjs/server": "0.75.301",
146
+ "@stacksjs/sites": "0.75.301",
147
+ "@stacksjs/skills": "0.75.301",
148
+ "@stacksjs/socials": "0.75.301",
149
+ "@stacksjs/storage": "0.75.301",
150
+ "@stacksjs/strings": "0.75.301",
151
151
  "@stacksjs/stx": "0.2.687",
152
- "@stacksjs/testing": "0.75.299",
153
- "@stacksjs/tinker": "0.75.299",
152
+ "@stacksjs/testing": "0.75.301",
153
+ "@stacksjs/tinker": "0.75.301",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
- "@stacksjs/ts-cloud": "^0.16.58",
156
- "@stacksjs/tunnel": "0.75.299",
157
- "@stacksjs/types": "0.75.299",
158
- "@stacksjs/ui": "0.75.299",
159
- "@stacksjs/utils": "0.75.299",
160
- "@stacksjs/validation": "0.75.299",
155
+ "@stacksjs/ts-cloud": "^0.16.69",
156
+ "@stacksjs/tunnel": "0.75.301",
157
+ "@stacksjs/types": "0.75.301",
158
+ "@stacksjs/ui": "0.75.301",
159
+ "@stacksjs/utils": "0.75.301",
160
+ "@stacksjs/validation": "0.75.301",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
163
  "bun-plugin-stx": "0.2.687",