@stacksjs/buddy 0.75.515 → 0.75.518
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-store-connect.js +2 -2
- package/dist/cli.js +4 -4
- package/dist/cloud-tenants.js +1 -1
- package/dist/commands/about.js +1 -1
- package/dist/commands/add.js +1 -1
- package/dist/commands/ai-access.js +2 -2
- package/dist/commands/ai-context.js +2 -2
- package/dist/commands/auth-prune-options.js +1 -1
- package/dist/commands/auth.js +1 -1
- package/dist/commands/build.js +1 -1
- package/dist/commands/cd.js +3 -3
- package/dist/commands/changelog.js +1 -1
- package/dist/commands/clean.js +1 -1
- package/dist/commands/cloud.js +7 -7
- package/dist/commands/comments.js +2 -2
- package/dist/commands/commerce-import.js +3 -3
- package/dist/commands/commit.js +1 -1
- package/dist/commands/completion.js +7 -7
- package/dist/commands/config-migrate.js +5 -5
- package/dist/commands/configure.js +2 -2
- package/dist/commands/create.js +1 -1
- package/dist/commands/db.js +1 -1
- package/dist/commands/deploy-fly.js +2 -2
- package/dist/commands/deploy-preview.js +1 -1
- package/dist/commands/deploy-ssh-target.js +1 -1
- package/dist/commands/deploy.js +588 -19
- package/dist/commands/desktop-apple.js +12 -12
- package/dist/commands/desktop-probe.js +1 -1
- package/dist/commands/dev.js +4 -4
- package/dist/commands/dns.js +2 -2
- package/dist/commands/docs/agent-counts.js +2 -2
- package/dist/commands/docs/buddy-commands.js +11 -11
- package/dist/commands/docs/capabilities.js +2 -2
- package/dist/commands/docs/desktop-matrix.js +2 -2
- package/dist/commands/docs/framework-repo.js +1 -1
- package/dist/commands/docs/generated-artifacts.js +3 -3
- package/dist/commands/docs/links.js +2 -2
- package/dist/commands/docs/native-skills.js +2 -2
- package/dist/commands/docs/snippets.js +7 -7
- package/dist/commands/doctor.js +3 -3
- package/dist/commands/domains.js +2 -2
- package/dist/commands/email.js +26 -26
- package/dist/commands/env.js +1 -1
- package/dist/commands/extension.js +3 -3
- package/dist/commands/features.js +3 -3
- package/dist/commands/feedback.js +3 -3
- package/dist/commands/fresh.js +1 -1
- package/dist/commands/gdpr.js +6 -6
- package/dist/commands/generate.js +5 -5
- package/dist/commands/http.js +1 -1
- package/dist/commands/install.js +1 -1
- package/dist/commands/integrations-probe.js +2 -2
- package/dist/commands/key.js +1 -1
- package/dist/commands/libs.js +1 -1
- package/dist/commands/link.js +2 -2
- package/dist/commands/lint.js +2 -2
- package/dist/commands/list.js +2 -2
- package/dist/commands/mail.js +13 -13
- package/dist/commands/maintenance.js +1 -1
- package/dist/commands/make.js +1 -1
- package/dist/commands/migrate-project.js +1 -1
- package/dist/commands/migrate.js +59 -59
- package/dist/commands/outdated.js +1 -1
- package/dist/commands/package.js +1 -1
- package/dist/commands/phone.js +13 -13
- package/dist/commands/ports.js +2 -2
- package/dist/commands/prepublish.js +1 -1
- package/dist/commands/preview-deploy.js +1 -1
- package/dist/commands/projects.js +1 -1
- package/dist/commands/publish.js +8 -8
- package/dist/commands/queue.js +1 -1
- package/dist/commands/release.js +7 -7
- package/dist/commands/route.js +1 -1
- package/dist/commands/saas.js +1 -1
- package/dist/commands/schedule.js +1 -1
- package/dist/commands/search.js +1 -1
- package/dist/commands/security.js +2 -2
- package/dist/commands/seed.js +1 -1
- package/dist/commands/serve.js +1 -1
- package/dist/commands/server-image.js +2 -2
- package/dist/commands/server-trust.js +2 -2
- package/dist/commands/server.js +10 -8
- package/dist/commands/setup-ai.js +2 -2
- package/dist/commands/setup.js +5 -5
- package/dist/commands/share.js +1 -1
- package/dist/commands/simulator.js +1 -1
- package/dist/commands/sms.js +25 -25
- package/dist/commands/socials.js +3 -3
- package/dist/commands/stacks.js +1 -1
- package/dist/commands/storage-backup.js +1 -1
- package/dist/commands/telemetry.js +1 -1
- package/dist/commands/test.js +1 -1
- package/dist/commands/tinker.js +1 -1
- package/dist/commands/types.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/commands/user.js +2 -2
- package/dist/config.js +1 -1
- package/dist/custom-cli.js +1 -1
- package/dist/database-backup.js +2 -2
- package/dist/database-preflight.js +1 -1
- package/dist/deploy-notify.js +3 -3
- package/dist/deployment-inputs.js +1 -1
- package/dist/deployment-revision.js +4 -4
- package/dist/dns-credentials.js +1 -1
- package/dist/email-reprocess.js +1 -1
- package/dist/feedback-links.js +1 -1
- package/dist/global-options.js +1 -1
- package/dist/lazy-commands.js +1 -1
- package/dist/mail-dns-health.js +1 -1
- package/dist/mail-users.js +1 -1
- package/dist/migrators/index.js +1 -1
- package/dist/migrators/laravel/index.js +1 -1
- package/dist/migrators/laravel/migrations.js +4 -4
- package/dist/migrators/laravel/models.js +4 -4
- package/dist/native-project.js +7 -7
- package/dist/native-site.js +2 -2
- package/dist/pantry-service-ports.js +2 -2
- package/dist/production-server.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/publish-stx.js +1 -1
- package/dist/registry.js +1 -1
- package/dist/release-ios.js +1 -1
- package/dist/result.js +1 -1
- package/dist/scaffold-app.js +4 -4
- package/dist/scaffold-desktop.js +1 -1
- package/dist/scaffold-package-app.js +7 -7
- package/dist/scaffold-site.js +1 -1
- package/dist/storage-backup.js +1 -1
- package/dist/system-dependencies.js +1 -1
- package/dist/unbacked-data.js +1 -1
- package/dist/unvendor-rewrite.js +2 -2
- package/dist/version-info.js +1 -1
- package/dist/workflow-prune.js +3 -3
- package/package.json +55 -55
package/dist/commands/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:!1}).option("-t, --pretty",descriptions.pretty,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:!1}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==void 0){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===void 0){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:!1}).option("--dry-run",descriptions.rotateDryRun,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli"),{storage}=await import("@stacksjs/storage"),{existsSync}=await import("node:fs"),{resolve}=await import("node:path");await intro("buddy env:check");const checks=[],envFile=resolveEnvFile(options.file,options.env)||".env",envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath),contentStr=typeof envContent==="string"?envContent:envContent.data,values=parseEnvAssignments(contentStr),varCount=Object.keys(values).length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});if("APP_KEY"in values)if((values.APP_KEY??"").length>0)checks.push({name:"APP_KEY",status:"pass",message:"Set"});else checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"});else checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"});const{publicKeyName,privateKeyName}=envKeyNames(envFile),privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"],publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY,hasPublicKey=Boolean(publicKey),privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean),hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey))checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`});if(hasPublicKey&&hasPrivateKey)checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"});else if(hasPublicKey||hasPrivateKey)checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"});else checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"});const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0)checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"});else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env"),foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants)),isShipped=/^\.env\.[a-z]+$/.test(envFile),total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0)checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`});else if(!isShipped)checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`});else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign)checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");if(!trackedEnvFiles(gitLsFiles()).includes(envFile))checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`});else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict}),metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material"),leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length)checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`});if(leaked.length===0)checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`});else checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else checks.push({name:`${envFile} file`,status:"fail",message:"Not found"});const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath))checks.push({name:".env.keys file",status:"pass",message:"Found"});else checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"});console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("\u2500".repeat(60)));console.log("");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}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("\u2500".repeat(60)));console.log("");if(hasFailures){console.log(red("\u2717 Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("\u26A0 Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("\u2713 All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config"),cloud=config.cloud;return{self:config.app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={},assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i,lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:void 0;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else raw=raw.replace(/\s+#.*$/,"").trim();values[key]=raw}return values}
|
|
1
|
+
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:false}).option("-t, --pretty",descriptions.pretty,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:false}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==undefined){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===undefined){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:false}).option("--dry-run",descriptions.rotateDryRun,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli");const{storage}=await import("@stacksjs/storage");const{existsSync}=await import("node:fs");const{resolve}=await import("node:path");await intro("buddy env:check");const checks=[];const envFile=resolveEnvFile(options.file,options.env)||".env";const envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath);const contentStr=typeof envContent==="string"?envContent:envContent.data;const values=parseEnvAssignments(contentStr);const keys=Object.keys(values);const varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});const hasAppKey="APP_KEY"in values;if(hasAppKey){const appKeyValue=values.APP_KEY??"";if(appKeyValue.length>0){checks.push({name:"APP_KEY",status:"pass",message:"Set"})}else{checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}}else{checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"})}const{publicKeyName,privateKeyName}=envKeyNames(envFile);const privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"];const publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY;const hasPublicKey=Boolean(publicKey);const privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean);const hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey)){checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`})}if(hasPublicKey&&hasPrivateKey){checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"})}else if(hasPublicKey||hasPrivateKey){checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"})}else{checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0){checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"})}else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants));const isShipped=/^\.env\.[a-z]+$/.test(envFile);const total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0){checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`})}else if(!isShipped){checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`})}else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign){checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");const tracked=trackedEnvFiles(gitLsFiles());if(!tracked.includes(envFile)){checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`})}else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict});const metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material");const leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length){checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`})}if(leaked.length===0){checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`})}else{checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else{checks.push({name:`${envFile} file`,status:"fail",message:"Not found"})}const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath)){checks.push({name:".env.keys file",status:"pass",message:"Found"})}else{checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"})}console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("─".repeat(60)));console.log("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("─".repeat(60)));console.log("");if(hasFailures){console.log(red("✗ Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("⚠ Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("✓ All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config");const cloud=config.cloud;const app=config.app;return{self:app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={};const assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i;const lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:undefined;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else{raw=raw.replace(/\s+#.*$/,"").trim()}values[key]=raw}return values}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import process from"node:process";import{log}from"@stacksjs/cli";function parseSafariPlatforms(platform){if(!platform)return;if(platform==="all")return["macos","ios"];if(platform==="macos"||platform==="ios")return[platform];throw Error(`Invalid Safari platform ${platform}; use macos, ios, or all`)}async function refreshAppStoreScreenshots(){try{const{generateProjectImages}=await import("@stacksjs/actions");await generateProjectImages({only:["app-store"]})}catch(error){log.warn(`[extension:publish] using the committed screenshots - could not regenerate: ${error.message}`)}}async function syncFirefoxListing(config,credentials){if(!config.firefoxAddons?.screenshots?.length)return;try{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension")
|
|
2
|
-
${formatPublishPlan(plan)}`);const publishing=plan.filter((decision)=>decision.publish);if(options.dryRun||!publishing.length){if(!publishing.length)log.warn("No store is both configured and credentialed, so nothing was published.");return}const failures=[];for(const{target}of publishing)try{if(target==="chrome"){const result=await publishChromeExtension(config,{version:options.version??version,blockOnWarnings
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";function parseSafariPlatforms(platform){if(!platform)return;if(platform==="all")return["macos","ios"];if(platform==="macos"||platform==="ios")return[platform];throw new Error(`Invalid Safari platform ${platform}; use macos, ios, or all`)}async function refreshAppStoreScreenshots(){try{const{generateProjectImages}=await import("@stacksjs/actions");await generateProjectImages({only:["app-store"]})}catch(error){log.warn(`[extension:publish] using the committed screenshots - could not regenerate: ${error.message}`)}}async function syncFirefoxListing(config,credentials){if(!config.firefoxAddons?.screenshots?.length)return;try{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension");const previews=await syncFirefoxPreviews(config,credentials);if(previews.unchanged)log.info("Firefox listing screenshots already match");else log.success(`Synced ${previews.uploaded.length} Firefox listing screenshot(s), removed ${previews.removed.length}`)}catch(error){log.warn(`[extension:publish] Firefox listing screenshots not synced: ${error.message}`)}}export function extension(buddy){const load=async()=>{const{loadExtensionConfig}=await import("@stacksjs/browser-extension");const config=await loadExtensionConfig(process.cwd());if(!config){await log.error("No extension config found. Create `config/extension.ts` exporting `defineExtension({ … })`.");process.exit(1)}const pkg=await Bun.file(`${process.cwd()}/package.json`).json().catch(()=>({}));return{config,version:pkg.version??"0.0.0"}};buddy.command("extension:build","Build the browser extension (Chrome + Firefox + Safari) from config/extension.ts").option("--target <target>","Build a single target (chrome | firefox | safari | webkit); omit to build all. webkit emits content-blocker lists and WKUserScripts for WKWebView apps").option("--version <version>","Override the extension version (defaults to package.json)").action(async(options)=>{const{buildExtension,buildAllTargets}=await import("@stacksjs/browser-extension");const{config,version}=await load();const v=options.version??version;if(options.target&&!["chrome","firefox","safari","webkit"].includes(options.target)){await log.error(`Unknown target ${options.target}; use chrome, firefox, safari or webkit`);process.exit(1)}if(options.target){const{outdir}=await buildExtension(config,{target:options.target,version:v});log.success(`Built ${config.name} ${v} (${options.target}) → ${outdir}`)}else{await buildAllTargets(config,{version:v});log.success(`Built ${config.name} ${v} for ${(config.targets??["chrome","firefox"]).join(", ")}`)}});buddy.command("extension:init","Scaffold a Chrome, Firefox, or Safari extension, including the Safari Xcode app").option("--name <name>","Extension display name").option("--target <target>","Scaffold chrome, firefox, safari, or all (default all)").option("--bundle-id <id>","Safari container bundle identifier").option("--team-id <id>","Apple Developer team used for Safari signing").option("--platform <platform>","Safari platform: macos, ios, or all (default all)").option("--force","Overwrite existing starter and Safari scaffold files").action(async(options)=>{const target=options.target??"all";if(!["chrome","firefox","safari","all"].includes(target))throw new Error(`Invalid extension target ${target}; use chrome, firefox, safari, or all`);const{scaffoldExtensionProject}=await import("@stacksjs/browser-extension");const result=await scaffoldExtensionProject({name:options.name,target,bundleId:options.bundleId,teamId:options.teamId,platforms:parseSafariPlatforms(options.platform)??["macos","ios"],force:Boolean(options.force)});for(const file of result.written)log.success(`created ${file}`);for(const file of result.skipped)log.info(`skip (exists): ${file}`);if(result.safari)log.success(`Scaffolded the Safari container app → ${result.safari.dir}`);log.info("Next: add icons under public/icons, then run `buddy extension:build`.")});buddy.command("extension:package","Build + zip the browser extension into store-ready archives").option("--target <target>","Package a single target (chrome | firefox | safari); omit to package all").option("--version <version>","Override the extension version (defaults to package.json)").action(async(options)=>{const{packageExtension}=await import("@stacksjs/browser-extension");const{config,version}=await load();const v=options.version??version;const targets=options.target?[options.target]:config.targets??["chrome","firefox"];for(const target of targets){const out=await packageExtension(config,{target,version:v});log.success(`Packaged ${config.name} (${target}) → ${out}`)}});buddy.command("extension:publish","Publish to every store this project is set up for - the release-tag entry point").option("--version <version>","Override the extension version (defaults to package.json)").option("--targets <targets>","Comma-separated subset of chrome,firefox,safari").option("--dry-run","Report the publish plan without uploading anything").action(async(options)=>{const{formatPublishPlan,planExtensionPublish,publishChromeExtension,publishFirefoxExtension,publishSafariApp}=await import("@stacksjs/browser-extension");const{config,version}=await load();const requested=options.targets?.split(",").map((value)=>value.trim()).filter(Boolean);const plan=planExtensionPublish(config,process.env,requested?.length?requested:undefined);log.info(`Extension publish plan for v${options.version??version}:
|
|
2
|
+
${formatPublishPlan(plan)}`);const publishing=plan.filter((decision)=>decision.publish);if(options.dryRun||!publishing.length){if(!publishing.length)log.warn("No store is both configured and credentialed, so nothing was published.");return}const failures=[];for(const{target}of publishing){try{if(target==="chrome"){const result=await publishChromeExtension(config,{version:options.version??version,blockOnWarnings:true});if(result.deferred)log.warn(`${result.deferred.reason}. Version ${options.version??version} remains queued for the next automated retry.`);else if(result.alreadyPublished)log.success(result.alreadyPublished.reason);else log.success(`Submitted Chrome Web Store item ${result.publish?.itemId??""}: ${result.publish?.state??"uploaded"}`)}else if(target==="firefox"){const result=await publishFirefoxExtension(config,{version:options.version??version});log.success(`Submitted Firefox extension (${result.channel}) → ${result.artifactsDir}`);await syncFirefoxListing(config,{})}else{await refreshAppStoreScreenshots();await publishSafariApp(config,{version:options.version??version});log.success("Uploaded Safari app to App Store Connect")}}catch(error){failures.push(`${target}: ${error.message}`);log.error(`[extension:publish] ${target} failed: ${error.message}`)}}if(failures.length){await log.error(`Failed to publish ${failures.length} of ${publishing.length} store(s):
|
|
3
3
|
${failures.join(`
|
|
4
|
-
`)}`);process.exit(1)}});buddy.command("extension:chrome:status","Fetch the Chrome Web Store item status").option("--service-account-path <path>","Google service-account JSON key path").option("--access-token <token>","Short-lived Chrome Web Store OAuth access token").action(async(options)=>{const{ChromeWebStoreClient}=await import("@stacksjs/browser-extension"),{config}=await load();if(!config.chromeWebStore)throw Error("Chrome status needs chromeWebStore.publisherId and chromeWebStore.itemId in config/extension.ts");const status=await new ChromeWebStoreClient(options).fetchStatus(config.chromeWebStore);log.info(`Chrome Web Store item ${status.itemId}`);log.info(`published: ${status.publishedItemRevisionStatus?.state??"none"}`);log.info(`submitted: ${status.submittedItemRevisionStatus?.state??"none"}`);if(status.warned)log.warn("Chrome has warned this item for a policy violation.");if(status.takenDown)log.error("Chrome has taken this item down for a policy violation.")});buddy.command("extension:chrome:publish","Build, upload, and submit the Chrome extension through Web Store API v2").option("--version <version>","Override the extension version (defaults to package.json)").option("--service-account-path <path>","Google service-account JSON key path").option("--access-token <token>","Short-lived Chrome Web Store OAuth access token").option("--upload-only","Upload without submitting the item for review").option("--allow-warnings","Submit even when Chrome reports validation warnings").action(async(options)=>{const{publishChromeExtension}=await import("@stacksjs/browser-extension"),{config,version}=await load(),result=await publishChromeExtension(config,{version:options.version??version,serviceAccountPath:options.serviceAccountPath,accessToken:options.accessToken,uploadOnly:Boolean(options.uploadOnly),blockOnWarnings:!options.allowWarnings});if(result.deferred){log.warn(`${result.deferred.reason}. Version ${options.version??version} remains queued for the next automated retry.`);return}if(result.alreadyPublished){log.success(result.alreadyPublished.reason);return}log.success(`Uploaded Chrome package ${result.packagePath} (${result.upload?.crxVersion??"processing complete"})`);if(result.publish)log.success(`Submitted Chrome Web Store item ${result.publish.itemId}: ${result.publish.state}`)});buddy.command("extension:firefox:previews","Sync the Firefox listing screenshots declared in config/extension.ts").option("--api-key <issuer>","AMO JWT issuer").option("--api-secret <secret>","AMO JWT secret").option("--dry-run","Report what would change without touching the listing").action(async(options)=>{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension"),{config}=await load(),result=await syncFirefoxPreviews(config,{issuer:options.apiKey,secret:options.apiSecret,dryRun:options.dryRun});if(result.unchanged)log.info("Firefox listing screenshots already match config/extension.ts");else if(options.dryRun)log.info(`Would replace ${result.removed.length} Firefox listing screenshot(s)`);else log.success(`Synced ${result.uploaded.length} Firefox listing screenshot(s), removed ${result.removed.length}`)});buddy.command("extension:firefox:publish","Build and submit the Firefox extension through Mozilla Add-ons").option("--version <version>","Override the extension version (defaults to package.json)").option("--api-key <issuer>","AMO JWT issuer").option("--api-secret <secret>","AMO JWT secret").option("--source-code <path>","Human-readable source archive for AMO review").option("--approval-timeout <milliseconds>","How long to wait for human approval (default 0)").action(async(options)=>{const{publishFirefoxExtension}=await import("@stacksjs/browser-extension"),{config,version}=await load(),result=await publishFirefoxExtension(config,{version:options.version??version,issuer:options.apiKey,secret:options.apiSecret,sourceCodePath:options.sourceCode,approvalTimeout:options.approvalTimeout===void 0?void 0:Number(options.approvalTimeout)});log.success(`Submitted Firefox extension (${result.channel}) \u2192 ${result.artifactsDir}`);if(config.firefoxAddons?.screenshots?.length)try{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension"),previews=await syncFirefoxPreviews(config,{issuer:options.apiKey,secret:options.apiSecret});if(previews.unchanged)log.info("Firefox listing screenshots already match");else log.success(`Synced ${previews.uploaded.length} Firefox listing screenshot(s), removed ${previews.removed.length}`)}catch(error){log.warn(`[extension:firefox:publish] listing screenshots left as they were: ${error.message}`)}if(result.artifacts.length)log.info(`new artifacts: ${result.artifacts.join(", ")}`)});buddy.command("extension:safari:provision","Register Safari Bundle IDs and check the App Store Connect app record").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--check","Report missing resources without creating Bundle IDs").option("--version <version>","Create or align App Store versions (defaults to package.json)").option("--platform <platform>","Provision macos, ios, or all (defaults to config safariPlatforms)").action(async(options)=>{const{provisionSafariApp}=await import("@stacksjs/browser-extension"),{config,version}=await load(),result=await provisionSafariApp(config,{keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,checkOnly:Boolean(options.check),version:options.version??version,platforms:parseSafariPlatforms(options.platform)});for(const resource of[result.container,result.extension])if(resource.created)log.success(`Registered Bundle ID ${resource.identifier}`);else if(resource.exists)log.success(`Bundle ID exists: ${resource.identifier}`);else log.warn(`Bundle ID is missing: ${resource.identifier}`);if(result.appRecord.exists)log.success(`App Store Connect app record exists (${result.appRecord.id})`);else log.warn("App Store Connect app record is missing. Apple requires creating it in the App Store Connect website.");for(const appStoreVersion of result.appStoreVersions){const action=appStoreVersion.created?"Created":appStoreVersion.updated?"Updated":"Ready";log.success(`${action} Safari ${appStoreVersion.platform} App Store version ${appStoreVersion.version}`)}});buddy.command("extension:safari:init","Scaffold the Safari container app (Xcode project) from the template").option("--bundle-id <id>","Base bundle identifier (defaults to config safariBundleId)").option("--dir <dir>","Output directory for the Xcode project (default safari)").option("--force","Overwrite existing scaffold files").option("--team-id <id>","Apple Developer team used for signing").action(async(options)=>{const{scaffoldSafariApp}=await import("@stacksjs/browser-extension"),{config}=await load(),{dir,written,skipped}=await scaffoldSafariApp(config,{bundleId:options.bundleId,dir:options.dir,force:Boolean(options.force),teamId:options.teamId});log.success(`Scaffolded the Safari container app \u2192 ${dir} (${written.length} files)`);if(skipped.length)log.info(`kept ${skipped.length} existing files (use --force to overwrite)`)});buddy.command("extension:safari:app","Build the extension and its macOS, iPhone, and iPad Safari container apps").option("--release","Build the Release configuration (default Debug)").option("--signed","Sign locally against the Apple ID in Xcode (local builds only - see below)").option("--skip-xcodebuild","Only build + sync the extension payload").option("--version <version>","Override the extension version (defaults to package.json)").option("--platform <platform>","Build macos, ios, or all (defaults to config safariPlatforms)").action(async(options)=>{const{buildSafariApp,buildSafariUniversalApp}=await import("@stacksjs/browser-extension"),{config,version}=await load(),platforms=parseSafariPlatforms(options.platform)??config.safariPlatforms??["macos"];if(platforms.includes("ios")){const result=await buildSafariUniversalApp(config,{version:options.version??version,release:Boolean(options.release),signed:Boolean(options.signed),skipXcodebuild:Boolean(options.skipXcodebuild),platforms});for(const platform of platforms){const appPath=result.appPaths[platform];if(appPath)log.success(`Built Safari ${platform} app ${appPath}`)}if(options.skipXcodebuild)log.success(`Generated universal Safari project \u2192 ${result.project}`);if(result.appPaths.macos)log.info("Open the macOS app once, then enable the extension in Safari > Settings > Extensions.");if(result.appPaths.ios)log.info("Install the iOS app on an iPhone, iPad, or Simulator, then enable it in Settings > Apps > Safari > Extensions.");return}const{appPath,resources}=await buildSafariApp(config,{version:options.version??version,release:Boolean(options.release),signed:Boolean(options.signed),skipXcodebuild:Boolean(options.skipXcodebuild)});if(appPath){log.success(`Built ${appPath}`);log.info("Open the app once, then enable the extension in Safari > Settings > Extensions.")}else log.success(`Extension payload synced \u2192 ${resources}`)});buddy.command("extension:safari:publish","Archive and validate or upload the Safari app to App Store Connect").option("--version <version>","Override the marketing version (defaults to package.json)").option("--build-number <number>","CFBundleVersion (defaults to GITHUB_RUN_NUMBER or Unix time)").option("--team-id <id>","Apple Developer team (defaults to config safariTeamId)").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--validate-only","Create and validate the archive without uploading it").option("--platform <platform>","Publish macos, ios, or all (defaults to config safariPlatforms)").option("--skip-screenshots","Do not regenerate the App Store screenshot set before publishing").action(async(options)=>{const{publishSafariApp}=await import("@stacksjs/browser-extension"),{config,version}=await load();if(!options.skipScreenshots)try{const{generateProjectImages}=await import("@stacksjs/actions");await generateProjectImages({only:["app-store"]})}catch(error){log.warn(`[extension:safari:publish] using the committed screenshots - could not regenerate: ${error.message}`)}const result=await publishSafariApp(config,{version:options.version??version,buildNumber:options.buildNumber,teamId:options.teamId,keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,validateOnly:Boolean(options.validateOnly),platforms:parseSafariPlatforms(options.platform)});for(const deferred of result.deferred)log.warn(`${deferred.reason}. Version ${deferred.version} remains queued for the next automated retry.`);for(const published of result.alreadyPublished)log.success(`Safari ${published.platform} version ${published.version} is already published${published.state?` (${published.state})`:""}`);if(result.artifacts.length)log.success(options.validateOnly?`Validated Safari ${result.artifacts.map((artifact)=>artifact.platform).join(" + ")} archives (build ${result.buildNumber})`:`Uploaded and selected Safari ${result.attachments.map((attachment)=>attachment.platform).join(" + ")} build ${result.buildNumber} in App Store Connect`);if(result.appStoreSubmission?.reviewSubmissionIds.length)log.success(`Submitted ${result.appStoreSubmission.reviewSubmissionIds.length} Safari version(s) to App Review`)});buddy.command("extension:safari:submit","Synchronize metadata and submit an existing Safari version to App Review").option("--version <version>","Marketing version to submit (defaults to package.json)").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--platform <platform>","Submit macos, ios, or all (defaults to config safariPlatforms)").option("--prepare-only","Synchronize the listing without submitting it for review").action(async(options)=>{const{submitSafariAppStore}=await import("@stacksjs/browser-extension"),{config,version}=await load(),result=await submitSafariAppStore(config,{version:options.version??version,keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,platforms:parseSafariPlatforms(options.platform),submit:!options.prepareOnly});log.success(`Synchronized ${result.versions.map((item)=>item.platform).join(" + ")} App Store listings`);if(result.reviewSubmissionIds.length)log.success(`Submitted ${result.reviewSubmissionIds.length} Safari version(s) to App Review`)})}
|
|
4
|
+
`)}`);process.exit(1)}});buddy.command("extension:chrome:status","Fetch the Chrome Web Store item status").option("--service-account-path <path>","Google service-account JSON key path").option("--access-token <token>","Short-lived Chrome Web Store OAuth access token").action(async(options)=>{const{ChromeWebStoreClient}=await import("@stacksjs/browser-extension");const{config}=await load();if(!config.chromeWebStore)throw new Error("Chrome status needs chromeWebStore.publisherId and chromeWebStore.itemId in config/extension.ts");const status=await new ChromeWebStoreClient(options).fetchStatus(config.chromeWebStore);log.info(`Chrome Web Store item ${status.itemId}`);log.info(`published: ${status.publishedItemRevisionStatus?.state??"none"}`);log.info(`submitted: ${status.submittedItemRevisionStatus?.state??"none"}`);if(status.warned)log.warn("Chrome has warned this item for a policy violation.");if(status.takenDown)log.error("Chrome has taken this item down for a policy violation.")});buddy.command("extension:chrome:publish","Build, upload, and submit the Chrome extension through Web Store API v2").option("--version <version>","Override the extension version (defaults to package.json)").option("--service-account-path <path>","Google service-account JSON key path").option("--access-token <token>","Short-lived Chrome Web Store OAuth access token").option("--upload-only","Upload without submitting the item for review").option("--allow-warnings","Submit even when Chrome reports validation warnings").action(async(options)=>{const{publishChromeExtension}=await import("@stacksjs/browser-extension");const{config,version}=await load();const result=await publishChromeExtension(config,{version:options.version??version,serviceAccountPath:options.serviceAccountPath,accessToken:options.accessToken,uploadOnly:Boolean(options.uploadOnly),blockOnWarnings:!options.allowWarnings});if(result.deferred){log.warn(`${result.deferred.reason}. Version ${options.version??version} remains queued for the next automated retry.`);return}if(result.alreadyPublished){log.success(result.alreadyPublished.reason);return}log.success(`Uploaded Chrome package ${result.packagePath} (${result.upload?.crxVersion??"processing complete"})`);if(result.publish)log.success(`Submitted Chrome Web Store item ${result.publish.itemId}: ${result.publish.state}`)});buddy.command("extension:firefox:previews","Sync the Firefox listing screenshots declared in config/extension.ts").option("--api-key <issuer>","AMO JWT issuer").option("--api-secret <secret>","AMO JWT secret").option("--dry-run","Report what would change without touching the listing").action(async(options)=>{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension");const{config}=await load();const result=await syncFirefoxPreviews(config,{issuer:options.apiKey,secret:options.apiSecret,dryRun:options.dryRun});if(result.unchanged)log.info("Firefox listing screenshots already match config/extension.ts");else if(options.dryRun)log.info(`Would replace ${result.removed.length} Firefox listing screenshot(s)`);else log.success(`Synced ${result.uploaded.length} Firefox listing screenshot(s), removed ${result.removed.length}`)});buddy.command("extension:firefox:publish","Build and submit the Firefox extension through Mozilla Add-ons").option("--version <version>","Override the extension version (defaults to package.json)").option("--api-key <issuer>","AMO JWT issuer").option("--api-secret <secret>","AMO JWT secret").option("--source-code <path>","Human-readable source archive for AMO review").option("--approval-timeout <milliseconds>","How long to wait for human approval (default 0)").action(async(options)=>{const{publishFirefoxExtension}=await import("@stacksjs/browser-extension");const{config,version}=await load();const result=await publishFirefoxExtension(config,{version:options.version??version,issuer:options.apiKey,secret:options.apiSecret,sourceCodePath:options.sourceCode,approvalTimeout:options.approvalTimeout===undefined?undefined:Number(options.approvalTimeout)});log.success(`Submitted Firefox extension (${result.channel}) → ${result.artifactsDir}`);if(config.firefoxAddons?.screenshots?.length){try{const{syncFirefoxPreviews}=await import("@stacksjs/browser-extension");const previews=await syncFirefoxPreviews(config,{issuer:options.apiKey,secret:options.apiSecret});if(previews.unchanged)log.info("Firefox listing screenshots already match");else log.success(`Synced ${previews.uploaded.length} Firefox listing screenshot(s), removed ${previews.removed.length}`)}catch(error){log.warn(`[extension:firefox:publish] listing screenshots left as they were: ${error.message}`)}}if(result.artifacts.length)log.info(`new artifacts: ${result.artifacts.join(", ")}`)});buddy.command("extension:safari:provision","Register Safari Bundle IDs and check the App Store Connect app record").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--check","Report missing resources without creating Bundle IDs").option("--version <version>","Create or align App Store versions (defaults to package.json)").option("--platform <platform>","Provision macos, ios, or all (defaults to config safariPlatforms)").action(async(options)=>{const{provisionSafariApp}=await import("@stacksjs/browser-extension");const{config,version}=await load();const result=await provisionSafariApp(config,{keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,checkOnly:Boolean(options.check),version:options.version??version,platforms:parseSafariPlatforms(options.platform)});for(const resource of[result.container,result.extension]){if(resource.created)log.success(`Registered Bundle ID ${resource.identifier}`);else if(resource.exists)log.success(`Bundle ID exists: ${resource.identifier}`);else log.warn(`Bundle ID is missing: ${resource.identifier}`)}if(result.appRecord.exists)log.success(`App Store Connect app record exists (${result.appRecord.id})`);else log.warn("App Store Connect app record is missing. Apple requires creating it in the App Store Connect website.");for(const appStoreVersion of result.appStoreVersions){const action=appStoreVersion.created?"Created":appStoreVersion.updated?"Updated":"Ready";log.success(`${action} Safari ${appStoreVersion.platform} App Store version ${appStoreVersion.version}`)}});buddy.command("extension:safari:init","Scaffold the Safari container app (Xcode project) from the template").option("--bundle-id <id>","Base bundle identifier (defaults to config safariBundleId)").option("--dir <dir>","Output directory for the Xcode project (default safari)").option("--force","Overwrite existing scaffold files").option("--team-id <id>","Apple Developer team used for signing").action(async(options)=>{const{scaffoldSafariApp}=await import("@stacksjs/browser-extension");const{config}=await load();const{dir,written,skipped}=await scaffoldSafariApp(config,{bundleId:options.bundleId,dir:options.dir,force:Boolean(options.force),teamId:options.teamId});log.success(`Scaffolded the Safari container app → ${dir} (${written.length} files)`);if(skipped.length)log.info(`kept ${skipped.length} existing files (use --force to overwrite)`)});buddy.command("extension:safari:app","Build the extension and its macOS, iPhone, and iPad Safari container apps").option("--release","Build the Release configuration (default Debug)").option("--signed","Sign locally against the Apple ID in Xcode (local builds only - see below)").option("--skip-xcodebuild","Only build + sync the extension payload").option("--version <version>","Override the extension version (defaults to package.json)").option("--platform <platform>","Build macos, ios, or all (defaults to config safariPlatforms)").action(async(options)=>{const{buildSafariApp,buildSafariUniversalApp}=await import("@stacksjs/browser-extension");const{config,version}=await load();const platforms=parseSafariPlatforms(options.platform)??config.safariPlatforms??["macos"];if(platforms.includes("ios")){const result=await buildSafariUniversalApp(config,{version:options.version??version,release:Boolean(options.release),signed:Boolean(options.signed),skipXcodebuild:Boolean(options.skipXcodebuild),platforms});for(const platform of platforms){const appPath=result.appPaths[platform];if(appPath)log.success(`Built Safari ${platform} app ${appPath}`)}if(options.skipXcodebuild)log.success(`Generated universal Safari project → ${result.project}`);if(result.appPaths.macos)log.info("Open the macOS app once, then enable the extension in Safari > Settings > Extensions.");if(result.appPaths.ios)log.info("Install the iOS app on an iPhone, iPad, or Simulator, then enable it in Settings > Apps > Safari > Extensions.");return}const{appPath,resources}=await buildSafariApp(config,{version:options.version??version,release:Boolean(options.release),signed:Boolean(options.signed),skipXcodebuild:Boolean(options.skipXcodebuild)});if(appPath){log.success(`Built ${appPath}`);log.info("Open the app once, then enable the extension in Safari > Settings > Extensions.")}else{log.success(`Extension payload synced → ${resources}`)}});buddy.command("extension:safari:publish","Archive and validate or upload the Safari app to App Store Connect").option("--version <version>","Override the marketing version (defaults to package.json)").option("--build-number <number>","CFBundleVersion (defaults to GITHUB_RUN_NUMBER or Unix time)").option("--team-id <id>","Apple Developer team (defaults to config safariTeamId)").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--validate-only","Create and validate the archive without uploading it").option("--platform <platform>","Publish macos, ios, or all (defaults to config safariPlatforms)").option("--skip-screenshots","Do not regenerate the App Store screenshot set before publishing").action(async(options)=>{const{publishSafariApp}=await import("@stacksjs/browser-extension");const{config,version}=await load();if(!options.skipScreenshots){try{const{generateProjectImages}=await import("@stacksjs/actions");await generateProjectImages({only:["app-store"]})}catch(error){log.warn(`[extension:safari:publish] using the committed screenshots - could not regenerate: ${error.message}`)}}const result=await publishSafariApp(config,{version:options.version??version,buildNumber:options.buildNumber,teamId:options.teamId,keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,validateOnly:Boolean(options.validateOnly),platforms:parseSafariPlatforms(options.platform)});for(const deferred of result.deferred)log.warn(`${deferred.reason}. Version ${deferred.version} remains queued for the next automated retry.`);for(const published of result.alreadyPublished)log.success(`Safari ${published.platform} version ${published.version} is already published${published.state?` (${published.state})`:""}`);if(result.artifacts.length){log.success(options.validateOnly?`Validated Safari ${result.artifacts.map((artifact)=>artifact.platform).join(" + ")} archives (build ${result.buildNumber})`:`Uploaded and selected Safari ${result.attachments.map((attachment)=>attachment.platform).join(" + ")} build ${result.buildNumber} in App Store Connect`)}if(result.appStoreSubmission?.reviewSubmissionIds.length)log.success(`Submitted ${result.appStoreSubmission.reviewSubmissionIds.length} Safari version(s) to App Review`)});buddy.command("extension:safari:submit","Synchronize metadata and submit an existing Safari version to App Review").option("--version <version>","Marketing version to submit (defaults to package.json)").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","Path to the App Store Connect AuthKey_*.p8 file").option("--platform <platform>","Submit macos, ios, or all (defaults to config safariPlatforms)").option("--prepare-only","Synchronize the listing without submitting it for review").action(async(options)=>{const{submitSafariAppStore}=await import("@stacksjs/browser-extension");const{config,version}=await load();const result=await submitSafariAppStore(config,{version:options.version??version,keyId:options.apiKeyId,issuerId:options.apiIssuerId,keyPath:options.apiKeyPath,platforms:parseSafariPlatforms(options.platform),submit:!options.prepareOnly});log.success(`Synchronized ${result.versions.map((item)=>item.platform).join(" + ")} App Store listings`);if(result.reviewSubmissionIds.length)log.success(`Submitted ${result.reviewSubmissionIds.length} Safari version(s) to App Review`)})}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes
|
|
1
|
+
import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes:true})){const rel=prefix?`${prefix}/${entry.name}`:entry.name;if(entry.isDirectory())out.push(...filesUnder(join(dir,entry.name),rel));else out.push(rel)}return out}function matchesTemplate(projectFile,templateFile){if(!existsSync(templateFile))return false;try{return readFileSync(projectFile).equals(readFileSync(templateFile))}catch{return false}}function pruneEmptyDirs(root,dir){let current=dir;while(current.startsWith(root)&¤t!==root){try{if(readdirSync(current).length>0)return;rmdirSync(current)}catch{return}current=join(current,"..")}}export async function deleteFeatureFiles(feature,root=projectPath(),options={}){const source=options.source??frameworkPath("defaults");const force=options.force===true;const dryRun=options.dryRun===true;const remove=async(path,recursive=false)=>{if(!dryRun)await rm(path,{recursive,force:true})};const removed=[];const preserved=[];for(const rel of FEATURE_FILES[feature]){const full=join(root,rel);if(!existsSync(full))continue;if(force){await remove(full,true);removed.push(rel);continue}const template=join(source,rel);if(!statSync(full).isDirectory()){if(matchesTemplate(full,template)){await remove(full);removed.push(rel)}else{preserved.push(rel)}continue}let keptAny=false;for(const child of filesUnder(full)){const projectFile=join(full,child);if(matchesTemplate(projectFile,join(template,child))){await remove(projectFile);removed.push(`${rel}${child}`)}else{keptAny=true;preserved.push(`${rel}${child}`)}}if(dryRun)continue;pruneEmptyDirs(root,full);if(!keptAny&&existsSync(full))await rm(full,{recursive:true,force:true})}return{removed,preserved}}export async function copyFeatureFiles(feature,options={}){const source=options.source??frameworkPath("defaults");const target=options.target??projectPath();const force=options.force===true;const copied=[];const skipped=[];for(const rel of FEATURE_FILES[feature]){const sourceFull=join(source,rel);if(!existsSync(sourceFull)){skipped.push(rel);continue}const targetFull=join(target,rel);if(existsSync(targetFull)&&!force){skipped.push(rel);continue}if(options.dryRun!==true)await cp(sourceFull,targetFull,{recursive:true,force});copied.push(rel)}return{copied,skipped}}const FEATURE_DESCRIPTIONS={dashboard:"Admin SPA shell + Activity/Log/Request/Deployment/Notification dashboards.",commerce:"Order/Cart/Product/Customer/Coupon/GiftCard/Shipping + storefront API.",cms:"Post/Page/Author/Comment/Tag models + content edit dashboards.",forms:"User-defined forms: builder models, conditional fields, public submit + CSV export.",marketing:"/api/email/subscribe, /api/contact, Campaign/EmailList/SocialPost.",monitoring:"Error model + error-tracking views and actions.",realtime:"WebSocket broadcaster + Websocket model + realtime-stats actions.",queue:"Job + FailedJob models + queue dashboard pages."};export const CONFIG_GATES={auth:"Loads the account models (Team, Referral, SocialAccount, Subscriber, Subscription, Site, ...). Auth routes are STACKS_DEFAULT_ROUTES, not this.",email:"Mounts the email provider webhook routes, when STACKS_DEFAULT_ROUTES does not name the bundles."};const STARTER_TEMPLATES={dashboard:`import type { DashboardConfig } from '@stacksjs/types'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* **Dashboard Configuration**
|
|
@@ -126,5 +126,5 @@ export default {
|
|
|
126
126
|
table: 'failed_jobs',
|
|
127
127
|
},
|
|
128
128
|
} satisfies QueueConfig
|
|
129
|
-
`};function withoutComments(src){return src.replace(/\/\*[\s\S]*?\*\//g,(m)=>" ".repeat(m.length)).replace(/\/\/[^\n]*/g,(m)=>" ".repeat(m.length))}function findTopLevelEnabled(src){const scan=withoutComments(src)
|
|
130
|
-
enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath()
|
|
129
|
+
`};function withoutComments(src){return src.replace(/\/\*[\s\S]*?\*\//g,(m)=>" ".repeat(m.length)).replace(/\/\/[^\n]*/g,(m)=>" ".repeat(m.length))}function findTopLevelEnabled(src){const scan=withoutComments(src);const start=scan.search(/export default\s*\{/);if(start===-1)return null;const open=scan.indexOf("{",start);let depth=0;for(let i=open;i<scan.length;i++){const char=scan[i];if(char==="{"){depth++;continue}if(char==="}"){depth--;if(depth===0)return null;continue}if(depth!==1||char!=="e")continue;const match=/^enabled\s*:\s*(true|false)/.exec(scan.slice(i));if(!match)continue;if(i>0&&/[\w$]/.test(scan[i-1]))continue;return{index:i,length:match[0].length,value:match[1]==="true"}}return null}export function readFeatureFlag(feature,root=projectPath()){const path=join(root,`config/${feature}.ts`);if(!existsSync(path))return"absent";const found=findTopLevelEnabled(readFileSync(path,"utf8"));if(!found)return"unset";return found.value}export function featureMigrationCounts(feature,root=projectPath()){const counts={active:0,hidden:0};const base=join(root,"database/migrations");if(!existsSync(base))return counts;const dirs=[base];for(const entry of readdirSync(base,{withFileTypes:true})){if(entry.isDirectory())dirs.push(join(base,entry.name))}for(const dir of dirs){for(const file of readdirSync(dir)){const hidden=file.endsWith(".sql.disabled");if(!hidden&&!file.endsWith(".sql"))continue;const sqlName=hidden?file.slice(0,-".disabled".length):file;if(migrationFeature(sqlName)!==feature)continue;if(hidden)counts.hidden++;else counts.active++}}return counts}export async function setFeatureEnabled(feature,enabled,options){const write=async(target,contents)=>{if(options.dryRun!==true)await Bun.write(target,contents)};const path=options.root?join(options.root,`config/${feature}.ts`):projectPath(`config/${feature}.ts`);const file=Bun.file(path);if(!await file.exists()){if(!options.createIfMissing)return"missing";await write(path,STARTER_TEMPLATES[feature]);return"created"}const src=await file.text();const found=findTopLevelEnabled(src);if(found){if(found.value===enabled)return"unchanged";const replaced=src.slice(0,found.index)+`enabled: ${enabled}`+src.slice(found.index+found.length);await write(path,replaced);return"flipped"}const insertRegex=/(export default\s*\{)/;if(!insertRegex.test(src)){throw new Error(`Could not locate \`export default {\` in ${path} - please add \`enabled: ${enabled}\` manually.`)}const next=src.replace(insertRegex,`$1
|
|
130
|
+
enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath();const results=[];for(const feature of FEATURE_NAMES){const configOutcome=await setFeatureEnabled(feature,false,{createIfMissing:false,root});const{removed:filesRemoved}=await deleteFeatureFiles(feature,root,{force:true});results.push({feature,configOutcome,filesRemoved})}return results}function isDryRun(options){return options.dryRun===true||process.argv.includes("--dry-run")}async function offerMigrate(feature){const{active,hidden}=featureMigrationCounts(feature);const total=active+hidden;if(total===0)return;const plural=total===1?"migration":"migrations";console.log(` → ${feature} owns ${total} ${plural}; its tables do not exist until they run.`);const answer=await confirmOrNull({message:`Run ./buddy migrate now?`,initial:false});if(answer!==true){console.log(answer===null?` → Not asking (non-interactive). Run ./buddy migrate when ready.`:` → Skipped. Run ./buddy migrate when ready.`);return}const result=await runCommand("./buddy migrate",{cwd:projectPath()});if(resultFailed(result)){console.error(`✗ ./buddy migrate failed: ${resultError(result)}`);console.error(` → ${feature} is installed; re-run ./buddy migrate once that is resolved.`);return}console.log(`✓ Migrated.`)}function registerInstallPair(buddy,feature){const desc=FEATURE_DESCRIPTIONS[feature];const configRel=`config/${feature}.ts`;buddy.command(`${feature}:install`,`Activate the ${feature} feature bundle. ${desc}`).option("--publish-all",`Also copy every ${feature} file into the project so you can edit it in place. Not needed to run the feature - see \`publish:action\`/\`publish:model\` to take ownership of one file at a time.`).option("--force",`With --publish-all, overwrite existing ${feature} files (default skips existing paths so the copy is idempotent).`).option("--dry-run",`Say what ${feature}:install would change, and change nothing.`,{default:false}).action(async(options)=>{try{const dryRun=isDryRun(options);const mark=dryRun?"·":"✓";const outcome=await setFeatureEnabled(feature,true,{createIfMissing:true,dryRun});switch(outcome){case"created":console.log(dryRun?`${mark} Would create ${configRel} with '${feature}' enabled.`:`${mark} Created ${configRel} with '${feature}' enabled.`);break;case"flipped":console.log(dryRun?`${mark} Would enable '${feature}' in ${configRel}.`:`${mark} Enabled '${feature}' in ${configRel}.`);break;case"unchanged":console.log(`${mark} '${feature}' is already enabled in ${configRel}.`);break}if(options.publishAll===true){const{copied}=await copyFeatureFiles(feature,{force:options.force===true,dryRun});if(copied.length>0){console.log(dryRun?`${mark} Would copy ${copied.length} stamped path(s) from framework defaults:`:`${mark} Copied ${copied.length} stamped path(s) from framework defaults:`);for(const path of copied)console.log(` - ${path}`);console.log(` → These now shadow storage/framework/defaults/; \`buddy upgrade\` will not update them.`)}else if(featurePathsPresent(feature).length>0){console.log(` → ${feature} files already in the project - use --force to overwrite.`)}}else{const present=featurePathsPresent(feature).length;if(present>0)console.log(` → ${present} ${feature} path(s) already in the project; those shadow the framework defaults.`);else console.log(` → Runs from the framework defaults. \`publish:action\`/\`publish:model\` copies one file into app/ when you want to change it.`)}if(dryRun){console.log(` → Dry run: nothing was written. Run it without --dry-run to install ${feature}.`);process.exit(ExitCode.Success)}await offerMigrate(feature);console.log(` → next ./buddy dev will boot with ${feature} loaded.`);process.exit(ExitCode.Success)}catch(err){console.error(`✗ Failed to install ${feature}:`,err);process.exit(ExitCode.FatalError)}});buddy.command(`${feature}:uninstall`,`Deactivate the ${feature} feature bundle.`).option("--keep-files",`Don't delete the ${feature} scaffolding (action/model/view files). Flip the flag only.`).option("--force",`Delete the ${feature} scaffolding even where you have edited it. Without this, changed files are kept.`).option("--dry-run",`Say what ${feature}:uninstall would change, and change nothing.`,{default:false}).action(async(options)=>{try{const dryRun=isDryRun(options);const mark=dryRun?"·":"✓";const outcome=await setFeatureEnabled(feature,false,{createIfMissing:false,dryRun});switch(outcome){case"missing":console.log(`${mark} '${feature}' is already disabled (${configRel} is absent).`);break;case"flipped":console.log(dryRun?`${mark} Would disable '${feature}' in ${configRel}.`:`${mark} Disabled '${feature}' in ${configRel}. Custom config preserved.`);break;case"unchanged":console.log(`${mark} '${feature}' is already disabled in ${configRel}.`);break;case"created":console.log(`✗ Unexpected create on uninstall for ${feature}; please re-run with --force or report this bug.`);break}if(options.keepFiles){const stillPresent=featurePathsPresent(feature);if(stillPresent.length>0)console.log(` → ${stillPresent.length} stamped path(s) preserved (--keep-files).`)}else{const{removed,preserved}=await deleteFeatureFiles(feature,projectPath(),{force:options.force,dryRun});if(removed.length>0){console.log(dryRun?`${mark} Would remove ${removed.length} stamped path(s):`:`${mark} Removed ${removed.length} stamped path(s):`);for(const path of removed)console.log(` - ${path}`)}if(preserved.length>0){console.log(dryRun?` → Would keep ${preserved.length} path(s) you have edited (--force would remove them):`:` → Kept ${preserved.length} path(s) you have edited (re-run with --force to remove):`);for(const path of preserved)console.log(` - ${path}`)}}console.log(dryRun?` → Dry run: nothing was written or removed. Run it without --dry-run to uninstall ${feature}.`:` → next ./buddy dev will boot without ${feature}.`);process.exit(ExitCode.Success)}catch(err){console.error(`✗ Failed to uninstall ${feature}:`,err);process.exit(ExitCode.FatalError)}})}function registerStatus(buddy){buddy.command("features","Show which framework feature bundles are active.").action(async()=>{try{const{feature,overridesReady}=await import("@stacksjs/config");await overridesReady;const rows=FEATURE_NAMES.map((name)=>{const declared=readFeatureFlag(name);const active=feature(name);const migrations=featureMigrationCounts(name);return{name,declared,active,migrations,scaffolded:featurePathsPresent(name).length}});const enabled=rows.filter((r)=>r.active).length;console.log("");console.log(`Feature bundles (${enabled} of ${rows.length} active)`);console.log("");for(const row of rows){const mark=row.active?"✓":"·";const declared=row.declared==="absent"?"no config":row.declared==="unset"?"flag unset":`enabled: ${row.declared}`;const parts=[`${mark} ${row.name.padEnd(11)}`,declared.padEnd(14)];const total=row.migrations.active+row.migrations.hidden;const plural=total===1?"migration":"migrations";if(total>0){parts.push(row.migrations.hidden>0?`${total} ${plural} (${row.migrations.hidden} hidden)`:`${total} ${plural}`)}else{parts.push("")}console.log(` ${parts.join(" ")}`);if(row.declared===true&&!row.active)console.log(` declared on but reading off - check \`env\` in config/${row.name}.ts against config.app.env`);if(row.declared===false&&row.active)console.log(` declared off but reading on - a runtime override is in play`);if(!row.active&&row.scaffolded>0)console.log(` ${row.scaffolded} scaffolded path(s) still present - \`./buddy ${row.name}:uninstall\` removes them`);if(row.active&&row.migrations.hidden>0)console.log(` ${row.migrations.hidden} migration(s) still hidden from a previous run - \`./buddy migrate\` restores them`)}console.log("");console.log(" ./buddy <feature>:install activates one, <feature>:uninstall turns it off.");console.log("");console.log("Config gates (switched by `enabled` in their config file)");console.log("");for(const[name,description]of Object.entries(CONFIG_GATES)){const declared=readFeatureFlag(name);const label=declared==="absent"?"no config":declared==="unset"?"flag unset":`enabled: ${declared}`;console.log(` ${feature(name)?"✓":"·"} ${name.padEnd(11)} ${label.padEnd(14)} ${description}`)}console.log("");process.exit(ExitCode.Success)}catch(err){console.error("✗ Failed to read feature status:",err);process.exit(ExitCode.FatalError)}})}export function features(buddy){registerStatus(buddy);for(const feature of FEATURE_NAMES)registerInstallPair(buddy,feature)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{FEEDBACK_BOARD_COLUMNS,FEEDBACK_BOARD_NAME,feedbackSubmitUrl,parseBoardRef,parseExpiryDays,parseRowRef,renderFeedbackTokens,toStoredTimestamp}from"../feedback-links";async function loadFeedbackToken(){const{existsSync}=await import("node:fs")
|
|
1
|
+
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{FEEDBACK_BOARD_COLUMNS,FEEDBACK_BOARD_NAME,feedbackSubmitUrl,parseBoardRef,parseExpiryDays,parseRowRef,renderFeedbackTokens,toStoredTimestamp}from"../feedback-links";async function loadFeedbackToken(){const{existsSync}=await import("node:fs");const{join}=await import("node:path");const relative="Actions/Dashboard/Feedback/feedback-token.ts";const candidates=[join(process.cwd(),"app",relative),join(process.cwd(),"storage/framework/defaults/app",relative),join(process.cwd(),"node_modules/@stacksjs/defaults/app",relative)];for(const candidate of candidates){if(!existsSync(candidate))continue;const loaded=await import(candidate);if(typeof loaded?.mintFeedbackToken==="function")return loaded}await log.error(`Could not find ${relative}. Looked in app/, the framework defaults and @stacksjs/defaults.`);await log.flush();process.exit(ExitCode.FatalError)}async function appUrl(){const{config,overridesReady}=await import("@stacksjs/config");await overridesReady.catch(()=>{});return config?.app?.url}async function database(){const{db}=await import("@stacksjs/database/runtime");return db}async function reportDatabaseError(err){const message=err instanceof Error?err.message:String(err);if(/feedback_tokens/.test(message)&&/no such table|does not exist|doesn't exist/i.test(message)){await log.error("There is no `feedback_tokens` table yet.");log.info("Run `buddy migrate` (the table ships with the dashboard feature).")}else{await log.error(message)}await log.flush();process.exit(ExitCode.FatalError)}async function resolveBoard(db,ref,create){const query=db.selectFrom("boards").select(["id","name"]);const found=ref.kind==="id"?await query.where("id","=",ref.id).executeTakeFirst():await query.where("name","=",ref.name).orderBy("id","asc").executeTakeFirst();if(found)return Number(found.id);if(ref.kind==="id"){await log.error(`There is no board ${ref.id}.`);await log.flush();process.exit(ExitCode.FatalError)}if(!create){await log.error(`There is no board called \`${ref.name}\`.`);log.info("Pass --create-board to make one, or --board <id> to pick an existing board.");await log.flush();process.exit(ExitCode.FatalError)}const position=await db.selectFrom("boards").select(["id"]).execute();await db.insertInto("boards").values({name:ref.name,description:"Feedback from external reviewers.",icon:"bubble.left.and.text.bubble.right.fill",color:"violet",position:position.length,archived:false}).execute();const created=await db.selectFrom("boards").select(["id"]).where("name","=",ref.name).orderBy("id","desc").executeTakeFirst();const boardId=Number(created?.id);if(!Number.isInteger(boardId)||boardId<=0){await log.error(`Created the \`${ref.name}\` board but could not read its id back.`);await log.flush();process.exit(ExitCode.FatalError)}for(const[index,name]of FEEDBACK_BOARD_COLUMNS.entries())await db.insertInto("board_columns").values({board_id:boardId,name,position:index}).execute();log.success(`Created the \`${ref.name}\` board with ${FEEDBACK_BOARD_COLUMNS.length} columns`);return boardId}export function feedback(buddy){buddy.command("feedback:invite <label>","Mint a revocable link an external reviewer files feedback through").option("--board <board>",`Board id or name to file into. Defaults to \`${FEEDBACK_BOARD_NAME}\`.`).option("--expires <days>","Expire the link after this many days. Omitted, it lasts until revoked.").option("--create-board",`Create the board, with columns, if it does not exist`,{default:false}).example("buddy feedback:invite Pawel").example("buddy feedback:invite Pawel --expires 30 --create-board").example('buddy feedback:invite "Design review" --board 3').action(async(label,options)=>{const name=String(label||"").trim();if(!name||name.length>120){await log.error("A label of 1 to 120 characters is required. It is who the link is for, and it is how you revoke the right one.");await log.flush();process.exit(ExitCode.FatalError)}const expiry=parseExpiryDays(options.expires,new Date);if(!expiry.ok){await log.error(expiry.message);await log.flush();process.exit(ExitCode.FatalError)}const url=await appUrl();if(!url?.trim()){await log.error("No app URL configured, so there is no link to hand out. Set APP_URL or config.app.url.");await log.flush();process.exit(ExitCode.FatalError)}const{mintFeedbackToken}=await loadFeedbackToken();const db=await database();try{const boardId=await resolveBoard(db,parseBoardRef(options.board),options.createBoard===true);const{raw,hash}=mintFeedbackToken();await db.insertInto("feedback_tokens").values({token:hash,label:name,board_id:boardId,expires_at:expiry.at?toStoredTimestamp(expiry.at):null}).execute();const row=await db.selectFrom("feedback_tokens").select(["id"]).where("token","=",hash).executeTakeFirst();process.stdout.write(`
|
|
2
2
|
${feedbackSubmitUrl(url,raw)}
|
|
3
3
|
|
|
4
|
-
`);log.info(`Link ${row?.id??"?"} for ${name}, filing into board ${boardId}${expiry.at?`, expires ${toStoredTimestamp(expiry.at)} UTC`:""}.`);log.info("That link is shown once; only its hash is stored. Revoke it with `buddy feedback:revoke`.")}catch(err){await reportDatabaseError(err)}await log.flush();process.exit(ExitCode.Success)});buddy.command("feedback:tokens","List the feedback links and whether they still work").option("--board <board>","Only links filing into this board id or name").example("buddy feedback:tokens").example("buddy feedback:tokens --board Feedback").action(async(options)=>{const{authorizeFeedbackToken}=await loadFeedbackToken()
|
|
5
|
-
`)}catch(err){await reportDatabaseError(err)}await log.flush();process.exit(ExitCode.Success)});buddy.command("feedback:revoke <link>","Stop a feedback link, by id or by the label it was minted with").example("buddy feedback:revoke 3").example("buddy feedback:revoke Pawel").action(async(link)=>{const ref=parseRowRef(link);if(!ref){await log.error("Name the link to revoke, by id or by label. `buddy feedback:tokens` lists them.");await log.flush();process.exit(ExitCode.FatalError)}const db=await database();try{const query=db.selectFrom("feedback_tokens").select(["id","label","revoked_at"])
|
|
4
|
+
`);log.info(`Link ${row?.id??"?"} for ${name}, filing into board ${boardId}${expiry.at?`, expires ${toStoredTimestamp(expiry.at)} UTC`:""}.`);log.info("That link is shown once; only its hash is stored. Revoke it with `buddy feedback:revoke`.")}catch(err){await reportDatabaseError(err)}await log.flush();process.exit(ExitCode.Success)});buddy.command("feedback:tokens","List the feedback links and whether they still work").option("--board <board>","Only links filing into this board id or name").example("buddy feedback:tokens").example("buddy feedback:tokens --board Feedback").action(async(options)=>{const{authorizeFeedbackToken}=await loadFeedbackToken();const db=await database();try{let query=db.selectFrom("feedback_tokens").select(["id","label","board_id","revoked_at","expires_at","last_used_at"]);if(options.board){const ref=parseRowRef(options.board);if(!ref){await log.error(`\`${options.board}\` is not a board id or name.`);await log.flush();process.exit(ExitCode.FatalError)}let ids=[ref.kind==="id"?ref.id:0];if(ref.kind==="name"){const boards=await db.selectFrom("boards").select(["id"]).where("name","=",ref.name).execute();if(boards.length===0){await log.error(`There is no board called \`${ref.name}\`.`);await log.flush();process.exit(ExitCode.FatalError)}ids=boards.map((board)=>Number(board.id))}query=query.where("board_id","in",ids)}const rows=await query.orderBy("id","desc").execute();process.stdout.write(`${renderFeedbackTokens(rows.map((row)=>{const verdict=authorizeFeedbackToken(row);return{id:Number(row.id),label:String(row.label??""),boardId:Number(row.board_id??0),status:verdict.ok?"active":verdict.reason,lastUsedAt:row.last_used_at??null,expiresAt:row.expires_at??null}}))}
|
|
5
|
+
`)}catch(err){await reportDatabaseError(err)}await log.flush();process.exit(ExitCode.Success)});buddy.command("feedback:revoke <link>","Stop a feedback link, by id or by the label it was minted with").example("buddy feedback:revoke 3").example("buddy feedback:revoke Pawel").action(async(link)=>{const ref=parseRowRef(link);if(!ref){await log.error("Name the link to revoke, by id or by label. `buddy feedback:tokens` lists them.");await log.flush();process.exit(ExitCode.FatalError)}const db=await database();try{const query=db.selectFrom("feedback_tokens").select(["id","label","revoked_at"]);const matches=await(ref.kind==="id"?query.where("id","=",ref.id):query.where("label","=",ref.name)).orderBy("id","asc").execute();if(matches.length===0){await log.error(ref.kind==="id"?`There is no feedback link ${ref.id}.`:`No feedback link is labelled \`${ref.name}\`.`);await log.flush();process.exit(ExitCode.FatalError)}const row=matches[0];if(matches.length>1){await log.error(`${matches.length} links are labelled \`${row.label}\`. Revoke one by id: ${matches.map((match)=>match.id).join(", ")}.`);await log.flush();process.exit(ExitCode.FatalError)}if(row.revoked_at){log.info(`Link ${row.id} (${row.label}) was already revoked at ${row.revoked_at} UTC.`);await log.flush();process.exit(ExitCode.Success)}const at=toStoredTimestamp(new Date);await db.updateTable("feedback_tokens").set({revoked_at:at}).where("id","=",Number(row.id)).execute();log.success(`Revoked link ${row.id} (${row.label}). Submissions through it are refused from now on.`)}catch(err){await reportDatabaseError(err)}await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"feedback")}
|
package/dist/commands/fresh.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function fresh(buddy){const descriptions={fresh:"Re-installs your npm dependencies",project:"Target a specific project",force:"Skip the confirmation prompt (required in CI/non-interactive shells)",verbose:"Enable verbose output"};buddy.command("fresh",descriptions.fresh).option("-p, --project [project]",descriptions.project,{default
|
|
1
|
+
import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function fresh(buddy){const descriptions={fresh:"Re-installs your npm dependencies",project:"Target a specific project",force:"Skip the confirmation prompt (required in CI/non-interactive shells)",verbose:"Enable verbose output"};buddy.command("fresh",descriptions.fresh).option("-p, --project [project]",descriptions.project,{default:false}).option("-f, --force",descriptions.force,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy fresh` ...",options);const skipConfirm=options.force===true||Boolean(buddy.isForce)||Boolean(buddy.isNoInteraction);if(!skipConfirm&&(isCI||!hasTTY||!process.stdin.isTTY)){log.syncError("Refusing to run `buddy fresh` from a non-interactive shell without confirmation.");log.fatal(" ➡️ Re-run with `--force` to proceed: `buddy fresh --force`")}if(!skipConfirm){const{confirm}=await import("@stacksjs/cli");const confirmed=await confirm({message:"This will remove and reinstall all dependencies. Continue?",initial:false});if(!confirmed){log.info("Fresh install cancelled");await log.flush();process.exit(ExitCode.Success)}}const perf=await intro("buddy fresh");const result=await runAction(Action.Fresh,{...options,stdout:"inherit"});if(resultFailed(result)){await outro("While running `buddy fresh`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Freshly reinstalled your dependencies",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"fresh")}
|
package/dist/commands/gdpr.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,resolve}from"node:path";import process from"node:process";import{confirm,log}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";const DEFAULT_REGISTER="database/processing-register";function printChanges(changes,dryRun){if(!changes.length){process.stdout.write(` Nothing declared for this request.
|
|
2
|
-
`);return}const verb=dryRun?"would change":"changed"
|
|
3
|
-
`)}}async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function errorMessage(error){return error instanceof Error?error.message:String(error)}function registerPath(format,out){return resolve(process.cwd(),out||`${DEFAULT_REGISTER}.${format==="json"?"json":"md"}`)}async function renderRegister(format){const{buildProcessingRegister,loadGdprModels,renderProcessingRegister,resolveGdprPlan}=await import("@stacksjs/orm")
|
|
2
|
+
`);return}const verb=dryRun?"would change":"changed";const width=Math.max(...changes.map((change)=>change.model.length));for(const change of changes){const fields=change.fields.length?` (${change.fields.join(", ")})`:"";process.stdout.write(` ${change.model.padEnd(width)} ${change.action.padEnd(9)} ${String(change.matched).padStart(5)} matched ${String(change.changed).padStart(5)} ${verb}${fields}
|
|
3
|
+
`)}}async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function errorMessage(error){return error instanceof Error?error.message:String(error)}function registerPath(format,out){return resolve(process.cwd(),out||`${DEFAULT_REGISTER}.${format==="json"?"json":"md"}`)}async function renderRegister(format){const{buildProcessingRegister,loadGdprModels,renderProcessingRegister,resolveGdprPlan}=await import("@stacksjs/orm");const plan=resolveGdprPlan(await loadGdprModels());if(plan.problems.length)await fail(`GDPR declarations cannot be honoured:
|
|
4
4
|
${plan.problems.map((p)=>` - ${p.model}: ${p.message}`).join(`
|
|
5
5
|
`)}`);return renderProcessingRegister(buildProcessingRegister(plan),format==="json"?"json":"markdown")}export function gdpr(buddy){buddy.command("gdpr:export <subject>","Export a data subject's personal data as JSON (user id, email or uuid)").option("--out <file>","Write the export to this file instead of stdout").example("buddy gdpr:export ada@example.com --out ada.json").action(async(subject,options)=>{const{exportSubjectData}=await import("@stacksjs/orm");let result;try{result=await exportSubjectData(subject,{actor:"cli"})}catch(error){return fail(errorMessage(error))}const json=`${JSON.stringify(result,null,2)}
|
|
6
|
-
`;if(options.out){const file=resolve(process.cwd(),options.out);mkdirSync(dirname(file),{recursive
|
|
6
|
+
`;if(options.out){const file=resolve(process.cwd(),options.out);mkdirSync(dirname(file),{recursive:true});writeFileSync(file,json,{mode:384});log.success(`Exported ${Object.keys(result.data).length} model(s) for subject ${String(result.subject.id)} to ${file}`)}else{process.stdout.write(json)}await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:erase <subject>","Erase a data subject: delete or anonymize their rows per each model's declaration").option("--dry-run","Print exactly what would change, and change nothing",{default:false}).option("-y, --yes","Skip the confirmation prompt",{default:false}).example("buddy gdpr:erase ada@example.com --dry-run").example("buddy gdpr:erase 42 --yes").action(async(subject,options)=>{const{eraseSubject}=await import("@stacksjs/orm");let preview;try{preview=await eraseSubject(subject,{dryRun:true})}catch(error){return fail(errorMessage(error))}process.stdout.write(`
|
|
7
7
|
Erasure of subject ${String(preview.subject.id)}:
|
|
8
|
-
`);printChanges(preview.changes
|
|
8
|
+
`);printChanges(preview.changes,true);if(preview.skipped.length)process.stdout.write(` Not in this database: ${preview.skipped.join(", ")}
|
|
9
9
|
`);process.stdout.write(`
|
|
10
|
-
`);if(options.dryRun){log.info("Dry run: nothing was changed.");await log.flush();process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY)return fail("Refusing to erase without confirmation in a non-interactive environment. Re-run with --yes.");await log.flush();
|
|
11
|
-
`);log.info(result.dryRun?"Dry run: nothing was changed.":"Retention applied.")}await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:register","Generate the processing register from the model declarations").option("--format <format>","markdown or json",{default:"markdown"}).option("--out <file>",`Where to write it. Defaults to ${DEFAULT_REGISTER}.md (or .json)`).option("--stdout","Print it instead of writing a file",{default
|
|
10
|
+
`);if(options.dryRun){log.info("Dry run: nothing was changed.");await log.flush();process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY)return fail("Refusing to erase without confirmation in a non-interactive environment. Re-run with --yes.");await log.flush();const proceed=await confirm({message:"Erase this subject? This cannot be undone.",initial:false});if(!proceed){log.info("Cancelled. Nothing was changed.");await log.flush();process.exit(ExitCode.Success)}}let result;try{result=await eraseSubject(subject,{actor:"cli"})}catch(error){return fail(errorMessage(error))}printChanges(result.changes,false);log.success(`Erased subject ${String(result.subject.id)} and recorded it in gdpr_requests.`);log.info(result.credentialsRevoked?"Their API tokens are revoked and their sessions destroyed.":"Credentials were not revoked: @stacksjs/auth is not available, or the subject key is not numeric.");await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:prune","Apply every model's retention policy (the daily PruneRetainedDataJob does the same)").option("--dry-run","Print what would be pruned, and change nothing",{default:false}).action(async(options)=>{const{pruneRetainedData}=await import("@stacksjs/orm");let result;try{result=await pruneRetainedData({dryRun:options.dryRun===true,actor:"cli"})}catch(error){return fail(errorMessage(error))}if(!result.changes.length&&!result.skipped.length){log.info("No model declares a retention policy.")}else{printChanges(result.changes,result.dryRun);if(result.skipped.length)process.stdout.write(` Not in this database: ${result.skipped.join(", ")}
|
|
11
|
+
`);log.info(result.dryRun?"Dry run: nothing was changed.":"Retention applied.")}await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:register","Generate the processing register from the model declarations").option("--format <format>","markdown or json",{default:"markdown"}).option("--out <file>",`Where to write it. Defaults to ${DEFAULT_REGISTER}.md (or .json)`).option("--stdout","Print it instead of writing a file",{default:false}).action(async(options)=>{const format=options.format==="json"?"json":"markdown";const rendered=await renderRegister(format);if(options.stdout){process.stdout.write(rendered);process.exit(ExitCode.Success)}const file=registerPath(format,options.out);mkdirSync(dirname(file),{recursive:true});writeFileSync(file,rendered);log.success(`Wrote ${file}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:register:check","Verify the committed processing register matches the model declarations").option("--format <format>","markdown or json",{default:"markdown"}).option("--out <file>",`The register to check. Defaults to ${DEFAULT_REGISTER}.md (or .json)`).action(async(options)=>{const format=options.format==="json"?"json":"markdown";const file=registerPath(format,options.out);if(!existsSync(file))return fail(`${file} does not exist. Run \`buddy gdpr:register\` and commit it.`);const rendered=await renderRegister(format);if(readFileSync(file,"utf8")!==rendered)return fail(`${file} is out of date with the model declarations. Run \`buddy gdpr:register\` and commit the result.`);log.success(`${file} is current.`);await log.flush();process.exit(ExitCode.Success)})}
|
|
@@ -1,5 +1,5 @@
|
|
|
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
|
|
2
|
-
|
|
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
|
|
4
|
-
|
|
5
|
-
`);process.exit(ExitCode.FatalError)}if(options.dryRun){console.log(result.diagram);return}log.success(`Wrote ${result.path} (${result.modelCount} models)`);if(result.skipped.length>0)log.warn(`${result.skipped.length} model(s) could not be read and are missing from the diagram`)});buddy.command("generate:entries",descriptions.entries).option("-p, --project [project]",descriptions.project,{default
|
|
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:false}).option("--core-symlink",descriptions.coreSymlink).option("--verbose",descriptions.verbose,{default:false}).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:false}).option("-w, --watch","Re-run on changes to models/ and config/",{default:false}).option("--verbose",descriptions.verbose,{default:false}).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:false}).option("--framework","Write the framework's own FrameworkSchema instead of the app's DatabaseSchema",{default:false}).option("--dialect <dialect>","Raw column dialect: sqlite, mysql, or postgres").action(async(options)=>{if(options.dialect&&!["sqlite","mysql","postgres"].includes(options.dialect))throw new Error("Database types require dialect sqlite, mysql, or postgres");const{buildDatabaseSchema}=await import("@stacksjs/orm");const 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:false}).option("--out [path]","Where to write the VSchema",{default:"database/vschema.json"}).action(async(options)=>{const{generateVSchema}=await import("@stacksjs/actions");const result=await generateVSchema({dryRun:options.dryRun,out:options.out});if(!result.ok){console.error(`
|
|
2
|
+
❌ ${result.error}
|
|
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:false}).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:true}).option("--only [tables]","Comma-separated tables or model names to include",{default:""}).action(async(options)=>{const{generateErd}=await import("@stacksjs/actions");const only=(options.only??"").split(",").map((entry)=>entry.trim()).filter(Boolean);const result=await generateErd({dryRun:options.dryRun,out:options.out,noColumns:options.columns===false,only});if(!result.ok){console.error(`
|
|
4
|
+
❌ ${result.error}
|
|
5
|
+
`);process.exit(ExitCode.FatalError)}if(options.dryRun){console.log(result.diagram);return}log.success(`Wrote ${result.path} (${result.modelCount} models)`);if(result.skipped.length>0)log.warn(`${result.skipped.length} model(s) could not be read and are missing from the diagram`)});buddy.command("generate:entries",descriptions.entries).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:entries` ...",options);await generateLibEntries(options)});buddy.command("generate:web-types",descriptions.webTypes).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:web-types` ...",options);await generateWebTypes()});buddy.command("generate:vscode-custom-data",descriptions.customData).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:vscode-custom-data` ...",options);await generateVsCodeCustomData()});buddy.command("generate:ide-helpers",descriptions.ideHelpers).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:ide-helpers` ...",options);await generateIdeHelpers()});buddy.command("generate:component-meta",descriptions.componentMeta).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:component-meta` ...",options);await generateComponentMeta()});buddy.command("generate:pantry-config",descriptions.pantry).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:pantry-config` ...",options);await generatePantryConfig()});buddy.command("generate:openapi-spec",descriptions.openApi).alias("generate:openapi").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:openapi-spec` ...",options);const perf=await intro("buddy generate:openapi-spec");await generateOpenApiSpec();await outro("Generated OpenAPI specification",{startTime:perf,useSeconds:true})});buddy.command("generate:migrations","Generate Migrations").option("--dialect <dialect>","Generate into this dialect's corpus instead of the connected one (sqlite, mysql, singlestore, vitess, postgres), or `all` for the connected dialect and every other one that keeps a corpus. No database of that dialect is needed").action(async(options)=>{log.debug("Running `buddy generate:migrations` ...",options);const{dialectsBehindModels,generateMigrations,siblingMigrationDialects}=await import("@stacksjs/database");const targets=options.dialect==="all"?[undefined,...await siblingMigrationDialects()]:[options.dialect];for(const dialect of targets){const result=await generateMigrations(dialect?{dialect}:{});if(resultFailed(result))reportFailure(result,"generateMigrations failed")}if(!options.dialect){for(const dialect of await dialectsBehindModels())log.warn(`The ${dialect} migrations are behind these models. Run \`./buddy generate:migrations --dialect ${dialect}\` (or \`--dialect all\`) and commit the result.`)}});buddy.command("generate:auto-imports","Regenerate the auto-import barrels and name registries in storage/framework/auto-imports").action(async(options)=>{log.debug("Running `buddy generate:auto-imports` ...",options);const perf=await intro("buddy generate:auto-imports");const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles();await outro("Regenerated storage/framework/auto-imports",{startTime:perf,useSeconds:true})});buddy.command("generate:core-symlink","Symlink `.framework` -> storage/framework. A shortcut for core developers.").action(async(options)=>{log.debug("Running `buddy generate:core-symlink` ...",options);await generateCoreSymlink()});buddy.command("generate:images",descriptions.images).alias("images:generate").option("--social","Only build the social cards").option("--app-store","Only build the App Store screenshots").option("--app-icons","Only build the app icons and favicons").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:images` ...",options);const perf=await intro("buddy generate:images");const only=[];if(options.social)only.push("social");if(options.appStore)only.push("app-store");if(options.appIcons)only.push("app-icons");await generateProjectImages({only,verbose:options.verbose});await outro("Generated images",{startTime:perf,useSeconds:true})});buddy.command("generate:og",descriptions.og).alias("generate:social").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:og` ...",options);const perf=await intro("buddy generate:og");await generateProjectImages({only:["social"],verbose:options.verbose});await outro("Generated social cards",{startTime:perf,useSeconds:true})});buddy.command("generate:app-store",descriptions.appStore).alias("generate:screenshots").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:app-store` ...",options);const perf=await intro("buddy generate:app-store");await generateProjectImages({only:["app-store"],verbose:options.verbose});await outro("Generated App Store screenshots",{startTime:perf,useSeconds:true})});buddy.command("generate:app-icons",descriptions.appIcons).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy generate:app-icons` ...",options);const perf=await intro("buddy generate:app-icons");await generateProjectImages({only:["app-icons"],verbose:options.verbose});await outro("Generated app icons",{startTime:perf,useSeconds:true})});onUnknownSubcommand(buddy,"generate")}
|
package/dist/commands/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{HttxClient}from"@stacksjs/httx";import{ExitCode}from"@stacksjs/types";export function http(buddy){const descriptions={http:"Send an HTTP request to a domain",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("http [domain]",descriptions.http).option("-p, --project [project]",descriptions.project,{default
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{HttxClient}from"@stacksjs/httx";import{ExitCode}from"@stacksjs/types";export function http(buddy){const descriptions={http:"Send an HTTP request to a domain",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("http [domain]",descriptions.http).option("-p, --project [project]",descriptions.project,{default:false}).option("-v, --verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{log.debug("Running `buddy http [domain]` ...",options);const url=domain||config.app.url;if(!url)throw new Error("No domain configured. Pass a domain or set config.app.url.");const client=new HttxClient({verbose:options.verbose});log.info(`GET ${url}`);const result=await client.request(url.startsWith("http")?url:`https://${url}`,{method:"GET"});result.match({ok:(response)=>{console.log(`${response.status} ${response.statusText} (${response.timings.duration.toFixed(0)}ms)`);console.log(typeof response.data==="string"?response.data:JSON.stringify(response.data,null,2));process.exit(ExitCode.Success)},err:(error)=>{console.error(`Request failed: ${error.message}`);process.exit(ExitCode.FatalError)}})})}
|
package/dist/commands/install.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function install(buddy){const descriptions={install:"Install your dependencies",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("install",descriptions.install).option("-p, --project [project]",descriptions.project,{default
|
|
1
|
+
import process from"node:process";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function install(buddy){const descriptions={install:"Install your dependencies",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("install",descriptions.install).option("-p, --project [project]",descriptions.project,{default:false}).option("-v, --verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy install` ...",options);const result=await runCommand("bun install",{...options,cwd:p.projectPath()});if(resultFailed(result)){await log.error("bun install failed");process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"install")}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import process from"node:process";export const PROBE_TARGETS=[{name:"FCM HTTP v1",url:"https://fcm.googleapis.com/v1/projects/stacks-probe/messages:send",method:"POST",observed:401},{name:"OpenAI",url:"https://api.openai.com/v1/models",method:"GET",observed:401},{name:"Anthropic",url:"https://api.anthropic.com/v1/messages",method:"POST",observed:401},{name:"SendGrid",url:"https://api.sendgrid.com/v3/mail/send",method:"POST",observed:401},{name:"Twilio",url:"https://api.twilio.com/2010-04-01/Accounts",method:"GET",observed:401},{name:"Twilio Lookups v2",url:"https://lookups.twilio.com/v2/PhoneNumbers/+15005550006",method:"GET",observed:401},{name:"Twilio Verify v2",url:"https://verify.twilio.com/v2/Services",method:"GET",observed:401},{name:"Google id_token signing keys",url:"https://www.googleapis.com/oauth2/v3/certs",method:"GET",observed:200},{name:"Google tokeninfo",url:"https://oauth2.googleapis.com/tokeninfo",method:"GET",observed:400},{name:"Apple id_token signing keys",url:"https://appleid.apple.com/auth/keys",method:"GET",observed:200},{name:"Discord",url:"https://discord.com/api/v10/users/@me",method:"GET",observed:401},{name:"Mozilla add-ons v5",url:"https://addons.mozilla.org/api/v5/addons/search/?q=test",method:"GET",observed:200},{name:"Hetzner Cloud",url:"https://api.hetzner.cloud/v1/servers",method:"GET",observed:401},{name:"fiskaly SIGN DE v2",url:"https://kassensichv-middleware.fiskaly.com/api/v2/tss",method:"GET",observed:401},{name:"Lemon Squeezy",url:"https://api.lemonsqueezy.com/v1/products",method:"GET",observed:401},{name:"Vonage Messages v1",url:"https://api.nexmo.com/v1/messages",method:"POST",observed:401},{name:"Vonage Verify v2",url:"https://api.nexmo.com/v2/verify",method:"POST",observed:422},{name:"Expo push",url:"https://exp.host/--/api/v2/push/send",method:"POST",observed:400},{name:"Threads",url:"https://graph.threads.net/v1.0/me",method:"GET",observed:400},{name:"Meta Graph",url:"https://graph.facebook.com/v24.0/me",method:"GET",observed:400},{name:"LinkedIn",url:"https://api.linkedin.com/rest/me",method:"GET",observed:401},{name:"GitHub",url:"https://api.github.com/user",method:"GET",observed:401}]
|
|
2
|
-
`)}async function probe(target,timeoutMs){try{const response=await fetch(target.url,{method:target.method,redirect:"manual",signal:AbortSignal.timeout(timeoutMs)});return{target,status:response.status,verdict:classifyStatus(response.status)}}catch{return{target,status:null,verdict:"inconclusive"}}}async function probeAll(targets,timeoutMs,concurrency=4){const results=[];for(let index=0;index<targets.length;index+=concurrency)results.push(...await Promise.all(targets.slice(index,index+concurrency).map((target)=>probe(target,timeoutMs))));return results}export function integrationsProbe(buddy){buddy.command("integrations:probe","Check whether the third-party endpoints this framework calls still exist (sends no credentials)").option("--timeout <ms>","How long to wait for each endpoint",{default:"12000"}).option("--json","Print the results as JSON instead of a report",{default
|
|
1
|
+
import process from"node:process";export const PROBE_TARGETS=[{name:"FCM HTTP v1",url:"https://fcm.googleapis.com/v1/projects/stacks-probe/messages:send",method:"POST",observed:401},{name:"OpenAI",url:"https://api.openai.com/v1/models",method:"GET",observed:401},{name:"Anthropic",url:"https://api.anthropic.com/v1/messages",method:"POST",observed:401},{name:"SendGrid",url:"https://api.sendgrid.com/v3/mail/send",method:"POST",observed:401},{name:"Twilio",url:"https://api.twilio.com/2010-04-01/Accounts",method:"GET",observed:401},{name:"Twilio Lookups v2",url:"https://lookups.twilio.com/v2/PhoneNumbers/+15005550006",method:"GET",observed:401},{name:"Twilio Verify v2",url:"https://verify.twilio.com/v2/Services",method:"GET",observed:401},{name:"Google id_token signing keys",url:"https://www.googleapis.com/oauth2/v3/certs",method:"GET",observed:200},{name:"Google tokeninfo",url:"https://oauth2.googleapis.com/tokeninfo",method:"GET",observed:400},{name:"Apple id_token signing keys",url:"https://appleid.apple.com/auth/keys",method:"GET",observed:200},{name:"Discord",url:"https://discord.com/api/v10/users/@me",method:"GET",observed:401},{name:"Mozilla add-ons v5",url:"https://addons.mozilla.org/api/v5/addons/search/?q=test",method:"GET",observed:200},{name:"Hetzner Cloud",url:"https://api.hetzner.cloud/v1/servers",method:"GET",observed:401},{name:"fiskaly SIGN DE v2",url:"https://kassensichv-middleware.fiskaly.com/api/v2/tss",method:"GET",observed:401},{name:"Lemon Squeezy",url:"https://api.lemonsqueezy.com/v1/products",method:"GET",observed:401},{name:"Vonage Messages v1",url:"https://api.nexmo.com/v1/messages",method:"POST",observed:401},{name:"Vonage Verify v2",url:"https://api.nexmo.com/v2/verify",method:"POST",observed:422},{name:"Expo push",url:"https://exp.host/--/api/v2/push/send",method:"POST",observed:400},{name:"Threads",url:"https://graph.threads.net/v1.0/me",method:"GET",observed:400},{name:"Meta Graph",url:"https://graph.facebook.com/v24.0/me",method:"GET",observed:400},{name:"LinkedIn",url:"https://api.linkedin.com/rest/me",method:"GET",observed:401},{name:"GitHub",url:"https://api.github.com/user",method:"GET",observed:401}];export const PROBE_CONTROLS=[{name:"FCM legacy send (decommissioned 2024-06-20)",url:"https://fcm.googleapis.com/fcm/send",method:"POST",observed:404},{name:"GitHub, a path that cannot exist",url:"https://api.github.com/stacks-probe-control-does-not-exist",method:"GET",observed:404},{name:"OpenAI, a path that cannot exist",url:"https://api.openai.com/v1/stacks-probe-control-does-not-exist",method:"GET",observed:404}];export function classifyStatus(status){if(status===null)return"inconclusive";if(status===404||status===410)return"gone";if(status>=500)return"inconclusive";return"alive"}export function concludeProbe(targets,controls){if(controls.length===0)return"untrustworthy";if(controls.some((result)=>result.verdict!=="gone"))return"untrustworthy";if(targets.some((result)=>result.verdict==="gone"))return"withdrawn";if(targets.some((result)=>result.verdict==="inconclusive"))return"inconclusive";return"ok"}export function exitCodeFor(conclusion){if(conclusion==="withdrawn")return 1;if(conclusion==="ok")return 0;return 2}export function renderReport(targets,controls,conclusion){const row=(result)=>{const status=result.status===null?"no answer":String(result.status);const moved=result.status!==null&&result.status!==result.target.observed?` (was ${result.target.observed})`:"";return`| ${result.target.name} | ${result.target.method} | ${status}${moved} | ${result.verdict} |`};const headline={ok:"Every endpoint this framework calls is still answering.",withdrawn:"An endpoint this framework calls has been withdrawn.",untrustworthy:"This run proves nothing: a control that must read as gone did not, so something is answering for the network.",inconclusive:"No conclusion: something did not answer. The controls were sound, so this is likely a transient failure."}[conclusion];return[`## Integration sunset probe`,"",headline,"","| Endpoint | Method | Status | Verdict |","| --- | --- | --- | --- |",...targets.map(row),"","### Controls","","Paths that must read as gone. If any does not, the table above says nothing.","","| Control | Method | Status | Verdict |","| --- | --- | --- | --- |",...controls.map(row),"","No credential is sent by any request here, which is what makes the signal readable: an endpoint that exists rejects an unauthenticated request, and one that is gone answers 404."].join(`
|
|
2
|
+
`)}async function probe(target,timeoutMs){try{const response=await fetch(target.url,{method:target.method,redirect:"manual",signal:AbortSignal.timeout(timeoutMs)});return{target,status:response.status,verdict:classifyStatus(response.status)}}catch{return{target,status:null,verdict:"inconclusive"}}}async function probeAll(targets,timeoutMs,concurrency=4){const results=[];for(let index=0;index<targets.length;index+=concurrency)results.push(...await Promise.all(targets.slice(index,index+concurrency).map((target)=>probe(target,timeoutMs))));return results}export function integrationsProbe(buddy){buddy.command("integrations:probe","Check whether the third-party endpoints this framework calls still exist (sends no credentials)").option("--timeout <ms>","How long to wait for each endpoint",{default:"12000"}).option("--json","Print the results as JSON instead of a report",{default:false}).action(async(options)=>{const timeoutMs=Number.parseInt(String(options.timeout??"12000"),10)||12000;const controls=await probeAll(PROBE_CONTROLS,timeoutMs);const targets=await probeAll(PROBE_TARGETS,timeoutMs);const conclusion=concludeProbe(targets,controls);if(options.json)console.log(JSON.stringify({conclusion,targets,controls},null,2));else console.log(renderReport(targets,controls,conclusion));process.exit(exitCodeFor(conclusion))})}
|
package/dist/commands/key.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function key(buddy){const descriptions={command:"Generate & set the application key.",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("key:generate",descriptions.command).option("-p, --project [project]",descriptions.project,{default
|
|
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{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function key(buddy){const descriptions={command:"Generate & set the application key.",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("key:generate",descriptions.command).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy key:generate` ...",options);await intro("buddy key:generate");const result=await runAction(Action.KeyGenerate,options);if(resultFailed(result)){await log.error("Failed to set random application key.",result.error);process.exit(ExitCode.FatalError)}await outro("Random application key set.")});onUnknownSubcommand(buddy,"key")}
|
package/dist/commands/libs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{relative}from"node:path";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,dim,log,onUnknownSubcommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function libs(buddy){const descriptions={list:"List the packages this project releases out of resources/functions and resources/components",build:"Build every configured library package",publish:"Publish the built library packages through pantry",json:"Print the resolved packages as JSON",dryRun:"Report what would be published without uploading anything",verbose:"Enable verbose output"};buddy.command("libs",descriptions.list).alias("libs:list").alias("libraries").option("--json",descriptions.json,{default
|
|
1
|
+
import{relative}from"node:path";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,dim,log,onUnknownSubcommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function libs(buddy){const descriptions={list:"List the packages this project releases out of resources/functions and resources/components",build:"Build every configured library package",publish:"Publish the built library packages through pantry",json:"Print the resolved packages as JSON",dryRun:"Report what would be published without uploading anything",verbose:"Enable verbose output"};buddy.command("libs",descriptions.list).alias("libs:list").alias("libraries").option("--json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy libs").action(async(options)=>{const{configuredLibrary,resolveLibraryPackages,LibraryConfigError}=await import("@stacksjs/actions");try{const packages=await resolveLibraryPackages(await configuredLibrary());if(options.json){console.log(JSON.stringify(packages.map((pkg)=>({name:pkg.name,kind:pkg.kind,dir:relative(process.cwd(),pkg.dir),private:pkg.private,runtime:pkg.runtime,sources:pkg.sources.map((source)=>relative(process.cwd(),source))})),null,2));return}if(!packages.length){log.info("No library packages are configured. Add one to `packages` in config/library.ts.");return}for(const pkg of packages){console.log(`${bold(pkg.name)} ${dim(`(${pkg.kind}${pkg.private?", private":""})`)}`);console.log(dim(` → ${relative(process.cwd(),pkg.dir)}`));for(const source of pkg.sources)console.log(dim(` · ${relative(process.cwd(),source)}`))}}catch(error){if(error instanceof LibraryConfigError){await log.exit(error.message,1);return}throw error}});buddy.command("libs:build",descriptions.build).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{const result=await runAction(Action.BuildLibs,options);if(resultFailed(result)){await log.error("Failed to build the library packages.",result.error);process.exit(ExitCode.FatalError)}});buddy.command("libs:publish",descriptions.publish).option("--dry-run",descriptions.dryRun,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy libs:publish --dry-run").action(async(options)=>{const result=await runAction(Action.LibraryPublish,{...options,verbose:true});if(resultFailed(result)){await log.error("Failed to publish the library packages.",result.error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"libs")}
|