@stacksjs/ts-cloud 0.16.23 → 0.16.24
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/client.d.ts +9 -0
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-0cwbg3pf.js +1 -0
- package/dist/bin/{chunk-6cfpdb35.js → chunk-0md2h0an.js} +4 -4
- package/dist/bin/chunk-0ytk5g2t.js +1 -0
- package/dist/bin/chunk-19tmmwmt.js +1 -0
- package/dist/bin/chunk-1fde3e2c.js +1 -0
- package/dist/bin/{chunk-2tk8egg8.js → chunk-1j9vy88a.js} +1 -1
- package/dist/bin/{chunk-wyanqf91.js → chunk-257sygzm.js} +2 -2
- package/dist/bin/{chunk-j0zg3mbm.js → chunk-2q27v6vz.js} +1 -1
- package/dist/bin/chunk-3b8a3knq.js +1 -0
- package/dist/bin/{chunk-9h7yjtz2.js → chunk-3jjggqfj.js} +3 -3
- package/dist/bin/{chunk-zcabmq4p.js → chunk-4sq6cvz5.js} +3 -3
- package/dist/bin/chunk-4y20ry45.js +1 -0
- package/dist/bin/{chunk-8vm7tpyv.js → chunk-5kc8s9gp.js} +1 -1
- package/dist/bin/{chunk-gzpwf3n4.js → chunk-5x59x4qw.js} +2 -2
- package/dist/bin/chunk-6aj3h8yk.js +1 -0
- package/dist/bin/{chunk-f3sd1hpa.js → chunk-6eesa8d1.js} +5 -5
- package/dist/bin/{chunk-jtnv8nwz.js → chunk-6nm91cfw.js} +1 -1
- package/dist/bin/{chunk-ht6tpmqw.js → chunk-7412q5cz.js} +2 -2
- package/dist/bin/chunk-78w3bn85.js +1 -0
- package/dist/bin/{chunk-cpwk0pbg.js → chunk-8e7n357e.js} +30 -30
- package/dist/bin/{chunk-ht318ydv.js → chunk-8knkt6sd.js} +1 -1
- package/dist/bin/{chunk-34kwhmbt.js → chunk-9464wvf2.js} +5 -5
- package/dist/bin/{chunk-jbpkwxht.js → chunk-988qv730.js} +4 -4
- package/dist/bin/chunk-9b6af1sj.js +1 -0
- package/dist/bin/{chunk-0r45d0s3.js → chunk-9e7pqhj1.js} +1 -1
- package/dist/bin/chunk-a07jfqvs.js +1 -0
- package/dist/bin/{chunk-cas0bp91.js → chunk-a3rq51az.js} +2 -2
- package/dist/bin/{chunk-gfwkmttt.js → chunk-apw5bbjg.js} +1 -1
- package/dist/bin/{chunk-33e0t7e5.js → chunk-ax41jhq7.js} +1 -1
- package/dist/bin/{chunk-k052rtd5.js → chunk-c35qm7as.js} +4 -4
- package/dist/bin/{chunk-f2yhthd1.js → chunk-d1psxeqj.js} +2 -2
- package/dist/bin/{chunk-0d98bem8.js → chunk-f0fpp4mk.js} +1 -1
- package/dist/bin/chunk-fpy7nv5g.js +1 -0
- package/dist/bin/chunk-fq4nxfec.js +1 -0
- package/dist/bin/chunk-ghe1nawv.js +1 -0
- package/dist/bin/{chunk-h90azajz.js → chunk-hez48c69.js} +1 -1
- package/dist/bin/{chunk-90kpnjdm.js → chunk-hjv1k8s9.js} +11 -11
- package/dist/bin/chunk-hwqvx1zb.js +1 -0
- package/dist/bin/{chunk-tyqxz92e.js → chunk-jdfbahjb.js} +101 -101
- package/dist/bin/chunk-jwdcx0mm.js +1 -0
- package/dist/bin/chunk-k9mzq7z9.js +1 -0
- package/dist/bin/chunk-kf1p7s61.js +1 -0
- package/dist/bin/{chunk-en7sf83z.js → chunk-m2gwzksz.js} +1 -1
- package/dist/bin/chunk-mh172wt8.js +1 -0
- package/dist/bin/{chunk-k1eezsj1.js → chunk-prj5b597.js} +2 -2
- package/dist/bin/{chunk-t1jpqn4x.js → chunk-q3xwh0r8.js} +6 -6
- package/dist/bin/chunk-q8crt80d.js +1 -0
- package/dist/bin/chunk-r3hkc2s3.js +1 -0
- package/dist/bin/{chunk-n298azax.js → chunk-rpfvv7hw.js} +1 -1
- package/dist/bin/{chunk-xs6afjat.js → chunk-wfa8j3wg.js} +3 -3
- package/dist/bin/{chunk-65rndjtr.js → chunk-wffaqgcc.js} +31 -31
- package/dist/bin/{chunk-hdsgfgnz.js → chunk-wg20x65t.js} +3 -3
- package/dist/bin/{chunk-21zhm1mk.js → chunk-wsedynyb.js} +6 -6
- package/dist/bin/chunk-xb82bmgf.js +1 -0
- package/dist/bin/{chunk-btr6zq53.js → chunk-xh5jcv64.js} +3 -3
- package/dist/bin/{chunk-v002yxaf.js → chunk-xss6yj73.js} +2 -2
- package/dist/bin/chunk-xxgybh3b.js +1 -0
- package/dist/bin/{chunk-hqmkfh4a.js → chunk-y6rgvb7r.js} +1 -1
- package/dist/bin/{chunk-yxyvhqhr.js → chunk-z5ycwy38.js} +2 -2
- package/dist/bin/chunk-zq02x716.js +1 -0
- package/dist/bin/cli.js +71 -71
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-1ba6keyk.js +1 -0
- package/dist/{chunk-4rb7stp5.js → chunk-3x9g48ey.js} +3 -3
- package/dist/{chunk-gm0qysea.js → chunk-4rkjhvgw.js} +6 -6
- package/dist/{chunk-nfkdgsgh.js → chunk-65yh2h1e.js} +1 -1
- package/dist/{chunk-60fn008g.js → chunk-6e5j40n9.js} +2 -2
- package/dist/{chunk-xkqx98bx.js → chunk-97trx8p9.js} +2 -2
- package/dist/{chunk-14zcywnp.js → chunk-9ca1yafd.js} +2 -2
- package/dist/{chunk-hpq0rrve.js → chunk-bzbryxfm.js} +1 -1
- package/dist/{chunk-c836kdrx.js → chunk-d8w90gsb.js} +17 -17
- package/dist/{chunk-j2w0cvnr.js → chunk-dm6kyz6e.js} +1 -1
- package/dist/chunk-e3axmek0.js +1 -0
- package/dist/chunk-e4z4tfh6.js +1 -0
- package/dist/{chunk-01rbgche.js → chunk-e7m70ex1.js} +1 -1
- package/dist/{chunk-bz1hp7es.js → chunk-gvybjt7y.js} +1 -1
- package/dist/{chunk-xassxhvq.js → chunk-h85wqdvr.js} +7 -7
- package/dist/{chunk-92gn9ght.js → chunk-hzbyj0xd.js} +19 -19
- package/dist/{chunk-b5xjjz3y.js → chunk-jrrw3ezm.js} +5 -5
- package/dist/{chunk-t7q4awss.js → chunk-mv7hne2c.js} +1 -1
- package/dist/chunk-qa6jjv3m.js +1 -0
- package/dist/{chunk-ckwdjb5q.js → chunk-qfqh21rq.js} +5 -5
- package/dist/{chunk-2hy7ny4k.js → chunk-qrchr75r.js} +4 -4
- package/dist/{chunk-4apkvhsc.js → chunk-rgq7m90a.js} +48 -48
- package/dist/chunk-rnjgde95.js +1 -0
- package/dist/{chunk-g6aev693.js → chunk-rr1qjxyj.js} +1 -1
- package/dist/{chunk-cwgy9pvc.js → chunk-t4ynyk8k.js} +3 -3
- package/dist/{chunk-ds2v2xpb.js → chunk-v7y50hhf.js} +82 -82
- package/dist/{chunk-cpyrhh52.js → chunk-vtm83crj.js} +79 -79
- package/dist/{chunk-5vxpgw8q.js → chunk-wrpnnrdf.js} +5 -5
- package/dist/{chunk-pdmfmsm9.js → chunk-x9bpm5s1.js} +1 -1
- package/dist/{chunk-rq0wrpz6.js → chunk-zv85cpt2.js} +4 -4
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +18 -18
- 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 +6 -6
- 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 +5 -5
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +6 -6
- 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 +1 -1
- 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 +1 -1
- package/dist/ui/serverless/alarms.html +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- 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-2g1j00yc.js +0 -1
- package/dist/bin/chunk-4xmhrvfa.js +0 -1
- package/dist/bin/chunk-6crapvp1.js +0 -1
- package/dist/bin/chunk-7b4gf64x.js +0 -1
- package/dist/bin/chunk-818tj49e.js +0 -1
- package/dist/bin/chunk-92qsww97.js +0 -1
- package/dist/bin/chunk-9947rscj.js +0 -1
- package/dist/bin/chunk-cyap08qg.js +0 -1
- package/dist/bin/chunk-dk92s260.js +0 -1
- package/dist/bin/chunk-ejxp74ks.js +0 -1
- package/dist/bin/chunk-gx98tkpf.js +0 -1
- package/dist/bin/chunk-hcdbw9j1.js +0 -1
- package/dist/bin/chunk-kay11qc7.js +0 -1
- package/dist/bin/chunk-n28a9a9c.js +0 -1
- package/dist/bin/chunk-q8w7fa56.js +0 -1
- package/dist/bin/chunk-qdnx952p.js +0 -1
- package/dist/bin/chunk-tr0pkm4p.js +0 -1
- package/dist/bin/chunk-tytvrehe.js +0 -1
- package/dist/bin/chunk-wpp0fa94.js +0 -1
- package/dist/bin/chunk-xzgxwnb7.js +0 -1
- package/dist/bin/chunk-y21yk6zv.js +0 -1
- package/dist/bin/chunk-yt1t5ct8.js +0 -1
- package/dist/bin/chunk-zs8ddeaz.js +0 -1
- package/dist/chunk-e4qh4c2n.js +0 -1
- package/dist/chunk-pj9z4fjv.js +0 -1
- package/dist/chunk-twhbns31.js +0 -1
- package/dist/chunk-wkg22nj5.js +0 -1
- package/dist/chunk-xtd0s5ep.js +0 -1
package/dist/aws/client.d.ts
CHANGED
|
@@ -81,6 +81,15 @@ export interface AWSError extends Error {
|
|
|
81
81
|
/**
|
|
82
82
|
* AWS API Client - Makes authenticated requests to AWS services
|
|
83
83
|
*/
|
|
84
|
+
/**
|
|
85
|
+
* Convert parsed XML text the way the parser's own option did, minus the
|
|
86
|
+
* lossy cases: `true`/`false` become booleans, and text becomes a number only
|
|
87
|
+
* when the number prints back as exactly the same text. So `16` and
|
|
88
|
+
* `923076644019` are numbers, while `+18082188241` (a phone number), `7.0`
|
|
89
|
+
* (an engine version), `1.50`, `0x1F`, `1e3` and a 20-digit ID stay strings.
|
|
90
|
+
* Exported for tests.
|
|
91
|
+
*/
|
|
92
|
+
export declare function coerceXmlValues(node: any): any;
|
|
84
93
|
export declare class AWSClient {
|
|
85
94
|
private credentials?;
|
|
86
95
|
private config;
|
package/dist/aws/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ae,nr,
|
|
1
|
+
import{Ae,nr,ls,us,bu,Qa,Ha,ps,gs,Ga,tt,z,rt,se,E,ye,An,qa,Oe,Va,yn,In,Sn,vh,Th,Ny,ky,By,_y,wt,xy,Oy,Ly,$y,Rt,wh,Rh,Dh,Dt,Ph,Nh,kh,Cn,My,Fy,Uy,ir,Qy,Hy,Gy,ja,za,vu,qy,Vy,jy,sr,Bh,_h,or,nt,En,Ka,Tu,zy,wu,Ky,Pt,Wy,Jy,Xy,Yy,ae,Zy,eI,tI,rI,ar,nI,iI,sI,bn,Wa,Ja,Ru,Du,Xa,cr}from"../chunk-4rkjhvgw.js";import{Ie,it,vn,xh}from"../chunk-t4ynyk8k.js";import{y}from"../chunk-65yh2h1e.js";import{Le}from"../chunk-dm6kyz6e.js";import{K}from"../chunk-e7m70ex1.js";import{st,ce,$e,Se,Nt,wn,hs,fs,dr,lr,Rn,ur,As,ys,Is,Ss,W,Cs,Es,bs,vs,de,Ts,ws,Rs,w,ec,Dn,tc,le,pr}from"../chunk-97trx8p9.js";import{I}from"../chunk-mv7hne2c.js";import{Tr,we}from"../chunk-x9bpm5s1.js";import{f}from"../chunk-bzbryxfm.js";import{o}from"../chunk-3x9g48ey.js";import{Rr,di,n,l,tf}from"../chunk-wrpnnrdf.js";export{le as ACMClient,pr as ACMDnsValidator,n as AWSClient,Ka as ApplicationAutoScalingClient,nr as AwsBackupClient,Th as BedrockAgentClient,vh as BedrockAgentRuntimeClient,Sn as BedrockClient,In as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ye as CloudWatchLogsClient,Se as CloudflareProvider,wt as ComprehendClient,An as ConnectClient,gs as CostExplorerClient,Dn as DnsProviderFactory,Oe as DynamoDBClient,Tr as EC2Client,Le as ECRClient,tt as ECSClient,cr as EFSClient,qa as ELBv2Client,nt as ElastiCacheClient,vn as EmailClient,or as EventBridgeClient,$e as GoDaddyProvider,Ie as IAMClient,Tu as ImapServer,sr as KendraClient,E as LambdaClient,Va as OpenSearchClient,st as PROXIABLE_RECORD_TYPES,ja as PersonalizeClient,vu as PersonalizeEventsClient,za as PersonalizeRuntimeClient,Cn as PollyClient,ce as PorkbunProvider,K as RDSClient,Rt as RekognitionClient,I as Route53Client,Ga as Route53DomainsClient,W as Route53Provider,o as S3Client,it as SESClient,rt as SNSClient,se as SQSClient,we as SSMClient,Ae as STSClient,En as SchedulerClient,z as SecretsManagerClient,Pt as SmsClient,Xa as SmsVoiceClient,wu as SmtpServer,bn as SupportClient,Wa as SupportTemplates,Dt as TextractClient,yn as TranscribeClient,ir as TranslateClient,de as UnifiedDnsValidator,ar as VoiceClient,xy as analyzeSentiment,Is as applyDeclaredZoneSettings,bs as applyZoneMigration,l as buildQueryParams,di as coerceXmlValues,By as completeWithClaude,$y as containsPii,Rh as countFacesInS3Image,Yy as createDeliveryReceiptHandler,w as createDnsProvider,ws as createGoDaddyValidator,ps as createObjectStorageClient,Ts as createPorkbunValidator,iI as createRecordingHandler,Rs as createRoute53Validator,Uy as createSSML,Jy as createScheduledSmsHandler,Xy as createSmsClient,Wy as createSmsInboxHandler,Du as createSmsInfrastructure,sI as createVoiceClient,nI as createVoicemailHandler,ur as delegateZone,As as delegateZoneFromConfig,ys as describeDelegation,Ss as describeZoneSettings,tf as detectCredentialSource,ec as detectDnsProvider,wh as detectLabelsFromS3,Ly as detectLanguage,tc as dnsProviders,xh as email,Cs as exportRoute53Zone,Oy as extractEntities,Nh as extractFormsFromS3,kh as extractTablesFromS3,Ph as extractTextFromS3,Zy as formatPhoneNumber,_y as generateEmbeddings,tI as getCountryCode,qy as getRecommendations,Vy as getSimilarItems,Ru as getSmsInfrastructureStatus,Dh as isContentSafe,dr as isNameserverRegistrar,rI as isSamePhoneNumber,eI as isValidPhoneNumber,lr as isZoneHost,us as keyMatchesFilters,ky as listClaudeModels,Gy as listLanguages,Fy as listVoices,bu as migrateObjectStorage,ae as normalizePhoneNumber,Es as planZoneMigration,Nt as policyTag,Qa as providerEndpoint,wn as qualifyName,fs as reconcileDeclaredRecords,ls as remapKey,Ny as requestModelAccess,hs as resolveDeclaredRecords,Ha as resolveObjectStorage,Rr as resolveS3Endpoint,_h as retrieveForRag,Rn as sameNameservers,Bh as search,Ja as setupSmsInfrastructure,zy as startImapServer,Ky as startSmtpServer,My as textToSpeech,jy as trackEvent,Qy as translate,Hy as translateToMultiple,vs as verifyZoneParity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{R}from"./chunk-1j9vy88a.js";import"./chunk-q3xwh0r8.js";export{R as LambdaClient};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{z,Rr}from"./chunk-
|
|
1
|
+
import{z,Rr}from"./chunk-jdfbahjb.js";function K(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ai(e){return e.type!=null&&_e.has(e.type)}function _s(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return _s(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ai(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ai(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function go(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function xs(e,t={}){let r=[],n=[],i=e.sites||{},s=go(e),c=Rr(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function $s(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function ac(e){return P(e)==="bucket"}function cc(e,t){if(z(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function br(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ze(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function fo(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",q="mail",F=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function G(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
2
2
|
`)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${G(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${G(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
|
|
3
3
|
`)}function he(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${S}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${S}`,"","[Install]","WantedBy=multi-user.target",""].join(`
|
|
4
4
|
`)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=G(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ze(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(te(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Te(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${M}/pantry/.bin`,W=15306,Y=15991,V=15999,ne=16101,w=2379,v="/var/lib/vitess",X=100;function ci(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
|
|
5
5
|
`)}function A(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${_}`,`Group=${_}`,`Environment="PATH=${be}"`,`Environment="VTDATAROOT=${v}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
|
|
6
|
-
`)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??W,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Y}`,`--grpc-port ${V}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${w}`,`--advertise-client-urls http://127.0.0.1:${w}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${w}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${V}`,`--port ${V+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${Y}`,`--grpc-port ${Y+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${w}`,n=`${g}/vtctldclient --server 127.0.0.1:${V}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function ho(e){if(!ci(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ze(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function li(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function vr(e,t="psql"){let r=e?.port??5432;if(li(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function yo(e={},t={}){let r=Ne(e),n=ho(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ze(r.packages),...fo(r.services),...n,...i]}function bt(e,t={}){if(!e?.name)return[];if(!li(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],B=[];for(let H of k)if(u.access==="readonly")B.push(`GRANT CONNECT ON DATABASE ${a(H)} TO ${a(u.username)};`,`\\connect ${a(H)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else B.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(H)} TO ${a(u.username)};`);return B},I=e.users||[],me=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${vr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[St(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${vr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function cc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",en="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
6
|
+
`)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??W,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Y}`,`--grpc-port ${V}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${w}`,`--advertise-client-urls http://127.0.0.1:${w}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${w}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${V}`,`--port ${V+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${Y}`,`--grpc-port ${Y+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${w}`,n=`${g}/vtctldclient --server 127.0.0.1:${V}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function ho(e){if(!ci(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ze(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function li(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function vr(e,t="psql"){let r=e?.port??5432;if(li(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function yo(e={},t={}){let r=Ne(e),n=ho(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ze(r.packages),...fo(r.services),...n,...i]}function bt(e,t={}){if(!e?.name)return[];if(!li(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],B=[];for(let H of k)if(u.access==="readonly")B.push(`GRANT CONNECT ON DATABASE ${a(H)} TO ${a(u.username)};`,`\\connect ${a(H)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else B.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(H)} TO ${a(u.username)};`);return B},I=e.users||[],me=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${vr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[St(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${vr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function lc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",en="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
7
7
|
`)}function Be(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
8
|
-
`)}function So(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${en} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${en}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${en} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function di(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${vr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var bo=["storage",".env"],ui=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function
|
|
9
|
-
export{K,ai,
|
|
8
|
+
`)}function So(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${en} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${en}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${en} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function di(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${vr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var bo=["storage",".env"],ui=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Os(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function vo(e){return`${e.shared}/stx-images`}function Bt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Ls(e){return typeof e==="string"?e:e.path}function dc(e){let t=new Map;for(let r of e)t.set(Ls(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function pi(e,t=bo){let r=[`mkdir -p ${e.releases} ${e.shared} ${vo(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ms(e,t=900){let r=`${C(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Us(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ge(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Bs(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ge(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Fs(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ye(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function To(e,t=bo){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ye(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function tn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function uc(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function rn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Ke(e){return`${C(e)}/owner`}function js(e,t){let r=Ke(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function Eo(e,t){let r=C(e),n=qe(e,t.releaseId),i=Os(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
|
|
9
|
+
export{K,ai,_s,P,go,xs,$s,ac,cc,M,br,St,Ze,fo,ci,ho,li,vr,yo,bt,lc,en,So,di,bo,ui,Os,vo,Bt,Ls,dc,pi,Ms,Us,Bs,Fs,To,tn,uc,rn,js,Eo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{zu,Hu,qu,Wu}from"./chunk-5x59x4qw.js";import"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";import"./chunk-jdfbahjb.js";export{Wu as deleteFailoverReplicaBuckets,zu as ensureFailoverReplicaBuckets,Hu as grantFailoverReplicaAccess,qu as seedFailoverReplicas};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g}from"./chunk-2q27v6vz.js";import"./chunk-q3xwh0r8.js";export{g as S3Client};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Gu,Xr,Hi,oe,Ku,Fa,nd,ns,Ju,Xu,Qu,ja,qi,is,Va,Qr,gr,Yu,ti,Zu,za,id,od,os,Ha,qa,fr,Wi,hr,Wa,ss,ri,sd,Gi,Ga,Ka,Ki,ad,Ja,Xa,Qa,Ya,as,cd,ld,ep,dd,Za,Ji,ud,pd,cs,xt,ls,ds,us,ec,md,tc,ps,tp,ft,rp,rc,$t,nc,np,ic,gd,ip,Y,fd,ms,op,Xi,ni,ii,gs,hd,yd,sp,fs,hs}from"./chunk-hjv1k8s9.js";import"./chunk-257sygzm.js";import"./chunk-jdfbahjb.js";export{cs as AnomalyConfigStore,hd as AwsSpendTransport,yd as ComputeSpendTransport,os as CounterTracker,za as DEFAULT_METER_MAPPINGS,ja as DEFAULT_PRICE_BOOK,Wi as DEFAULT_THRESHOLDS,xt as DETECTABLE_SIGNALS,Hi as ENFORCEMENT_ACTIONS,Ki as ENFORCEMENT_DESCRIPTIONS,oe as ENFORCEMENT_SEVERITY,md as FOCUS_VERSION,Xr as METERS,Gu as METER_KEYS,Ku as MICRO_CENTS,sd as MIN_PROJECTION_CONFIDENCE,gd as RecordingSpendTransport,ud as SENSITIVITY_THRESHOLDS,ii as SPEND_CYCLE_SECONDS,rc as SPEND_GATE_SETTING,op as SPEND_LEASE_SETTING,ds as SignalSource,nc as SpendCapError,$t as SpendGate,Xi as SpendLoopLease,ms as SpendNotificationRouter,ni as SpendRunner,ft as SpendService,hr as SpendStore,ip as URGENT_SPEND_EVENTS,ad as USER_VISIBLE_ACTIONS,qa as aggregateDeltas,Ji as anomalyOptionsForSignal,np as assertSpendAllows,gr as budgetWindow,sp as compositeSpendTransport,ic as createEnforcementHandlers,dd as detectAnomalies,Za as detectLatestAnomaly,Ga as evaluateBudget,ep as ewma,id as findMapping,nd as findPriceEntry,Y as formatCents,ri as formatTimeToExhaustion,Gi as governingLimitCents,fs as handleSpendRequest,ti as hourBucket,Zu as hourBucketsBetween,Ya as isOperationAllowed,qi as isValidTimeZone,ec as lookbackHoursForSignal,as as median,cd as medianAbsoluteDeviation,Ka as mergeDecisions,Qu as mergePriceBooks,Ha as meterTelemetry,us as optionsForSignal,ss as percentOfLimit,Ja as planEnforcement,Yu as previousBudgetWindow,ns as priceUsage,Ju as priceUsageLines,Wa as projectSpend,ld as robustZScore,Xu as roundCents,pd as routeMatches,Xa as runEnforcement,fr as scopeKey,ls as signalDefinition,fd as spendNotificationText,hs as spendOpenApiPaths,gs as startSpendLoop,tp as streamFocusJsonl,Qa as strongestActiveAction,Fa as tieredMicroCents,ps as toFocusJsonl,tc as toFocusRecords,od as usageDeltaKey,Qr as utcInstantOfLocal,rp as zeroFill,Va as zoneOffsetMs,is as zonedParts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u}from"./chunk-t1jpqn4x.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.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),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}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 R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(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=d(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 l=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:l,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((l)=>setTimeout(l,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=d(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{u}from"./chunk-q3xwh0r8.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.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),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}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 R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(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=d(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 l=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:l,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((l)=>setTimeout(l,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=d(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{R};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A}from"./chunk-
|
|
1
|
+
import{A}from"./chunk-jdfbahjb.js";var se=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(se),admin:new Set(se.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function on(e){return Ee[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function te(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(on(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function sn(e){return se.filter((t)=>te({...e,capability:t}).allowed)}import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as de}from"node:fs";import{dirname as ee}from"node:path";import{Database as Ne}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
|
|
2
2
|
CREATE TABLE projects (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
slug TEXT NOT NULL UNIQUE,
|
|
@@ -1504,4 +1504,4 @@ import{A}from"./chunk-tyqxz92e.js";var se=["project:read","config:read","config:
|
|
|
1504
1504
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.organizationId,i.membershipId,i.effect,i.capability,i.scope.type,i.scope.id??null,i.source??"manual",i.createdAt,i.updatedAt]);for(let i of e.operations)o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
|
|
1505
1505
|
input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
|
|
1506
1506
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId??null,i.environmentId??null,i.resourceId??null,i.actorId??null,i.kind,i.state,i.correlationId,i.idempotencyKey??null,N(i.input),N(i.output),M(i.error)??null,i.attempt,i.priority,i.leaseOwner??null,i.leaseExpiresAt??null,i.cancelRequestedAt??null,i.startedAt??null,i.finishedAt??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.events)o(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1507
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function
|
|
1507
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Hs(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ae(n.desiredState,pe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ne)=>ne.name)].filter(Boolean).join(" "),X=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ae(n.input,ue),U=n.kind.includes("deploy"),m=C[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{se,on,te,sn,h,Ir,Hs};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{gi,u}from"./chunk-
|
|
1
|
+
import{gi,u}from"./chunk-q3xwh0r8.js";import{mi}from"./chunk-z5ycwy38.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 vt(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}=mi("node:fs"),{homedir:i}=mi("node:os"),{join:n}=mi("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 h of o.split(`
|
|
2
2
|
`)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.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?gi({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 u(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=vt(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>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Lu,Ql,Ca,Aa,Yl,Mu,Uu,Gt,un,Kt,Ii,Bu,pn,Vo}from"./chunk-8knkt6sd.js";import{Xe,ys,oc,oi,Ss,ap}from"./chunk-9464wvf2.js";import{Sd,Yi,bd,vd,Td,yr,cp,Zi}from"./chunk-wsedynyb.js";import{Sa,ba,va,Bl,Bo,Fl,jl,Ta,Vl,zl}from"./chunk-jdfbahjb.js";export{ba as CHAIN_HEADER,un as DEFAULT_ATTACK_MODE_HOURS,Sd as DEFAULT_DDOS_THRESHOLDS,Bo as DEFAULT_RECURSION_LIMITS,Sa as DEPTH_HEADER,Gt as MAX_CONTROL_HOURS,Kt as ProtectionControlStore,Lu as RATE_LIMIT_KEY_SEPARATOR,Yl as RateLimiter,Ta as RecursionGuard,va as TRACE_HEADER,pn as applyControlsToDdos,Bu as applyControlsToRateLimits,Zi as applyMitigationFactor,Uu as defaultRateLimitRules,Ii as describePosture,Xe as escapeSecLang,Bl as functionFingerprint,Ql as globMatches,oc as globToRegex,jl as inspectInvocation,ys as isSafePattern,Yi as isValidCidr,Vo as mergeControlsIntoConfig,Fl as parseChain,cp as planMitigation,Vl as propagationHeaders,Mu as rateLimitHeaders,Aa as rateLimitKey,zl as recursionBlockedResponse,yr as renderDdosInstallScript,Td as renderNftablesRuleset,vd as renderSysctlFile,oi as renderWafConfig,Ss as renderWafInstallScript,Ca as ruleMatches,bd as sysctlHardening,ap as wafEventTelemetry};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Id}from"./chunk-z5ycwy38.js";var f={};Id(f,{ProgressBar:()=>v,Spinner:()=>o,box:()=>Se,checkAwsCli:()=>Is,checkAwsCredentials:()=>Rs,colorize:()=>Ut,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>Zr,formatDuration:()=>b,getAwsAccountId:()=>Ps,getAwsRegions:()=>Ns,header:()=>i,info:()=>e,prompt:()=>I,select:()=>mo,step:()=>p,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Sr});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Ut(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Sr=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function p(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
|
|
2
2
|
${T.bright}${T.cyan}${t}${T.reset}
|
|
3
3
|
`)}var x=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class o{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,x&&this.interval)console.log(` ${t}`)}start(){if(x){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${T.cyan}${this.frames[this.currentFrame]}${T.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),n(t||this.message)}fail(t){this.stop(),r(t||this.message)}warn(t){this.stop(),Sr(t||this.message)}stop(){if(this.interval){if(!x)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class v{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),s=Math.floor(this.current/this.total*this.width),l=this.width-s,u=`${"█".repeat(s)}${"░".repeat(l)}`;if(process.stdout.write(`\r${T.cyan}${u}${T.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
|
|
4
4
|
`)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((h)=>{let g=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(g,(m)=>{u.close(),h(m||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function mo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((h,g)=>{console.log(` ${T.gray}${g+1}.${T.reset} ${h}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((h,g)=>{let m=Math.max(...s.map((w)=>(w[g]||"").length));return Math.max(h.length,m)}),u=t.map((h,g)=>h.padEnd(l[g])).join(" ");console.log(Ut(u,"bright")),console.log(Ut("─".repeat(u.length),"gray")),s.forEach((h)=>{let g=h.map((m,w)=>(m||"").padEnd(l[w])).join(" ");console.log(g)})}function Zr(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let h=Math.floor(l/60),g=l%60;return`${h}h ${g}m`}function Se(t,s="cyan"){let l=t.split(`
|
|
5
|
-
`),u=Math.max(...l.map((g)=>g.length)),h="─".repeat(u+2);console.log(Ut(`┌${h}┐`,s)),l.forEach((g)=>{console.log(Ut(`│ ${g.padEnd(u)} │`,s))}),console.log(Ut(`└${h}┘`,s))}async function
|
|
6
|
-
export{T,Ut,n,r,a,Sr,e,p,i,o,I,d,mo,c,Zr,Se,
|
|
5
|
+
`),u=Math.max(...l.map((g)=>g.length)),h="─".repeat(u+2);console.log(Ut(`┌${h}┐`,s)),l.forEach((g)=>{console.log(Ut(`│ ${g.padEnd(u)} │`,s))}),console.log(Ut(`└${h}┘`,s))}async function Is(){return!0}async function Rs(){try{let{AWSClient:t}=await import("./chunk-hwqvx1zb.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Ps(){try{let{AWSClient:t}=await import("./chunk-hwqvx1zb.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ns(){try{let{AWSClient:t}=await import("./chunk-hwqvx1zb.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let h=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...h.map((g)=>g.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
|
|
6
|
+
export{T,Ut,n,r,a,Sr,e,p,i,o,I,d,mo,c,Zr,Se,Is,Rs,Ps,Ns,f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{De,Wt}from"./chunk-tyqxz92e.js";import{u,N}from"./chunk-t1jpqn4x.js";import{v}from"./chunk-0r45d0s3.js";import{vt,g}from"./chunk-j0zg3mbm.js";import{R}from"./chunk-2tk8egg8.js";import{j}from"./chunk-n298azax.js";import{Mt,V}from"./chunk-btr6zq53.js";import{xa}from"./chunk-v002yxaf.js";class q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(vt(t))}async query(e){let t=new URLSearchParams(N({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 p of m)if(p?.key!=null)f[p.key]=Number(p.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)}}class ie{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(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)})}}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 ae=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!==ae)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:ae,savedAt:Date.now(),key:t,response:r};ye(W(a,`${oe(t)}.json`),JSON.stringify(s))}function Pa(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 Na(e){return e===void 0?X():Q(e)}class Ve{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new u(vt(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}],p={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,p);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 A of K?.Groups??[]){let F=A.Keys?.[0]??"Unknown",H=Number.parseFloat(A.Metrics?.UnblendedCost?.Amount??"0"),Y=A.Metrics?.UnblendedCost?.Unit??"USD",O=y.get(F);y.set(F,{key:F,amount:(O?.amount??0)+H,unit:Y})}i=E?.NextPageToken||void 0}while(i);let I=[...y.values()].filter((b)=>b.amount>0).sort((b,E)=>E.amount-b.amount);if(this.useCache)ce(this.profile,p,I);return I}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 u}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 u}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 z(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,p)=>m+(p.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,p)=>m+(p.Average??0),0)/f.length}async function B(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((p,y)=>p+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((p)=>p.Maximum??0));return m.reduce((p,y)=>p+(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 qn(e,t){let r=await V(e,t),a=r.region,s=new q(a),o=new R(a),f=new ie(a),m=new Date,p=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 I=0,b=0,E=0,K=[],A=[],F=[];for(let n of r.functions){let[l,d,c,C,h,T,M,x,L]=await Promise.all([z(s,n.name,"Invocations","Sum",p,m),z(s,n.name,"Errors","Sum",p,m),z(s,n.name,"Throttles","Sum",p,m),z(s,n.name,"Duration","Average",p,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",p,m),te(s,n.name,"p95",p,m),te(s,n.name,"p99",p,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(()=>[])]);I+=l,b+=d,E=Math.max(E,C);let U=h?.Configuration?.MemorySize??0,D=Object.keys(h?.Configuration?.Environment?.Variables??{}),_=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:p.getTime(),limit:120});for(let w of J){let k=(w.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(k);if(re)S=Math.max(S,Number(re[1]));if(k&&!/^(?:START|END|REPORT|INIT_START)/.test(k))F.push({source:n.mode||n.name,timestamp:new Date(w.timestamp??0).toISOString(),when:Ae(w.timestamp??0),message:k.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(k)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(k)?"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,...L);K.push({key:n.mode,name:n.name,version:n.version,memory:U,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(l),errors:Math.round(d),p95:M||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),A.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:U,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(l),errors:Math.round(d),throttles:Math.round(c),p50:T||Math.round(C),p95:M||Math.round(C),p99:x||Math.round(C),maxMem:S,spark:L.length?L.map((J)=>Math.round(J/P*100)):[0],env:D.length?D:["(none)"],recent:_.length?_:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=A,i.serverlessLogs=F.sort((n,l)=>String(l.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=F.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=I?Number((b/I*100).toFixed(2)):0,Y=Math.round(await z(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",p,m));i.metrics={invocations:Math.round(I),errorRatePct:H,p95Ms:Math.round(E),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new j(a),l=[],d=[],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?Wt(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),M=0,x=0;try{let{QueueUrl:U}=await n.getQueueUrl(h.name),{Attributes:D}=await n.getQueueAttributes(U);M=Number(D.ApproximateNumberOfMessages??0),x=Number(D.ApproximateNumberOfMessagesNotVisible??0)}catch{}let L=Math.round(await B(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",p,m));l.push({name:T,visible:M,inFlight:x,processed:L,dlq:c}),d.push({name:h.name,short:T,visible:M,inFlight:x,delayed:0,processed:L,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(l.length)i.queues=l;if(d.length)i.queuesDetail=d;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:l}=await n.describeStacks({stackName:De(e,t)}),d={};for(let c of l?.[0]?.Outputs??[])if(c.OutputKey)d[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([B(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",p,m),B(s,"AWS/RDS","DatabaseConnections",C,"Maximum",p,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:d.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:d.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([B(s,"AWS/ElastiCache","CacheHits",C,"Sum",p,m),B(s,"AWS/ElastiCache","CacheMisses",C,"Sum",p,m)]),M=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:M,status:d.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(d.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:d.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:d.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=d.AssetsCdnDomain?{bucket:d.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:d.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 l=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=l.length,i.assetsInfo.sizeMb=Number((l.reduce((d,c)=>d+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=l.slice(0,8).map((d)=>({path:`/${d.Key}`,size:`${Math.max(1,Math.round((d.Size??0)/1024))} KB`,type:d.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((l)=>({key:l.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:l})):Object.entries(y.secrets).map(([l,d])=>({key:l,source:String(d)}));i.secretsList=n.map((l)=>({...l,updated:"—"}))}}catch{}try{let n=new g(a),l=`${r.slug}-${t}-deployments`,d=await n.getObjectJson(l,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(d?.records?.length)i.deploymentsDetail=d.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:A.reduce((n,l)=>n+l.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=A.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 Ve,l=m,d=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),1)),c=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:G(d),end:G(l),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:G(c),end:G(d),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,P)=>S+P.amount,0),M=h.reduce((S,P)=>S+P.amount,0),x=l.getUTCDate(),L=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/x*L).toFixed(2)),lastMonthUsd:Number(M.toFixed(2)),dailyAvgUsd:Number((T/x).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/x).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:G(d),end:G(l)}).catch(()=>[]);let U=C.find((S)=>/lambda/i.test(S.service))?.amount??0,D=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),_=A.reduce((S,P)=>S+D(P),0)||1;i.costPerFn=A.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(D(S)),usd:Number((U*(D(S)/_)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:p,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),l=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:p,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(l.reduce((d,c)=>d+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((d,c)=>d+(c.Sum??0),0))};try{let d=new ee(a),c=await d.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 d.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 Mt(e,t,"schedule:list"),l=[];for(let d of(n||"").split(`
|
|
2
|
-
`)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(d);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)l.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(l.length)i.schedulerTasks=l}catch{}return i.topology
|
|
3
|
-
export{ie,q,
|
|
1
|
+
import{De,Wt}from"./chunk-jdfbahjb.js";import{u,N}from"./chunk-q3xwh0r8.js";import{v}from"./chunk-9e7pqhj1.js";import{vt,g}from"./chunk-2q27v6vz.js";import{R}from"./chunk-1j9vy88a.js";import{j}from"./chunk-rpfvv7hw.js";import{Mt,V}from"./chunk-xh5jcv64.js";import{$a}from"./chunk-xss6yj73.js";class q{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(vt(t))}async query(e){let t=new URLSearchParams(N({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 p of m)if(p?.key!=null)f[p.key]=Number(p.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)}}class ie{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(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)})}}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 ae=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!==ae)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:ae,savedAt:Date.now(),key:t,response:r};ye(W(a,`${oe(t)}.json`),JSON.stringify(s))}function Na(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 Da(e){return e===void 0?X():Q(e)}class Ve{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new u(vt(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}],p={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,p);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 A of K?.Groups??[]){let F=A.Keys?.[0]??"Unknown",H=Number.parseFloat(A.Metrics?.UnblendedCost?.Amount??"0"),Y=A.Metrics?.UnblendedCost?.Unit??"USD",O=y.get(F);y.set(F,{key:F,amount:(O?.amount??0)+H,unit:Y})}i=E?.NextPageToken||void 0}while(i);let I=[...y.values()].filter((b)=>b.amount>0).sort((b,E)=>E.amount-b.amount);if(this.useCache)ce(this.profile,p,I);return I}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 u}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 u}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 z(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,p)=>m+(p.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,p)=>m+(p.Average??0),0)/f.length}async function B(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((p,y)=>p+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((p)=>p.Maximum??0));return m.reduce((p,y)=>p+(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 qn(e,t){let r=await V(e,t),a=r.region,s=new q(a),o=new R(a),f=new ie(a),m=new Date,p=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 I=0,b=0,E=0,K=[],A=[],F=[];for(let n of r.functions){let[l,d,c,C,h,T,M,x,L]=await Promise.all([z(s,n.name,"Invocations","Sum",p,m),z(s,n.name,"Errors","Sum",p,m),z(s,n.name,"Throttles","Sum",p,m),z(s,n.name,"Duration","Average",p,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",p,m),te(s,n.name,"p95",p,m),te(s,n.name,"p99",p,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(()=>[])]);I+=l,b+=d,E=Math.max(E,C);let U=h?.Configuration?.MemorySize??0,D=Object.keys(h?.Configuration?.Environment?.Variables??{}),_=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:p.getTime(),limit:120});for(let w of J){let k=(w.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(k);if(re)S=Math.max(S,Number(re[1]));if(k&&!/^(?:START|END|REPORT|INIT_START)/.test(k))F.push({source:n.mode||n.name,timestamp:new Date(w.timestamp??0).toISOString(),when:Ae(w.timestamp??0),message:k.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(k)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(k)?"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,...L);K.push({key:n.mode,name:n.name,version:n.version,memory:U,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(l),errors:Math.round(d),p95:M||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),A.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:U,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(l),errors:Math.round(d),throttles:Math.round(c),p50:T||Math.round(C),p95:M||Math.round(C),p99:x||Math.round(C),maxMem:S,spark:L.length?L.map((J)=>Math.round(J/P*100)):[0],env:D.length?D:["(none)"],recent:_.length?_:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=A,i.serverlessLogs=F.sort((n,l)=>String(l.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=F.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=I?Number((b/I*100).toFixed(2)):0,Y=Math.round(await z(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",p,m));i.metrics={invocations:Math.round(I),errorRatePct:H,p95Ms:Math.round(E),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new j(a),l=[],d=[],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?Wt(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),M=0,x=0;try{let{QueueUrl:U}=await n.getQueueUrl(h.name),{Attributes:D}=await n.getQueueAttributes(U);M=Number(D.ApproximateNumberOfMessages??0),x=Number(D.ApproximateNumberOfMessagesNotVisible??0)}catch{}let L=Math.round(await B(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",p,m));l.push({name:T,visible:M,inFlight:x,processed:L,dlq:c}),d.push({name:h.name,short:T,visible:M,inFlight:x,delayed:0,processed:L,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(l.length)i.queues=l;if(d.length)i.queuesDetail=d;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:l}=await n.describeStacks({stackName:De(e,t)}),d={};for(let c of l?.[0]?.Outputs??[])if(c.OutputKey)d[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([B(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",p,m),B(s,"AWS/RDS","DatabaseConnections",C,"Maximum",p,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:d.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:d.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([B(s,"AWS/ElastiCache","CacheHits",C,"Sum",p,m),B(s,"AWS/ElastiCache","CacheMisses",C,"Sum",p,m)]),M=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:M,status:d.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(d.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:d.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:d.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=d.AssetsCdnDomain?{bucket:d.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:d.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 l=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=l.length,i.assetsInfo.sizeMb=Number((l.reduce((d,c)=>d+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=l.slice(0,8).map((d)=>({path:`/${d.Key}`,size:`${Math.max(1,Math.round((d.Size??0)/1024))} KB`,type:d.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((l)=>({key:l.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:l})):Object.entries(y.secrets).map(([l,d])=>({key:l,source:String(d)}));i.secretsList=n.map((l)=>({...l,updated:"—"}))}}catch{}try{let n=new g(a),l=`${r.slug}-${t}-deployments`,d=await n.getObjectJson(l,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(d?.records?.length)i.deploymentsDetail=d.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:A.reduce((n,l)=>n+l.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=A.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 Ve,l=m,d=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),1)),c=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:G(d),end:G(l),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:G(c),end:G(d),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,P)=>S+P.amount,0),M=h.reduce((S,P)=>S+P.amount,0),x=l.getUTCDate(),L=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/x*L).toFixed(2)),lastMonthUsd:Number(M.toFixed(2)),dailyAvgUsd:Number((T/x).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/x).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:G(d),end:G(l)}).catch(()=>[]);let U=C.find((S)=>/lambda/i.test(S.service))?.amount??0,D=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),_=A.reduce((S,P)=>S+D(P),0)||1;i.costPerFn=A.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(D(S)),usd:Number((U*(D(S)/_)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:p,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),l=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:p,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(l.reduce((d,c)=>d+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((d,c)=>d+(c.Sum??0),0))};try{let d=new ee(a),c=await d.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 d.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 Mt(e,t,"schedule:list"),l=[];for(let d of(n||"").split(`
|
|
2
|
+
`)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(d);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)l.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(l.length)i.schedulerTasks=l}catch{}return i.topology=$a(i,{project:e.project.name,environment:t}),i}
|
|
3
|
+
export{ie,q,Na,Da,Ve,qn};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ed,sc,wd,ao,co,lo,Ts}from"./chunk-c35qm7as.js";import"./chunk-jdfbahjb.js";export{Ed as MANAGEMENT_DASHBOARD_SITE,Ts as buildManagementDashboardArtifact,sc as dashboardCredentialsFile,co as ensureManagementDashboard,lo as managementDashboardSiteNames,wd as resolveDashboardAuth,ao as resolveUiSource};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{u}from"./chunk-
|
|
1
|
+
import{u}from"./chunk-q3xwh0r8.js";class U{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
3
3
|
<Name>${e.Name}</Name>
|
|
4
4
|
<CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
|