@stacksjs/buddy 0.75.515 → 0.75.519
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 +10 -10
- 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 +2 -2
- package/dist/commands/docs/links.js +2 -2
- package/dist/commands/docs/native-skills.js +2 -2
- package/dist/commands/docs/snippets.js +6 -6
- 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/sms.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import{getErrorMessage}from"@stacksjs/utils";import{readFileSync,existsSync}from"node:fs";const TIMEOUT_MS=30000;async function withTimeout(promise,ms=TIMEOUT_MS){let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error(`Operation timed out after ${ms}ms`)),ms)});try{return await Promise.race([promise,timeoutPromise])}finally{clearTimeout(timeoutId)}}function loadAwsCredentials(){const envPath=".env.production";if(existsSync(envPath)){const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
|
|
2
|
-
`)){const eq=line.indexOf("=");if(eq>0&&!line.startsWith("#"))process.env[line.slice(0,eq).trim()]=line.slice(eq+1).trim()}}}const descriptions={sms:"SMS service management commands",status:"Show SMS service status",send:"Send a test SMS",setup:"Initialize SMS infrastructure",verify:"Verify a sandbox phone number","add-phone":"Add a phone to sandbox for testing"};export function sms(buddy){buddy.command("sms",descriptions.sms).action(async()=>{console.log(`
|
|
1
|
+
import{getErrorMessage}from"@stacksjs/utils";import{readFileSync,existsSync}from"node:fs";const TIMEOUT_MS=30000;async function withTimeout(promise,ms=TIMEOUT_MS){let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error(`Operation timed out after ${ms}ms`)),ms)});try{return await Promise.race([promise,timeoutPromise])}finally{clearTimeout(timeoutId)}}function loadAwsCredentials(){const envPath=".env.production";if(existsSync(envPath)){const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
|
|
2
|
+
`)){const eq=line.indexOf("=");if(eq>0&&!line.startsWith("#")){process.env[line.slice(0,eq).trim()]=line.slice(eq+1).trim()}}}}const descriptions={sms:"SMS service management commands",status:"Show SMS service status",send:"Send a test SMS",setup:"Initialize SMS infrastructure",verify:"Verify a sandbox phone number","add-phone":"Add a phone to sandbox for testing"};export function sms(buddy){buddy.command("sms",descriptions.sms).action(async()=>{console.log(`
|
|
3
3
|
\uD83D\uDCF1 SMS Service Commands
|
|
4
4
|
`);console.log(" buddy sms:status - Show SMS service status");console.log(" buddy sms:send - Send a test SMS");console.log(" buddy sms:setup - Initialize SMS infrastructure");console.log(" buddy sms:add-phone - Add a phone to sandbox for testing");console.log(" buddy sms:verify - Verify a sandbox phone number with OTP");console.log("");process.exit(0)});buddy.command("sms:status",descriptions.status).action(async()=>{console.log(`
|
|
5
5
|
\uD83D\uDCF1 SMS Service Status
|
|
6
|
-
`);loadAwsCredentials();try{const{getSmsInfrastructureStatus}=await import("@stacksjs/ts-cloud")
|
|
7
|
-
Account:`);console.log(` Sandbox Status: ${status.sandboxStatus==="IN_SANDBOX"?"
|
|
8
|
-
SNS Topics:`);if(status.topics.length===0)console.log(" No SMS topics configured")
|
|
9
|
-
\uD83D\uDCA1 To exit sandbox mode:`);console.log(" Run `buddy sms:setup` to file a support request");console.log(" Or visit AWS Console > End User Messaging > SMS > Request production access")}if(status.phoneNumbers.some((p)=>p.status==="PENDING"))console.log(`
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
6
|
+
`);loadAwsCredentials();try{const{getSmsInfrastructureStatus}=await import("@stacksjs/ts-cloud");const status=await withTimeout(getSmsInfrastructureStatus({region:process.env.AWS_REGION||"us-east-1",accountName:"stacks"}),30000);console.log("Phone Numbers:");if(status.phoneNumbers.length===0){console.log(" No phone numbers provisioned");console.log(" Run `buddy sms:setup` to provision a phone number")}else{for(const phone of status.phoneNumbers){console.log(` ${phone.phoneNumber}`);console.log(` Status: ${phone.status}`);console.log(` Two-Way: ${phone.twoWayEnabled?"Enabled":"Disabled"}`);console.log(` Capabilities: ${phone.capabilities.join(", ")||"N/A"}`)}}console.log(`
|
|
7
|
+
Account:`);console.log(` Sandbox Status: ${status.sandboxStatus==="IN_SANDBOX"?"⚠️ In Sandbox":"✅ Production"}`);console.log(` Spending Limit: $${status.spendingLimit}/month`);console.log(`
|
|
8
|
+
SNS Topics:`);if(status.topics.length===0){console.log(" No SMS topics configured")}else{for(const topic of status.topics){console.log(` ${topic.name}`)}}if(status.sandboxStatus==="IN_SANDBOX"){console.log(`
|
|
9
|
+
\uD83D\uDCA1 To exit sandbox mode:`);console.log(" Run `buddy sms:setup` to file a support request");console.log(" Or visit AWS Console > End User Messaging > SMS > Request production access")}if(status.phoneNumbers.some((p)=>p.status==="PENDING")){console.log(`
|
|
10
|
+
⏳ Note: Phone number verification can take 24-72 hours for toll-free numbers`)}}catch(error){console.error("Error checking status:",getErrorMessage(error));try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud");const smsClient=new SmsVoiceClient(process.env.AWS_REGION||"us-east-1");const phoneNumbers=await withTimeout(smsClient.describePhoneNumbers({}));const activeNumbers=phoneNumbers.PhoneNumbers?.filter((p)=>p.Status==="ACTIVE"||p.Status==="PENDING");if(activeNumbers&&activeNumbers.length>0){console.log(`
|
|
11
|
+
✅ SMS Service Active (End User Messaging)`);for(const phone of activeNumbers){console.log(` Phone: ${phone.PhoneNumber} (${phone.Status})`)}}else{console.log(`
|
|
12
|
+
❌ SMS service not deployed.`);console.log(" Run `buddy sms:setup` to initialize")}}catch{console.log(`
|
|
13
|
+
❌ Could not connect to AWS. Check credentials.`)}}process.exit(0)});buddy.command("sms:send <phone> [message]",descriptions.send).option("--template <name>","Use a message template").action(async(phone,message,options)=>{const msg=message||"Test message from Stacks";console.log(`
|
|
14
14
|
\uD83D\uDCF1 Sending SMS to ${phone}...
|
|
15
|
-
`);loadAwsCredentials();try{const{SmsClient}=await import("@stacksjs/ts-cloud")
|
|
16
|
-
\uD83D\uDCA1 No origination phone number available.`);console.log(" Run `buddy sms:setup` to provision a phone number.")}else if(getErrorMessage(error).includes("not authorized"))console.log(`
|
|
17
|
-
\uD83D\uDCA1 Make sure your AWS account has SMS permissions.`)
|
|
15
|
+
`);loadAwsCredentials();try{const{SmsClient}=await import("@stacksjs/ts-cloud");const smsClient=new SmsClient({region:process.env.AWS_REGION||"us-east-1"});const smsConfig=await import("@stacksjs/config").then((m)=>m.config?.sms);let originationNumber=smsConfig?.originationNumber;if(!originationNumber){const{SmsVoiceClient}=await import("@stacksjs/ts-cloud");const pinpointV2=new SmsVoiceClient(process.env.AWS_REGION||"us-east-1");const phoneNumbers=await withTimeout(pinpointV2.describePhoneNumbers({}));const activePhone=phoneNumbers.PhoneNumbers?.find((p)=>p.Status==="ACTIVE");originationNumber=activePhone?.PhoneNumber}let finalMessage=msg;if(options?.template&&smsConfig?.templates){const template=smsConfig.templates.find((t)=>t.name===options.template);if(template){finalMessage=template.body;console.log(`Using template: ${options.template}`)}else{console.log(`Template "${options.template}" not found. Using default message.`)}}const result=await withTimeout(smsClient.send({to:phone,body:finalMessage,from:originationNumber}),30000);if(result.messageId){console.log("✅ SMS sent successfully!");console.log(` Message ID: ${result.messageId}`);if(originationNumber){console.log(` From: ${originationNumber}`)}}else{console.log("❌ SMS send failed")}}catch(error){console.error("Error sending SMS:",getErrorMessage(error));if(getErrorMessage(error).includes("not found")||getErrorMessage(error).includes("No phone")){console.log(`
|
|
16
|
+
\uD83D\uDCA1 No origination phone number available.`);console.log(" Run `buddy sms:setup` to provision a phone number.")}else if(getErrorMessage(error).includes("not authorized")){console.log(`
|
|
17
|
+
\uD83D\uDCA1 Make sure your AWS account has SMS permissions.`)}else if(getErrorMessage(error).includes("sandbox")){console.log("\n\uD83D\uDCA1 Your account is in SMS sandbox. Run `buddy sms:setup` to request production access.")}else if(getErrorMessage(error).includes("PENDING")){console.log(`
|
|
18
18
|
\uD83D\uDCA1 Phone number is still pending verification (24-72 hours for toll-free).`);console.log(" Run `buddy sms:status` to check current status.")}}process.exit(0)});buddy.command("sms:setup",descriptions.setup).option("--dry-run","Show what would be done without making changes").action(async(options)=>{console.log(`
|
|
19
19
|
\uD83D\uDCF1 SMS Service Setup
|
|
20
20
|
`);loadAwsCredentials();try{const smsConfig=await import("@stacksjs/config").then((m)=>m.config?.sms);if(!smsConfig?.enabled){console.log("SMS is disabled in config/sms.ts");console.log(`
|
|
21
21
|
To enable SMS:`);console.log("1. Edit config/sms.ts and set enabled: true");console.log("2. Run `buddy sms:setup` again");process.exit(0);return}if(options.dryRun){console.log("[Dry Run] Would set up SMS infrastructure with config:");console.log(` Provider: ${smsConfig.provider}`);console.log(` Country: ${smsConfig.defaultCountryCode}`);console.log(` Message Type: ${smsConfig.messageType}`);console.log(` Monthly Limit: $${smsConfig.maxSpendPerMonth||1}`);console.log(` Two-Way: ${smsConfig.twoWay?.enabled?"Enabled":"Disabled"}`);console.log(` Inbox: ${smsConfig.inbox?.enabled?"Enabled":"Disabled"}`);process.exit(0);return}console.log(`Setting up SMS infrastructure...
|
|
22
|
-
`);const{createSmsInfrastructure}=await import("@stacksjs/ts-cloud")
|
|
23
|
-
|
|
24
|
-
`);if(result.phoneNumber)console.log(` Phone Number: ${result.phoneNumber} (${result.phoneNumberStatus})`)
|
|
22
|
+
`);const{createSmsInfrastructure}=await import("@stacksjs/ts-cloud");const result=await withTimeout(createSmsInfrastructure({enabled:smsConfig.enabled,provider:"sns",originationNumber:smsConfig.originationNumber,defaultCountryCode:smsConfig.defaultCountryCode||"US",messageType:smsConfig.messageType||"TRANSACTIONAL",maxSpendPerMonth:smsConfig.maxSpendPerMonth,inbox:smsConfig.inbox,twoWay:smsConfig.twoWay,optOut:smsConfig.optOut||{enabled:true,keywords:["STOP"]}}),120000);if(result.success){console.log(`
|
|
23
|
+
✅ SMS infrastructure setup complete!
|
|
24
|
+
`);if(result.phoneNumber){console.log(` Phone Number: ${result.phoneNumber} (${result.phoneNumberStatus})`)}if(result.twoWayTopicArn){console.log(` Two-Way Topic: ${result.twoWayTopicArn}`)}if(result.inboxBucket){console.log(` Inbox: s3://${result.inboxBucket}/${result.inboxPrefix}`)}console.log(` Spending Limit: $${result.spendingLimit}/month`);console.log(` Sandbox Status: ${result.sandboxStatus}`);if(result.supportCaseId){console.log(`
|
|
25
25
|
\uD83D\uDCCB Support Case: ${result.supportCaseId}`);console.log(" A support ticket has been filed for sandbox exit.")}if(result.warnings.length>0){console.log(`
|
|
26
|
-
|
|
26
|
+
⚠️ Warnings:`);for(const warning of result.warnings){console.log(` - ${warning}`)}}console.log(`
|
|
27
27
|
\uD83D\uDCA1 Next steps:`);console.log(' - Run `buddy sms:send +1234567890 "Test"` to send a test SMS');console.log(" - Run `buddy sms:status` to check current status")}else{console.log(`
|
|
28
|
-
|
|
29
|
-
`);for(const error of result.errors)console.log(` - ${error}`)}}catch(error){console.error("Error setting up SMS:",getErrorMessage(error));if(getErrorMessage(error).includes("timeout")){console.log(`
|
|
28
|
+
❌ SMS setup completed with errors:
|
|
29
|
+
`);for(const error of result.errors){console.log(` - ${error}`)}}}catch(error){console.error("Error setting up SMS:",getErrorMessage(error));if(getErrorMessage(error).includes("timeout")){console.log(`
|
|
30
30
|
\uD83D\uDCA1 Setup timed out. Some operations may have completed.`);console.log(" Run `buddy sms:status` to check current status.")}}process.exit(0)});buddy.command("sms:add-phone <phone>",descriptions["add-phone"]).action(async(phone)=>{console.log(`
|
|
31
31
|
\uD83D\uDCF1 Adding ${phone} to SMS sandbox...
|
|
32
|
-
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud")
|
|
33
|
-
\uD83D\uDCA1 Next step:`);console.log(` Run: buddy sms:verify ${result.verifiedDestinationNumberId} <code>`);console.log(" Replace <code> with the 6-digit code you received")}else{console.log("
|
|
32
|
+
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud");const smsClient=new SmsVoiceClient(process.env.AWS_REGION||"us-east-1");const result=await withTimeout(smsClient.addSandboxPhone(phone),30000);if(result.status==="VERIFIED"){console.log("✅ Phone is already verified!");console.log(` ID: ${result.verifiedDestinationNumberId}`)}else if(result.status==="PENDING"){console.log("\uD83D\uDCE8 Verification code sent to phone!");console.log(` ID: ${result.verifiedDestinationNumberId}`);console.log(`
|
|
33
|
+
\uD83D\uDCA1 Next step:`);console.log(` Run: buddy sms:verify ${result.verifiedDestinationNumberId} <code>`);console.log(" Replace <code> with the 6-digit code you received")}else{console.log("❓ Unexpected status:",result.status);console.log(" Message:",result.message)}}catch(error){console.error("Error adding phone:",getErrorMessage(error));if(getErrorMessage(error).includes("already exists")){console.log(`
|
|
34
34
|
\uD83D\uDCA1 Phone number may already be in the sandbox.`);console.log(" Run `buddy sms:status` to check sandbox numbers.")}}process.exit(0)});buddy.command("sms:verify <id> <code>",descriptions.verify).action(async(id,code)=>{console.log(`
|
|
35
35
|
\uD83D\uDCF1 Verifying sandbox phone...
|
|
36
|
-
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud")
|
|
37
|
-
\uD83D\uDCA1 You can now send SMS to this phone while in sandbox mode.`);console.log(` Run: buddy sms:send ${result.phoneNumber} "Test message"`)}else{console.log("
|
|
36
|
+
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud");const smsClient=new SmsVoiceClient(process.env.AWS_REGION||"us-east-1");const result=await withTimeout(smsClient.verifySandboxPhone(id,code),30000);if(result.success){console.log("✅ Phone verified successfully!");console.log(` Phone: ${result.phoneNumber}`);console.log(`
|
|
37
|
+
\uD83D\uDCA1 You can now send SMS to this phone while in sandbox mode.`);console.log(` Run: buddy sms:send ${result.phoneNumber} "Test message"`)}else{console.log("❌ Verification failed");console.log(` Error: ${result.message}`);console.log(`
|
|
38
38
|
\uD83D\uDCA1 Make sure you entered the correct 6-digit code.`);console.log(" Run `buddy sms:add-phone <phone>` to resend the code.")}}catch(error){console.error("Error verifying phone:",getErrorMessage(error))}process.exit(0)});buddy.command("sms:sandbox-list","List sandbox verified phone numbers").action(async()=>{console.log(`
|
|
39
39
|
\uD83D\uDCF1 Sandbox Verified Numbers
|
|
40
|
-
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud")
|
|
41
|
-
To add a phone:`);console.log(" buddy sms:add-phone +1234567890")}else
|
|
40
|
+
`);loadAwsCredentials();try{const{SmsVoiceClient}=await import("@stacksjs/ts-cloud");const smsClient=new SmsVoiceClient(process.env.AWS_REGION||"us-east-1");const phones=await withTimeout(smsClient.listSandboxPhones(),30000);if(phones.length===0){console.log("No verified sandbox numbers yet.");console.log(`
|
|
41
|
+
To add a phone:`);console.log(" buddy sms:add-phone +1234567890")}else{for(const phone of phones){const statusIcon=phone.status==="VERIFIED"?"✅":"⏳";console.log(` ${statusIcon} ${phone.phoneNumber} (${phone.status})`);console.log(` ID: ${phone.id}`)}}}catch(error){console.error("Error listing sandbox phones:",getErrorMessage(error))}process.exit(0)})}
|
package/dist/commands/socials.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const DEFAULT_PORT=7731
|
|
2
|
-
`));await log.flush();process.exit(ExitCode.Success)});buddy.command("socials:authorize [identity]","Run a platform consent flow and print the tokens for .env").option("--platform <platform>","Which platform to authorize. Only `twitter` needs a consent flow today.",{default:"twitter"}).option("--port <port>"
|
|
1
|
+
import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const DEFAULT_PORT=7731;const DEFAULT_TIMEOUT_SECONDS=300;async function socialsModule(){return import("@stacksjs/socials")}async function fail(message,hint){await log.error(message);if(hint)log.info(hint);await log.flush();process.exit(ExitCode.FatalError)}export function socials(buddy){buddy.command("socials:identities","List the social identities and whether each platform is ready to post").example("buddy socials:identities").action(async()=>{const{pickIdentity,readCredentials,REQUIRED_SOCIAL_CREDENTIALS,socialsConfig}=await socialsModule();const config=await socialsConfig();const names=Object.keys(config.identities??{});if(names.length===0){log.info("config/socials.ts declares no identities, so there is no account to post as.");await log.flush();process.exit(ExitCode.Success)}let fallback="";try{fallback=pickIdentity(config)}catch{}const out=[""];for(const name of names){const declared=config.identities?.[name]??{};const platforms=declared.platforms??[];const marker=name===fallback?"*":" ";out.push(` ${marker} ${name}${declared.handle?` (${declared.handle})`:""}`);if(platforms.length===0){out.push(" no platforms declared");continue}for(const platform of platforms){const resolved=readCredentials(config,platform,name);const missing=REQUIRED_SOCIAL_CREDENTIALS[platform].filter((field)=>!resolved[field]);out.push(missing.length===0?` ok ${platform}`:` MISSING ${platform} ${missing.join(", ")}`)}}if(fallback)out.push("",` * is the identity a call with no name uses.`);else if(names.length>1)out.push(""," No default, so a call has to name its identity.");console.log(out.join(`
|
|
2
|
+
`));await log.flush();process.exit(ExitCode.Success)});buddy.command("socials:authorize [identity]","Run a platform consent flow and print the tokens for .env").option("--platform <platform>","Which platform to authorize. Only `twitter` needs a consent flow today.",{default:"twitter"}).option("--port <port>",`Loopback port the redirect comes back on. Must match the registered redirect URI.`,{default:String(DEFAULT_PORT)}).option("--timeout <seconds>","How long to wait at the browser",{default:String(DEFAULT_TIMEOUT_SECONDS)}).example("buddy socials:authorize home-lang").example("buddy socials:authorize stacks --platform twitter --port 7731").action(async(identity,options)=>{const{callbackPage,callbackUri,completeTwitterAuthorization,envLines,isAuthorizablePlatform,newState,readCallback,readCredentials,resolveIdentityName,socialsConfig,startTwitterAuthorization,TWITTER_PUBLISH_SCOPES}=await socialsModule();const platform=String(options.platform||"twitter").toLowerCase();if(!isAuthorizablePlatform(platform)){return fail(`There is no consent flow for '${platform}'.`,"Bluesky uses an app password and Mastodon a manually generated token, so both go straight into .env. Only `twitter` needs this.")}const port=Number(options.port);const timeoutMs=Math.max(10,Number(options.timeout)||DEFAULT_TIMEOUT_SECONDS)*1000;let name;let redirectUrl;try{name=await resolveIdentityName(identity);redirectUrl=callbackUri(port)}catch(error){return fail(error instanceof Error?error.message:String(error))}const config=await socialsConfig();const credentials=readCredentials(config,"twitter",name);if(!credentials.clientId){return fail(`Identity '${name}' has no X client id, so there is nothing to start a consent flow with.`,"Set SOCIALS_"+name.toUpperCase().replace(/[^A-Z0-9]/g,"")+"_TWITTER_CLIENT_ID (and _CLIENT_SECRET for a confidential app) first.")}const state=newState();const{url,codeVerifier}=await startTwitterAuthorization({clientId:credentials.clientId,redirectUrl,state});log.info(`Authorizing '${name}' on X, asking for: ${TWITTER_PUBLISH_SCOPES.join(" ")}`);log.info(`The app's registered redirect URI must be exactly ${redirectUrl}`);await log.flush();process.stdout.write(`
|
|
3
3
|
Open this and approve:
|
|
4
4
|
|
|
5
5
|
${url}
|
|
6
6
|
|
|
7
7
|
Waiting for the redirect...
|
|
8
|
-
`);const outcome=await new Promise((resolve)=>{const timer=setTimeout(()=>{resolve({ok
|
|
8
|
+
`);const outcome=await new Promise((resolve)=>{const timer=setTimeout(()=>{resolve({ok:false,message:`Nothing came back within ${Math.round(timeoutMs/1000)}s.`})},timeoutMs);let server;const settle=(value)=>{clearTimeout(timer);resolve(value);setTimeout(()=>server?.stop(true),500).unref()};try{server=Bun.serve({port,hostname:"127.0.0.1",fetch(request){const reading=readCallback(request.url,state);if(!reading.ok&&reading.reason==="not-the-callback"){return new Response("Not found",{status:404})}if(!reading.ok){settle({ok:false,message:reading.message});return new Response(callbackPage("Could not authorize",reading.message),{status:400,headers:{"content-type":"text/html; charset=utf-8"}})}settle({ok:true,code:reading.code});return new Response(callbackPage("Authorized","You can close this tab and go back to the terminal."),{headers:{"content-type":"text/html; charset=utf-8"}})}})}catch(error){const message=error instanceof Error?error.message:String(error);clearTimeout(timer);resolve({ok:false,message:`Could not listen on ${port}: ${message}`})}});if(!outcome.ok)return fail(outcome.message,`Run it again when you are ready; nothing was changed.`);let authorized;try{authorized=await completeTwitterAuthorization({clientId:credentials.clientId,clientSecret:credentials.clientSecret,redirectUrl,code:outcome.code,codeVerifier})}catch(error){return fail(`X refused the exchange: ${error instanceof Error?error.message:String(error)}`,"The authorization code is single-use, so start over rather than retrying.")}log.success(`Authorized @${authorized.handle} (${authorized.accountId}) for identity '${name}'`);if(!authorized.renewable){log.warn("X returned no refresh token, so this access token cannot be renewed.");log.info("Add `offline.access` to the app's scopes and run this again, or the identity stops posting in a couple of hours.")}await log.flush();const lines=envLines(name,"twitter",{accessToken:authorized.accessToken,refreshToken:authorized.refreshToken});process.stdout.write(`
|
|
9
9
|
${lines.map((line)=>` ${line}`).join(`
|
|
10
10
|
`)}
|
|
11
11
|
|
package/dist/commands/stacks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{installStack,listStacks,uninstallStack}from"@stacksjs/actions";import{intro,italic,onUnknownSubcommand,outro}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function stacks(buddy){const descriptions={install:"Install a stack into your project",uninstall:"Uninstall a stack from your project",list:"List available and installed stacks",force:"Force overwrite existing files",dryRun:"Show what would be installed without making changes",conflict:"Conflict resolution strategy: skip, overwrite, or backup",verbose:"Enable verbose output",project:"Target a specific Stacks project"};buddy.command("stack:install <name>",descriptions.install).option("--force",descriptions.force,{default
|
|
1
|
+
import process from"node:process";import{installStack,listStacks,uninstallStack}from"@stacksjs/actions";import{intro,italic,onUnknownSubcommand,outro}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function stacks(buddy){const descriptions={install:"Install a stack into your project",uninstall:"Uninstall a stack from your project",list:"List available and installed stacks",force:"Force overwrite existing files",dryRun:"Show what would be installed without making changes",conflict:"Conflict resolution strategy: skip, overwrite, or backup",verbose:"Enable verbose output",project:"Target a specific Stacks project"};buddy.command("stack:install <name>",descriptions.install).option("--force",descriptions.force,{default:false}).option("--dry-run",descriptions.dryRun,{default:false}).option("--conflict <strategy>",descriptions.conflict,{default:"skip"}).option("-p, --project <path>",descriptions.project).option("--verbose",descriptions.verbose,{default:false}).example("buddy add calendar").example("buddy add table --force").example("buddy add calendar --conflict backup --verbose").example("buddy add table --dry-run").action(async(name,options)=>{const perf=await intro("buddy stack:install");if(!name){await log.error("You need to specify a stack name.");log.info("Example: buddy add calendar");await log.flush();process.exit(ExitCode.FatalError)}const result=await installStack({name,force:options.force,dryRun:options.dryRun,conflict:options.conflict||"skip",project:options.project,verbose:options.verbose});if(!result&&!options.dryRun){await outro("Failed to install stack",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Stack ${italic(name)} installed.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("stack:uninstall <name>",descriptions.uninstall).option("--force",descriptions.force,{default:false}).option("-p, --project <path>",descriptions.project).option("--verbose",descriptions.verbose,{default:false}).example("buddy stack:uninstall blog").example("buddy stack:uninstall blog --force").action(async(name,options)=>{const perf=await intro("buddy stack:uninstall");if(!name){await log.error("You need to specify a stack name.");process.exit(ExitCode.FatalError)}const result=await uninstallStack({name,force:options.force,project:options.project,verbose:options.verbose});if(!result){await outro("Failed to uninstall stack",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Stack ${italic(name)} uninstalled.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("stack:list",descriptions.list).alias("stack:ls").option("-p, --project <path>",descriptions.project).example("buddy stack:list").action(async(options)=>{const perf=await intro("buddy stack:list");const entries=await listStacks(options.project);if(entries.length===0){log.info("No stacks found. Install one with: buddy add <name>")}else{log.info(`Found ${entries.length} stack(s):`);log.info("");for(const entry of entries){const status=entry.installed?"[installed]":"[available]";const desc=entry.description?` - ${entry.description}`:"";const files=entry.fileCount?` (${entry.fileCount} files)`:"";log.info(` ${entry.name} ${italic(`v${entry.version}`)} ${status}${files}${desc}`)}}await outro("",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"stack")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,readdirSync,rmSync,statSync}from"node:fs";import{isAbsolute,join,resolve}from"node:path";import process from"node:process";import{intro,log,outro}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";import{backupObjectKey,parseBackupDestination}from"../database-backup";import{isStorageBackupFileName,prunableStorageBackups,resolveStorageTarget,storageBackupFileName}from"../storage-backup";const DEFAULT_BACKUP_DIR="storage/backups/storage"
|
|
1
|
+
import{existsSync,mkdirSync,readdirSync,rmSync,statSync}from"node:fs";import{isAbsolute,join,resolve}from"node:path";import process from"node:process";import{intro,log,outro}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";import{backupObjectKey,parseBackupDestination}from"../database-backup";import{isStorageBackupFileName,prunableStorageBackups,resolveStorageTarget,storageBackupFileName}from"../storage-backup";const DEFAULT_BACKUP_DIR="storage/backups/storage";const DEFAULT_RETAIN=7;function backupDir(out){const dir=out?.trim()||DEFAULT_BACKUP_DIR;return isAbsolute(dir)?dir:resolve(process.cwd(),dir)}function existingBackups(dir){if(!existsSync(dir))return[];return readdirSync(dir).filter(isStorageBackupFileName)}function prune(dir,retain,disk){const removed=prunableStorageBackups(existingBackups(dir),retain,disk);for(const name of removed)rmSync(join(dir,name),{force:true});return removed}function humanSize(bytes){if(bytes<1024)return`${bytes} B`;const units=["KB","MB","GB","TB"];let value=bytes/1024;let unit=0;while(value>=1024&&unit<units.length-1){value/=1024;unit++}return`${value.toFixed(1)} ${units[unit]}`}async function uploadBackup(destinationUri,file,fileName){const destination=parseBackupDestination(destinationUri);const{Storage}=await import("@stacksjs/storage");const key=backupObjectKey(destination,fileName);const diskName=destination.kind==="disk"?destination.target:"s3";const disk=Storage.disk(diskName);if(typeof disk.putStream!=="function"){throw new TypeError(`The '${diskName}' disk cannot stream uploads, so a storage archive cannot be copied to it. Use an S3-backed disk for the destination.`)}await disk.putStream(key,Bun.file(file).stream());return destination.kind==="disk"?`disk://${destination.target}/${key}`:`s3://${destination.target}/${key}`}export function storageBackup(buddy){buddy.command("storage:backup [disk]","Archive a storage disk to a file").option("--out [dir]",`Where to write the archive (default: ${DEFAULT_BACKUP_DIR})`).option("--retain [count]","How many archives to keep, per disk",{default:String(DEFAULT_RETAIN)}).option("--destination [uri]","Copy the archive offsite: s3://bucket/prefix or disk://name/prefix").option("--verbose","Enable verbose output",{default:false}).example("buddy storage:backup").example("buddy storage:backup public --retain 30").example("buddy storage:backup --destination disk://backups/uploads").action(async(disk,options)=>{const perf=await intro("buddy storage:backup");const diskName=disk?.trim()||"local";try{const resolution=resolveStorageTarget(config.filesystems,diskName,process.cwd());if(!resolution.ok){await log.error(resolution.refusal.reason);process.exit(ExitCode.InvalidArgument)}const{root}=resolution.target;if(!existsSync(root)){await outro(`Nothing to archive: ${root} does not exist yet`,{startTime:perf,useSeconds:true});return}const dir=backupDir(options.out);mkdirSync(dir,{recursive:true});const fileName=storageBackupFileName(diskName,new Date);const file=join(dir,fileName);const entries=readdirSync(root);if(entries.length===0){await outro(`Nothing to archive: ${root} is empty`,{startTime:perf,useSeconds:true});return}const{zip}=await import("@stacksjs/storage");const result=await zip(entries,file,{cwd:root});if(result.isErr){await log.error(`Could not archive ${root}: ${result.error}`);process.exit(ExitCode.FatalError)}const size=statSync(file).size;log.success(`Archived ${diskName} (${humanSize(size)}) to ${file}`);if(options.destination){const uri=await uploadBackup(options.destination,file,fileName);log.success(`Copied to ${uri}`)}const retain=Number.parseInt(options.retain??String(DEFAULT_RETAIN),10);const removed=prune(dir,retain,diskName);if(removed.length>0&&options.verbose)log.info(`Pruned ${removed.length} older ${diskName} archive(s)`);await outro("Storage backup complete",{startTime:perf,useSeconds:true})}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}});buddy.command("storage:backups","List the storage archives that have been taken").option("--out [dir]",`Where the archives are (default: ${DEFAULT_BACKUP_DIR})`).action(async(options)=>{const dir=backupDir(options.out);const backups=existingBackups(dir).sort().reverse();if(backups.length===0){log.info(`No storage archives in ${dir}`);return}const{table}=await import("@stacksjs/cli");console.log(table(backups.map((name)=>({archive:name,size:humanSize(statSync(join(dir,name)).size)})),{columns:[{key:"archive",header:"Archive"},{key:"size",header:"Size",align:"right"}]}))});buddy.command("storage:restore <archive> [disk]","Restore a storage disk from an archive").option("--out [dir]",`Where the archives are (default: ${DEFAULT_BACKUP_DIR})`).option("--force","Restore even though it overwrites files that are there now",{default:false}).example("buddy storage:restore 2026-09-10T08-15-00-000.local.zip").action(async(archive,disk,options)=>{const perf=await intro("buddy storage:restore");try{const diskName=disk?.trim()||"local";const resolution=resolveStorageTarget(config.filesystems,diskName,process.cwd());if(!resolution.ok){await log.error(resolution.refusal.reason);process.exit(ExitCode.InvalidArgument)}const dir=backupDir(options.out);const file=isAbsolute(archive)?archive:join(dir,archive);if(!existsSync(file)){await log.error(`No such archive: ${file}`);process.exit(ExitCode.InvalidArgument)}const{root}=resolution.target;if(!options.force&&existsSync(root)&&readdirSync(root).length>0){await log.error(`${root} is not empty. Restoring merges the archive over what is there, which cannot be undone. Re-run with --force once you are sure this is the right disk.`);process.exit(ExitCode.InvalidArgument)}mkdirSync(root,{recursive:true});const{unzip}=await import("@stacksjs/storage");const result=await unzip([file],{cwd:root});if(result.isErr){await log.error(`Could not restore ${file}: ${result.error}`);process.exit(ExitCode.FatalError)}log.success(`Restored ${diskName} from ${file}`);await outro("Storage restore complete",{startTime:perf,useSeconds:true})}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand}from"@stacksjs/cli";const telemetry={async enable(){},async disable(){},async status(){return{enabled
|
|
1
|
+
import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand}from"@stacksjs/cli";const telemetry={async enable(){},async disable(){},async status(){return{enabled:false,doNotTrack:!!process.env.DO_NOT_TRACK,eventsQueued:0,lastSent:null}}};export function telemetryCommand(buddy){buddy.command("telemetry","Manage telemetry settings").option("--enable","Enable telemetry").option("--disable","Disable telemetry").option("--status","Show telemetry status").example("buddy telemetry --status").example("buddy telemetry --enable").example("buddy telemetry --disable").action(async(options)=>{log.debug("Running `buddy telemetry` ...",options);await intro("buddy telemetry");try{if(options.enable){await telemetry.enable();log.success("Telemetry enabled");log.info("");log.info(dim("Anonymous usage statistics will be collected"));log.info(dim("to help improve Buddy CLI."));log.info("");log.info(dim("You can disable telemetry anytime with:"));log.info(dim(" buddy telemetry --disable"));log.info("");return}if(options.disable){await telemetry.disable();log.success("Telemetry disabled");log.info("");log.info(dim("No usage statistics will be collected."));log.info("");return}const status=await telemetry.status();log.info("");log.info(green(bold("Telemetry Status")));log.info(dim("─".repeat(50)));log.info("");log.info(bold("Configuration:"));log.info(` Enabled: ${dim(status.enabled?"Yes":"No")}`);log.info(` DO_NOT_TRACK: ${dim(status.doNotTrack?"Yes (respected)":"No")}`);log.info(` Events queued: ${dim(status.eventsQueued)}`);if(status.lastSent){const lastSent=new Date(status.lastSent);log.info(` Last sent: ${dim(lastSent.toLocaleString())}`)}else{log.info(` Last sent: ${dim("Never")}`)}log.info("");log.info(bold("Privacy:"));log.info(` ${dim("• Opt-in only (disabled by default)")}`);log.info(` ${dim("• No personal information collected")}`);log.info(` ${dim("• Anonymous user IDs only")}`);log.info(` ${dim("• Respects DO_NOT_TRACK environment variable")}`);log.info("");if(!status.enabled){log.info(dim("To enable telemetry: buddy telemetry --enable"));log.info("")}else{log.info(dim("To disable telemetry: buddy telemetry --disable"));log.info("")}}catch(error){await log.error("Failed to manage telemetry:",error);process.exit(1)}});onUnknownSubcommand(buddy,"telemetry")}
|
package/dist/commands/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";function testPathEnv(paths){return paths?.length?{STACKS_TEST_PATHS:JSON.stringify(paths)}:
|
|
1
|
+
import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";function testPathEnv(paths){return paths?.length?{STACKS_TEST_PATHS:JSON.stringify(paths)}:undefined}function scopedTests(label,paths){if(!paths?.length)return label;return`${label} for ${paths.length===1?paths[0]:`${paths.length} paths`}`}export function test(buddy){const descriptions={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("test [...paths]",descriptions.command).option("-f, --feature",descriptions.feature,{default:false}).option("-u, --unit",descriptions.unit,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:true}).example("buddy test").example("buddy test tests/unit/auth.test.ts").example("buddy test storage/framework/core/scheduler/tests").action(async(paths,options)=>{const perf=await intro("buddy test");const env=testPathEnv(paths);if(options.feature&&options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}}if(options.feature&&!options.unit){log.info("Running Feature tests...");const result=await runAction(Action.TestFeature,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&options.unit){log.info("Running Unit tests...");const result=await runAction(Action.TestUnit,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&!options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}}await outro(scopedTests("Finished running tests",paths),{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("test:unit [...paths]",descriptions.unit).option("--verbose",descriptions.verbose,{default:false}).example("buddy test:unit").example("buddy test:unit tests/unit/auth.test.ts").action(async(paths,options)=>{const perf=await intro("buddy test:unit");const result=await runAction(Action.TestUnit,{...options,verbose:true,cwd:projectPath(),env:testPathEnv(paths)});if(resultFailed(result)){await outro("While running `buddy test:unit`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(scopedTests("Finished running unit tests",paths),{startTime:perf,useSeconds:true})});buddy.command("test:feature [...paths]",descriptions.feature).option("--verbose",descriptions.verbose,{default:false}).example("buddy test:feature").example("buddy test:feature tests/feature/login.test.ts").action(async(paths,options)=>{const perf=await intro("buddy test:feature");const result=await runAction(Action.TestFeature,{...options,verbose:true,cwd:projectPath(),env:testPathEnv(paths)});if(resultFailed(result)){await outro("While running `buddy test:feature`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(scopedTests("Finished running feature tests",paths),{startTime:perf,useSeconds:true})});buddy.command("test:ui",descriptions.command).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{const perf=await intro("buddy test:ui");const result=await runAction(Action.TestUi,{...options,verbose:true,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:ui`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running tests in the browser",{startTime:perf,useSeconds:true})});buddy.command("test:types",descriptions.types).alias("typecheck").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{const perf=await intro("buddy test:types");const result=await runAction(Action.Typecheck,{...options,verbose:true,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:types`, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running typecheck",{startTime:perf,useSeconds:true})});buddy.command("test:page-audit","Loads pages in headless Chrome and reports duplicate API requests, failed requests and console errors").option("--url <urls>","Page URLs to audit, comma-separated (paths resolve against --base)").option("--base [base]","Origin that paths in --url resolve against",{default:"http://localhost:3000"}).option("--quiet-ms [ms]","How long the network must stay quiet before a page counts as loaded",{default:1000}).option("--timeout [ms]","Give up waiting for a page to settle after this long",{default:15000}).option("--mobile","Audit at a 390px phone viewport instead of 1440px",{default:false}).option("--json","Print the reports as JSON",{default:false}).example("buddy test:page-audit --url /,/dashboard --base http://localhost:3000").example("buddy test:page-audit --url http://localhost:3000/pricing --json").action(async(options)=>{const targets=String(options.url??"").split(",").map((url)=>url.trim()).filter(Boolean);if(!targets.length){await log.error("Pass the pages to audit with --url (comma-separated URLs or paths)");process.exit(ExitCode.InvalidArgument)}const{auditPage,formatPageAudit,launch,pageAuditClean}=await import("@stacksjs/testing/browser");const viewport=options.mobile?{width:390,height:844,mobile:true,deviceScaleFactor:2}:{width:1440,height:900};const{cdp,close}=await launch({viewport});const reports=[];try{for(const target of targets){const url=new URL(target,options.base||"http://localhost:3000").href;const report=await auditPage(url,{cdp,quietMs:Number(options.quietMs)||1000,timeoutMs:Number(options.timeout)||15000});reports.push(report);if(!options.json)await log.info(formatPageAudit(report))}}finally{await close()}if(options.json)process.stdout.write(`${JSON.stringify(reports,null,2)}
|
|
2
2
|
`);process.exit(reports.every(pageAuditClean)?ExitCode.Success:ExitCode.FatalError)});onUnknownSubcommand(buddy,"test")}
|
package/dist/commands/tinker.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function tinker(buddy){const descriptions={tinker:"Interactive REPL with Stacks framework preloaded",eval:"Evaluate a single expression and exit",print:"Evaluate, print, and exit",noBanner:"Skip the welcome banner",preload:"Additional modules to preload (comma-separated)",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("tinker",descriptions.tinker).option("-e, --eval [expression]",descriptions.eval,{default:""}).option("--print [expression]",descriptions.print,{default:""}).option("--no-banner",descriptions.noBanner).option("--preload [modules]",descriptions.preload,{default:""}).option("--verbose",descriptions.verbose,{default
|
|
1
|
+
import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function tinker(buddy){const descriptions={tinker:"Interactive REPL with Stacks framework preloaded",eval:"Evaluate a single expression and exit",print:"Evaluate, print, and exit",noBanner:"Skip the welcome banner",preload:"Additional modules to preload (comma-separated)",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("tinker",descriptions.tinker).option("-e, --eval [expression]",descriptions.eval,{default:""}).option("--print [expression]",descriptions.print,{default:""}).option("--no-banner",descriptions.noBanner).option("--preload [modules]",descriptions.preload,{default:""}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy tinker` ...",options);const perf=await intro("buddy tinker");try{const{startTinker}=await import("@stacksjs/tinker");const preloadModules=typeof options.preload==="string"&&options.preload?options.preload.split(",").map((m)=>m.trim()):undefined;const result=await startTinker({eval:typeof options.eval==="string"&&options.eval?options.eval:undefined,print:typeof options.print==="string"&&options.print?options.print:undefined,banner:options.banner!==false,preload:preloadModules,verbose:options.verbose===true});if(result.exitCode!==0){await outro("Tinker session ended with errors",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("Tinker session ended.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}catch(error){await outro("While running the tinker command, there was an issue",{startTime:perf,useSeconds:true},error instanceof Error?error:undefined);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"tinker")}
|
package/dist/commands/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";import{runTypeGeneration}from"./generate";export function types(buddy){const descriptions={generate:"Generate the types of & for your library/libraries",fix:"Fix the generated types of & for your library/libraries (not yet implemented)",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("types:generate",descriptions.generate).option("-p, --project [project]",descriptions.project,{default
|
|
1
|
+
import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";import{runTypeGeneration}from"./generate";export function types(buddy){const descriptions={generate:"Generate the types of & for your library/libraries",fix:"Fix the generated types of & for your library/libraries (not yet implemented)",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("types:generate",descriptions.generate).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 types:generate` ...",options);await runTypeGeneration(options)});buddy.command("types:fix",descriptions.fix).option("--verbose",descriptions.verbose,{default:false}).action(async()=>{});onUnknownSubcommand(buddy,"types")}
|
package/dist/commands/upgrade.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 upgrade(buddy){const descriptions={upgrade:"Upgrade the Stacks framework to the latest version",version:"Install a specific version (e.g., 0.70.23)",canary:"Upgrade to the latest canary (bleeding-edge `main`) build",stable:"Switch to the latest vetted stable release",dryRun:"Preview the upgrade (which dependencies would change) without writing or installing",allowDowngrade:"Accept a release that moves a dependency this app declares to an older version (refused by default)",force:"Force re-download, bypassing cache and version checks",from:"Sync from a local stacks checkout (e.g. ~/Code/stacks). Skips GitHub.",noPostinstall:"Skip post-sync hooks (auto-imports,
|
|
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 upgrade(buddy){const descriptions={upgrade:"Upgrade the Stacks framework to the latest version",version:"Install a specific version (e.g., 0.70.23)",canary:"Upgrade to the latest canary (bleeding-edge `main`) build",stable:"Switch to the latest vetted stable release",dryRun:"Preview the upgrade (which dependencies would change) without writing or installing",allowDowngrade:"Accept a release that moves a dependency this app declares to an older version (refused by default)",force:"Force re-download, bypassing cache and version checks",from:"Sync from a local stacks checkout (e.g. ~/Code/stacks). Skips GitHub.",noPostinstall:"Skip dependency installation and post-sync hooks (auto-imports, database types, migrations, AI setup)",verbose:"Enable verbose output",dependencies:"Upgrade your dependencies (pantry.yaml & package.json)",bun:"Upgrade Bun to the latest version",shell:"Upgrade the shell integration (currently only supports Oh My Zsh)",binary:"Upgrade the `stacks` binary to the latest version",project:"Target a specific project",all:"Upgrade framework, dependencies, Bun, and binary"};buddy.command("upgrade",descriptions.upgrade).option("-V, --version <version>",descriptions.version).option("--canary",descriptions.canary,{default:false}).option("--stable",descriptions.stable,{default:false}).option("--dry-run",descriptions.dryRun,{default:false}).option("--allow-downgrade",descriptions.allowDowngrade,{default:false}).option("-f, --force",descriptions.force,{default:false}).option("--from <path>",descriptions.from).option("--no-postinstall",descriptions.noPostinstall).option("--verbose",descriptions.verbose,{default:false}).alias("update").example("buddy upgrade").example("buddy update").example("buddy upgrade --from ~/Code/stacks").example("buddy upgrade --version 0.70.23").example("buddy upgrade --dry-run").example("buddy upgrade --allow-downgrade").example("buddy upgrade --canary").example("buddy upgrade --stable").example("buddy upgrade --force").action(async(options)=>{log.debug("Running `buddy upgrade` ...",options);const opts={...options};if(opts.postinstall===false){delete opts.postinstall;opts.noPostinstall=true}const perf=await intro("buddy upgrade");const result=await runAction(Action.UpgradeFramework,opts);if(resultFailed(result)){await outro("While running buddy upgrade, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Upgrade complete.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("upgrade:all",descriptions.all).option("--canary",descriptions.canary,{default:false}).option("-f, --force",descriptions.force,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy upgrade:all").action(async(options)=>{log.debug("Running `buddy upgrade:all` ...",options);const perf=await intro("buddy upgrade:all");options.all=true;const result=await runAction(Action.Upgrade,options);if(resultFailed(result)){await outro("While running buddy upgrade:all, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("All upgrades complete.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("upgrade:dependencies",descriptions.dependencies).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).alias("upgrade:deps").example("buddy upgrade:dependencies").action(async(options)=>{log.debug("Running `buddy upgrade:dependencies` ...",options);const perf=await intro("buddy upgrade:dependencies");options.dependencies=true;const result=await runAction(Action.Upgrade,options);if(resultFailed(result)){await outro("While running buddy upgrade:dependencies, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Dependencies upgraded.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("upgrade:bun",descriptions.bun).option("--verbose",descriptions.verbose,{default:false}).example("buddy upgrade:bun").action(async(options)=>{log.debug("Running `buddy upgrade:bun` ...",options);const perf=await intro("buddy upgrade:bun");const result=await runAction(Action.UpgradeBun,options);if(resultFailed(result)){await outro("While running buddy upgrade:bun, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Bun upgraded.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("upgrade:shell",descriptions.shell).option("--verbose",descriptions.verbose,{default:false}).example("buddy upgrade:shell").action(async(options)=>{log.debug("Running `buddy upgrade:shell` ...",options);const perf=await intro("buddy upgrade:shell");const result=await runAction(Action.UpgradeShell,options);if(resultFailed(result)){await outro("While running buddy upgrade:shell, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Shell integration upgraded.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("upgrade:binary",descriptions.binary).option("--verbose",descriptions.verbose,{default:false}).example("buddy upgrade:binary").action(async(options)=>{if(process.getuid&&process.getuid()!==0){log.warn("To upgrade the binary, you need to run this command with sudo, or as root.");await log.flush();process.exit(ExitCode.FatalError)}log.debug("Running `buddy upgrade:binary` ...",options);const perf=await intro("buddy upgrade:binary");const result=await runAction(Action.UpgradeBinary,options);if(resultFailed(result)){await outro("While running buddy upgrade:binary, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Binary upgraded.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"upgrade")}
|
package/dist/commands/user.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";function generatePassword(){return randomBytes(18).toString("base64url")}async function loadUserModel(){const{existsSync}=await import("node:fs")
|
|
1
|
+
import{randomBytes}from"node:crypto";import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";function generatePassword(){return randomBytes(18).toString("base64url")}async function loadUserModel(){const{existsSync}=await import("node:fs");const{join}=await import("node:path");const candidates=[join(process.cwd(),"app/Models/User.ts"),join(process.cwd(),"storage/framework/defaults/app/Models/User.ts"),join(process.cwd(),"node_modules/@stacksjs/defaults/app/Models/User.ts")];for(const candidate of candidates){if(!existsSync(candidate))continue;const loaded=(await import(candidate)).default;if(loaded?.where)return loaded}const{User}=await import("@stacksjs/orm");if(User)return User;await log.error("Could not find a User model. Looked in app/Models, the framework defaults and @stacksjs/orm.");await log.flush();process.exit(ExitCode.FatalError)}export function user(buddy){buddy.command("user:add <email>","Create a user account (optionally an admin)").option("--name <name>","Display name. Defaults to the local part of the email.").option("--password <password>","Password. Generated and printed once if omitted.").option("--role <role>","Role to assign, e.g. admin. Seeds the default roles if the table is empty.").option("--update","If the account already exists, reset its password and ensure the role",{default:false}).example("buddy user:add chris@example.com --role admin").example("buddy user:add support@example.com --name Support --password s3cret").action(async(email,options)=>{const address=String(email||"").trim().toLowerCase();if(!address.includes("@")){await log.error(`\`${email}\` is not an email address.`);await log.flush();process.exit(ExitCode.FatalError)}const password=options.password||generatePassword();const generated=!options.password;const name=options.name||address.split("@")[0];const User=await loadUserModel();let account=await User.where("email",address).first();if(account&&!options.update){await log.error(`${address} already exists. Pass --update to reset its password and role.`);await log.flush();process.exit(ExitCode.FatalError)}if(account){await User.where("email",address).update({password});log.success(`Updated ${address}`)}else{await User.create({email:address,name,password});account=await User.where("email",address).first();log.success(`Created ${address}`)}if(options.role){const{createBqbRbacStore,Rbac,seedDefaultRoles}=await import("@stacksjs/auth");try{Rbac.setStore(createBqbRbacStore());await seedDefaultRoles();await Rbac.assignRole(account,options.role);log.success(`Assigned the ${options.role} role`)}catch(error){log.error(`Could not assign the ${options.role} role: ${error instanceof Error?error.message:String(error)}`);log.info("The account exists; assign the role once the roles tables are migrated.")}}if(generated){process.stdout.write(`
|
|
2
2
|
${address}
|
|
3
3
|
${password}
|
|
4
4
|
|
|
5
|
-
`);log.info("That password is shown once. Store it in a password manager now.")}await log.flush();process.exit(ExitCode.Success)});buddy.command("user:list","List the accounts that can sign in").option("--limit <limit>","How many to show",{default:"25"}).action(async(options)=>{const User=await loadUserModel()
|
|
5
|
+
`);log.info("That password is shown once. Store it in a password manager now.")}await log.flush();process.exit(ExitCode.Success)});buddy.command("user:list","List the accounts that can sign in").option("--limit <limit>","How many to show",{default:"25"}).action(async(options)=>{const User=await loadUserModel();const limit=Number(options.limit)||25;const rows=await User.orderBy("id").limit(limit).get();if(rows.length===0){log.info("No accounts yet. Create one with `buddy user:add <email> --role admin`.");await log.flush();process.exit(ExitCode.Success)}for(const row of rows)process.stdout.write(` ${String(row.id).padStart(4)} ${String(row.email).padEnd(34)} ${row.name??""}
|
|
6
6
|
`);await log.flush();process.exit(ExitCode.Success)})}
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{pathToFileURL}from"node:url";import{log}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";export async function loadProjectDnsConfig(fallback){const configPath=p.projectConfigPath("dns.ts");if(!existsSync(configPath))return fallback;const loaded=await import(`${pathToFileURL(configPath).href}?updated=${Date.now()}`);return loaded.default??loaded.dns??fallback}export function validateConfig(config){const errors=[];if(typeof config!=="object"||config===null){errors.push({path:"config",message:"Config must be an object",value:config});return errors}const candidate=config;if(candidate.theme!==
|
|
1
|
+
import{existsSync}from"node:fs";import{pathToFileURL}from"node:url";import{log}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";export async function loadProjectDnsConfig(fallback){const configPath=p.projectConfigPath("dns.ts");if(!existsSync(configPath))return fallback;const loaded=await import(`${pathToFileURL(configPath).href}?updated=${Date.now()}`);return loaded.default??loaded.dns??fallback}export function validateConfig(config){const errors=[];if(typeof config!=="object"||config===null){errors.push({path:"config",message:"Config must be an object",value:config});return errors}const candidate=config;if(candidate.theme!==undefined){const validThemes=["default","dracula","nord","solarized","monokai"];if(typeof candidate.theme!=="string"||!validThemes.includes(candidate.theme)){errors.push({path:"theme",message:`Theme must be one of: ${validThemes.join(", ")}`,value:candidate.theme})}}if(candidate.emoji!==undefined&&typeof candidate.emoji!=="boolean"){errors.push({path:"emoji",message:"Emoji must be a boolean",value:candidate.emoji})}if(candidate.commands!==undefined){if(!Array.isArray(candidate.commands)){errors.push({path:"commands",message:"Commands must be an array",value:candidate.commands})}else{candidate.commands.forEach((cmd,index)=>{if(typeof cmd!=="function"){errors.push({path:`commands[${index}]`,message:"Each command must be a function",value:cmd})}})}}if(candidate.defaultFlags!==undefined){if(typeof candidate.defaultFlags!=="object"||candidate.defaultFlags===null){errors.push({path:"defaultFlags",message:"Default flags must be an object",value:candidate.defaultFlags})}else{const defaultFlags=candidate.defaultFlags;const flagKeys=["verbose","quiet","debug"];for(const key of Object.keys(defaultFlags)){if(!flagKeys.includes(key)){errors.push({path:`defaultFlags.${key}`,message:`Unknown flag. Valid flags are: ${flagKeys.join(", ")}`,value:defaultFlags[key]})}else if(typeof defaultFlags[key]!=="boolean"){errors.push({path:`defaultFlags.${key}`,message:"Flag value must be a boolean",value:defaultFlags[key]})}}}}if(candidate.aliases!==undefined){if(typeof candidate.aliases!=="object"||candidate.aliases===null||Array.isArray(candidate.aliases)){errors.push({path:"aliases",message:"Aliases must be an object mapping alias names to command names",value:candidate.aliases})}else{for(const[alias,command]of Object.entries(candidate.aliases)){if(typeof command!=="string"){errors.push({path:`aliases.${alias}`,message:"Alias target must be a string",value:command})}}}}if(candidate.plugins!==undefined){if(!Array.isArray(candidate.plugins)){errors.push({path:"plugins",message:"Plugins must be an array",value:candidate.plugins})}else{candidate.plugins.forEach((plugin,index)=>{if(typeof plugin==="string"){return}if(typeof plugin!=="object"||plugin===null){errors.push({path:`plugins[${index}]`,message:"Each plugin must be an object or a string (module path)",value:plugin});return}if(!plugin.name||typeof plugin.name!=="string"){errors.push({path:`plugins[${index}].name`,message:"Plugin must have a name property of type string",value:plugin.name})}if(!plugin.setup||typeof plugin.setup!=="function"){errors.push({path:`plugins[${index}].setup`,message:"Plugin must have a setup function",value:plugin.setup})}if(plugin.hooks!==undefined){if(typeof plugin.hooks!=="object"||plugin.hooks===null){errors.push({path:`plugins[${index}].hooks`,message:"Plugin hooks must be an object",value:plugin.hooks})}}})}}const validKeys=["theme","emoji","commands","defaultFlags","aliases","plugins"];for(const key of Object.keys(config)){if(!validKeys.includes(key)){errors.push({path:key,message:`Unknown configuration key. Valid keys are: ${validKeys.join(", ")}`,value:candidate[key]})}}return errors}let cachedConfig=null;export async function loadBuddyConfig(){if(cachedConfig){return cachedConfig}const configPaths=[p.projectPath("buddy.config.ts"),p.projectPath("buddy.config.js"),p.projectPath(".buddy.config.ts"),p.projectPath(".buddy.config.js")];for(const configPath of configPaths){if(existsSync(configPath)){try{log.debug(`Loading buddy config from ${configPath}`);const configModule=await import(configPath);const config=configModule.default||configModule;const validationErrors=validateConfig(config);if(validationErrors.length>0){log.error("Invalid buddy.config.ts:");for(const error of validationErrors){log.error(` - ${error.path}: ${error.message}`)}throw new Error("Configuration validation failed")}cachedConfig=config;return config}catch(error){log.warn(`Failed to load buddy config from ${configPath}:`,error)}}}cachedConfig={};return cachedConfig}export async function loadPlugins(cli,config){if(!config.plugins||config.plugins.length===0){return}log.debug(`Loading ${config.plugins.length} plugin(s)`);for(const pluginConfig of config.plugins){let plugin;if(typeof pluginConfig==="string"){try{const pluginModule=await import(pluginConfig);plugin=pluginModule.default||pluginModule}catch(error){log.error(`Failed to load plugin from ${pluginConfig}:`,error);continue}}else{plugin=pluginConfig}try{log.debug(`Initializing plugin: ${plugin.name}${plugin.version?` v${plugin.version}`:""}`);await plugin.setup(cli);if(plugin.hooks){if(plugin.hooks.beforeCommand){cli.on("command:*",async(command)=>{if(plugin.hooks?.beforeCommand){await plugin.hooks.beforeCommand({command})}})}if(plugin.hooks.afterCommand){cli.on("command:*",async(command)=>{if(plugin.hooks?.afterCommand){await plugin.hooks.afterCommand({command})}})}}log.debug(`Plugin ${plugin.name} initialized successfully`)}catch(error){log.error(`Failed to initialize plugin ${plugin.name}:`,error)}}}export async function applyBuddyConfig(buddy){const config=await loadBuddyConfig();if(config.emoji!==undefined&&buddy.options.noEmoji===undefined){buddy.useEmoji=config.emoji}if(config.defaultFlags){if(config.defaultFlags.verbose&&!buddy.isVerbose){buddy.isVerbose=true}if(config.defaultFlags.quiet&&!buddy.isQuiet){buddy.isQuiet=true}if(config.defaultFlags.debug&&!buddy.isDebug){buddy.isDebug=true}}if(config.commands&&Array.isArray(config.commands)){for(const registerCommand of config.commands){if(typeof registerCommand==="function"){registerCommand(buddy)}}}if(config.aliases){for(const[alias,command]of Object.entries(config.aliases)){const targetCommand=buddy.commands.find((cmd)=>cmd.name===command);if(targetCommand&&!targetCommand.aliasNames.includes(alias)){targetCommand.aliasNames.push(alias)}}}}
|
package/dist/custom-cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{cli,loadCommands,log}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{fs}from"@stacksjs/storage";process.on("uncaughtException",handleError);process.on("unhandledRejection",handleError);async function main(){const buddy=cli(config.cli.name);if(!fs.existsSync(p.projectPath(config.cli.command)))fs.writeFileSync(p.projectPath(config.cli.command)
|
|
1
|
+
import process from"node:process";import{cli,loadCommands,log}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{fs}from"@stacksjs/storage";process.on("uncaughtException",handleError);process.on("unhandledRejection",handleError);async function main(){const buddy=cli(config.cli.name);if(!fs.existsSync(p.projectPath(config.cli.command)))fs.writeFileSync(p.projectPath(config.cli.command),`import('./storage/framework/core/buddy/src/custom-cli')`);await loadCommands(buddy,{commandsDir:p.appPath("Commands"),registryPath:p.appPath("Commands.ts"),onError:(message,error)=>log.error(`${message}:`,error),onDebug:(message)=>log.debug(message)});buddy.parse()}await main();
|
package/dist/database-backup.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import process from"node:process";const ENGINES={sqlite:"sqlite",postgres:"postgres",postgresql:"postgres",mysql:"mysql",mariadb:"mysql"};export function resolveBackupTarget(databaseConfig){const cfg=databaseConfig
|
|
2
|
-
`).map((l)=>l.trim()).filter(Boolean).map((l)=>bin&&l.startsWith(`${bin}: `)?l.slice(bin.length+2):l);if(!lines.length)return"";const errorAt=lines.findIndex((l)=>/^error\b|\berror:/i.test(l));if(errorAt===-1)return lines[lines.length-1]??"";const kept=[lines[errorAt]];for(const line of lines.slice(errorAt+1))if(/^(?:detail|hint):/i.test(line))kept.push(line)
|
|
1
|
+
import process from"node:process";const ENGINES={sqlite:"sqlite",postgres:"postgres",postgresql:"postgres",mysql:"mysql",mariadb:"mysql"};export function resolveBackupTarget(databaseConfig){const cfg=databaseConfig;const dialect=String(cfg?.default??"").trim().toLowerCase();const engine=ENGINES[dialect];if(!engine)return null;const connection=cfg?.connections?.[dialect];if(!connection)return null;if(engine==="sqlite"){const database=String(connection.database??"").trim();return database?{engine,database}:null}const database=String(connection.name??connection.database??"").trim();if(!database)return null;return{engine,database,host:String(connection.host??"127.0.0.1"),port:Number(connection.port)||(engine==="postgres"?5432:3306),username:String(connection.username??""),password:String(connection.password??"")}}export function backupFileName(target,at){const stamp=at.toISOString().replace(/[:.]/g,"-").replace("Z","");const extension=target.engine==="sqlite"?"sqlite":"sql.gz";return`${stamp}.${target.engine}.${extension}`}export function isBackupFileName(name){return/^\d{4}-\d{2}-\d{2}T[\d-]+\.(?:sqlite|postgres|mysql)\.(?:sqlite|sql|sql\.gz)$/.test(name)}export function isCompressedBackup(name){return name.endsWith(".gz")}export function dumpCommand(target){if(target.engine==="sqlite")return null;if(target.engine==="postgres"){return{bin:"pg_dump",args:["--host",String(target.host),"--port",String(target.port),"--username",String(target.username),"--no-owner","--no-acl",target.database],env:target.password?{PGPASSWORD:target.password}:{}}}return{bin:"mysqldump",args:[`--host=${target.host}`,`--port=${target.port}`,`--user=${target.username}`,"--single-transaction",target.database],env:target.password?{MYSQL_PWD:target.password}:{}}}export function restoreCommand(target){if(target.engine==="sqlite")return null;if(target.engine==="postgres"){return{bin:"psql",args:["--host",String(target.host),"--port",String(target.port),"--username",String(target.username),"--set","ON_ERROR_STOP=1",target.database],env:target.password?{PGPASSWORD:target.password}:{}}}return{bin:"mysql",args:[`--host=${target.host}`,`--port=${target.port}`,`--user=${target.username}`,`--database=${target.database}`],env:target.password?{MYSQL_PWD:target.password}:{}}}export async function writeDump(command,destination,password){const{renameSync,rmSync}=await import("node:fs");const partial=`${destination}.partial`;const proc=Bun.spawn([command.bin,...command.args],{env:{...process.env,...command.env},stdout:"pipe",stderr:"pipe"});try{const[,code,stderr]=await Promise.all([Bun.write(partial,new Response(proc.stdout.pipeThrough(new CompressionStream("gzip")))),proc.exited,new Response(proc.stderr).text()]);if(code!==0)throw new Error(withoutPassword(`${command.bin}: ${toolFailureDetail(stderr,command.bin)||`exit code ${code}`}`,password));renameSync(partial,destination)}finally{rmSync(partial,{force:true})}}export async function readDump(command,source,password){const dump=Bun.file(source).stream();const proc=Bun.spawn([command.bin,...command.args],{env:{...process.env,...command.env},stdin:isCompressedBackup(source)?dump.pipeThrough(new DecompressionStream("gzip")):dump,stdout:"pipe",stderr:"pipe"});const[code,stderr]=await Promise.all([proc.exited,new Response(proc.stderr).text()]);if(code!==0)throw new Error(withoutPassword(`${command.bin}: ${toolFailureDetail(stderr,command.bin)||`exit code ${code}`}`,password))}export function prunableBackups(existing,retain){if(!Number.isFinite(retain)||retain<1)return[];const backups=existing.filter(isBackupFileName).sort();const excess=backups.length-retain;return excess>0?backups.slice(0,excess):[]}export async function dumpSqlite(source,destination){const{Database}=await import("bun:sqlite");const database=new Database(source,{readonly:true});try{database.exec(`VACUUM INTO '${destination.replace(/'/g,"''")}'`)}finally{database.close()}}export async function restoreSqlite(source,live,stamp){const{existsSync,renameSync}=await import("node:fs");let displaced=null;if(existsSync(live)){displaced=`${live}.replaced-${stamp}`;renameSync(live,displaced)}await Bun.write(live,Bun.file(source));return displaced}export function withoutPassword(text,password){return password?text.split(password).join("***"):text}export function describeCommand(command){return[command.bin,...command.args].join(" ")}export function toolFailureDetail(stderr,bin){const lines=String(stderr).split(`
|
|
2
|
+
`).map((l)=>l.trim()).filter(Boolean).map((l)=>bin&&l.startsWith(`${bin}: `)?l.slice(bin.length+2):l);if(!lines.length)return"";const errorAt=lines.findIndex((l)=>/^error\b|\berror:/i.test(l));if(errorAt===-1)return lines[lines.length-1]??"";const kept=[lines[errorAt]];for(const line of lines.slice(errorAt+1)){if(/^(?:detail|hint):/i.test(line))kept.push(line)}return kept.join(" ")}export function parseBackupDestination(uri){const trimmed=uri.trim();const match=trimmed.match(/^(s3|disk):\/\/([^/]+)(?:\/(.*))?$/);if(!match){throw new Error(`Backup destination must be \`s3://bucket/prefix\` or \`disk://name/prefix\`, got ${JSON.stringify(uri)}. `+"A local path is not accepted here — `--out` already writes locally, and a second copy on the same disk "+"is not a backup of the box.")}const[,kind,target,rawPrefix=""]=match;const prefix=rawPrefix.replace(/^\/+|\/+$/g,"");if(!target){throw new Error(`Backup destination ${JSON.stringify(uri)} names no ${kind==="s3"?"bucket":"disk"}.`)}return{kind,target,prefix}}export function backupObjectKey(destination,fileName){return destination.prefix?`${destination.prefix}/${fileName}`:fileName}export const DEFAULT_RETAIN=7;export function resolveBackupRetain(databaseConfig,env={},flag){const configured=databaseConfig?.backups?.retain;const sources=[["--retain",flag],["DB_BACKUP_RETAIN",env.DB_BACKUP_RETAIN],["backups.retain",configured]];for(const[name,value]of sources){if(value===undefined||value===null||String(value).trim()==="")continue;const count=Number(String(value).trim());if(!Number.isInteger(count)||count<1)throw new Error(`${name} must be a whole number of dumps to keep, at least 1; got ${JSON.stringify(value)}.`);return count}return DEFAULT_RETAIN}export function resolveBackupDestination(databaseConfig,env={}){const configured=env.DB_BACKUP_DESTINATION??databaseConfig?.backups?.destination;if(typeof configured!=="string"||!configured.trim())return null;return parseBackupDestination(configured)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{confirmOrNull,log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function canPromptInteractively(){if(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID)return
|
|
1
|
+
import process from"node:process";import{confirmOrNull,log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function canPromptInteractively(){if(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID)return false;return Boolean(process.stdin.isTTY&&process.stdout.isTTY)}export function resolveCreatePolicy(){const value=String(process.env.DB_CREATE_DATABASE||"").toLowerCase();if(value==="always"||value==="true"||value==="1")return"always";if(value==="never"||value==="false"||value==="0")return"never";return"prompt"}function decide(create){process.env.STACKS_CREATE_DATABASE=create?"1":"0"}const UNANSWERED=Symbol("unanswered");async function confirmWithTimeout(message,timeoutMs){let timer;try{return await Promise.race([confirmOrNull({message,initial:true}).then((v)=>v===null?UNANSWERED:v),new Promise((resolve)=>{timer=setTimeout(()=>resolve(UNANSWERED),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}export async function preflightDatabase(options={}){const commandName=options.command||"migrate";const{canCreateDatabases,describeTarget,manualCreateHint,probeTargetDatabase,resolveConnectionTarget}=await import("@stacksjs/database");const target=resolveConnectionTarget();if(!target)return;const probe=await probeTargetDatabase(target);if(probe.ok||probe.kind!=="missing-database")return;const where=describeTarget(target);const standing=resolveCreatePolicy();if(standing==="never"){decide(false);return}if(options.createDatabase||standing==="always"){decide(true);return}if(!canPromptInteractively()){log.syncError(`The database "${target.database}" does not exist on ${where}.`);log.syncError("Refusing to create it in a non-interactive shell.");log.syncError(` Create it ahead of time, re-run with --create-database, or set DB_CREATE_DATABASE=always.`);log.syncError(` ${manualCreateHint(target)}`);process.exit(ExitCode.FatalError)}const permitted=await canCreateDatabases(target);if(permitted===false){log.syncError(`The database "${target.database}" does not exist on ${where}.`);log.syncError(`The user "${target.username}" is not allowed to create databases, so I cannot create it for you.`);log.syncError(` Grant it with: ALTER ROLE "${target.username}" CREATEDB;`);log.syncError(` Or create the database yourself with: ${manualCreateHint(target)}`);process.exit(ExitCode.FatalError)}log.warn(`The database "${target.database}" does not exist on ${where}.`);await log.flush();const timeoutMs=Number(process.env.DB_CREATE_DATABASE_TIMEOUT_MS||120000);const answer=await confirmWithTimeout("Would you like to create it?",timeoutMs);if(answer===UNANSWERED){log.syncError(`No answer after ${Math.round(timeoutMs/1000)}s, so nothing was created.`);log.syncError(` Re-run with --create-database, or set DB_CREATE_DATABASE=always, to skip this question.`);log.syncError(` ${manualCreateHint(target)}`);process.exit(ExitCode.FatalError)}const create=answer;if(!create){decide(false);log.info("Nothing was changed. Create it yourself with:");log.info(` ${manualCreateHint(target)}`);log.info(`Then re-run \`buddy ${commandName}\`, or re-run with --create-database to skip this question.`);await log.flush();process.exit(ExitCode.Success)}decide(true)}
|
package/dist/deploy-notify.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import process from"node:process";import{sendToDiscord,sendToSlack,sendToTeams}from"@stacksjs/chat";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function driverForWebhookUrl(url){let host="";try{host=new URL(url).hostname.toLowerCase()}catch{return"slack"}if(host.endsWith("discord.com")||host.endsWith("discordapp.com"))return"discord";if(host.endsWith("office.com")||host.endsWith("office365.com")||host.endsWith("outlook.com"))return"teams";return"slack"}export function resolveDeployNotifyConfig(env=process.env){const url=env.DEPLOY_WEBHOOK_URL?.trim();if(!url)return{};const rawDriver=env.DEPLOY_WEBHOOK_DRIVER?.trim().toLowerCase();
|
|
2
|
-
|
|
3
|
-
`)}export async function notifyDeployOutcome(outcome,config=resolveDeployNotifyConfig()){try{if(!config.url){log.debug("[deploy] no DEPLOY_WEBHOOK_URL set - skipping deploy notification");return
|
|
1
|
+
import process from"node:process";import{sendToDiscord,sendToSlack,sendToTeams}from"@stacksjs/chat";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function driverForWebhookUrl(url){let host="";try{host=new URL(url).hostname.toLowerCase()}catch{return"slack"}if(host.endsWith("discord.com")||host.endsWith("discordapp.com"))return"discord";if(host.endsWith("office.com")||host.endsWith("office365.com")||host.endsWith("outlook.com"))return"teams";return"slack"}export function resolveDeployNotifyConfig(env=process.env){const url=env.DEPLOY_WEBHOOK_URL?.trim();if(!url)return{};const rawDriver=env.DEPLOY_WEBHOOK_DRIVER?.trim().toLowerCase();const driver=rawDriver==="slack"||rawDriver==="discord"||rawDriver==="teams"?rawDriver:undefined;return{url,driver:driver??driverForWebhookUrl(url),notifyOn:env.DEPLOY_WEBHOOK_NOTIFY?.trim().toLowerCase()==="all"?"all":"failure"}}function summarizeError(error,limit=1200){if(error==null)return"No error detail was captured.";const text=error instanceof Error?error.stack||error.message:String(error);const trimmed=text.trim();return trimmed.length>limit?`${trimmed.slice(0,limit)}
|
|
2
|
+
… (truncated)`:trimmed}function formatDuration(ms){if(typeof ms!=="number"||!Number.isFinite(ms)||ms<0)return null;const total=Math.round(ms/1000);return total<60?`${total}s`:`${Math.floor(total/60)}m ${total%60}s`}function ciContext(env=process.env){const lines=[];const repo=env.GITHUB_REPOSITORY;const sha=env.GITHUB_SHA;if(repo&&sha)lines.push(`Commit: ${repo}@${sha.slice(0,7)}`);else if(sha)lines.push(`Commit: ${sha.slice(0,7)}`);if(repo&&env.GITHUB_RUN_ID)lines.push(`Run: ${env.GITHUB_SERVER_URL||"https://github.com"}/${repo}/actions/runs/${env.GITHUB_RUN_ID}`);return lines}export function buildDeployMessage(outcome,env=process.env){const failed=outcome.status==="failed";const target=[outcome.project,outcome.environment].filter(Boolean).join(" · ")||"project";const heading=failed?`\uD83D\uDD34 Deploy FAILED - ${target}`:`✅ Deploy succeeded - ${target}`;const lines=[heading];if(outcome.provider)lines.push(`Provider: ${outcome.provider}`);const duration=formatDuration(outcome.durationMs);if(duration)lines.push(`Duration: ${duration}`);lines.push(...ciContext(env));if(failed){lines.push("");lines.push("```");lines.push(summarizeError(outcome.error));lines.push("```");const envLabel=outcome.environment||"The target environment";lines.push(`${envLabel==="production"?"Production":envLabel} is still serving the previous release.`)}return lines.join(`
|
|
3
|
+
`)}export async function notifyDeployOutcome(outcome,config=resolveDeployNotifyConfig()){try{if(!config.url){log.debug("[deploy] no DEPLOY_WEBHOOK_URL set - skipping deploy notification");return false}const notifyOn=config.notifyOn??"failure";if(outcome.status==="succeeded"&¬ifyOn!=="all"){log.debug('[deploy] deploy succeeded and DEPLOY_WEBHOOK_NOTIFY is not "all" - not notifying');return false}const driver=config.driver??driverForWebhookUrl(config.url);const message=buildDeployMessage(outcome);const result=driver==="discord"?await sendToDiscord(config.url,message):driver==="teams"?await sendToTeams(config.url,message):await sendToSlack(config.url,message);if(!result?.success){log.warn(`[deploy] deploy notification to ${driver} failed: ${result?.message??"unknown error"}`);return false}log.debug(`[deploy] deploy ${outcome.status} notification sent via ${driver}`);return true}catch(error){log.warn(`[deploy] deploy notification could not be sent: ${error instanceof Error?error.message:String(error)}`);return false}}export function getDeployErrorMessage(error){if(error instanceof Error&&error.message)return error.message;if(typeof error==="string"&&error)return error;try{const rendered=JSON.stringify(error);if(rendered&&rendered!=="{}"&&rendered!=="null")return rendered}catch{}return`${String(error)} (no message; re-run with --verbose for the stack)`}export function withDeployNotification(action){return async(...args)=>{const startedAt=Date.now();const environment=typeof args[0]==="string"&&args[0]?args[0]:"production";const context={environment,provider:process.env.CLOUD_PROVIDER||undefined,project:process.env.APP_NAME||undefined};try{await action(...args)}catch(error){log.error(`Deploy to ${environment} failed: ${getDeployErrorMessage(error)}`);const stack=error instanceof Error?error.stack:undefined;if(stack)log.debug(stack);await log.flush();await notifyDeployOutcome({...context,status:"failed",durationMs:Date.now()-startedAt,error});await log.flush();process.exit(ExitCode.FatalError)}await notifyDeployOutcome({...context,status:"succeeded",durationMs:Date.now()-startedAt})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{resolve}from"node:path";export function explicitDeploymentEnvFile(root,file){if(file===
|
|
1
|
+
import{existsSync}from"node:fs";import{resolve}from"node:path";export function explicitDeploymentEnvFile(root,file){if(file===undefined)return;if(!file.trim()||/[\r\n\0]/.test(file))throw new Error("--env-file must name one environment file");const path=resolve(root,file);if(!existsSync(path))throw new Error(`The selected deployment environment file does not exist: ${file}`);return path}export function deploymentRetirements(config,input){if(input===undefined)return config;const domains=[...new Set(input.split(",").map((domain)=>domain.trim().toLowerCase()))];if(!domains.length||domains.some((domain)=>domain.length>253||domain.replace(/^\*\./,"").split(".").some((label)=>!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))))throw new Error("--retire-domains must contain comma-separated hostnames");const declared=Object.values(config.sites??{}).flatMap((site)=>[site.domain,...site.aliases??[]]).filter(Boolean).map((domain)=>String(domain).toLowerCase());if(domains.some((domain)=>declared.includes(domain)))throw new Error("A retired domain is still declared in sites. Remove its site first.");return{...config,cloud:{...config.cloud,retiredDomains:[...new Set([...config.cloud?.retiredDomains??[],...domains])]}}}export function validateDeploymentProviderInputs(provider,options){const ssh=provider==="ssh"||provider==="hetzner";if(options.envFile&&!ssh&&provider!=="fly")throw new Error("--env-file requires an SSH, Hetzner or Fly deployment");if(options.retireDomains!==undefined&&!ssh)throw new Error("--retire-domains requires an SSH or Hetzner gateway")}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{readFile}from"node:fs/promises";import{resolve}from"node:path";import process from"node:process";import{promisify}from"node:util";const execute=promisify(execFile);export function automatedDeploymentRevision(environment,variables=process.env){if(environment!=="production")return;const prefix=variables.REVIEWOS==="true"?"REVIEWOS":variables.GITHUB_ACTIONS==="true"?"GITHUB":
|
|
2
|
-
`).map((line)=>line.split(/\s+/));if(lines.length!==1||lines[0]?.[1]!==revision.ref||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(lines[0]?.[0]??""))throw Error("Origin did not return one authoritative branch head; production deployment stopped.");
|
|
3
|
-
`).map((line)=>line.trim().toLowerCase()).filter(Boolean),()=>[]);for(const boundary of boundaries){if(!await isAncestor(boundary,tip))continue;if(boundary===revision.sha||!await isAncestor(boundary,revision.sha))return
|
|
4
|
-
`).map((line)=>line.trim().toLowerCase()).filter(Boolean);return Object.freeze({revision,newer})}export function assertNotBehindLiveRelease(check,liveReleases){if(!check||check.newer.length===0)return;for(const raw of liveReleases){const id=String(raw??"").trim().toLowerCase();if(!/^[a-f0-9]{7,64}$/.test(id))continue;if(check.newer.some((sha)=>sha.startsWith(id)))throw Error(`Production already runs ${id}, which is newer than this CI commit; production deployment stopped. Deploy the current branch head.`)}}export function liveReleasesCommand(slug){if(!/^[a-z0-9][a-z0-9-]*$/i.test(slug))throw Error("A project slug is letters, digits and dashes.");return`for d in /var/www/${slug}-*/current; do [ -L "$d" ] && basename "$(readlink -f "$d")"; done; true`}
|
|
1
|
+
import{execFile}from"node:child_process";import{readFile}from"node:fs/promises";import{resolve}from"node:path";import process from"node:process";import{promisify}from"node:util";const execute=promisify(execFile);export function automatedDeploymentRevision(environment,variables=process.env){if(environment!=="production")return;const prefix=variables.REVIEWOS==="true"?"REVIEWOS":variables.GITHUB_ACTIONS==="true"?"GITHUB":undefined;if(!prefix)return;const ref=variables[`${prefix}_REF`];const sha=variables[`${prefix}_SHA`];if(!ref?.startsWith("refs/heads/")||!sha||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(sha))throw new Error("Automated production deployment requires a branch ref and full commit SHA from the CI provider.");return Object.freeze({ref,sha:sha.toLowerCase()})}export async function assertCurrentDeploymentRevision(revision,cwd=process.cwd()){if(!revision)return;const git=async(operation,args,options={})=>{const timeoutSeconds=options.timeoutSeconds??60;try{const result=await execute("git",args,{cwd,timeout:timeoutSeconds*1000,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"}});return result.stdout.trim()}catch(error){if(options.allowFailure)return null;let status="Git failed to execute";if(error instanceof Error){if("code"in error&&error.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")status="Git exceeded its output limit";else if("killed"in error&&error.killed===true)status=`Git exceeded its ${timeoutSeconds}-second limit`;else if("code"in error&&typeof error.code==="number"&&Number.isSafeInteger(error.code)&&error.code>=0)status=`Git exited with status ${error.code}`}throw new Error(`Cannot verify the automated deployment revision against origin while ${operation}: ${status}; production deployment stopped.`)}};const isAncestor=async(ancestor,descendant)=>await git("checking revision ancestry",["merge-base","--is-ancestor",ancestor,descendant],{allowFailure:true})!==null;const isShallow=async()=>await git("checking repository history depth",["rev-parse","--is-shallow-repository"])==="true";const fetchedTip=async()=>String(await git("reading the fetched branch head",["rev-parse","--verify","FETCH_HEAD^{commit}"])).toLowerCase();await git("validating the branch ref",["check-ref-format",revision.ref]);const checkout=await git("reading the checkout revision",["rev-parse","--verify","HEAD"]);if(checkout?.toLowerCase()!==revision.sha)throw new Error("The deployment checkout does not match the CI commit; production deployment stopped.");const remote=await git("reading the origin branch head",["ls-remote","--exit-code","--refs","origin",revision.ref]);const lines=String(remote).split(`
|
|
2
|
+
`).map((line)=>line.split(/\s+/));if(lines.length!==1||lines[0]?.[1]!==revision.ref||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(lines[0]?.[0]??""))throw new Error("Origin did not return one authoritative branch head; production deployment stopped.");const head=lines[0][0].toLowerCase();if(head===revision.sha)return Object.freeze({revision,newer:[]});const historySuffices=async(tip)=>{if(!await isAncestor(revision.sha,tip))return false;if(!await isShallow())return true;const shallowFile=resolve(cwd,String(await git("locating the shallow boundary list",["rev-parse","--git-path","shallow"])));const boundaries=await readFile(shallowFile,"utf8").then((text)=>text.split(`
|
|
3
|
+
`).map((line)=>line.trim().toLowerCase()).filter(Boolean),()=>[]);for(const boundary of boundaries){if(!await isAncestor(boundary,tip))continue;if(boundary===revision.sha||!await isAncestor(boundary,revision.sha))return false}return true};let tip;if(!await isShallow()){await git("fetching the origin branch history",["fetch","--quiet","--no-tags","origin",revision.ref],{timeoutSeconds:180});tip=await fetchedTip()}else{let enough=false;tip="";for(const depth of[64,512,4096]){await git("deepening the origin branch history",["fetch","--quiet","--no-tags",`--depth=${depth}`,"origin",revision.ref],{timeoutSeconds:180});tip=await fetchedTip();if(enough=await historySuffices(tip))break;if(!await isShallow())break}if(!enough&&await isShallow()){await git("fetching the origin branch history",["fetch","--quiet","--no-tags","--unshallow","origin",revision.ref],{timeoutSeconds:600});if(await isShallow())throw new Error("Cannot verify complete origin history; production deployment stopped.");tip=await fetchedTip()}}if(!await isAncestor(revision.sha,tip))throw new Error("This CI commit is no longer on the origin branch; production deployment stopped. Deploy the current branch head.");const newer=String(await git("listing newer branch revisions",["rev-list",`${revision.sha}..${tip}`])).split(`
|
|
4
|
+
`).map((line)=>line.trim().toLowerCase()).filter(Boolean);return Object.freeze({revision,newer})}export function assertNotBehindLiveRelease(check,liveReleases){if(!check||check.newer.length===0)return;for(const raw of liveReleases){const id=String(raw??"").trim().toLowerCase();if(!/^[a-f0-9]{7,64}$/.test(id))continue;if(check.newer.some((sha)=>sha.startsWith(id)))throw new Error(`Production already runs ${id}, which is newer than this CI commit; production deployment stopped. Deploy the current branch head.`)}}export function liveReleasesCommand(slug){if(!/^[a-z0-9][a-z0-9-]*$/i.test(slug))throw new Error("A project slug is letters, digits and dashes.");return`for d in /var/www/${slug}-*/current; do [ -L "$d" ] && basename "$(readlink -f "$d")"; done; true`}
|
package/dist/dns-credentials.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DNS_PROVIDER_ENV_KEYS={porkbun:[["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"]],cloudflare:[["CLOUDFLARE_API_TOKEN"]],godaddy:[["GODADDY_API_KEY","GODADDY_API_SECRET"]],route53:[["AWS_ACCESS_KEY_ID"],["AWS_PROFILE"]]};const PROVIDER_LABELS={porkbun:"Porkbun",cloudflare:"Cloudflare",godaddy:"GoDaddy",route53:"Route 53"};export function dnsProviderLabel(provider){return PROVIDER_LABELS[provider]??provider}export function isKnownDnsProvider(provider){return typeof provider==="string"&&provider in DNS_PROVIDER_ENV_KEYS}export function envFileForEnvironment(environment="production"){return`.env.${environment||"production"}`}export function envFileKeys(content){const keys=new Set;for(const line of content.split(/\r?\n/)){const match=line.match(/^\s*(?:export\s+)?([A-Z_][\w.]*)\s*=\s*(.*)$/i);if(!match)continue;
|
|
1
|
+
export const DNS_PROVIDER_ENV_KEYS={porkbun:[["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"]],cloudflare:[["CLOUDFLARE_API_TOKEN"]],godaddy:[["GODADDY_API_KEY","GODADDY_API_SECRET"]],route53:[["AWS_ACCESS_KEY_ID"],["AWS_PROFILE"]]};const PROVIDER_LABELS={porkbun:"Porkbun",cloudflare:"Cloudflare",godaddy:"GoDaddy",route53:"Route 53"};export function dnsProviderLabel(provider){return PROVIDER_LABELS[provider]??provider}export function isKnownDnsProvider(provider){return typeof provider==="string"&&provider in DNS_PROVIDER_ENV_KEYS}export function envFileForEnvironment(environment="production"){return`.env.${environment||"production"}`}export function envFileKeys(content){const keys=new Set;for(const line of content.split(/\r?\n/)){const match=line.match(/^\s*(?:export\s+)?([A-Z_][\w.]*)\s*=\s*(.*)$/i);if(!match)continue;const value=match[2].trim().replace(/^(["'])(.*)\1$/,"$2").trim();if(value)keys.add(match[1])}return keys}export function dnsCredentialPresence(provider,fileKeys,env=process.env){const alternatives=DNS_PROVIDER_ENV_KEYS[provider];for(const source of["file","environment"]){const has=(key)=>source==="file"?fileKeys.has(key):!!env[key]?.trim();if(alternatives.some((keys)=>keys.every(has)))return{provider,configured:true,source,missing:[]}}const first=alternatives[0];return{provider,configured:false,missing:first.filter((key)=>!fileKeys.has(key)&&!env[key]?.trim())}}export function dnsCredentialFix(provider,envFile=".env.production",nameservers=[]){if(!isKnownDnsProvider(provider)){const where=nameservers.length>0?` (${nameservers.slice(0,2).join(", ")})`:"";return`the zone's nameservers${where} belong to no DNS provider Stacks can write (Porkbun, Cloudflare, Route 53, GoDaddy), so add the records by hand at that DNS host.`}const keys=DNS_PROVIDER_ENV_KEYS[provider][0];const commands=keys.map((key)=>`buddy env:set ${key} <value> -f ${envFile}`).join(" && ");return`the zone is on ${dnsProviderLabel(provider)}: ${commands}, then deploy again.`}export async function resolveZoneNameservers(domain,timeoutMs=1500){const{Resolver}=await import("node:dns/promises");const resolver=new Resolver({timeout:timeoutMs,tries:1});const labels=domain.replace(/\.$/,"").toLowerCase().split(".");for(let i=0;i<labels.length-1;i++){const zone=labels.slice(i).join(".");try{const nameservers=await resolver.resolveNs(zone);if(nameservers.length>0)return{zone,nameservers}}catch{}}return{zone:domain,nameservers:[]}}
|