@stacksjs/actions 0.70.53 → 0.70.54
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.
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
import"./chunk-4qzb8g3z.js";var q={type:"aws",useLoadBalancer:!0,app:{name:"app-server-1",domain:"stacksjs.com",region:"us-east-1",type:"app",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26",database:"sqlite",databaseName:"stacks"},app2:{name:"app-server-2",domain:"stacksjs.com",instanceType:"t3.micro",userData:`#!/bin/bash
|
|
3
3
|
echo "Hello World from App Server 2!" > /tmp/test.txt
|
|
4
4
|
chown ubuntu:ubuntu /tmp/test.txt
|
|
5
|
-
`},web:{name:"web-server",domain:"ow3.org",region:"us-east-1",type:"web",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"},cache:{name:"cache-server",domain:"stacksjs.com",region:"us-east-1",type:"cache",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"}};import{env as m}from"@stacksjs/env";var C={project:{name:"stacks",slug:"stacks",region:"us-east-1"},cloud:{provider:"hetzner"},mode:"server",environments:{production:{type:"production",deployBranch:"main",region:"us-east-1",variables:{NODE_ENV:"production",LOG_LEVEL:"info"}},staging:{type:"staging",deployBranch:"stage",domainPrefix:"staging",region:"us-east-1",variables:{NODE_ENV:"staging",LOG_LEVEL:"debug"}},development:{type:"development",deployBranch:"dev",domainPrefix:"dev",region:"us-east-1",variables:{NODE_ENV:"development",LOG_LEVEL:"debug"}}},infrastructure:{compute:{instances:1,size:"small",disk:{size:20,type:"ssd",encrypted:!0},webServer:"rpx",proxy:{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:"hello@stacksjs.com"}},servers:{app:q.app},containers:{api:{cpu:512,memory:1024,port:3000,healthCheck:"/health",desiredCount:2,autoScaling:{min:1,max:10,targetCpuUtilization:70,targetMemoryUtilization:80}}},loadBalancer:{enabled:!0,type:"application",healthCheck:{path:"/health",interval:30,healthyThreshold:2,unhealthyThreshold:5}},ssl:{enabled:!0,provider:"acm",domains:m.SSL_DOMAINS?.split(",")||["stacksjs.com","www.stacksjs.com"],redirectHttp:!0,letsEncrypt:{email:m.LETSENCRYPT_EMAIL||"admin@stacksjs.com",staging:!1,autoRenew:!0}},dns:{domain:m.APP_DOMAIN||"stacksjs.com",hostedZoneId:m.AWS_HOSTED_ZONE_ID||"Z01455702Q7952O6RCY37"},storage:{public:{public:!0,encryption:!0,versioning:!0,website:{indexDocument:"index.html",errorDocument:"index.html"}},private:{encryption:!0,versioning:!0},docs:{public:!0,encryption:!0,versioning:!0,path:"/docs",pathRewriteStyle:"flat",website:{indexDocument:"index.html",errorDocument:"404.html"}},blog:{public:!0,encryption:!0,versioning:!0,path:"/blog",website:{indexDocument:"index.html",errorDocument:"404.html"}},logs:{encryption:!0,versioning:!1},backups:{encryption:!0,versioning:!0},email:{public:!1,encryption:!0,versioning:!1}},functions:{},queues:{jobs:{visibilityTimeout:120,deadLetterQueue:!0,maxReceiveCount:3}},databases:{},cdn:{},monitoring:{}},sites:{main:{root:".",path:"/",domain:m.APP_DOMAIN||"stacksjs.com",start:"
|
|
5
|
+
`},web:{name:"web-server",domain:"ow3.org",region:"us-east-1",type:"web",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"},cache:{name:"cache-server",domain:"stacksjs.com",region:"us-east-1",type:"cache",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"}};import{env as m}from"@stacksjs/env";var C={project:{name:"stacks",slug:"stacks",region:"us-east-1"},cloud:{provider:"hetzner"},mode:"server",environments:{production:{type:"production",deployBranch:"main",region:"us-east-1",variables:{NODE_ENV:"production",LOG_LEVEL:"info"}},staging:{type:"staging",deployBranch:"stage",domainPrefix:"staging",region:"us-east-1",variables:{NODE_ENV:"staging",LOG_LEVEL:"debug"}},development:{type:"development",deployBranch:"dev",domainPrefix:"dev",region:"us-east-1",variables:{NODE_ENV:"development",LOG_LEVEL:"debug"}}},infrastructure:{compute:{instances:1,size:"small",disk:{size:20,type:"ssd",encrypted:!0},webServer:"rpx",proxy:{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:"hello@stacksjs.com"}},servers:{app:q.app},containers:{api:{cpu:512,memory:1024,port:3000,healthCheck:"/health",desiredCount:2,autoScaling:{min:1,max:10,targetCpuUtilization:70,targetMemoryUtilization:80}}},loadBalancer:{enabled:!0,type:"application",healthCheck:{path:"/health",interval:30,healthyThreshold:2,unhealthyThreshold:5}},ssl:{enabled:!0,provider:"acm",domains:m.SSL_DOMAINS?.split(",")||["stacksjs.com","www.stacksjs.com"],redirectHttp:!0,letsEncrypt:{email:m.LETSENCRYPT_EMAIL||"admin@stacksjs.com",staging:!1,autoRenew:!0}},dns:{domain:m.APP_DOMAIN||"stacksjs.com",hostedZoneId:m.AWS_HOSTED_ZONE_ID||"Z01455702Q7952O6RCY37"},storage:{public:{public:!0,encryption:!0,versioning:!0,website:{indexDocument:"index.html",errorDocument:"index.html"}},private:{encryption:!0,versioning:!0},docs:{public:!0,encryption:!0,versioning:!0,path:"/docs",pathRewriteStyle:"flat",website:{indexDocument:"index.html",errorDocument:"404.html"}},blog:{public:!0,encryption:!0,versioning:!0,path:"/blog",website:{indexDocument:"index.html",errorDocument:"404.html"}},logs:{encryption:!0,versioning:!1},backups:{encryption:!0,versioning:!0},email:{public:!1,encryption:!0,versioning:!1}},functions:{},queues:{jobs:{visibilityTimeout:120,deadLetterQueue:!0,maxReceiveCount:3}},databases:{},cdn:{},monitoring:{}},sites:{main:{root:".",path:"/",domain:m.APP_DOMAIN||"stacksjs.com",start:"bun storage/framework/core/buddy/src/cli.ts serve",port:3000,preStart:["bun install"]},api:{root:".",start:"bun storage/framework/core/actions/src/serve/api.ts",port:3008,preStart:["bun install"],env:{HOST:"127.0.0.1",APP_ENV:"production"}},docs:{deploy:"server",root:"dist/docs/.bunpress",path:"/docs",domain:m.APP_DOMAIN||"stacksjs.com",build:"bunx @stacksjs/bunpress build --dir ./docs --outdir ./dist/docs",pathRewriteStyle:"directory"},blog:{deploy:"server",root:"dist/blog",path:"/blog",domain:m.APP_DOMAIN||"stacksjs.com",build:`bun -e "const {buildBlog}=await import('./storage/framework/core/actions/src/blog'); await buildBlog({outDir:'./dist/blog', baseUrl: (process.env.APP_URL?(/^https?:/.test(process.env.APP_URL)?process.env.APP_URL:'https://'+process.env.APP_URL):'https://stacksjs.com')})"`,pathRewriteStyle:"directory"},wwwStacksjs:{domain:"www.stacksjs.com",redirect:"https://stacksjs.com"}}},w={},E=w;export{C as tsCloud,E as default};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pb as L}from"./chunk-4qzb8g3z.js";import f from"process";import{log as N}from"@stacksjs/cli";import{getErrorMessage as E}from"@stacksjs/utils";async function C(){try{return(await import("./chunk-
|
|
2
|
+
import{pb as L}from"./chunk-4qzb8g3z.js";import f from"process";import{log as N}from"@stacksjs/cli";import{getErrorMessage as E}from"@stacksjs/utils";async function C(){try{return(await import("./chunk-17srgdca.js")).tsCloud||null}catch{return null}}async function b(){let G=await C();return{name:G?.project?.name||"stacks",region:G?.project?.region||"us-east-1"}}async function v(G){try{let{AWSClient:Q}=await import("@stacksjs/ts-cloud"),J=new Q,_=new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}),K=await J.request({service:"sts",region:G,method:"POST",path:"/",body:_.toString()}),j=String(K).match(/<Account>(\d+)<\/Account>/);if(j&&j[1])return j[1];return f.env.AWS_ACCOUNT_ID||""}catch(Q){return f.env.AWS_ACCOUNT_ID||""}}async function p(G){let{environment:Q}=G,J=await C();if(!J)throw Error("Cloud configuration not found. Ensure config/cloud.ts exports tsCloud.");let{InfrastructureGenerator:_}=await import("@stacksjs/ts-cloud"),j=new _({config:J,environment:Q}).generate().getBuilder().build();return JSON.stringify(j)}function S(G){let Q={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m"};if(G.includes("COMPLETE")&&!G.includes("ROLLBACK"))return`${Q.green}${G}${Q.reset}`;if(G.includes("IN_PROGRESS"))return`${Q.yellow}${G}${Q.reset}`;if(G.includes("FAILED")||G.includes("ROLLBACK"))return`${Q.red}${G}${Q.reset}`;if(G.includes("DELETE"))return`${Q.gray}${G}${Q.reset}`;return G}async function k(G){let{region:Q,domain:J,sslDomains:_,hostedZoneId:K,albDnsName:j,stackName:Y}=G;console.log(""),console.log("Setting up SSL certificate...");try{let{Route53Client:$,ACMClient:w,AWSClient:F}=await import("@stacksjs/ts-cloud"),P=new $(Q),V=new w(Q),W=new F;console.log(` Requesting SSL certificate for ${J}...`);let Z=await V.requestCertificate({DomainName:_[0]??J,SubjectAlternativeNames:_.length>1?_.slice(1):void 0,ValidationMethod:"DNS"});console.log(` Certificate ARN: ${Z.CertificateArn}`),await new Promise((R)=>setTimeout(R,5000));let U=await V.describeCertificate({CertificateArn:Z.CertificateArn});console.log(" Adding DNS validation records...");for(let R of U.DomainValidationOptions||[])if(R.ResourceRecord)await P.changeResourceRecordSets({HostedZoneId:K,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:R.ResourceRecord.Name,Type:"CNAME",TTL:300,ResourceRecords:[{Value:R.ResourceRecord.Value}]}}]}});console.log("\u2713 Validation records added"),console.log(" Waiting for certificate validation (this may take 1-5 minutes)...");for(let R=0;R<30;R++){let M=await V.describeCertificate({CertificateArn:Z.CertificateArn});if(M.Status==="ISSUED"){console.log("\u2713 Certificate issued!");let{AWSCloudFormationClient:A}=await import("@stacksjs/ts-cloud"),B=await new A(Q).listStackResources(Y),I=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="ApplicationLoadBalancer")?.PhysicalResourceId,X=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="ECSTargetGroup")?.PhysicalResourceId||B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="WebTargetGroup")?.PhysicalResourceId;if(I&&X){console.log(" Creating HTTPS listener...");let O=new URLSearchParams({Action:"CreateListener",LoadBalancerArn:I,Protocol:"HTTPS",Port:"443","Certificates.member.1.CertificateArn":Z.CertificateArn,"DefaultActions.member.1.Type":"forward","DefaultActions.member.1.TargetGroupArn":X,Version:"2015-12-01"});await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:O.toString()}),console.log("\u2713 HTTPS listener created!"),console.log(" Configuring HTTP to HTTPS redirect...");let h=new URLSearchParams({Action:"DescribeListeners",LoadBalancerArn:I,Version:"2015-12-01"}),H=await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:h.toString()}),x=H?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member||H?.DescribeListenersResult?.Listeners?.member,T=(Array.isArray(x)?x:x?[x]:[]).find((D)=>D.Port==="80"||D.Port===80);if(T){let D=new URLSearchParams({Action:"ModifyListener",ListenerArn:T.ListenerArn,"DefaultActions.member.1.Type":"redirect","DefaultActions.member.1.RedirectConfig.Protocol":"HTTPS","DefaultActions.member.1.RedirectConfig.Port":"443","DefaultActions.member.1.RedirectConfig.StatusCode":"HTTP_301",Version:"2015-12-01"});await W.request({service:"elasticloadbalancing",region:Q,method:"POST",path:"/",body:D.toString()}),console.log("\u2713 HTTP to HTTPS redirect configured!")}}let z=B.StackResourceSummaries.find((O)=>O.LogicalResourceId==="CloudFrontDistribution")?.PhysicalResourceId;if(z){console.log(" Updating CloudFront distribution with SSL certificate...");let O=await W.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${z}/config`}),h=O._headers?.etag||O._headers?.ETag,H=O.DistributionConfig;if(H&&h){H.Aliases={Quantity:_.length,Items:_},H.ViewerCertificate={ACMCertificateArn:Z.CertificateArn,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CloudFrontDefaultCertificate:!1};let x=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
4
4
|
<CallerReference>${H.CallerReference}</CallerReference>
|
|
5
5
|
<Aliases>
|
package/dist/src/deploy/index.js
CHANGED
|
@@ -8,7 +8,7 @@ ${Q}${H}</${J}>
|
|
|
8
8
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
9
9
|
${Object.entries(J).filter(([U])=>!U.startsWith("@_")).map(([U,H])=>AJ(U,H," ")).join("")}</DistributionConfig>
|
|
10
10
|
`}function _J(J){let U=[...new Set(J)].filter((Q)=>Number.isFinite(Q)&&Q>0).sort((Q,_)=>Q-_);if(U.length===0)return"true";return`if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --permanent ${U.map((Q)=>`--add-port=${Q}/tcp`).join(" ")} && firewall-cmd --reload; fi`}async function CJ(J,U,H){if(!U)return;if(((await J.describeSecurityGroups({GroupIds:[U]}))?.SecurityGroups?.[0]?.IpPermissions||[]).some((G)=>{return G.IpProtocol==="tcp"&&Number(G.FromPort)<=H&&Number(G.ToPort)>=H&&wJ(G.IpRanges).some((y)=>y.CidrIp==="0.0.0.0/0")}))return;try{await J.authorizeSecurityGroupIngress({GroupId:U,IpPermissions:[{IpProtocol:"tcp",FromPort:H,ToPort:H,IpRanges:[{CidrIp:"0.0.0.0/0",Description:`Stacks API port ${H}`}]}]})}catch(G){if(!String(G?.message||"").includes("InvalidPermission.Duplicate"))throw G}}async function kJ(J,U,H){if(!U)return;let Q=await J.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${U}/config`,returnHeaders:!0}),_=Q.headers?.etag||Q.headers?.ETag||"",b=Q.body?.DistributionConfig||Q.DistributionConfig||Q.body;if(!_||!b?.Origins?.Items)return;let y=wJ(b.Origins.Items.Origin).find((c)=>String(c.Id||"").includes("-api"));if(!y?.CustomOriginConfig)return;if(Number(y.CustomOriginConfig.HTTPPort)===H)return;y.CustomOriginConfig.HTTPPort=H,await J.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${U}/config`,body:hJ(b),headers:{"Content-Type":"application/xml","If-Match":_}})}var xJ=S("Building framework...");xJ.start();await KJ("bun run build",{cwd:X.frameworkPath("core"),quiet:!1});xJ.succeed("Framework built");var LJ=X.projectPath("docs"),SJ=X.projectPath("dist/docs/.bunpress");if(RJ.hasFiles(LJ)){let J=S("Building documentation with BunPress...");J.start();try{let{rm:U}=await import("fs/promises"),H=`${T.env.HOME}/Code/Tools/bunpress/packages/bunpress/bin/cli.ts`,Q=X.projectPath("node_modules/@stacksjs/bunpress/dist/bin/cli.js"),_=await Bun.file(H).exists(),b=await Bun.file(Q).exists(),G=_?`bun ${H} build --dir ${LJ} --outdir ${X.projectPath("dist/docs")}`:b?`bun ${Q} build --dir ${LJ} --outdir ${X.projectPath("dist/docs")}`:"bunx @stacksjs/bunpress@0.1.5 build --dir ./docs --outdir ./dist/docs";await U(SJ,{recursive:!0,force:!0}),await KJ(G,{cwd:X.projectPath(),quiet:!V}),J.succeed(`Documentation built with BunPress${_?" (local checkout)":""}`)}catch(U){if(J.stop(),console.log(`\u26A0 Documentation build skipped: ${U.message}`),V)$.debug("To build docs manually: cd ~/Code/Tools/bunpress && bun packages/bunpress/bin/cli.ts build --dir /path/to/docs --outdir /path/to/dist/docs")}}else if(V)$.debug("No docs directory found, skipping documentation build");var vJ=RJ.hasFiles(X.projectPath("dist/blog")),yJ=["CampmateScript-Regular.woff2","SequoiaSans-Regular.woff2","Switchback-Regular.woff2"].every((J)=>JJ(X.projectPath(`dist/blog/assets/fonts/nps/${J}`))),gJ=["topography.svg","park-ridge.svg"].every((J)=>JJ(X.projectPath(`dist/blog/assets/images/${J}`))),ZJ=X.projectPath("dist/blog/index.html"),i=JJ(ZJ)?BJ(ZJ,"utf8"):"",cJ=i.length>0&&!i.includes("woff2-variations"),mJ=i.includes("--on-primary")&&i.includes("--newsletter-bg"),dJ=i.includes("topography.svg")&&i.includes("park-ridge.svg"),pJ=!i.includes("stamp-trail")&&!i.includes("blog-sign-tree.svg"),uJ=X.frameworkPath("core/cms/src/build.ts"),sJ=X.projectPath("config/blog.ts"),lJ=JJ(ZJ)&&[uJ,sJ].filter((J)=>JJ(J)).every((J)=>TJ(ZJ).mtimeMs>=TJ(J).mtimeMs);if(!vJ||!yJ||!gJ||!cJ||!mJ||!dJ||!pJ||!lJ){let J=S("Building blog...");J.start();try{let U=(await import(X.projectPath("config/blog"))).default,{buildBlogSite:H}=await import(X.frameworkPath("core/cms/src/build"));await H({config:U,outDir:X.projectPath("dist/blog")}),J.succeed("Blog built successfully")}catch(U){if(J.stop(),console.log(`\u26A0 Blog build skipped: ${U.message}`),V)$.debug(`Blog build error: ${U.stack}`)}}else if(V)$.debug("Pre-built blog found at dist/blog, skipping build");if(V)$.debug("Skipping views build (vite-config not configured)");var aJ=await import(X.projectPath("config/cloud")),iJ=aJ?.tsCloud?.mode||"server";if(iJ==="serverless"){let J=S("Building server...");J.start(),await KJ("bun build.ts",{cwd:X.frameworkPath("server"),quiet:!V}),J.succeed("Server built");let U=S("Packaging for deployment...");U.start(),await KJ("bun zip.ts",{cwd:X.corePath("cloud"),quiet:!V}),U.succeed("Package ready")}else if(V)$.debug("Skipping server build and packaging (server mode)");if(!T.env.AWS_ACCESS_KEY_ID||!T.env.AWS_SECRET_ACCESS_KEY){let{existsSync:J,readFileSync:U}=await import("fs"),H=T.env.APP_ENV||T.env.NODE_ENV||"production",Q=[X.projectPath(`.env.${H}`),X.projectPath(".env")];for(let _ of Q)if(J(_)){let b=U(_,"utf-8");for(let G of b.split(`
|
|
11
|
-
`)){let y=G.trim();if(y.startsWith("#")||!y.includes("="))continue;let c=y.indexOf("="),k=y.slice(0,c).trim(),N=y.slice(c+1).trim();if(N.startsWith('"')&&N.endsWith('"')||N.startsWith("'")&&N.endsWith("'"))N=N.slice(1,-1);if(k==="AWS_ACCESS_KEY_ID"&&N)T.env.AWS_ACCESS_KEY_ID=N;else if(k==="AWS_SECRET_ACCESS_KEY"&&N)T.env.AWS_SECRET_ACCESS_KEY=N;else if(k==="AWS_REGION"&&N&&!T.env.AWS_REGION)T.env.AWS_REGION=N;else if(k==="AWS_ACCOUNT_ID"&&N&&!T.env.AWS_ACCOUNT_ID)T.env.AWS_ACCOUNT_ID=N;else if(k.startsWith("MAIL_PASSWORD_")&&N&&!T.env[k])T.env[k]=N}if(V)$.debug(`Loaded AWS credentials from ${_}`);break}}try{let{deployStack:J,deployFrontend:U}=await import("../../chunk-
|
|
11
|
+
`)){let y=G.trim();if(y.startsWith("#")||!y.includes("="))continue;let c=y.indexOf("="),k=y.slice(0,c).trim(),N=y.slice(c+1).trim();if(N.startsWith('"')&&N.endsWith('"')||N.startsWith("'")&&N.endsWith("'"))N=N.slice(1,-1);if(k==="AWS_ACCESS_KEY_ID"&&N)T.env.AWS_ACCESS_KEY_ID=N;else if(k==="AWS_SECRET_ACCESS_KEY"&&N)T.env.AWS_SECRET_ACCESS_KEY=N;else if(k==="AWS_REGION"&&N&&!T.env.AWS_REGION)T.env.AWS_REGION=N;else if(k==="AWS_ACCOUNT_ID"&&N&&!T.env.AWS_ACCOUNT_ID)T.env.AWS_ACCOUNT_ID=N;else if(k.startsWith("MAIL_PASSWORD_")&&N&&!T.env[k])T.env[k]=N}if(V)$.debug(`Loaded AWS credentials from ${_}`);break}}try{let{deployStack:J,deployFrontend:U}=await import("../../chunk-qg9crz2r.js"),H=T.env.APP_ENV||T.env.NODE_ENV||"production",Q=T.env.AWS_REGION||"us-east-1",_=await import(X.projectPath("config/cloud")),b=_?.tsCloud?.mode||"server",G=_?.tsCloud?.project?.name||_?.tsCloud?.project?.slug||"stacks";if(b==="serverless"){console.log(""),console.log("Serverless deployment mode detected"),console.log("Building and pushing container image..."),console.log("");let z=T.env.AWS_ACCOUNT_ID||await y(Q);if(!z||z.length<10)throw Error(`Invalid AWS Account ID: "${z||"(empty)"}"
|
|
12
12
|
Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`);let q=`${z}.dkr.ecr.${Q}.amazonaws.com/${G}-${H}-api`,A=`${q}:latest`;if(V)$.debug(`ECR repository: ${q}`);if(V)$.debug("ECR credentials will be validated before push...");let W=S("Building Docker image...");W.start();try{let{exec:Y}=await import("child_process"),{promisify:F}=await import("util"),x=F(Y),E=`docker build --platform linux/amd64 -t ${A} -f Dockerfile .`,{stdout:M,stderr:O}=await x(E,{cwd:X.projectPath(),env:T.env,maxBuffer:10485760,timeout:900000});if(V&&M)$.debug(M);if(V&&O)$.debug(O);W.succeed(`Docker image built: ${A}`)}catch(Y){if(W.fail("Docker build failed"),V)$.debug(`Docker build error: ${Y.message}`);throw Y}let K=S("Checking ECR repository...");K.start();try{let{ECRClient:Y}=await import("@stacksjs/ts-cloud"),F=new Y(Q),x=`${G}-${H}-api`;try{await F.describeRepositories({repositoryNames:[x]}),K.succeed(`ECR repository exists: ${x}`)}catch(E){if(E.code==="RepositoryNotFoundException"||E.message?.includes("RepositoryNotFoundException"))K.text=`Creating ECR repository: ${x}...`,await F.createRepository({repositoryName:x,imageScanningConfiguration:{scanOnPush:!0},imageTagMutability:"MUTABLE"}),K.succeed(`ECR repository created: ${x}`);else throw E}}catch(Y){if(K.fail("ECR repository check failed"),V)$.debug(`ECR repository error: ${Y.message}`);throw Y}let w=S("Authenticating to ECR...");w.start();try{let{ECRClient:Y}=await import("@stacksjs/ts-cloud"),E=(await new Y(Q).getAuthorizationToken()).authorizationData?.[0];if(!E?.authorizationToken)throw Error("No authorization token received from ECR");let M=Buffer.from(E.authorizationToken,"base64").toString("utf-8"),O=M.indexOf(":");if(O===-1)throw Error("ECR authorization token has unexpected format (missing colon separator)");let L=M.slice(O+1),j=Bun.spawnSync(["docker","login","--username","AWS","--password-stdin",`${z}.dkr.ecr.${Q}.amazonaws.com`],{stdin:new TextEncoder().encode(L),stdout:"pipe",stderr:"pipe"});if(j.exitCode!==0){let P=new TextDecoder().decode(j.stderr);throw Error(`Docker login failed: ${P}`)}w.succeed("Authenticated to ECR")}catch(Y){if(w.fail("ECR authentication failed"),V)$.debug(`ECR auth error: ${Y.message}`);throw Y}console.log("");let I=S("Pushing image to ECR...");I.start();try{let{exec:Y}=await import("child_process"),{promisify:F}=await import("util"),x=F(Y),E=`docker push ${A}`;await x(E,{env:T.env}),I.succeed(`Image pushed: ${A}`)}catch(Y){if(I.fail("Docker push failed"),V)$.debug(`Push error: ${Y.message}`);throw Y}console.log(""),console.log("Container image ready in ECR. CloudFormation will use this image."),console.log("")}else console.log(""),console.log("Server deployment mode detected"),console.log("Deploying EC2 infrastructure via CloudFormation..."),console.log("");async function y(z){try{let{STSClient:q}=await import("@stacksjs/ts-cloud"),K=(await new q(z).getCallerIdentity()).Account||T.env.AWS_ACCOUNT_ID||"";if(V)$.debug(`Retrieved AWS Account ID: ${K||"(empty)"}`);return K}catch(q){if(V)$.debug(`Failed to get AWS Account ID: ${q.message}`);return T.env.AWS_ACCOUNT_ID||""}}try{let z=await import(X.projectPath("cloud/deploy-script"));if(typeof z.beforeDeploy==="function")await z.beforeDeploy({environment:H,region:Q})}catch(z){if(z.code==="ERR_MODULE_NOT_FOUND"||z.code==="MODULE_NOT_FOUND"){if(V)$.debug("No beforeDeploy hook found (cloud/deploy-script not found)")}else if(console.warn(`\u26A0 beforeDeploy hook failed: ${z.message}`),V)$.debug(`beforeDeploy error stack: ${z.stack}`)}await J({environment:H,region:Q,waitForCompletion:!0,verbose:V});try{let z=await import(X.projectPath("cloud/deploy-script"));if(typeof z.afterDeploy==="function"){let{CloudFormationClient:q}=await import("@stacksjs/ts-cloud"),A=new q(Q),W=`${G}-cloud`,K={};try{K=await A.getStackOutputs(W)}catch(w){if(V)$.debug(`Failed to get stack outputs: ${w instanceof Error?w.message:String(w)}`)}await z.afterDeploy({environment:H,region:Q,outputs:K})}}catch(z){if(z.code==="ERR_MODULE_NOT_FOUND"||z.code==="MODULE_NOT_FOUND"){if(V)$.debug("No afterDeploy hook found (cloud/deploy-script not found)")}else if(console.warn(`\u26A0 afterDeploy hook failed: ${z.message}`),V)$.debug(`afterDeploy error stack: ${z.stack}`)}let c=S("Running database migrations...");c.start();try{let{generateMigrations:z,runDatabaseMigration:q}=await import("@stacksjs/database");await z(),await q(),c.succeed("Database migrations completed")}catch(z){if(c.stop(),console.log(`\u26A0 Database migrations skipped: ${z.message}`),V)$.debug(`Migration error: ${z.stack}`)}let k=S("Ensuring framework tables (auth, notifications, RBAC)...");k.start();try{let{migrateAuthTables:z,migrateNotificationTables:q,migrateRbacTables:A}=await import("@stacksjs/database"),W=[],K=[["auth",z],["notification",q],["RBAC",A]];for(let[w,I]of K){let Y=await I({verbose:V});if(!Y.success)W.push(`${w}: ${Y.error}`)}if(W.length>0)k.stop(),console.log(`\u26A0 Some framework tables could not be migrated: ${W.join("; ")}`);else k.succeed("Framework tables ensured (auth, notifications, RBAC)")}catch(z){if(k.stop(),console.log(`\u26A0 Framework table migrations skipped: ${z.message}`),V)$.debug(`Framework table migration error: ${z.stack}`)}if(b==="server"){let z=S("Retrieving server instance details...");z.start();try{let{CloudFormationClient:W}=await import("@stacksjs/ts-cloud"),K=new W(Q),w=`${G}-cloud`,I=await K.getStackOutputs(w);z.succeed("Server instances deployed"),console.log(""),console.log("Server instances:");for(let[Y,F]of Object.entries(I)){if(Y.endsWith("PublicIp"))console.log(` ${Y}: ${F}`);if(Y.endsWith("InstanceId"))console.log(` ${Y}: ${F}`)}console.log("")}catch(W){if(z.stop(),console.log(`\u26A0 Could not retrieve server details: ${W.message}`),V)$.debug(`Output retrieval error: ${W.stack}`)}let q=S("Deploying API server to EC2...");q.start();try{let{S3Client:W,CloudFormationClient:K,AWSClient:w}=await import("@stacksjs/ts-cloud"),{readFileSync:I,existsSync:Y}=await import("fs"),{resolve:F}=await import("path"),x=new W(Q),E=new K(Q),M=new w,O=`${G}-cloud`,L=await E.getStackOutputs(O),j=L.FrontendBucketName,P=Number(OJ.ports?.api||3008),C;for(let[g,v]of Object.entries(L))if(g.endsWith("InstanceId")&&typeof v==="string"){C=v;break}let f;if(C){let{EC2Client:g}=await import("@stacksjs/ts-cloud"),v=new g(Q);f=(await v.describeInstances({Filters:[{Name:"instance-id",Values:[C]}]}))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups?.[0]?.GroupId,await CJ(v,f,P)}if(!C||!j){if(q.stop(),!C)console.log("\u26A0 No EC2 instance found in stack outputs, skipping server deploy");if(!j)console.log("\u26A0 No S3 bucket found for staging server artifacts")}else{let g=L.publicCloudFrontDistributionId||L.CloudFrontDistributionId;await kJ(M,g,P);let v=F(X.projectPath("node_modules/@stacksjs/ts-cloud/dist/index.js"));if(Y(v)){let R=I(v);if(await a(()=>x.putObject({bucket:j,key:"_deploy/ts-cloud-dist.js",body:R,contentType:"application/javascript"}),"upload ts-cloud dist"),V)$.debug(" Uploaded ts-cloud dist to S3")}let m=`import { Database } from "bun:sqlite";
|
|
13
13
|
import { SESClient } from "./ts-cloud-dist.js";
|
|
14
14
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.70.
|
|
4
|
+
"version": "0.70.54",
|
|
5
5
|
"description": "The Stacks actions.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -59,22 +59,22 @@
|
|
|
59
59
|
"@stacksjs/ts-md": "^0.1.1"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
-
"@stacksjs/api": "0.70.
|
|
63
|
-
"@stacksjs/cli": "0.70.
|
|
64
|
-
"@stacksjs/config": "0.70.
|
|
65
|
-
"@stacksjs/database": "0.70.
|
|
62
|
+
"@stacksjs/api": "0.70.54",
|
|
63
|
+
"@stacksjs/cli": "0.70.54",
|
|
64
|
+
"@stacksjs/config": "0.70.54",
|
|
65
|
+
"@stacksjs/database": "0.70.54",
|
|
66
66
|
"@stacksjs/tlsx": "^0.13.2",
|
|
67
67
|
"better-dx": "^0.2.12",
|
|
68
|
-
"@stacksjs/dns": "0.70.
|
|
69
|
-
"@stacksjs/enums": "0.70.
|
|
70
|
-
"@stacksjs/env": "0.70.
|
|
71
|
-
"@stacksjs/error-handling": "0.70.
|
|
72
|
-
"@stacksjs/logging": "0.70.
|
|
73
|
-
"@stacksjs/path": "0.70.
|
|
74
|
-
"@stacksjs/security": "0.70.
|
|
75
|
-
"@stacksjs/storage": "0.70.
|
|
76
|
-
"@stacksjs/strings": "0.70.
|
|
77
|
-
"@stacksjs/utils": "0.70.
|
|
78
|
-
"@stacksjs/validation": "0.70.
|
|
68
|
+
"@stacksjs/dns": "0.70.54",
|
|
69
|
+
"@stacksjs/enums": "0.70.54",
|
|
70
|
+
"@stacksjs/env": "0.70.54",
|
|
71
|
+
"@stacksjs/error-handling": "0.70.54",
|
|
72
|
+
"@stacksjs/logging": "0.70.54",
|
|
73
|
+
"@stacksjs/path": "0.70.54",
|
|
74
|
+
"@stacksjs/security": "0.70.54",
|
|
75
|
+
"@stacksjs/storage": "0.70.54",
|
|
76
|
+
"@stacksjs/strings": "0.70.54",
|
|
77
|
+
"@stacksjs/utils": "0.70.54",
|
|
78
|
+
"@stacksjs/validation": "0.70.54"
|
|
79
79
|
}
|
|
80
80
|
}
|