@stacksjs/ts-cloud 0.16.80 → 0.16.81
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/aws/index.js +1 -1
- package/dist/bin/{chunk-nbffypj8.js → chunk-08sws53b.js} +3 -3
- package/dist/bin/{chunk-f0djc6da.js → chunk-0z3n1v9g.js} +3 -3
- package/dist/bin/{chunk-6xx24qev.js → chunk-19mhwmfp.js} +1 -1
- package/dist/bin/chunk-1qez75tb.js +1 -0
- package/dist/bin/chunk-1rrmswhq.js +1 -0
- package/dist/bin/{chunk-gqstb8zn.js → chunk-1wgyq50e.js} +1 -1
- package/dist/bin/{chunk-0r8k7qth.js → chunk-20rfyk4x.js} +4 -4
- package/dist/bin/{chunk-rdqcr78z.js → chunk-35325988.js} +2 -2
- package/dist/bin/chunk-3rjer1mp.js +1 -0
- package/dist/bin/{chunk-06hwds44.js → chunk-3wvpgb8m.js} +3 -3
- package/dist/bin/{chunk-jcehsvnm.js → chunk-462swbg5.js} +13 -13
- package/dist/bin/chunk-4c4q96vm.js +1 -0
- package/dist/bin/chunk-5hmrqjmq.js +1 -0
- package/dist/bin/chunk-5tzygzdy.js +1 -0
- package/dist/bin/{chunk-e12679p1.js → chunk-69mejej3.js} +1 -1
- package/dist/bin/{chunk-hyrvmjq0.js → chunk-6b6yr784.js} +2 -2
- package/dist/bin/chunk-6ybjfjbc.js +1 -0
- package/dist/bin/chunk-7848wre2.js +1 -0
- package/dist/bin/chunk-7haewmr7.js +1 -0
- package/dist/bin/chunk-7yhy2a7h.js +1 -0
- package/dist/bin/{chunk-k3cyh23p.js → chunk-83tt2t15.js} +5 -5
- package/dist/bin/{chunk-y5gx3dq2.js → chunk-89v3ec9n.js} +1 -1
- package/dist/bin/{chunk-33shhgye.js → chunk-8rkfwgb4.js} +7 -7
- package/dist/bin/{chunk-p35e4j11.js → chunk-9gp8p8hv.js} +2 -2
- package/dist/bin/chunk-9zwvysdn.js +1 -0
- package/dist/bin/{chunk-hhbmtgkq.js → chunk-b1cb27m8.js} +6 -6
- package/dist/bin/chunk-b9ersj22.js +1 -0
- package/dist/bin/{chunk-gbbcp2bw.js → chunk-bkx2kapc.js} +2 -2
- package/dist/bin/{chunk-540wkkhs.js → chunk-btrxye8p.js} +5 -5
- package/dist/bin/{chunk-qssb91v3.js → chunk-byqyjckv.js} +9 -9
- package/dist/bin/chunk-ce4mbne7.js +1 -0
- package/dist/bin/{chunk-9ktyfegk.js → chunk-cgyk48s5.js} +1 -1
- package/dist/bin/{chunk-th05q1gs.js → chunk-cxf9pmmw.js} +2 -2
- package/dist/bin/{chunk-0zydd9s4.js → chunk-d0m01m6d.js} +5 -5
- package/dist/bin/{chunk-eyzdhtp4.js → chunk-f7jzs1h1.js} +4 -4
- package/dist/bin/{chunk-ma0d990n.js → chunk-gn7rdyz7.js} +2 -2
- package/dist/bin/chunk-haezjam0.js +1 -0
- package/dist/bin/{chunk-jhydr9dp.js → chunk-hgs5fr4v.js} +91 -90
- package/dist/bin/chunk-hp1cqk45.js +1 -0
- package/dist/bin/{chunk-tf5tf414.js → chunk-jqs2ywj2.js} +2 -2
- package/dist/bin/{chunk-c1znyyca.js → chunk-jx062xpq.js} +1 -1
- package/dist/bin/chunk-k9s81q0g.js +1 -0
- package/dist/bin/chunk-nba35r6z.js +1 -0
- package/dist/bin/{chunk-0v5q5sh0.js → chunk-nzg624aj.js} +3 -3
- package/dist/bin/chunk-q3mtvtem.js +1 -0
- package/dist/bin/{chunk-s076q9sj.js → chunk-qmwqntnx.js} +2 -2
- package/dist/bin/{chunk-4m2k5mvd.js → chunk-qpasspad.js} +4 -4
- package/dist/bin/chunk-qpd51n1j.js +1 -0
- package/dist/bin/chunk-rtpc6djg.js +1 -0
- package/dist/bin/chunk-s9k81gq6.js +1 -0
- package/dist/bin/{chunk-wayhpmn7.js → chunk-sacx9p6f.js} +86 -86
- package/dist/bin/{chunk-fhqjr3ba.js → chunk-ssnvdxh4.js} +3 -3
- package/dist/bin/{chunk-kq526rgc.js → chunk-t0r1rdj2.js} +1 -1
- package/dist/bin/chunk-tpy9t3cv.js +1 -0
- package/dist/bin/{chunk-by7dtwtj.js → chunk-w40r35vn.js} +1 -1
- package/dist/bin/chunk-wm0rq725.js +1 -0
- package/dist/bin/chunk-y9qdpwa6.js +1 -0
- package/dist/bin/chunk-ybekawxv.js +1 -0
- package/dist/bin/{chunk-4vtyjj7c.js → chunk-yf2drw7r.js} +1 -1
- package/dist/bin/{chunk-6kx0fddd.js → chunk-z03ytarv.js} +46 -46
- package/dist/bin/{chunk-gq4htm3f.js → chunk-z9g7fa1w.js} +1 -1
- package/dist/bin/{chunk-0e7y7q0t.js → chunk-zfn3a9sx.js} +1 -1
- package/dist/bin/chunk-zg8nnq7k.js +1 -0
- package/dist/bin/{chunk-kyqe19mh.js → chunk-zn9wmqd1.js} +2 -2
- package/dist/bin/cli.js +215 -215
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/bin/stacks-queue-worker.js +1 -1
- package/dist/bin/stacks-scheduler.js +1 -1
- package/dist/chunk-18dqxyz5.js +1 -0
- package/dist/{chunk-etv0rcjd.js → chunk-1h95atas.js} +1 -1
- package/dist/{chunk-nxj8pwa7.js → chunk-3wh3hsvp.js} +1 -1
- package/dist/{chunk-t7qgvz8z.js → chunk-5rds38z9.js} +55 -55
- package/dist/chunk-5v2wpf1k.js +1 -0
- package/dist/{chunk-tp37gyhc.js → chunk-7ea0q5tg.js} +1 -1
- package/dist/{chunk-kjkkh11z.js → chunk-7v2f53s0.js} +4 -4
- package/dist/{chunk-dvma06m5.js → chunk-9w8qtr4p.js} +1 -1
- package/dist/{chunk-hg93a2g9.js → chunk-c71hhcsb.js} +2 -2
- package/dist/{chunk-w8sctn7m.js → chunk-cf274f07.js} +1 -1
- package/dist/{chunk-v6s9k1mp.js → chunk-cz4dw2hk.js} +1 -1
- package/dist/{chunk-0cgrk9g3.js → chunk-dh5m9b05.js} +1 -1
- package/dist/{chunk-z5c5amm1.js → chunk-dvw5dy32.js} +4 -4
- package/dist/{chunk-b6wsc7jp.js → chunk-eyc2tvze.js} +1 -1
- package/dist/{chunk-8k44kaz0.js → chunk-pk8ppz98.js} +1 -1
- package/dist/{chunk-z52n96sa.js → chunk-svvfj380.js} +89 -88
- package/dist/{chunk-f4fggc5f.js → chunk-tb5hy7rm.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/hetzner/driver.d.ts +1 -0
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/compute-provision.d.ts +2 -0
- package/dist/index.js +2 -2
- package/dist/mail/index.js +2 -2
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-00j7xxxg.js +0 -1
- package/dist/bin/chunk-1xfn93bc.js +0 -1
- package/dist/bin/chunk-413nb697.js +0 -1
- package/dist/bin/chunk-8esaawk6.js +0 -1
- package/dist/bin/chunk-8zc4kx6k.js +0 -1
- package/dist/bin/chunk-9t6wztvn.js +0 -1
- package/dist/bin/chunk-b074y2np.js +0 -1
- package/dist/bin/chunk-b77qsk6r.js +0 -1
- package/dist/bin/chunk-d73xkm0k.js +0 -1
- package/dist/bin/chunk-dmj5xv74.js +0 -1
- package/dist/bin/chunk-dnswjyen.js +0 -1
- package/dist/bin/chunk-h28tfah9.js +0 -1
- package/dist/bin/chunk-k1bdndgj.js +0 -1
- package/dist/bin/chunk-kkrp8100.js +0 -1
- package/dist/bin/chunk-m1w3p30q.js +0 -1
- package/dist/bin/chunk-nwcpck34.js +0 -1
- package/dist/bin/chunk-p96975b7.js +0 -1
- package/dist/bin/chunk-rgwwr6x2.js +0 -1
- package/dist/bin/chunk-sky689gw.js +0 -1
- package/dist/bin/chunk-tx56y5qk.js +0 -1
- package/dist/bin/chunk-v0fkhtgq.js +0 -1
- package/dist/bin/chunk-v7dk21w9.js +0 -1
- package/dist/bin/chunk-ww4r3r7x.js +0 -1
- package/dist/bin/chunk-x9dep4ew.js +0 -1
- package/dist/bin/chunk-y5hsmt17.js +0 -1
- package/dist/bin/chunk-zfy6f6ph.js +0 -1
- package/dist/chunk-fmhqz3eg.js +0 -1
- package/dist/chunk-pev4cpbd.js +0 -1
package/dist/aws/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Te,vr,Os,_s,Eg,yc,Sc,Ls,$s,Ic,ut,re,gt,me,T,we,Un,bc,Ue,Cc,Qn,vg,Rh,Ms,Fs,Hn,Gn,Dh,Ph,ZS,eI,tI,rI,Gt,nI,iI,sI,oI,Vt,kh,Nh,Bh,qt,xh,Oh,_h,Vn,aI,cI,dI,Tr,lI,uI,gI,Ec,vc,Tg,pI,mI,fI,wr,Lh,$h,Rr,pt,qn,Tc,wg,hI,Rg,yI,jt,SI,II,bI,CI,he,EI,vI,TI,wI,Dr,RI,DI,PI,jn,wc,Rc,Dg,Pg,Dc,Pr}from"../chunk-
|
|
1
|
+
import{Te,vr,Os,_s,Eg,yc,Sc,Ls,$s,Ic,ut,re,gt,me,T,we,Un,bc,Ue,Cc,Qn,vg,Rh,Ms,Fs,Hn,Gn,Dh,Ph,ZS,eI,tI,rI,Gt,nI,iI,sI,oI,Vt,kh,Nh,Bh,qt,xh,Oh,_h,Vn,aI,cI,dI,Tr,lI,uI,gI,Ec,vc,Tg,pI,mI,fI,wr,Lh,$h,Rr,pt,qn,Tc,wg,hI,Rg,yI,jt,SI,II,bI,CI,he,EI,vI,TI,wI,Dr,RI,DI,PI,jn,wc,Rc,Dg,Pg,Dc,Pr}from"../chunk-7ea0q5tg.js";import{ne}from"../chunk-nftqsker.js";import{Re,mt,zn,Mh}from"../chunk-cz4dw2hk.js";import{Pc,Qe,I}from"../chunk-z56sccfh.js";import{He}from"../chunk-fdf181e6.js";import{ft,Ae,Ge,H,Jt,Wn,Us,Qs,kr,Nr,Jn,Br,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,ye,Js,Xs,Ys,N,Bc,Xn,xc,Se,xr}from"../chunk-pk8ppz98.js";import{C}from"../chunk-c71hhcsb.js";import{qr,Be}from"../chunk-vq8bejep.js";import{A}from"../chunk-tmp2ym80.js";import{o}from"../chunk-c8kf2268.js";import{We,Tp,wp,Ni,n,g,tA}from"../chunk-m9szynnf.js";export{Se as ACMClient,xr as ACMDnsValidator,n as AWSClient,Tc as ApplicationAutoScalingClient,vr as AwsBackupClient,Ph as BedrockAgentClient,Dh as BedrockAgentRuntimeClient,Gn as BedrockClient,Hn as BedrockRuntimeClient,A as CloudFormationClient,I as CloudFrontClient,we as CloudWatchLogsClient,H as CloudflareProvider,Gt as ComprehendClient,Un as ConnectClient,$s as CostExplorerClient,Xn as DnsProviderFactory,Ue as DynamoDBClient,qr as EC2Client,He as ECRClient,ut as ECSClient,Pr as EFSClient,bc as ELBv2Client,pt as ElastiCacheClient,zn as EmailClient,Rr as EventBridgeClient,Ge as GoDaddyProvider,Re as IAMClient,wg as ImapServer,wr as KendraClient,T as LambdaClient,Cc as OpenSearchClient,ft as PROXIABLE_RECORD_TYPES,Ec as PersonalizeClient,Tg as PersonalizeEventsClient,vc as PersonalizeRuntimeClient,Vn as PollyClient,Ae as PorkbunProvider,ne as RDSClient,Vt as RekognitionClient,C as Route53Client,Ic as Route53DomainsClient,ie as Route53Provider,o as S3Client,mt as SESClient,gt as SNSClient,me as SQSClient,Be as SSMClient,Te as STSClient,qn as SchedulerClient,re as SecretsManagerClient,jt as SmsClient,Dc as SmsVoiceClient,Rg as SmtpServer,jn as SupportClient,wc as SupportTemplates,qt as TextractClient,Qn as TranscribeClient,Tr as TranslateClient,ye as UnifiedDnsValidator,Dr as VoiceClient,nI as analyzeSentiment,Vs as applyDeclaredZoneSettings,Ks as applyZoneMigration,g as buildQueryParams,wp as canonicalUriFor,Ni as coerceXmlValues,tI as completeWithClaude,Pc as configOrigins,oI as containsPii,Nh as countFacesInS3Image,vg as crc32,CI as createDeliveryReceiptHandler,N as createDnsProvider,Xs as createGoDaddyValidator,Ls as createObjectStorageClient,Js as createPorkbunValidator,DI as createRecordingHandler,Ys as createRoute53Validator,dI as createSSML,II as createScheduledSmsHandler,bI as createSmsClient,SI as createSmsInboxHandler,Pg as createSmsInfrastructure,PI as createVoiceClient,RI as createVoicemailHandler,Ms as decodeEventStream,Rh as decodeEventStreamMessage,Br as delegateZone,Hs as delegateZoneFromConfig,Gs as describeDelegation,qs as describeZoneSettings,tA as detectCredentialSource,Bc as detectDnsProvider,kh as detectLabelsFromS3,sI as detectLanguage,xc as dnsProviders,Mh as email,Fs as eventStreamError,js as exportRoute53Zone,iI as extractEntities,Oh as extractFormsFromS3,_h as extractTablesFromS3,xh as extractTextFromS3,EI as formatPhoneNumber,rI as generateEmbeddings,TI as getCountryCode,pI as getRecommendations,mI as getSimilarItems,Dg as getSmsInfrastructureStatus,Bh as isContentSafe,kr as isNameserverRegistrar,wI as isSamePhoneNumber,vI as isValidPhoneNumber,Nr as isZoneHost,_s as keyMatchesFilters,eI as listClaudeModels,gI as listLanguages,cI as listVoices,Eg as migrateObjectStorage,he as normalizePhoneNumber,zs as planZoneMigration,Jt as policyTag,yc as providerEndpoint,Wn as qualifyName,Qs as reconcileDeclaredRecords,Os as remapKey,ZS as requestModelAccess,Us as resolveDeclaredRecords,Sc as resolveObjectStorage,We as resolveS3Endpoint,$h as retrieveForRag,Qe as s3OriginBucket,Jn as sameNameservers,Lh as search,Rc as setupSmsInfrastructure,Tp as signingNameFor,hI as startImapServer,yI as startSmtpServer,aI as textToSpeech,fI as trackEvent,lI as translate,uI as translateToMultiple,Ws as verifyZoneParity};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Jt,p}from"./chunk-540wkkhs.js";import{g}from"./chunk-gqstb8zn.js";import{F}from"./chunk-e12679p1.js";import{L}from"./chunk-gbbcp2bw.js";import{Gr}from"./chunk-2h1q758c.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${u}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new Jt({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class te{client;region;constructor(e="us-east-1",t){this.client=new p(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let u=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class we{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=L(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=L(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class tl{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new we(this.region),this.s3=new g(this.region),this.iam=new te(this.region),this.route53=new F(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-00j7xxxg.js"),a=new r,i=(m,y)=>{let P={Action:m,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let d=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:d,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Gr("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
1
|
+
import{Jt,p}from"./chunk-btrxye8p.js";import{g}from"./chunk-1wgyq50e.js";import{F}from"./chunk-69mejej3.js";import{L}from"./chunk-bkx2kapc.js";import{Gr}from"./chunk-2h1q758c.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${u}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new Jt({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class re{client;region;constructor(e="us-east-1",t){this.client=new p(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let u=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class we{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=L(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=L(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class rl{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new we(this.region),this.s3=new g(this.region),this.iam=new re(this.region),this.route53=new F(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-5tzygzdy.js"),a=new r,i=(m,y)=>{let P={Action:m,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let d=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:d,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Gr("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
2
2
|
`,i+=`To: ${r.join(", ")}\r
|
|
3
3
|
`,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
|
|
4
4
|
`}if(i+=`Subject: ${e.subject}\r
|
|
@@ -30,5 +30,5 @@ import{Jt,p}from"./chunk-540wkkhs.js";import{g}from"./chunk-gqstb8zn.js";import{
|
|
|
30
30
|
`,i+=`\r
|
|
31
31
|
`,i+=`${n.content}\r
|
|
32
32
|
`;return i+=`--${a}--\r
|
|
33
|
-
`,i}}var
|
|
34
|
-
export{
|
|
33
|
+
`,i}}var Tm=new rl;
|
|
34
|
+
export{re,we,rl,Tm};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{W,
|
|
2
|
-
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,t,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function u(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function
|
|
3
|
-
export{
|
|
1
|
+
import{W,A,R,_i,Vs,Ht,Qc,Yc}from"./chunk-byqyjckv.js";function g(e){return`'${e.split("'").join("'\\''")}'`}function p(e){let r=e.user||"root",t=e.script.join(`
|
|
2
|
+
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,t,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function u(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function Ds(e,r){let t=e.logger||c,s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=W(e.slug,r.siteName),o=Ht(n,r.to||"unused"),a=r.onlyIfLive?f(o.current,r.siteName,r.onlyIfLive):[];if(r.dryRun){let l=await e.driver.runRemoteDeploy({targets:s,commands:["set -uo pipefail",...a,...Qc(o,r.to?{to:r.to}:{})],comment:`ts-cloud rollback plan ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:l.success,error:l.error,perInstance:l.perInstance}}let m=["set -euo pipefail",...a,...Yc(o,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`})];if(r.site&&A(r.site)==="server-php")m.push(`(cd ${R} && pantry restart php-fpm)`,`if [ -f ${o.current}/artisan ]; then (cd ${o.current} && TS_CLOUD_RB_ENV=$(cd ${R} && pantry env) && eval "$TS_CLOUD_RB_ENV" && php artisan queue:restart); fi`);t.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${s.length} server(s)...`);let i=await e.driver.runRemoteDeploy({targets:s,commands:m,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!i.success)t.error(`Rollback failed: ${i.error||"unknown error"}`);else t.success(`Rolled back ${r.siteName}.`);return{success:i.success,error:i.error,perInstance:i.perInstance}}function f(e,r,t){let s=t.replace(/[^0-9A-Za-z._-]/g,"");return[`TS_CLOUD_LIVE_ID=$(basename "$(readlink -f ${e} 2>/dev/null)" 2>/dev/null || true)`,`if [ -z "$TS_CLOUD_LIVE_ID" ] || [ "$TS_CLOUD_LIVE_ID" = "." ]; then echo "${r}: no live release here; left alone"; exit 0; fi`,`case "${s}" in "$TS_CLOUD_LIVE_ID"*) ;; *) echo "${r} serves $TS_CLOUD_LIVE_ID, not ${s}; left alone"; exit 0 ;; esac`]}async function mm(e,r){let t=await u(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let s=Vs(W(e.slug,r.siteName)),n=Math.max(1,r.limit??20),o=[`[ -f ${s} ] && tail -n ${n} ${s} || echo "no deploy history for ${r.siteName}"`],a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:a.success,error:a.error,perInstance:a.perInstance}}async function gm(e,r){let t=e.logger||c,s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};t.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${s.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:s,commands:p({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)t.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else t.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function ks(e,r){let t=e.logger||c;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let s=await u(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};t.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${s.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:s,commands:_i(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)t.error(`Restore failed: ${n.error||"unknown error"}`);else t.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
|
|
3
|
+
export{Ds,mm,gm,ks};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{p}from"./chunk-540wkkhs.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let d=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(d,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class D{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new p(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
1
|
+
import{p}from"./chunk-btrxye8p.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let d=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(d,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class D{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new p(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
2
2
|
export{D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Q}from"./chunk-cgyk48s5.js";import"./chunk-btrxye8p.js";export{Q as EC2Client};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g}from"./chunk-1wgyq50e.js";import"./chunk-btrxye8p.js";export{g as S3Client};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xt,p}from"./chunk-
|
|
1
|
+
import{Xt,p}from"./chunk-btrxye8p.js";import{Gr}from"./chunk-2h1q758c.js";import*as c from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function It(e){if(e){let i=D(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=Gr("node:fs"),{homedir:i}=Gr("node:os"),{join:n}=Gr("node:path"),r=process.env.AWS_SHARED_CREDENTIALS_FILE||n(i(),".aws","credentials");if(!t(r))return null;let o=s(r,"utf-8"),a=null,l,d,y;for(let u of o.split(`
|
|
2
2
|
`)){let h=u.trim();if(!h||h.startsWith("#")||h.startsWith(";"))continue;let m=h.match(/^\[([^\]]+)\]$/);if(m){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=m[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=h.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?Xt({region:n,path:"/",endpoint:i.endpoint}):void 0;this.region=n,this.explicitProfile=r,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new p(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=It(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)t.push({Name:r.Name,CreationDate:r.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
4
|
<LocationConstraint>${this.region}</LocationConstraint>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{ze,I,er,Vr,
|
|
2
|
-
`)}var
|
|
1
|
+
import{ze,I,er,Vr,Gi}from"./chunk-sacx9p6f.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
|
|
2
|
+
`)}var eu="dashboard";function el(){return ze("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function tu(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=el(),i=I(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
|
|
3
3
|
`),j(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
|
|
4
4
|
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var L={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return ze("dashboard-release")}function T(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||T()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=I(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=T(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
|
|
5
|
-
`),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function
|
|
6
|
-
export{
|
|
5
|
+
`),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function zo(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=v(C(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function Ho(e,r={}){let t=r.logger??L,s=r.cwd??process.cwd();if(b(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(er(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!b(process.env.TS_CLOUD_UI_STATIC)){let g=V(e,s,t);if(!g)return e;let p=Gi(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:A,site:_}of p)o[A]=_,t.info(`Management dashboard → https://${_.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=zo(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=tu(s,l,t),S=Gi(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(S.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let k=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${el()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of S)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${k})`);return e.sites=o,e}function Go(e){return Object.keys(e.sites??{}).filter(Vr)}function Zs(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??L;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),D(e.build,{cwd:t,stdio:"inherit"});let n=O(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(E(),`${r.slug}-${r.siteName??eu}-${r.sha}.tar.gz`);return D(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
|
|
6
|
+
export{eu,el,tu,zo,Ho,Go,Zs};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
export{
|
|
1
|
+
function Gp(t,e){if(!Array.isArray(t.countries)||!t.countries.length||t.countries.some((n)=>!/^[A-Z]{2}$/.test(n)))throw Error("Residency requires an explicit country allowlist");if(!e.country||!t.countries.includes(e.country)||t.locations&&(!t.locations.length||!e.location||!t.locations.includes(e.location)))throw Error("Compute target is outside the required residency policy, or its provider location is unknown")}
|
|
2
|
+
export{Gp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bt}from"./chunk-t0r1rdj2.js";import"./chunk-btrxye8p.js";export{bt as STSClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{p,k}from"./chunk-540wkkhs.js";import{It,g}from"./chunk-gqstb8zn.js";import{$e,rr}from"./chunk-wayhpmn7.js";import{v}from"./chunk-4vtyjj7c.js";import{D}from"./chunk-6xx24qev.js";import{V}from"./chunk-y5gx3dq2.js";import{Wt,z}from"./chunk-0v5q5sh0.js";import{Yc}from"./chunk-ma0d990n.js";class ae{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}class q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(It(t))}async query(e){let t=new URLSearchParams(k({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,f)=>{t[`Statistics.member.${f+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,f)=>{t[`ExtendedStatistics.member.${f+1}`]=o}),(e.Dimensions??[]).forEach((o,f)=>{t[`Dimensions.member.${f+1}.Name`]=o.Name,t[`Dimensions.member.${f+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let f={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)f[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(f).length?f:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as W}from"node:path";var ie=1,ne=3600000,Se=24*ne,Ce=ne,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return W(e&&e.trim()?e:W(fe(),".cache"),"ts-cloud","cost-explorer")}function Q(e){return W(X(),e??"__default__")}function oe(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=W(Q(e),`${oe(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=Q(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(W(a,`${oe(t)}.json`),JSON.stringify(s))}function Fc(e){let t=e===void 0?X():Q(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let f=W(s,o.name);if(o.isDirectory())a(f);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function jc(e){return e===void 0?X():Q(e)}class Ye{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new p(It(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,f=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,d);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let y=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:f,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let E=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let K of E?.ResultsByTime??[])for(let N of K?.Groups??[]){let I=N.Keys?.[0]??"Unknown",H=Number.parseFloat(N.Metrics?.UnblendedCost?.Amount??"0"),Y=N.Metrics?.UnblendedCost?.Unit??"USD",O=y.get(I);y.set(I,{key:I,amount:(O?.amount??0)+H,unit:Y})}i=E?.NextPageToken||void 0}while(i);let L=[...y.values()].filter((b)=>b.amount>0).sort((b,E)=>E.amount-b.amount);if(this.useCache)ce(this.profile,d,L);return L}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function G(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function B(e,t,r,a,s,o){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!f.length)return 0;if(a==="Sum")return f.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,d)=>m+(d.Average??0),0)/f.length}async function j(e,t,r,a,s,o,f){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:f,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,y)=>d+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,y)=>d+(y.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((f,m)=>f+(m.Percentiles?.[r]??0),0))}async function Ti(e,t){let r=await z(e,t),a=r.region,s=new q(a),o=new D(a),f=new ae(a),m=new Date,d=new Date(m.getTime()-86400000),y=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let L=0,b=0,E=0,K=[],N=[],I=[];for(let n of r.functions){let[u,l,c,C,h,T,A,M,R]=await Promise.all([B(s,n.name,"Invocations","Sum",d,m),B(s,n.name,"Errors","Sum",d,m),B(s,n.name,"Throttles","Sum",d,m),B(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",d,m),te(s,n.name,"p95",d,m),te(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);L+=u,b+=l,E=Math.max(E,C);let F=h?.Configuration?.MemorySize??0,x=Object.keys(h?.Configuration?.Environment?.Variables??{}),_=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let w of J){let U=(w.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(U);if(re)S=Math.max(S,Number(re[1]));if(U&&!/^(?:START|END|REPORT|INIT_START)/.test(U))I.push({source:n.mode||n.name,timestamp:new Date(w.timestamp??0).toISOString(),when:Ae(w.timestamp??0),message:U.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(U)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(U)?"warn":"info"})}_=J.filter((w)=>!/^(?:START|END|REPORT|INIT_START)/.test((w.message??"").trim())).slice(-6).map((w)=>({ts:new Date(w.timestamp??0).toISOString().slice(11,19),msg:(w.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(w.message??"")}))}catch{}let P=Math.max(1,...R);K.push({key:n.mode,name:n.name,version:n.version,memory:F,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:A||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),N.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:F,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:T||Math.round(C),p95:A||Math.round(C),p99:M||Math.round(C),maxMem:S,spark:R.length?R.map((J)=>Math.round(J/P*100)):[0],env:x.length?x:["(none)"],recent:_.length?_:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=N,i.serverlessLogs=I.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=I.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=L?Number((b/L*100).toFixed(2)):0,Y=Math.round(await B(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(L),errorRatePct:H,p95Ms:Math.round(E),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new V(a),u=[],l=[],c=0;try{let{QueueUrl:h}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(h);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=y?rr(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),A=0,M=0;try{let{QueueUrl:F}=await n.getQueueUrl(h.name),{Attributes:x}=await n.getQueueAttributes(F);A=Number(x.ApproximateNumberOfMessages??0),M=Number(x.ApproximateNumberOfMessagesNotVisible??0)}catch{}let R=Math.round(await j(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",d,m));u.push({name:T,visible:A,inFlight:M,processed:R,dlq:c}),l.push({name:h.name,short:T,visible:A,inFlight:M,delayed:0,processed:R,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:u}=await n.describeStacks({stackName:$e(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[h,T]=await Promise.all([j(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",d,m),j(s,"AWS/RDS","DatabaseConnections",C,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:h?Number(h.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:l.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(y?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[h,T]=await Promise.all([j(s,"AWS/ElastiCache","CacheHits",C,"Sum",d,m),j(s,"AWS/ElastiCache","CacheMisses",C,"Sum",d,m)]),A=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:A,status:l.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(l.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(y.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new g(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:H,p95Ms:i.metrics.p95Ms,throttles:N.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=N.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Ye,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:G(l),end:G(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:G(c),end:G(l),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,P)=>S+P.amount,0),A=h.reduce((S,P)=>S+P.amount,0),M=u.getUTCDate(),R=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/M*R).toFixed(2)),lastMonthUsd:Number(A.toFixed(2)),dailyAvgUsd:Number((T/M).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,P)=>P.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/M).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:G(l),end:G(u)}).catch(()=>[]);let F=C.find((S)=>/lambda/i.test(S.service))?.amount??0,x=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),_=N.reduce((S,P)=>S+x(P),0)||1;i.costPerFn=N.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(x(S)),usd:Number((F*(x(S)/_)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new ee(a),c=await l.listWebACLs("REGIONAL"),C=c.find((h)=>h.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let h=await l.getWebACLRules(C.Name,C.Id,"REGIONAL");if(h.length)i.wafRules=h.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let O=[];if(i.aurora)O.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)O.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)O.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)O.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(O.length)i.dataServices=O;if(r.scheduler!=="off"&&y?.kind==="php")try{let n=await Wt(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
|
|
2
|
-
`)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(l);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)u.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(u.length)i.schedulerTasks=u}catch{}return i.topology=
|
|
3
|
-
export{ae,q,
|
|
1
|
+
import{p,k}from"./chunk-btrxye8p.js";import{It,g}from"./chunk-1wgyq50e.js";import{$e,rr}from"./chunk-sacx9p6f.js";import{v}from"./chunk-yf2drw7r.js";import{D}from"./chunk-19mhwmfp.js";import{V}from"./chunk-89v3ec9n.js";import{Wt,z}from"./chunk-nzg624aj.js";import{Zc}from"./chunk-gn7rdyz7.js";class ae{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}class q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(It(t))}async query(e){let t=new URLSearchParams(k({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,f)=>{t[`Statistics.member.${f+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,f)=>{t[`ExtendedStatistics.member.${f+1}`]=o}),(e.Dimensions??[]).forEach((o,f)=>{t[`Dimensions.member.${f+1}.Name`]=o.Name,t[`Dimensions.member.${f+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let f={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)f[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(f).length?f:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as W}from"node:path";var ie=1,ne=3600000,Se=24*ne,Ce=ne,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return W(e&&e.trim()?e:W(fe(),".cache"),"ts-cloud","cost-explorer")}function Q(e){return W(X(),e??"__default__")}function oe(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=W(Q(e),`${oe(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=Q(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(W(a,`${oe(t)}.json`),JSON.stringify(s))}function jc(e){let t=e===void 0?X():Q(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let f=W(s,o.name);if(o.isDirectory())a(f);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function Vc(e){return e===void 0?X():Q(e)}class Ye{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new p(It(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,f=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,d);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let y=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:f,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let E=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let K of E?.ResultsByTime??[])for(let N of K?.Groups??[]){let I=N.Keys?.[0]??"Unknown",H=Number.parseFloat(N.Metrics?.UnblendedCost?.Amount??"0"),Y=N.Metrics?.UnblendedCost?.Unit??"USD",O=y.get(I);y.set(I,{key:I,amount:(O?.amount??0)+H,unit:Y})}i=E?.NextPageToken||void 0}while(i);let L=[...y.values()].filter((b)=>b.amount>0).sort((b,E)=>E.amount-b.amount);if(this.useCache)ce(this.profile,d,L);return L}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function G(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function B(e,t,r,a,s,o){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!f.length)return 0;if(a==="Sum")return f.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,d)=>m+(d.Average??0),0)/f.length}async function j(e,t,r,a,s,o,f){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:f,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,y)=>d+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,y)=>d+(y.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((f,m)=>f+(m.Percentiles?.[r]??0),0))}async function Ti(e,t){let r=await z(e,t),a=r.region,s=new q(a),o=new D(a),f=new ae(a),m=new Date,d=new Date(m.getTime()-86400000),y=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let L=0,b=0,E=0,K=[],N=[],I=[];for(let n of r.functions){let[u,l,c,C,h,T,A,M,R]=await Promise.all([B(s,n.name,"Invocations","Sum",d,m),B(s,n.name,"Errors","Sum",d,m),B(s,n.name,"Throttles","Sum",d,m),B(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",d,m),te(s,n.name,"p95",d,m),te(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);L+=u,b+=l,E=Math.max(E,C);let F=h?.Configuration?.MemorySize??0,x=Object.keys(h?.Configuration?.Environment?.Variables??{}),_=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let w of J){let U=(w.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(U);if(re)S=Math.max(S,Number(re[1]));if(U&&!/^(?:START|END|REPORT|INIT_START)/.test(U))I.push({source:n.mode||n.name,timestamp:new Date(w.timestamp??0).toISOString(),when:Ae(w.timestamp??0),message:U.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(U)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(U)?"warn":"info"})}_=J.filter((w)=>!/^(?:START|END|REPORT|INIT_START)/.test((w.message??"").trim())).slice(-6).map((w)=>({ts:new Date(w.timestamp??0).toISOString().slice(11,19),msg:(w.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(w.message??"")}))}catch{}let P=Math.max(1,...R);K.push({key:n.mode,name:n.name,version:n.version,memory:F,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:A||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),N.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:F,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:T||Math.round(C),p95:A||Math.round(C),p99:M||Math.round(C),maxMem:S,spark:R.length?R.map((J)=>Math.round(J/P*100)):[0],env:x.length?x:["(none)"],recent:_.length?_:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=N,i.serverlessLogs=I.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=I.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=L?Number((b/L*100).toFixed(2)):0,Y=Math.round(await B(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(L),errorRatePct:H,p95Ms:Math.round(E),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new V(a),u=[],l=[],c=0;try{let{QueueUrl:h}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(h);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=y?rr(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),A=0,M=0;try{let{QueueUrl:F}=await n.getQueueUrl(h.name),{Attributes:x}=await n.getQueueAttributes(F);A=Number(x.ApproximateNumberOfMessages??0),M=Number(x.ApproximateNumberOfMessagesNotVisible??0)}catch{}let R=Math.round(await j(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",d,m));u.push({name:T,visible:A,inFlight:M,processed:R,dlq:c}),l.push({name:h.name,short:T,visible:A,inFlight:M,delayed:0,processed:R,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:u}=await n.describeStacks({stackName:$e(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[h,T]=await Promise.all([j(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",d,m),j(s,"AWS/RDS","DatabaseConnections",C,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:h?Number(h.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:l.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(y?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[h,T]=await Promise.all([j(s,"AWS/ElastiCache","CacheHits",C,"Sum",d,m),j(s,"AWS/ElastiCache","CacheMisses",C,"Sum",d,m)]),A=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:A,status:l.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(l.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(y.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new g(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:H,p95Ms:i.metrics.p95Ms,throttles:N.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=N.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Ye,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:G(l),end:G(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:G(c),end:G(l),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,P)=>S+P.amount,0),A=h.reduce((S,P)=>S+P.amount,0),M=u.getUTCDate(),R=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/M*R).toFixed(2)),lastMonthUsd:Number(A.toFixed(2)),dailyAvgUsd:Number((T/M).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,P)=>P.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/M).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:G(l),end:G(u)}).catch(()=>[]);let F=C.find((S)=>/lambda/i.test(S.service))?.amount??0,x=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),_=N.reduce((S,P)=>S+x(P),0)||1;i.costPerFn=N.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(x(S)),usd:Number((F*(x(S)/_)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new ee(a),c=await l.listWebACLs("REGIONAL"),C=c.find((h)=>h.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let h=await l.getWebACLRules(C.Name,C.Id,"REGIONAL");if(h.length)i.wafRules=h.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let O=[];if(i.aurora)O.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)O.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)O.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)O.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(O.length)i.dataServices=O;if(r.scheduler!=="off"&&y?.kind==="php")try{let n=await Wt(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
|
|
2
|
+
`)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(l);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)u.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(u.length)i.schedulerTasks=u}catch{}return i.topology=Zc(i,{project:e.project.name,environment:t}),i}
|
|
3
|
+
export{ae,q,jc,Vc,Ye,Ti};
|