@stacksjs/ts-cloud 0.12.10 → 0.12.11

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.
Files changed (199) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-tfbs8k8v.js → chunk-0x8szp53.js} +1 -1
  3. package/dist/bin/chunk-1hggd7yz.js +1 -0
  4. package/dist/bin/{chunk-rtecnmts.js → chunk-2pevjm25.js} +2 -2
  5. package/dist/bin/{chunk-0zwknfwp.js → chunk-2tsg6e8j.js} +1 -1
  6. package/dist/{chunk-c8cadhgc.js → bin/chunk-3f27aa5r.js} +2 -2
  7. package/dist/bin/{chunk-dz1ec589.js → chunk-3g80gjw6.js} +2 -2
  8. package/dist/bin/chunk-40j9hgzc.js +1 -0
  9. package/dist/bin/{chunk-82mj52xr.js → chunk-48eb4z0c.js} +1 -1
  10. package/dist/bin/chunk-4gqfdr7t.js +1 -0
  11. package/dist/{chunk-pb47hr0h.js → bin/chunk-5gx38418.js} +1 -1
  12. package/dist/bin/chunk-5jv4cpky.js +1 -0
  13. package/dist/bin/chunk-5kxm5mx7.js +1 -0
  14. package/dist/bin/{chunk-my3ewh3a.js → chunk-5rhvcgzt.js} +2 -2
  15. package/dist/bin/{chunk-mcr0r4at.js → chunk-8223r1xn.js} +2 -2
  16. package/dist/bin/{chunk-4q6tad44.js → chunk-84703zpq.js} +91 -91
  17. package/dist/bin/{chunk-3aph4c1w.js → chunk-9edyzdm0.js} +1 -1
  18. package/dist/bin/{chunk-xhwqpgwq.js → chunk-9xbsmz1f.js} +1 -1
  19. package/dist/bin/{chunk-mfrf9q4b.js → chunk-a8t3c4qe.js} +1 -1
  20. package/dist/bin/chunk-aghy01we.js +1 -0
  21. package/dist/{chunk-w2ddj42w.js → bin/chunk-akwfvn5k.js} +1 -1
  22. package/dist/bin/chunk-asvz121j.js +1 -0
  23. package/dist/bin/{chunk-6tfwm33r.js → chunk-b0xtsv8k.js} +3 -3
  24. package/dist/bin/chunk-bcpdj01b.js +1 -0
  25. package/dist/bin/{chunk-btsyjhk7.js → chunk-bj4ft4qc.js} +2 -2
  26. package/dist/bin/chunk-da49my09.js +1 -0
  27. package/dist/bin/{chunk-hq9x489e.js → chunk-dep2n31v.js} +1 -1
  28. package/dist/bin/{chunk-b4wt9jcg.js → chunk-ewxf62t8.js} +2 -2
  29. package/dist/bin/{chunk-e2bybahr.js → chunk-f42gqn6c.js} +1 -1
  30. package/dist/bin/{chunk-s4yzes15.js → chunk-fc6r1ack.js} +1 -1
  31. package/dist/bin/{chunk-vj2dp0nh.js → chunk-ftcjjf76.js} +6 -6
  32. package/dist/bin/chunk-g76sry03.js +1 -0
  33. package/dist/bin/{chunk-e5ab5twy.js → chunk-hv3w2qy1.js} +2 -2
  34. package/dist/bin/{chunk-9a88fp00.js → chunk-hwdfky19.js} +2 -2
  35. package/dist/bin/chunk-j02d6qmn.js +1 -0
  36. package/dist/bin/{chunk-8ewncfce.js → chunk-j2cb8we4.js} +1 -1
  37. package/dist/bin/chunk-kmz8vb77.js +1 -0
  38. package/dist/bin/{chunk-0thy7q96.js → chunk-kyr5rasx.js} +74 -75
  39. package/dist/bin/{chunk-ja1vjdn1.js → chunk-mhrtx0p1.js} +1 -1
  40. package/dist/bin/{chunk-w32xv8n4.js → chunk-nc9pp87y.js} +2 -2
  41. package/dist/bin/{chunk-xk08030d.js → chunk-ncrnbcsa.js} +2 -2
  42. package/dist/bin/chunk-py1hyeb2.js +1 -0
  43. package/dist/bin/{chunk-q5cmfpzt.js → chunk-qa06sft7.js} +1 -1
  44. package/dist/bin/{chunk-azymqbcy.js → chunk-qr0xck72.js} +1 -1
  45. package/dist/bin/chunk-r85ahkwq.js +1 -0
  46. package/dist/bin/{chunk-ehc63fvs.js → chunk-re15e6p4.js} +1 -1
  47. package/dist/bin/chunk-t6y3pkm8.js +1 -0
  48. package/dist/bin/{chunk-c0bdafbx.js → chunk-tfmx17he.js} +1 -1
  49. package/dist/bin/chunk-vfcchrby.js +1 -0
  50. package/dist/bin/chunk-vmdh41kp.js +1 -0
  51. package/dist/bin/{chunk-cd0ps58j.js → chunk-vrc7eemq.js} +1 -1
  52. package/dist/bin/{chunk-d7ke90zt.js → chunk-vsd7670h.js} +1 -1
  53. package/dist/bin/{chunk-kg61p5hw.js → chunk-vwqn3yx6.js} +2 -2
  54. package/dist/bin/{chunk-71t1gmsq.js → chunk-vxbnjz78.js} +1 -1
  55. package/dist/bin/chunk-w8s8vgdj.js +1 -0
  56. package/dist/bin/chunk-yq9vetf8.js +698 -0
  57. package/dist/bin/{chunk-zpe64t4r.js → chunk-zrgd65r8.js} +1 -1
  58. package/dist/bin/cli.js +143 -143
  59. package/dist/bin/dashboard-server.js +1 -1
  60. package/dist/{chunk-y3tbcxb7.js → chunk-0a4tqwm9.js} +89 -90
  61. package/dist/{chunk-982rye5b.js → chunk-2ybcnrte.js} +1 -1
  62. package/dist/chunk-4884der5.js +1 -0
  63. package/dist/{bin/chunk-9kf0np8j.js → chunk-4wdxsnn2.js} +1 -1
  64. package/dist/{bin/chunk-xkfrqqcs.js → chunk-5hhyyhjt.js} +1 -1
  65. package/dist/chunk-5zkacdw1.js +1 -0
  66. package/dist/{chunk-557qj7q9.js → chunk-6cxb8d6y.js} +2 -2
  67. package/dist/chunk-6f68caq0.js +1 -0
  68. package/dist/{chunk-2qm3rw8b.js → chunk-7z50g5xz.js} +2 -2
  69. package/dist/chunk-8fh4m5ge.js +1 -0
  70. package/dist/chunk-97pb7wb1.js +1 -0
  71. package/dist/{chunk-a368cs92.js → chunk-ac87ds1k.js} +1 -1
  72. package/dist/{chunk-qrte4gy2.js → chunk-dndxwssj.js} +1 -1
  73. package/dist/{bin/chunk-a7w13qfm.js → chunk-ess6vxfj.js} +2 -2
  74. package/dist/chunk-fvpkxznh.js +558 -0
  75. package/dist/{chunk-rg7d67xk.js → chunk-j06r5rwv.js} +1 -1
  76. package/dist/{chunk-70v77sqv.js → chunk-j1g67djb.js} +2 -2
  77. package/dist/{chunk-fbwpm0zm.js → chunk-k8x8mrkr.js} +1 -1
  78. package/dist/{chunk-82gezmen.js → chunk-mnmz8t7q.js} +1 -1
  79. package/dist/{chunk-7j100g7w.js → chunk-n1fyryha.js} +1 -1
  80. package/dist/{chunk-c1hr34a5.js → chunk-n1hg0jxs.js} +2 -2
  81. package/dist/{chunk-bcffjsnj.js → chunk-n5xmh0ma.js} +1 -1
  82. package/dist/chunk-q22qfwsc.js +22 -0
  83. package/dist/{chunk-5hkq5081.js → chunk-q9a1z53k.js} +2 -2
  84. package/dist/{chunk-fsssdd5k.js → chunk-r8t25tbm.js} +91 -91
  85. package/dist/{chunk-2k0mt6j5.js → chunk-whyttetx.js} +1 -1
  86. package/dist/{chunk-gkj1tpsn.js → chunk-yf8stygs.js} +1 -1
  87. package/dist/{chunk-jphewtbx.js → chunk-ze5x2bpm.js} +1 -1
  88. package/dist/{chunk-jxrs1219.js → chunk-zh0apedk.js} +2 -2
  89. package/dist/{chunk-0hw5wjjg.js → chunk-zjyz926j.js} +1 -1
  90. package/dist/deploy/index.js +1 -1
  91. package/dist/dns/index.js +1 -1
  92. package/dist/drivers/hetzner/cloud-init.d.ts +14 -1
  93. package/dist/drivers/hetzner/driver.d.ts +2 -15
  94. package/dist/drivers/hetzner/state.d.ts +17 -2
  95. package/dist/drivers/index.d.ts +17 -1
  96. package/dist/drivers/index.js +1 -1
  97. package/dist/drivers/local-box/driver.d.ts +1 -1
  98. package/dist/drivers/shared/compute-provision.d.ts +7 -0
  99. package/dist/drivers/shared/driver-state.d.ts +68 -0
  100. package/dist/drivers/shared/remote-exec.d.ts +10 -1
  101. package/dist/drivers/shared/remote-failure.d.ts +41 -0
  102. package/dist/drivers/shared/ssh-transport.d.ts +121 -0
  103. package/dist/drivers/ssh/bootstrap.d.ts +61 -0
  104. package/dist/drivers/ssh/config.d.ts +86 -0
  105. package/dist/drivers/ssh/config.test.d.ts +1 -0
  106. package/dist/drivers/ssh/driver.d.ts +107 -0
  107. package/dist/drivers/ssh/factory-wiring.test.d.ts +1 -0
  108. package/dist/drivers/ssh/first-boot.d.ts +38 -0
  109. package/dist/drivers/ssh/preflight.d.ts +76 -0
  110. package/dist/index.d.ts +2 -1
  111. package/dist/index.js +7 -7
  112. package/dist/operations/index.js +1 -1
  113. package/dist/operations/inventory.d.ts +46 -1
  114. package/dist/protection/index.js +1 -1
  115. package/dist/push/index.js +1 -1
  116. package/dist/spend/index.js +1 -1
  117. package/dist/ui/404.html +1 -1
  118. package/dist/ui/accept-invitation.html +1 -1
  119. package/dist/ui/access-denied.html +2 -2
  120. package/dist/ui/account/automation.html +5 -5
  121. package/dist/ui/account/security.html +1 -1
  122. package/dist/ui/applications/compose.html +5 -5
  123. package/dist/ui/applications/new.html +1 -1
  124. package/dist/ui/data/backups.html +6 -6
  125. package/dist/ui/data/services.html +6 -6
  126. package/dist/ui/data/volumes.html +6 -6
  127. package/dist/ui/index.html +6 -6
  128. package/dist/ui/infrastructure/topology.html +5 -5
  129. package/dist/ui/integrations.html +2 -2
  130. package/dist/ui/operations/alerts.html +6 -6
  131. package/dist/ui/operations/configuration.html +6 -6
  132. package/dist/ui/operations/jobs.html +6 -6
  133. package/dist/ui/operations/maintenance.html +5 -5
  134. package/dist/ui/operations/observability.html +6 -6
  135. package/dist/ui/operations/previews.html +6 -6
  136. package/dist/ui/operations/queue.html +6 -6
  137. package/dist/ui/operations/regions.html +5 -5
  138. package/dist/ui/operations/releases.html +5 -5
  139. package/dist/ui/operations/spend.html +6 -6
  140. package/dist/ui/operations/workloads.html +6 -6
  141. package/dist/ui/security.html +2 -2
  142. package/dist/ui/server/actions.html +6 -6
  143. package/dist/ui/server/activity.html +2 -2
  144. package/dist/ui/server/capacity.html +6 -6
  145. package/dist/ui/server/database.html +6 -6
  146. package/dist/ui/server/deployments.html +5 -5
  147. package/dist/ui/server/diagnostics.html +2 -2
  148. package/dist/ui/server/firewall.html +6 -6
  149. package/dist/ui/server/fleet.html +6 -6
  150. package/dist/ui/server/logs.html +5 -5
  151. package/dist/ui/server/metrics.html +5 -5
  152. package/dist/ui/server/security.html +2 -2
  153. package/dist/ui/server/services.html +1 -1
  154. package/dist/ui/server/sites.html +5 -5
  155. package/dist/ui/server/ssh-keys.html +5 -5
  156. package/dist/ui/server/team.html +5 -5
  157. package/dist/ui/server/terminal.html +2 -2
  158. package/dist/ui/serverless/alarms.html +6 -6
  159. package/dist/ui/serverless/assets.html +2 -2
  160. package/dist/ui/serverless/cost.html +2 -2
  161. package/dist/ui/serverless/data.html +6 -6
  162. package/dist/ui/serverless/deployments.html +1 -1
  163. package/dist/ui/serverless/firewall.html +2 -2
  164. package/dist/ui/serverless/functions.html +5 -5
  165. package/dist/ui/serverless/logs.html +5 -5
  166. package/dist/ui/serverless/metrics.html +2 -2
  167. package/dist/ui/serverless/queues.html +6 -6
  168. package/dist/ui/serverless/secrets.html +6 -6
  169. package/dist/ui/serverless/traces.html +6 -6
  170. package/dist/ui/serverless.html +6 -6
  171. package/dist/ui-src/src/charts.ts +1 -1
  172. package/dist/ui-src/src/topology.ts +1 -1
  173. package/package.json +3 -3
  174. package/dist/bin/chunk-04dkwaqp.js +0 -1
  175. package/dist/bin/chunk-5nkqza92.js +0 -1
  176. package/dist/bin/chunk-64vczwwt.js +0 -1
  177. package/dist/bin/chunk-7g2ahkse.js +0 -1
  178. package/dist/bin/chunk-aw8bhggq.js +0 -594
  179. package/dist/bin/chunk-cxt74wsj.js +0 -1
  180. package/dist/bin/chunk-djg4zyqk.js +0 -1
  181. package/dist/bin/chunk-dkaz333b.js +0 -1
  182. package/dist/bin/chunk-edvvx3hg.js +0 -1
  183. package/dist/bin/chunk-f06c5np9.js +0 -1
  184. package/dist/bin/chunk-gq8794k6.js +0 -1
  185. package/dist/bin/chunk-k3120rx6.js +0 -1
  186. package/dist/bin/chunk-nw3d4k52.js +0 -1
  187. package/dist/bin/chunk-p70bc9yr.js +0 -1
  188. package/dist/bin/chunk-sg1g92cf.js +0 -1
  189. package/dist/bin/chunk-tvz9c388.js +0 -1
  190. package/dist/bin/chunk-y1h63vpm.js +0 -1
  191. package/dist/bin/chunk-zdt2rjk6.js +0 -1
  192. package/dist/bin/chunk-zh2d4704.js +0 -1
  193. package/dist/chunk-1bj94sc2.js +0 -1
  194. package/dist/chunk-3swnmwfc.js +0 -454
  195. package/dist/chunk-5pbtmy2k.js +0 -1
  196. package/dist/chunk-7sc8t7v1.js +0 -1
  197. package/dist/chunk-gny5s4kp.js +0 -1
  198. package/dist/chunk-qpjcd415.js +0 -22
  199. package/dist/chunk-xkw7h4pw.js +0 -1
@@ -3,4 +3,4 @@ import*as _ from"node:crypto";import{existsSync as V,readFileSync as Y}from"node
3
3
  `).join(""),l=u.map((E)=>E.toLowerCase()).join(";"),C=[s,A,b,c,l,f].join(`
4
4
  `),y="AWS4-HMAC-SHA256",S=r;if(r==="email")S="ses";let x=`${g}/${i}/${S}/aws4_request`,K=[y,p,x,this.sha256(C)].join(`
5
5
  `),F=this.getSignatureKey(e.secretAccessKey,g,i,S),q=this.hmac(F,K),U=`${y} Credential=${e.accessKeyId}/${x}, SignedHeaders=${l}, Signature=${q}`;return{...m,Authorization:U}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return _.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return _.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=_.createHmac("sha256",`AWS4${t}`).update(e).digest(),n=_.createHmac("sha256",s).update(r).digest(),a=_.createHmac("sha256",n).update(i).digest();return _.createHmac("sha256",a).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let n=s.ErrorResponse.Error;return i.code=n.Code,i.message=`AWS Error [${n.Code}]: ${n.Message||"Unknown error"}`,i.type=n.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function ie(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,n)=>{e[`${r}.${n+1}`]=String(s)});else if(typeof i==="object")for(let[s,n]of Object.entries(i))e[`${r}.${s}`]=String(n);else e[r]=String(i)}return e}function se(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",n=process.env.AWS_SHARED_CREDENTIALS_FILE||B(W(),".aws","credentials");if(V(n))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
6
- export{R as ch,J as dh,ie as eh,se as fh};
6
+ export{R as nh,J as oh,ie as ph,se as qh};
@@ -1,8 +1,8 @@
1
- import{Eg as I}from"./chunk-dz1ec589.js";var y=(e)=>e==null?void 0:String(e),b=(e)=>Number(e)===1,E=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function S(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:b(e.required),metadata:E(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function C(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:b(e.required),requiresRedeploy:b(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class q{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?S(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?S(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(S)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(C)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(C)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:E(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var _=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function A(e){let r={n:`
1
+ import{Pg as I}from"./chunk-3g80gjw6.js";var y=(e)=>e==null?void 0:String(e),b=(e)=>Number(e)===1,E=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function S(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:b(e.required),metadata:E(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function C(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:b(e.required),requiresRedeploy:b(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class q{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?S(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?S(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(S)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(C)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(C)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:E(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var _=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function A(e){let r={n:`
2
2
  `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function R(e){let r={},n=[],t=e.replace(/\r\n?/g,`
3
3
  `).split(`
4
4
  `);for(let i=0;i<t.length;i++){let s=i+1,c=t[i];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let u=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!u){n.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let o=u[1],a=u[2];if(!_.test(o)){n.push({line:s,key:o,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${o}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],l=[a.slice(1)],v=!1;while(!0){let f=l[l.length-1],m=!1,k=-1;for(let h=0;h<f.length;h++){if(g==='"'&&f[h]==="\\"&&!m){m=!0;continue}if(f[h]===g&&!m){k=h;break}m=!1}if(k>=0){l[l.length-1]=f.slice(0,k),v=!0;break}if(++i>=t.length)break;l.push(t[i])}if(!v){n.push({line:s,key:o,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${o}.`});continue}if(d=l.join(`
5
5
  `),g==='"')d=A(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,o)){let g=r[o]!==d;if(n.push({line:s,key:o,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${o} has conflicting values.`:`${o} is duplicated with the same value.`}),g)continue}r[o]=d}return{values:r,diagnostics:n,valid:!n.some((i)=>i.severity==="error")}}function j(e){return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!_.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(n)}`}).join(`
6
6
  `)+(Object.keys(e).length?`
7
7
  `:"")}import{createCipheriv as D,createDecipheriv as O,createHash as x,randomBytes as M}from"node:crypto";class w{controlPlane;now;kind="local_encrypted";key;constructor(e,r,n=()=>new Date){this.controlPlane=e;this.now=n;if(!r)throw Error("Configuration encryption key is required.");this.key=x("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=M(12),n=D("aes-256-gcm",this.key,r),t=Buffer.concat([n.update(e,"utf8"),n.final()]);return`v1.${r.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,n,t,i]=e.split(".");if(r!=="v1"||!n||!t||!i)throw Error("Encrypted configuration secret is unavailable.");try{let s=O("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(i,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),x("sha256").update(e.value).digest("hex"),t,i,i]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class T{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let n=this.id(e.reference),t=await this.client.putSecretValue({SecretId:n,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class V{client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,n=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(n.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class W{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as B}from"node:crypto";var K=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,N=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function p(e){return[...new Set(e)].sort()}function P(e,r={}){let n=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!n||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!n||r.canReadSecretMetadata?e.backendVersion:void 0,reference:n&&r.canReadSecretMetadata?e.secretRef:void 0,value:!n?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class L{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let n=r.backends??[new w(e.controlPlane,r.encryptionKey,this.now)];for(let t of n)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((n)=>!r||n.key.toLowerCase().includes(r)).map((n)=>P(n,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),n=new Map(r.map((o)=>[o.key,o])),t=[],i=[],s=[],c=[];for(let[o,a]of Object.entries(e.values)){t.push(...this.warnings(o,a));let d=n.get(o);if(!d)i.push(o);else if(d.valueFingerprint!==this.fingerprint(a))s.push(o);else c.push(o)}let u=e.removeMissing?r.filter((o)=>!Object.hasOwn(e.values,o.key)).map((o)=>o.key):[];return{added:p(i),changed:p(s),removed:p(u),unchanged:p(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...s,...u]),warnings:t}}async set(e){let r=this.requestHash(e),n=e.idempotencyKey;if(n){let f=this.store.mutation(n);if(f){if(f.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let m=this.store.get(String(f.result.entryId??""));if(!m)throw Error("Idempotent configuration result is no longer available.");return{entry:m,mutation:f.result.mutation,warnings:[]}}}if(e.value!=null&&K.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==i||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let u=e.reference,o;if(e.kind==="secret"){let f=this.backend(s);if(e.reference&&e.value==null){if(!await f.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");o=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let m=await f.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:n??crypto.randomUUID()});u=m.reference,o=m.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==i||t.backend!==s||t.secretRef!==u||t.backendVersion!==o||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,required:!!e.required,metadata:I(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,origin:e.origin??"managed",required:!!e.required,metadata:I(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),l=this.affectedResources(e.projectId,e.scope,[e.key]),v={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:l,versions:{[e.key]:g.version}};if(n)this.store.recordMutation({projectId:e.projectId,idempotencyKey:n,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:v}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,l),{entry:g,mutation:v,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=R(e.source);if(!r.valid)return{document:r,warnings:[]};let n=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[s,c]of Object.entries(r.values)){let u=await this.set({...e,source:void 0,key:s,value:c,kind:n.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...u.mutation.added),t.changed.push(...u.mutation.changed),t.unchanged.push(...u.mutation.unchanged),t.affectedResourceIds.push(...u.mutation.affectedResourceIds),Object.assign(t.versions,u.mutation.versions),i.push(...u.warnings)}return t.added=p(t.added),t.changed=p(t.changed),t.unchanged=p(t.unchanged),t.affectedResourceIds=p(t.affectedResourceIds),{document:r,mutation:t,warnings:i}}exportVariables(e){return j(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let n=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,i=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:n,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:p([...i.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),n=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,i=new Set;for(let a of n){if(t.has(a.key))i.add(a.key);t.set(a.key,a)}let s={},c={},u=[],o=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!o.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(u.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)u.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=P(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:u,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
8
- `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${B("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(N.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function X(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{q as rg,R as sg,j as tg,w as ug,T as vg,V as wg,W as xg,L as yg,X as zg};
8
+ `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${B("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(N.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function X(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{q as Cg,R as Dg,j as Eg,w as Fg,T as Gg,V as Hg,W as Ig,L as Jg,X as Kg};
@@ -1,6 +1,6 @@
1
- import{Ah as S,Bh as _,nj as C,qj as I,rj as m}from"./chunk-4q6tad44.js";import{execSync as O}from"node:child_process";import{randomBytes as P}from"node:crypto";import{chmodSync as B,copyFileSync as F,existsSync as u,mkdirSync as L,readFileSync as T,statSync as J,writeFileSync as b}from"node:fs";import{tmpdir as z}from"node:os";import{basename as V,dirname as y,isAbsolute as k,join as a,resolve as W}from"node:path";import{fileURLToPath as A}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function E(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function U(e){let r=E(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
1
+ import{Cj as I,Dj as m,Mh as S,Nh as _,zj as C}from"./chunk-84703zpq.js";import{execSync as O}from"node:child_process";import{randomBytes as P}from"node:crypto";import{chmodSync as B,copyFileSync as F,existsSync as u,mkdirSync as L,readFileSync as T,statSync as J,writeFileSync as b}from"node:fs";import{tmpdir as z}from"node:os";import{basename as V,dirname as y,isAbsolute as k,join as a,resolve as W}from"node:path";import{fileURLToPath as A}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function E(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function U(e){let r=E(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
2
  `)}var G="dashboard";function M(){return S("dashboard-credentials.json")}function H(){return P(24).toString("base64url")}function q(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(v(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=M(),i=_(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(T(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=H();try{L(y(i),{recursive:!0}),b(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
3
3
  `),B(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
4
4
  This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var R={info:()=>{},warn:()=>{}};function v(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function K(){return S("dashboard-release")}function j(){let e=y(A(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(T(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function Q(){return process.env.TS_CLOUD_UI_VERSION?.trim()||j()}function X(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=_(r,"dashboard-release");try{L(s,{recursive:!0}),b(a(s,"cloud.config.ts"),U(e));let n=Q();if(n.startsWith("file:")){let d=n.slice(5),o=k(d)?d:W(r,d);if(!u(o)||!J(o).isFile())n=j(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=V(o),l=a(s,c);if(o!==l)F(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return b(a(s,"package.json"),`${JSON.stringify(i,null,2)}
5
5
  `),K()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function Y(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=y(A(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function de(e,r={}){let t=r.logger??R,s=r.cwd??process.cwd();if(v(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(C(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!v(process.env.TS_CLOUD_UI_STATIC)){let g=X(e,s,t);if(!g)return e;let p=m(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:N,site:w}of p)o[N]=w,t.info(`Management dashboard → https://${w.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=Y(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=q(s,l,t),D=m(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(D.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let x=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${M()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of D)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${x})`);return e.sites=o,e}function ue(e){return Object.keys(e.sites??{}).filter(I)}function ce(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??R;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),O(e.build,{cwd:t,stdio:"inherit"});let n=k(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(z(),`${r.slug}-${r.siteName??G}-${r.sha}.tar.gz`);return O(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
6
- export{G as lf,M as mf,q as nf,K as of,Q as pf,X as qf,Y as rf,de as sf,ue as tf,ce as uf};
6
+ export{G as vf,M as wf,q as xf,K as yf,Q as zf,X as Af,Y as Bf,de as Cf,ue as Df,ce as Ef};
@@ -0,0 +1 @@
1
+ import{Sg as a}from"./chunk-8223r1xn.js";import"./chunk-hwdfky19.js";import"./chunk-b0xtsv8k.js";import"./chunk-mhrtx0p1.js";import"./chunk-84703zpq.js";import"./chunk-re15e6p4.js";export{a as buildAndPushServerlessImage};
@@ -1 +1 @@
1
- import{$b as z,$c as Aa,Ac as _,Bc as aa,Cb as a,Cc as ba,Db as b,Dc as ca,Eb as c,Ec as da,Fb as d,Fc as ea,Gb as e,Gc as fa,Hb as f,Hc as ga,Ib as g,Ic as ha,Jb as h,Jc as ia,Kb as i,Kc as ja,Lb as j,Lc as ka,Mb as k,Mc as la,Nb as l,Nc as ma,Ob as m,Oc as na,Pb as n,Pc as oa,Qb as o,Qc as pa,Rb as p,Rc as qa,Sb as q,Sc as ra,Tb as r,Tc as sa,Ub as s,Uc as ta,Vb as t,Vc as ua,Wb as u,Wc as va,Xb as v,Xc as wa,Yb as w,Yc as xa,Zb as x,Zc as ya,_b as y,_c as za,ac as A,ad as Ba,bc as B,cc as C,dc as D,dd as Ca,ec as E,ed as Da,fc as F,gc as G,hc as H,ic as I,jc as J,kc as K,lc as L,mc as M,nc as N,oc as O,pc as P,qc as Q,rc as R,sc as S,tc as T,uc as U,vc as V,wc as W,xc as X,yc as Y,zc as Z}from"./chunk-tfbs8k8v.js";import"./chunk-9kf0np8j.js";import"./chunk-dz1ec589.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{Z as AnomalyConfigStore,za as AwsSpendTransport,Aa as ComputeSpendTransport,x as CounterTracker,u as DEFAULT_METER_MAPPINGS,l as DEFAULT_PRICE_BOOK,B as DEFAULT_THRESHOLDS,_ as DETECTABLE_SIGNALS,c as ENFORCEMENT_ACTIONS,K as ENFORCEMENT_DESCRIPTIONS,d as ENFORCEMENT_SEVERITY,ea as FOCUS_VERSION,b as METERS,a as METER_KEYS,e as MICRO_CENTS,G as MIN_PROJECTION_CONFIDENCE,pa as RecordingSpendTransport,X as SENSITIVITY_THRESHOLDS,xa as SPEND_CYCLE_SECONDS,ka as SPEND_GATE_SETTING,ua as SPEND_LEASE_SETTING,ba as SignalSource,ma as SpendCapError,la as SpendGate,va as SpendLoopLease,ta as SpendNotificationRouter,wa as SpendRunner,ia as SpendService,C as SpendStore,qa as URGENT_SPEND_EVENTS,L as USER_VISIBLE_ACTIONS,z as aggregateDeltas,W as anomalyOptionsForSignal,na as assertSpendAllows,q as budgetWindow,Ba as compositeSpendTransport,oa as createEnforcementHandlers,U as detectAnomalies,V as detectLatestAnomaly,I as evaluateBudget,T as ewma,v as findMapping,g as findPriceEntry,ra as formatCents,F as formatTimeToExhaustion,H as governingLimitCents,Ca as handleSpendRequest,s as hourBucket,t as hourBucketsBetween,P as isOperationAllowed,m as isValidTimeZone,da as lookbackHoursForSignal,Q as median,R as medianAbsoluteDeviation,J as mergeDecisions,k as mergePriceBooks,y as meterTelemetry,ca as optionsForSignal,E as percentOfLimit,M as planEnforcement,r as previousBudgetWindow,h as priceUsage,i as priceUsageLines,D as projectSpend,S as robustZScore,j as roundCents,Y as routeMatches,N as runEnforcement,A as scopeKey,aa as signalDefinition,sa as spendNotificationText,Da as spendOpenApiPaths,ya as startSpendLoop,ha as streamFocusJsonl,O as strongestActiveAction,f as tieredMicroCents,ga as toFocusJsonl,fa as toFocusRecords,w as usageDeltaKey,p as utcInstantOfLocal,ja as zeroFill,o as zoneOffsetMs,n as zonedParts};
1
+ import{$b as z,$c as Aa,Ac as _,Bc as aa,Cb as a,Cc as ba,Db as b,Dc as ca,Eb as c,Ec as da,Fb as d,Fc as ea,Gb as e,Gc as fa,Hb as f,Hc as ga,Ib as g,Ic as ha,Jb as h,Jc as ia,Kb as i,Kc as ja,Lb as j,Lc as ka,Mb as k,Mc as la,Nb as l,Nc as ma,Ob as m,Oc as na,Pb as n,Pc as oa,Qb as o,Qc as pa,Rb as p,Rc as qa,Sb as q,Sc as ra,Tb as r,Tc as sa,Ub as s,Uc as ta,Vb as t,Vc as ua,Wb as u,Wc as va,Xb as v,Xc as wa,Yb as w,Yc as xa,Zb as x,Zc as ya,_b as y,_c as za,ac as A,ad as Ba,bc as B,cc as C,dc as D,dd as Ca,ec as E,ed as Da,fc as F,gc as G,hc as H,ic as I,jc as J,kc as K,lc as L,mc as M,nc as N,oc as O,pc as P,qc as Q,rc as R,sc as S,tc as T,uc as U,vc as V,wc as W,xc as X,yc as Y,zc as Z}from"./chunk-0x8szp53.js";import"./chunk-5gx38418.js";import"./chunk-3g80gjw6.js";import"./chunk-84703zpq.js";import"./chunk-re15e6p4.js";export{Z as AnomalyConfigStore,za as AwsSpendTransport,Aa as ComputeSpendTransport,x as CounterTracker,u as DEFAULT_METER_MAPPINGS,l as DEFAULT_PRICE_BOOK,B as DEFAULT_THRESHOLDS,_ as DETECTABLE_SIGNALS,c as ENFORCEMENT_ACTIONS,K as ENFORCEMENT_DESCRIPTIONS,d as ENFORCEMENT_SEVERITY,ea as FOCUS_VERSION,b as METERS,a as METER_KEYS,e as MICRO_CENTS,G as MIN_PROJECTION_CONFIDENCE,pa as RecordingSpendTransport,X as SENSITIVITY_THRESHOLDS,xa as SPEND_CYCLE_SECONDS,ka as SPEND_GATE_SETTING,ua as SPEND_LEASE_SETTING,ba as SignalSource,ma as SpendCapError,la as SpendGate,va as SpendLoopLease,ta as SpendNotificationRouter,wa as SpendRunner,ia as SpendService,C as SpendStore,qa as URGENT_SPEND_EVENTS,L as USER_VISIBLE_ACTIONS,z as aggregateDeltas,W as anomalyOptionsForSignal,na as assertSpendAllows,q as budgetWindow,Ba as compositeSpendTransport,oa as createEnforcementHandlers,U as detectAnomalies,V as detectLatestAnomaly,I as evaluateBudget,T as ewma,v as findMapping,g as findPriceEntry,ra as formatCents,F as formatTimeToExhaustion,H as governingLimitCents,Ca as handleSpendRequest,s as hourBucket,t as hourBucketsBetween,P as isOperationAllowed,m as isValidTimeZone,da as lookbackHoursForSignal,Q as median,R as medianAbsoluteDeviation,J as mergeDecisions,k as mergePriceBooks,y as meterTelemetry,ca as optionsForSignal,E as percentOfLimit,M as planEnforcement,r as previousBudgetWindow,h as priceUsage,i as priceUsageLines,D as projectSpend,S as robustZScore,j as roundCents,Y as routeMatches,N as runEnforcement,A as scopeKey,aa as signalDefinition,sa as spendNotificationText,Da as spendOpenApiPaths,ya as startSpendLoop,ha as streamFocusJsonl,O as strongestActiveAction,f as tieredMicroCents,ga as toFocusJsonl,fa as toFocusRecords,w as usageDeltaKey,p as utcInstantOfLocal,ja as zeroFill,o as zoneOffsetMs,n as zonedParts};
@@ -1,3 +1,3 @@
1
- import{Ef as l,Rf as g,Uf as f,Vf as d,dg as C,vf as m}from"./chunk-vj2dp0nh.js";function R(e){return`'${e.split("'").join("'\\''")}'`}function p(e){let r=e.user||"root",s=e.script.join(`
1
+ import{Ff as m,Of as l,ag as g,dg as f,eg as d,og as C}from"./chunk-ftcjjf76.js";function R(e){return`'${e.split("'").join("'\\''")}'`}function p(e){let r=e.user||"root",s=e.script.join(`
2
2
  `),t=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${R(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,s,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',t,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function i(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function y(e,r){let s=e.logger||c,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=m(e.slug,r.siteName),u=d(n,r.to||"unused"),o=["set -uo pipefail",...C(u,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${l} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${u.current} && eval "$(cd ${l} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];s.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${t.length} server(s)...`);let a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!a.success)s.error(`Rollback failed: ${a.error||"unknown error"}`);else s.success(`Rolled back ${r.siteName}.`);return{success:a.success,error:a.error,perInstance:a.perInstance}}async function h(e,r){let s=await i(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=f(m(e.slug,r.siteName)),n=Math.max(1,r.limit??20),u=[`[ -f ${t} ] && tail -n ${n} ${t} || echo "no deploy history for ${r.siteName}"`],o=await e.driver.runRemoteDeploy({targets:s,commands:u,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:o.success,error:o.error,perInstance:o.perInstance}}async function I(e,r){let s=e.logger||c,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:p({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else s.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function P(e,r){let s=e.logger||c;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:g(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Restore failed: ${n.error||"unknown error"}`);else s.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
3
3
  export{y as xd,h as yd,I as zd,P as Ad};
@@ -0,0 +1 @@
1
+ import{gf as a}from"./chunk-2pevjm25.js";import"./chunk-mhrtx0p1.js";import"./chunk-re15e6p4.js";export{a as EC2Client};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as g}from"node:module";var d=Object.defineProperty;var e=(a)=>a;function f(a,b){this[a]=e.bind(null,b)}var h=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0,configurable:!0,set:f.bind(b,c)})};var j=g(import.meta.url);
2
- export{h as np,j as op};
2
+ export{h as zp,j as Ap};
@@ -0,0 +1 @@
1
+ import{$e as d,Ye as a,Ze as b,_e as c,af as e,bf as f,cf as g,df as h,ef as i,ff as j}from"./chunk-yq9vetf8.js";import"./chunk-2pevjm25.js";import"./chunk-j2cb8we4.js";import"./chunk-5gx38418.js";import"./chunk-ncrnbcsa.js";import"./chunk-ftcjjf76.js";import"./chunk-9xbsmz1f.js";import"./chunk-3f27aa5r.js";import"./chunk-bj4ft4qc.js";import"./chunk-mhrtx0p1.js";import"./chunk-84703zpq.js";import"./chunk-re15e6p4.js";export{d as mergeDiscoveredSites,b as metricsScript,c as parseBlock,h as parseDeployHistory,f as parseServerLogs,g as parseServerSecurity,i as resolveConfigOnlyServerDashboardData,j as resolveServerDashboardData,e as serverLogSources,a as sharedBoxProbeScript};
@@ -1,2 +1,2 @@
1
- import{dh as d}from"./chunk-ja1vjdn1.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let p=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(p,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class C{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new d(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
1
+ import{oh as d}from"./chunk-mhrtx0p1.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let p=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(p,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class C{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new d(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
2
2
  export{C as _d};
@@ -0,0 +1 @@
1
+ import{p as a,q as b,r as c,s as d,t as e,u as f}from"./chunk-ewxf62t8.js";import"./chunk-a8t3c4qe.js";import"./chunk-48eb4z0c.js";import"./chunk-3f27aa5r.js";import"./chunk-hv3w2qy1.js";import"./chunk-bj4ft4qc.js";import"./chunk-mhrtx0p1.js";import"./chunk-re15e6p4.js";export{e as deleteStaticSite,b as deployStaticSite,f as deployStaticSiteFull,a as generateStaticSiteTemplate,d as invalidateCache,c as uploadStaticFiles};
@@ -0,0 +1 @@
1
+ import{rd as a,sd as b}from"./chunk-a8t3c4qe.js";import"./chunk-hv3w2qy1.js";import"./chunk-mhrtx0p1.js";import"./chunk-re15e6p4.js";export{a as ACMClient,b as ACMDnsValidator};
@@ -1 +1 @@
1
- import{rg as a,sg as b,tg as c,ug as d,vg as e,wg as f,xg as g,yg as h,zg as i}from"./chunk-w32xv8n4.js";import"./chunk-dz1ec589.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{e as AwsSecretsManagerConfigurationBackend,f as AwsSsmConfigurationBackend,h as ConfigurationService,a as ConfigurationStore,g as ExternalConfigurationBackend,d as LocalEncryptedConfigurationBackend,b as parseDotenv,c as serializeDotenv,i as synchronizeConfiguredConfiguration};
1
+ import{Cg as a,Dg as b,Eg as c,Fg as d,Gg as e,Hg as f,Ig as g,Jg as h,Kg as i}from"./chunk-nc9pp87y.js";import"./chunk-3g80gjw6.js";import"./chunk-84703zpq.js";import"./chunk-re15e6p4.js";export{e as AwsSecretsManagerConfigurationBackend,f as AwsSsmConfigurationBackend,h as ConfigurationService,a as ConfigurationStore,g as ExternalConfigurationBackend,d as LocalEncryptedConfigurationBackend,b as parseDotenv,c as serializeDotenv,i as synchronizeConfiguredConfiguration};
@@ -1,2 +1,2 @@
1
- import{dh as u}from"./chunk-ja1vjdn1.js";class d{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
1
+ import{oh as u}from"./chunk-mhrtx0p1.js";class d{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
2
2
  export{d as Hd};
@@ -1,3 +1,3 @@
1
- import{_d as b}from"./chunk-c0bdafbx.js";import{jg as Z}from"./chunk-a7w13qfm.js";import{qg as P}from"./chunk-btsyjhk7.js";import{Lg as V,Mg as ne,Ng as U,Pg as R,Qg as m,Rg as M,Yg as ie}from"./chunk-6tfwm33r.js";import{dh as se}from"./chunk-ja1vjdn1.js";import{$h as ae,Yo as pe,ai as oe,bi as ce,cp as fe,jo as le,ko as ue,mo as ge,oo as de,po as me}from"./chunk-4q6tad44.js";import{op as Q}from"./chunk-ehc63fvs.js";import{existsSync as Ae,readdirSync as Te,readFileSync as be,statSync as ke}from"node:fs";import{join as Se,relative as Ee}from"node:path";class _{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new se}async createSecret(e){let t={Name:e.Name};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.AddReplicaRegions&&e.AddReplicaRegions.length>0)t.AddReplicaRegions=e.AddReplicaRegions;if(e.ForceOverwriteReplicaSecret!==void 0)t.ForceOverwriteReplicaSecret=e.ForceOverwriteReplicaSecret;t.ClientRequestToken=e.ClientRequestToken||crypto.randomUUID();let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,ReplicationStatus:r.ReplicationStatus}}async updateSecret(e){let t={SecretId:e.SecretId};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async putSecretValue(e){let t={SecretId:e.SecretId};if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.VersionStages&&e.VersionStages.length>0)t.VersionStages=e.VersionStages;if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,VersionStages:r.VersionStages}}async getSecretValue(e){let t={SecretId:e.SecretId};if(e.VersionId)t.VersionId=e.VersionId;if(e.VersionStage)t.VersionStage=e.VersionStage;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,SecretBinary:r.SecretBinary,SecretString:r.SecretString,VersionStages:r.VersionStages,CreatedDate:r.CreatedDate}}async describeSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return this.parseSecret(r)}async listSecrets(e){let t={};if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.SortOrder)t.SortOrder=e.SortOrder;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{SecretList:r.SecretList?.map((s)=>this.parseSecret(s)),NextToken:r.NextToken}}async deleteSecret(e){let t={SecretId:e.SecretId};if(e.RecoveryWindowInDays!==void 0)t.RecoveryWindowInDays=e.RecoveryWindowInDays;if(e.ForceDeleteWithoutRecovery!==void 0)t.ForceDeleteWithoutRecovery=e.ForceDeleteWithoutRecovery;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,DeletionDate:r.DeletionDate}}async restoreSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async rotateSecret(e){let t={SecretId:e.SecretId};if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;if(e.RotationLambdaARN)t.RotationLambdaARN=e.RotationLambdaARN;if(e.RotationRules)t.RotationRules=e.RotationRules;if(e.RotateImmediately!==void 0)t.RotateImmediately=e.RotateImmediately;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async cancelRotateSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async getResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,ResourcePolicy:r.ResourcePolicy}}async putResourcePolicy(e){let t={SecretId:e.SecretId,ResourcePolicy:e.ResourcePolicy};if(e.BlockPublicPolicy!==void 0)t.BlockPublicPolicy=e.BlockPublicPolicy;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async deleteResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async tagResource(e){let t={SecretId:e.SecretId,Tags:e.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async untagResource(e){let t={SecretId:e.SecretId,TagKeys:e.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async setString(e,t,r){try{let s=await this.putSecretValue({SecretId:e,SecretString:t});return{ARN:s.ARN,VersionId:s.VersionId}}catch(s){if(s.code==="ResourceNotFoundException"){let n=await this.createSecret({Name:e,SecretString:t,Description:r?.description,KmsKeyId:r?.kmsKeyId,Tags:r?.tags});return{ARN:n.ARN,VersionId:n.VersionId}}throw s}}async setJson(e,t,r){return this.setString(e,JSON.stringify(t),r)}async getString(e){return(await this.getSecretValue({SecretId:e})).SecretString}async getJson(e){let t=await this.getString(e);if(t)return JSON.parse(t);return}async listAll(){let e=[],t;do{let r=await this.listSecrets({NextToken:t});if(r.SecretList)e.push(...r.SecretList);t=r.NextToken}while(t);return e}parseSecret(e){return{ARN:e.ARN,Name:e.Name,Description:e.Description,KmsKeyId:e.KmsKeyId,RotationEnabled:e.RotationEnabled,RotationLambdaARN:e.RotationLambdaARN,RotationRules:e.RotationRules,LastRotatedDate:e.LastRotatedDate,LastChangedDate:e.LastChangedDate,LastAccessedDate:e.LastAccessedDate,DeletedDate:e.DeletedDate,NextRotationDate:e.NextRotationDate,Tags:e.Tags,SecretVersionsToStages:e.SecretVersionsToStages,CreatedDate:e.CreatedDate,PrimaryRegion:e.PrimaryRegion}}}function v(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let s=e.project.slug,n=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:s,region:n,stackName:ae(e,t),artifactBucket:oe(s,t),assetsBucket:ce(s,t)}}function He(e,t){let r=v(e,t),s=`${r.slug}-${t}`;return{region:r.region,slug:r.slug,stackName:r.stackName,functions:{http:`${s}-http`,queue:`${s}-queue`,cli:`${s}-cli`}}}async function D(e,t=8){let r;for(let s=0;s<t;s++)try{return await e()}catch(n){let i=n?.code||n?.name||"",a=String(n?.message||"");if(i==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(a)){r=n,await new Promise((o)=>setTimeout(o,3000));continue}throw n}throw r}var ye=(e,t)=>`releases/${e}/${t}/current.json`;async function J(e,t,r,s){try{return await e.getObjectJson(t,ye(r,s))}catch{return null}}async function Re(e,t,r,s,n){await e.putObjectJson(t,ye(r,s),n)}async function Ie(e,t){if(!e.secrets)return{};let r=new _(t),s={},n=Array.isArray(e.secrets)?e.secrets.map((i)=>({envName:i.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:i})):Object.entries(e.secrets).map(([i,a])=>({envName:i,secretId:a}));if(Array.isArray(e.secrets)){let i=new Map;for(let{envName:o,secretId:c}of n)i.set(o,[...i.get(o)??[],c]);let a=[...i.entries()].filter(([,o])=>o.length>1);if(a.length){let o=a.map(([c,u])=>`${c} ← ${u.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${o}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:i,secretId:a}of n){let c=(await r.getSecretValue({SecretId:a})).SecretString??"";try{let u=JSON.parse(c);if(u&&typeof u==="object"&&!Array.isArray(u)){for(let[p,d]of Object.entries(u))s[p]=String(d);continue}}catch{}s[i]=c}return s}function De(e,t){let r={},s=t.DbProxyEndpoint||t.DbEndpoint;if(s)r.DB_CONNECTION="mysql",r.DB_HOST=s,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Y(e,t,r,s,n,i,a,o={}){let c=e.kind==="php"?pe({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:s,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...c,...o,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...a?{TSCLOUD_QUEUE:a,SQS_QUEUE:a}:{},...i?{ASSET_URL:i}:{},...e.env??{},...n}}function Pe(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*he(e){for(let t of Te(e)){let r=Se(e,t);if(ke(r).isDirectory())yield*he(r);else yield r}}async function $e(e,t,r,s,n=!1){let i=0;for(let a of he(r)){let o=Ee(r,a).replace(/\\/g,"/");if(!n&&o.split("/").some((c)=>c.startsWith(".")))continue;await e.putObject({bucket:t,key:`${s}/${o}`,body:be(a),contentType:Pe(a),cacheControl:"public, max-age=31536000, immutable"}),i++}return i}function Oe(e,t){let r=Object.entries(t).reduce((s,[n,i])=>s+Buffer.byteLength(`${n}=${i}`,"utf8"),0);if(r>4096){let s=Object.entries(t).map(([n,i])=>[n,Buffer.byteLength(`${n}=${i}`,"utf8")]).sort((n,i)=>i[1]-n[1]).slice(0,5).map(([n,i])=>`${n} (${i}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${s}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function F(e,t,r,s){Oe(t,r),await D(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let n=s.kind==="image"?{FunctionName:t,ImageUri:s.imageUri}:{FunctionName:t,S3Bucket:s.bucket,S3Key:s.key};await D(()=>e.updateFunctionCode(n)),await e.waitForFunctionActive(t,120)}async function z(e,t){let s=(await D(()=>e.publishVersion({FunctionName:t}))).Version;if(!s)throw Error(`publishVersion returned no version for ${t}`);return await D(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:s})),s}async function We(e,t,r={}){let s=v(e,t),{app:n,slug:i,region:a,stackName:o,artifactBucket:c}=s,u=r.projectRoot??process.cwd();M(`Deploying serverless app: ${i} (${t})`),R(`Stack: ${o}`),R(`Region: ${a}`);let p=new P(a),d=new Z(a),y=new b(a),C=n.kind==="php",A=n.packaging==="image",g=ge(n),k,N,h,H,L=[];if(A&&g.usesLayer&&g.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${g.kind}${g.kind==="node"?` ${g.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(A){m("Building + pushing container image");let{buildAndPushServerlessImage:l}=await import("./chunk-p70bc9yr.js"),f=await l({app:n,projectRoot:u,region:a,repository:`${i}-${t}`,skipBuild:r.skipBuild,onStep:(w)=>R(` ${w}`)});k=f.handlers,N={kind:"image",imageUri:f.imageUri},h=f.tag,L.push({ParameterKey:"ImageUri",ParameterValue:f.imageUri})}else{m("Packaging application");let l=C?fe({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}):await ue({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}),f=le(i,t,l.sha256);if(R(`Artifact: ${l.sha256.slice(0,12)} (${(l.zip.length/1024).toFixed(0)} KB)`),k=l.handlers,h=l.sha256,g.usesLayer){let T=g.layerEnvVar?process.env[g.layerEnvVar]:void 0;if(H=n.layers??(T?[T]:void 0),!H?.length){let Ce=g.layerKind==="php"?"serverless:build-php-layer":g.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${g.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${g.layerEnvVar} env var (build one with \`cloud ${Ce}\`)${g.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await p.bucketExists(c))m(`Creating artifact bucket ${c}`),await p.createBucket(c);if(await p.headObject(c,f).then((T)=>T!==null).catch(()=>!1))R("Artifact already uploaded — reusing");else m("Uploading artifact"),await p.putObject({bucket:c,key:f,body:l.zip,contentType:"application/zip"});N={kind:"zip",bucket:c,key:f},L.push({ParameterKey:"ArtifactBucket",ParameterValue:c},{ParameterKey:"ArtifactKey",ParameterValue:f})}let S=me({config:e,environment:t,app:n,handlers:k,runtimeLayers:H}),ee=JSON.stringify(S.template),te=["CAPABILITY_NAMED_IAM"],O=await d.describeStacks({stackName:o}).then((l)=>l.Stacks[0]?.StackStatus).catch(()=>{return}),q=O!==void 0;if(O&&/DELETE_IN_PROGRESS/.test(O))m("Waiting for an in-progress stack delete to finish"),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;else if(O&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(O))m(`Deleting unusable stack (status ${O}) before recreate`),await d.deleteStack(o),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;m(q?"Updating infrastructure stack":"Creating infrastructure stack");try{if(q)await d.updateStack({stackName:o,templateBody:ee,parameters:L,capabilities:te}),await d.waitForStack(o,"stack-update-complete");else await d.createStack({stackName:o,templateBody:ee,parameters:L,capabilities:te,onFailure:"DELETE"}),await d.waitForStack(o,"stack-create-complete")}catch(l){if(/No updates are to be performed/i.test(String(l?.message)))R("No infrastructure changes");else throw l}let W=await d.getStackOutputs(o).catch(()=>({})),E;if(n.assets){let l=Se(u,n.assets);if(Ae(l)){let f=n.assetDomain||W.AssetsCdnDomain;E=f?`https://${f}/${h}`:void 0,m(`Syncing assets from ${n.assets}`);let w=await $e(p,s.assetsBucket,l,h,n.dotFilesAsAssets);R(`Uploaded ${w} asset(s)${E?` → ${E}`:""}`)}else U(`Assets directory not found: ${l}`)}m("Resolving secrets");let B=await Ie(n,a);if(n.database?.connection==="aurora-serverless")try{let f=await new _(a).getSecretValue({SecretId:`${i}/${t}/db`}),w=JSON.parse(f.SecretString??"{}");if(w.username)B.DB_USERNAME=w.username;if(w.password)B.DB_PASSWORD=w.password}catch(l){U(`Could not resolve Aurora DB credentials: ${l.message}`)}if(!await p.bucketExists(c))await p.createBucket(c);let K=await J(p,c,i,t),I={},X=S.queueNames[0],G=De(n,W);if(m("Activating functions"),I.http=Y(n,s,t,"http",B,E,X,G),await F(y,S.functionNames.http,I.http,N),I.cli=Y(n,s,t,"cli",B,E,X,G),await F(y,S.functionNames.cli,I.cli,N),S.queueNames.length)I.queue=Y(n,s,t,"queue",B,E,X,G),await F(y,S.functionNames.queue,I.queue,N);let re=(n.provisionedConcurrency??0)>0,j={};if(re){if(m("Publishing versions + flipping live alias"),j.http=await z(y,S.functionNames.http),j.cli=await z(y,S.functionNames.cli),S.queueNames.length)j.queue=await z(y,S.functionNames.queue)}if(await Re(p,c,i,t,{sha:h,code:N,previousSha:K?.sha,previousCode:K?.code,previousFunctionEnv:K?.functionEnv,...re?{functionVersions:j,previousFunctionVersions:K?.functionVersions}:{},functionEnv:I,functionNames:{http:S.functionNames.http,cli:S.functionNames.cli,...S.queueNames.length?{queue:S.functionNames.queue}:{}},assetUrl:E,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&n.deploy?.length){m("Running deploy hooks");for(let l of n.deploy){R(` deploy: ${l}`);let f=await y.invoke({FunctionName:S.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:l},LogType:"Tail"});if(f.FunctionError)throw ne("Deploy hook failed — the new build is ALREADY LIVE."),R(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${l}): ${f.Payload}`)}}let x=W.HttpApiEndpoint;if(!r.skipHealthCheck&&x){m("Health check");try{let l=await fetch(x,{method:"GET"});R(`GET ${x} → ${l.status}`)}catch(l){U(`Health check could not reach ${x}: ${l.message}`)}}ie(["Serverless deploy complete","",x?`URL: ${x}`:"",`Stack: ${o}`,`Build: ${h.slice(0,12)}`].filter(Boolean).join(`
2
- `),"green")}async function Xe(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i)throw Error("No previous release to redeploy. Run a full deploy first.");M(`Redeploying ${r.slug} (${t}) — build ${i.sha.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Re-activating ${a} (${o})`),await F(n,o,i.functionEnv[a]??{},i.code);let c=i.functionVersions?.[a];if(c)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:c}))}V("Redeploy complete")}async function Ge(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i?.previousCode)throw Error("No previous release to roll back to.");M(`Rolling back ${r.slug} (${t}) → ${i.previousSha?.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Restoring ${a} (${o})`);let c=i.previousFunctionEnv?.[a]??i.functionEnv[a]??{};await F(n,o,c,i.previousCode);let u=i.previousFunctionVersions?.[a];if(u)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:u}))}await Re(s,r.artifactBucket,r.slug,t,{...i,sha:i.previousSha??i.sha,code:i.previousCode,functionEnv:i.previousFunctionEnv??i.functionEnv,functionVersions:i.previousFunctionVersions??i.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),V("Rollback complete")}async function Ye(e,t,r,s){let n=v(e,t),i=new b(n.region),a=`${n.slug}-${t}-http`,c={...(await i.getFunction(a)).Configuration?.Environment?.Variables??{}};if(c.MAINTENANCE_MODE=r?"1":"0",r&&s)c.MAINTENANCE_BYPASS_SECRET=s;if(!r)delete c.MAINTENANCE_BYPASS_SECRET;if(await D(()=>i.updateFunctionConfiguration({FunctionName:a,Environment:{Variables:c}})),(n.app.provisionedConcurrency??0)>0)await i.waitForFunctionActive(a,120),await z(i,a);V(r?"Application is now in maintenance mode (503)":"Application is live")}async function xe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(a.FunctionError)throw Error(`Command failed: ${a.Payload}`);return a.Payload??""}var ve=(e,t)=>`commands/${e}/${t}/history.json`,Ve=50;async function Ne(e,t,r,s){try{return(await e.getObjectJson(t,ve(r,s)))?.records??[]}catch{return[]}}async function Qe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"}),o=a.Payload??"",c=a.FunctionError?"error":"ok",u=-1;try{let p=new P(s.region);if(await p.bucketExists(s.artifactBucket)){let d=await Ne(p,s.artifactBucket,s.slug,t);u=d.reduce((y,C)=>Math.max(y,C.id),0)+1,d.push({id:u,command:r,timestamp:new Date().toISOString(),status:c,output:o.slice(0,4000)}),await p.putObjectJson(s.artifactBucket,ve(s.slug,t),{records:d.slice(-Ve)})}}catch{}if(a.FunctionError)throw Error(`Command failed${u>0?` (#${u})`:""}: ${o}`);return{id:u,status:c,output:o}}async function Be(e,t){let r=v(e,t),s=new P(r.region);return Ne(s,r.artifactBucket,r.slug,t)}async function Ze(e,t,r){let s=await Be(e,t);if(!s.length)return;return r==null?s[s.length-1]:s.find((n)=>n.id===r)}async function et(e,t,r){let s=Buffer.from(r,"utf-8").toString("base64");return xe(e,t,`tscloud:db-query --sql-base64=${s}`)}async function tt(e,t){let r=v(e,t),s=new Z(r.region),n=new b(r.region),i=new P(r.region),a="not deployed",o={};try{let{Stacks:A}=await s.describeStacks({stackName:r.stackName});a=A?.[0]?.StackStatus??a;for(let g of A?.[0]?.Outputs??[])if(g.OutputKey)o[g.OutputKey]=g.OutputValue??""}catch{}let c=de(r.app,r.slug,t),u=r.app.provisionedConcurrency??0,p=["http","cli",...c.length?["queue"]:[]],d=`${r.slug}-${t}`,y=[];for(let A of p){let g=`${d}-${A}`,k={mode:A,name:g,version:"$LATEST"};if(u>0){let N=await n.getAlias(g,"live").catch(()=>null);if(N?.FunctionVersion){k.version=N.FunctionVersion;let h=await n.getProvisionedConcurrencyConfig(g,"live").catch(()=>null);if(h)k.provisioned={status:h.Status??"-",allocated:h.AllocatedProvisionedConcurrentExecutions??0,requested:h.RequestedProvisionedConcurrentExecutions??0}}}y.push(k)}let C=await J(i,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:a,endpoint:o.HttpApiEndpoint,assetUrl:C?.assetUrl,scheduler:r.app.scheduler??"on",queues:c,provisionedConcurrency:u,functions:y,lastRelease:C?{sha:C.sha,timestamp:C.timestamp}:void 0}}function we(e,t){return`${e}-${t}-db`}async function rt(e,t,r,s){let n=v(e,t);if(n.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:i}=await import("./chunk-tvz9c388.js"),a=new i(n.region),o=we(n.slug,t);m(`Scaling ${o} → ${r}–${s} ACUs`),await a.modifyDBCluster({DBClusterIdentifier:o,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:s},ApplyImmediately:!0}),V(`Scaling applied to ${o} (takes effect shortly).`)}async function st(e,t,r){let s=v(e,t);if(s.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!r.toTime&&!r.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:n}=await import("./chunk-tvz9c388.js"),i=new n(s.region),a=we(s.slug,t),o=r.latest?"latest":r.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),c=r.target??`${a}-restore-${o}`;m(`Restoring ${a} → new cluster ${c} (${r.latest?"latest restorable time":r.toTime.toISOString()})`),await i.restoreDBClusterToPointInTime({DBClusterIdentifier:c,SourceDBClusterIdentifier:a,RestoreToTime:r.toTime,UseLatestRestorableTime:r.latest}),m("Waiting for the restored cluster to be ready");for(let u=0;u<120;u++){let{DBClusters:p}=await i.describeDBClusters({DBClusterIdentifier:c}),d=p?.[0]?.Status;if(d&&d!=="creating")break;await new Promise((y)=>setTimeout(y,15000))}return m("Adding a writer instance"),await i.createDBInstance({DBInstanceIdentifier:`${c}-1`,DBClusterIdentifier:c,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),V(`Restore complete → cluster ${c} with writer ${c}-1. Point an env's database at it once available.`),c}
1
+ import{_d as b}from"./chunk-tfmx17he.js";import{ug as Z}from"./chunk-3f27aa5r.js";import{Bg as P}from"./chunk-bj4ft4qc.js";import{$g as m,Wg as V,Xg as ne,Yg as U,_g as R,ah as M,hh as ie}from"./chunk-b0xtsv8k.js";import{oh as se}from"./chunk-mhrtx0p1.js";import{Ao as de,Bo as me,ip as pe,li as ae,mi as oe,ni as ce,op as fe,vo as le,wo as ue,yo as ge}from"./chunk-84703zpq.js";import{Ap as Q}from"./chunk-re15e6p4.js";import{existsSync as Ae,readdirSync as Te,readFileSync as be,statSync as ke}from"node:fs";import{join as Se,relative as Ee}from"node:path";class _{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new se}async createSecret(e){let t={Name:e.Name};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.AddReplicaRegions&&e.AddReplicaRegions.length>0)t.AddReplicaRegions=e.AddReplicaRegions;if(e.ForceOverwriteReplicaSecret!==void 0)t.ForceOverwriteReplicaSecret=e.ForceOverwriteReplicaSecret;t.ClientRequestToken=e.ClientRequestToken||crypto.randomUUID();let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,ReplicationStatus:r.ReplicationStatus}}async updateSecret(e){let t={SecretId:e.SecretId};if(e.Description)t.Description=e.Description;if(e.KmsKeyId)t.KmsKeyId=e.KmsKeyId;if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async putSecretValue(e){let t={SecretId:e.SecretId};if(e.SecretBinary)t.SecretBinary=e.SecretBinary;if(e.SecretString)t.SecretString=e.SecretString;if(e.VersionStages&&e.VersionStages.length>0)t.VersionStages=e.VersionStages;if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,VersionStages:r.VersionStages}}async getSecretValue(e){let t={SecretId:e.SecretId};if(e.VersionId)t.VersionId=e.VersionId;if(e.VersionStage)t.VersionStage=e.VersionStage;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId,SecretBinary:r.SecretBinary,SecretString:r.SecretString,VersionStages:r.VersionStages,CreatedDate:r.CreatedDate}}async describeSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return this.parseSecret(r)}async listSecrets(e){let t={};if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.SortOrder)t.SortOrder=e.SortOrder;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{SecretList:r.SecretList?.map((s)=>this.parseSecret(s)),NextToken:r.NextToken}}async deleteSecret(e){let t={SecretId:e.SecretId};if(e.RecoveryWindowInDays!==void 0)t.RecoveryWindowInDays=e.RecoveryWindowInDays;if(e.ForceDeleteWithoutRecovery!==void 0)t.ForceDeleteWithoutRecovery=e.ForceDeleteWithoutRecovery;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,DeletionDate:r.DeletionDate}}async restoreSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async rotateSecret(e){let t={SecretId:e.SecretId};if(e.ClientRequestToken)t.ClientRequestToken=e.ClientRequestToken;if(e.RotationLambdaARN)t.RotationLambdaARN=e.RotationLambdaARN;if(e.RotationRules)t.RotationRules=e.RotationRules;if(e.RotateImmediately!==void 0)t.RotateImmediately=e.RotateImmediately;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,VersionId:r.VersionId}}async cancelRotateSecret(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async getResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name,ResourcePolicy:r.ResourcePolicy}}async putResourcePolicy(e){let t={SecretId:e.SecretId,ResourcePolicy:e.ResourcePolicy};if(e.BlockPublicPolicy!==void 0)t.BlockPublicPolicy=e.BlockPublicPolicy;let r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async deleteResourcePolicy(e){let t={SecretId:e},r=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{ARN:r.ARN,Name:r.Name}}async tagResource(e){let t={SecretId:e.SecretId,Tags:e.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async untagResource(e){let t={SecretId:e.SecretId,TagKeys:e.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async setString(e,t,r){try{let s=await this.putSecretValue({SecretId:e,SecretString:t});return{ARN:s.ARN,VersionId:s.VersionId}}catch(s){if(s.code==="ResourceNotFoundException"){let n=await this.createSecret({Name:e,SecretString:t,Description:r?.description,KmsKeyId:r?.kmsKeyId,Tags:r?.tags});return{ARN:n.ARN,VersionId:n.VersionId}}throw s}}async setJson(e,t,r){return this.setString(e,JSON.stringify(t),r)}async getString(e){return(await this.getSecretValue({SecretId:e})).SecretString}async getJson(e){let t=await this.getString(e);if(t)return JSON.parse(t);return}async listAll(){let e=[],t;do{let r=await this.listSecrets({NextToken:t});if(r.SecretList)e.push(...r.SecretList);t=r.NextToken}while(t);return e}parseSecret(e){return{ARN:e.ARN,Name:e.Name,Description:e.Description,KmsKeyId:e.KmsKeyId,RotationEnabled:e.RotationEnabled,RotationLambdaARN:e.RotationLambdaARN,RotationRules:e.RotationRules,LastRotatedDate:e.LastRotatedDate,LastChangedDate:e.LastChangedDate,LastAccessedDate:e.LastAccessedDate,DeletedDate:e.DeletedDate,NextRotationDate:e.NextRotationDate,Tags:e.Tags,SecretVersionsToStages:e.SecretVersionsToStages,CreatedDate:e.CreatedDate,PrimaryRegion:e.PrimaryRegion}}}function v(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let s=e.project.slug,n=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:s,region:n,stackName:ae(e,t),artifactBucket:oe(s,t),assetsBucket:ce(s,t)}}function He(e,t){let r=v(e,t),s=`${r.slug}-${t}`;return{region:r.region,slug:r.slug,stackName:r.stackName,functions:{http:`${s}-http`,queue:`${s}-queue`,cli:`${s}-cli`}}}async function D(e,t=8){let r;for(let s=0;s<t;s++)try{return await e()}catch(n){let i=n?.code||n?.name||"",a=String(n?.message||"");if(i==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(a)){r=n,await new Promise((o)=>setTimeout(o,3000));continue}throw n}throw r}var ye=(e,t)=>`releases/${e}/${t}/current.json`;async function J(e,t,r,s){try{return await e.getObjectJson(t,ye(r,s))}catch{return null}}async function Re(e,t,r,s,n){await e.putObjectJson(t,ye(r,s),n)}async function Ie(e,t){if(!e.secrets)return{};let r=new _(t),s={},n=Array.isArray(e.secrets)?e.secrets.map((i)=>({envName:i.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:i})):Object.entries(e.secrets).map(([i,a])=>({envName:i,secretId:a}));if(Array.isArray(e.secrets)){let i=new Map;for(let{envName:o,secretId:c}of n)i.set(o,[...i.get(o)??[],c]);let a=[...i.entries()].filter(([,o])=>o.length>1);if(a.length){let o=a.map(([c,u])=>`${c} ← ${u.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${o}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:i,secretId:a}of n){let c=(await r.getSecretValue({SecretId:a})).SecretString??"";try{let u=JSON.parse(c);if(u&&typeof u==="object"&&!Array.isArray(u)){for(let[p,d]of Object.entries(u))s[p]=String(d);continue}}catch{}s[i]=c}return s}function De(e,t){let r={},s=t.DbProxyEndpoint||t.DbEndpoint;if(s)r.DB_CONNECTION="mysql",r.DB_HOST=s,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Y(e,t,r,s,n,i,a,o={}){let c=e.kind==="php"?pe({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:s,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...c,...o,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...a?{TSCLOUD_QUEUE:a,SQS_QUEUE:a}:{},...i?{ASSET_URL:i}:{},...e.env??{},...n}}function Pe(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*he(e){for(let t of Te(e)){let r=Se(e,t);if(ke(r).isDirectory())yield*he(r);else yield r}}async function $e(e,t,r,s,n=!1){let i=0;for(let a of he(r)){let o=Ee(r,a).replace(/\\/g,"/");if(!n&&o.split("/").some((c)=>c.startsWith(".")))continue;await e.putObject({bucket:t,key:`${s}/${o}`,body:be(a),contentType:Pe(a),cacheControl:"public, max-age=31536000, immutable"}),i++}return i}function Oe(e,t){let r=Object.entries(t).reduce((s,[n,i])=>s+Buffer.byteLength(`${n}=${i}`,"utf8"),0);if(r>4096){let s=Object.entries(t).map(([n,i])=>[n,Buffer.byteLength(`${n}=${i}`,"utf8")]).sort((n,i)=>i[1]-n[1]).slice(0,5).map(([n,i])=>`${n} (${i}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${s}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function F(e,t,r,s){Oe(t,r),await D(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let n=s.kind==="image"?{FunctionName:t,ImageUri:s.imageUri}:{FunctionName:t,S3Bucket:s.bucket,S3Key:s.key};await D(()=>e.updateFunctionCode(n)),await e.waitForFunctionActive(t,120)}async function z(e,t){let s=(await D(()=>e.publishVersion({FunctionName:t}))).Version;if(!s)throw Error(`publishVersion returned no version for ${t}`);return await D(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:s})),s}async function We(e,t,r={}){let s=v(e,t),{app:n,slug:i,region:a,stackName:o,artifactBucket:c}=s,u=r.projectRoot??process.cwd();M(`Deploying serverless app: ${i} (${t})`),R(`Stack: ${o}`),R(`Region: ${a}`);let p=new P(a),d=new Z(a),y=new b(a),C=n.kind==="php",A=n.packaging==="image",g=ge(n),k,N,h,H,L=[];if(A&&g.usesLayer&&g.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${g.kind}${g.kind==="node"?` ${g.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(A){m("Building + pushing container image");let{buildAndPushServerlessImage:l}=await import("./chunk-py1hyeb2.js"),f=await l({app:n,projectRoot:u,region:a,repository:`${i}-${t}`,skipBuild:r.skipBuild,onStep:(w)=>R(` ${w}`)});k=f.handlers,N={kind:"image",imageUri:f.imageUri},h=f.tag,L.push({ParameterKey:"ImageUri",ParameterValue:f.imageUri})}else{m("Packaging application");let l=C?fe({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}):await ue({projectRoot:u,app:n,skipBuild:r.skipBuild,onStep:(T)=>R(` ${T}`)}),f=le(i,t,l.sha256);if(R(`Artifact: ${l.sha256.slice(0,12)} (${(l.zip.length/1024).toFixed(0)} KB)`),k=l.handlers,h=l.sha256,g.usesLayer){let T=g.layerEnvVar?process.env[g.layerEnvVar]:void 0;if(H=n.layers??(T?[T]:void 0),!H?.length){let Ce=g.layerKind==="php"?"serverless:build-php-layer":g.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${g.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${g.layerEnvVar} env var (build one with \`cloud ${Ce}\`)${g.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await p.bucketExists(c))m(`Creating artifact bucket ${c}`),await p.createBucket(c);if(await p.headObject(c,f).then((T)=>T!==null).catch(()=>!1))R("Artifact already uploaded — reusing");else m("Uploading artifact"),await p.putObject({bucket:c,key:f,body:l.zip,contentType:"application/zip"});N={kind:"zip",bucket:c,key:f},L.push({ParameterKey:"ArtifactBucket",ParameterValue:c},{ParameterKey:"ArtifactKey",ParameterValue:f})}let S=me({config:e,environment:t,app:n,handlers:k,runtimeLayers:H}),ee=JSON.stringify(S.template),te=["CAPABILITY_NAMED_IAM"],O=await d.describeStacks({stackName:o}).then((l)=>l.Stacks[0]?.StackStatus).catch(()=>{return}),q=O!==void 0;if(O&&/DELETE_IN_PROGRESS/.test(O))m("Waiting for an in-progress stack delete to finish"),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;else if(O&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(O))m(`Deleting unusable stack (status ${O}) before recreate`),await d.deleteStack(o),await d.waitForStack(o,"stack-delete-complete").catch(()=>{}),q=!1;m(q?"Updating infrastructure stack":"Creating infrastructure stack");try{if(q)await d.updateStack({stackName:o,templateBody:ee,parameters:L,capabilities:te}),await d.waitForStack(o,"stack-update-complete");else await d.createStack({stackName:o,templateBody:ee,parameters:L,capabilities:te,onFailure:"DELETE"}),await d.waitForStack(o,"stack-create-complete")}catch(l){if(/No updates are to be performed/i.test(String(l?.message)))R("No infrastructure changes");else throw l}let W=await d.getStackOutputs(o).catch(()=>({})),E;if(n.assets){let l=Se(u,n.assets);if(Ae(l)){let f=n.assetDomain||W.AssetsCdnDomain;E=f?`https://${f}/${h}`:void 0,m(`Syncing assets from ${n.assets}`);let w=await $e(p,s.assetsBucket,l,h,n.dotFilesAsAssets);R(`Uploaded ${w} asset(s)${E?` → ${E}`:""}`)}else U(`Assets directory not found: ${l}`)}m("Resolving secrets");let B=await Ie(n,a);if(n.database?.connection==="aurora-serverless")try{let f=await new _(a).getSecretValue({SecretId:`${i}/${t}/db`}),w=JSON.parse(f.SecretString??"{}");if(w.username)B.DB_USERNAME=w.username;if(w.password)B.DB_PASSWORD=w.password}catch(l){U(`Could not resolve Aurora DB credentials: ${l.message}`)}if(!await p.bucketExists(c))await p.createBucket(c);let K=await J(p,c,i,t),I={},X=S.queueNames[0],G=De(n,W);if(m("Activating functions"),I.http=Y(n,s,t,"http",B,E,X,G),await F(y,S.functionNames.http,I.http,N),I.cli=Y(n,s,t,"cli",B,E,X,G),await F(y,S.functionNames.cli,I.cli,N),S.queueNames.length)I.queue=Y(n,s,t,"queue",B,E,X,G),await F(y,S.functionNames.queue,I.queue,N);let re=(n.provisionedConcurrency??0)>0,j={};if(re){if(m("Publishing versions + flipping live alias"),j.http=await z(y,S.functionNames.http),j.cli=await z(y,S.functionNames.cli),S.queueNames.length)j.queue=await z(y,S.functionNames.queue)}if(await Re(p,c,i,t,{sha:h,code:N,previousSha:K?.sha,previousCode:K?.code,previousFunctionEnv:K?.functionEnv,...re?{functionVersions:j,previousFunctionVersions:K?.functionVersions}:{},functionEnv:I,functionNames:{http:S.functionNames.http,cli:S.functionNames.cli,...S.queueNames.length?{queue:S.functionNames.queue}:{}},assetUrl:E,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&n.deploy?.length){m("Running deploy hooks");for(let l of n.deploy){R(` deploy: ${l}`);let f=await y.invoke({FunctionName:S.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:l},LogType:"Tail"});if(f.FunctionError)throw ne("Deploy hook failed — the new build is ALREADY LIVE."),R(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${l}): ${f.Payload}`)}}let x=W.HttpApiEndpoint;if(!r.skipHealthCheck&&x){m("Health check");try{let l=await fetch(x,{method:"GET"});R(`GET ${x} → ${l.status}`)}catch(l){U(`Health check could not reach ${x}: ${l.message}`)}}ie(["Serverless deploy complete","",x?`URL: ${x}`:"",`Stack: ${o}`,`Build: ${h.slice(0,12)}`].filter(Boolean).join(`
2
+ `),"green")}async function Xe(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i)throw Error("No previous release to redeploy. Run a full deploy first.");M(`Redeploying ${r.slug} (${t}) — build ${i.sha.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Re-activating ${a} (${o})`),await F(n,o,i.functionEnv[a]??{},i.code);let c=i.functionVersions?.[a];if(c)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:c}))}V("Redeploy complete")}async function Ge(e,t){let r=v(e,t),s=new P(r.region),n=new b(r.region),i=await J(s,r.artifactBucket,r.slug,t);if(!i?.previousCode)throw Error("No previous release to roll back to.");M(`Rolling back ${r.slug} (${t}) → ${i.previousSha?.slice(0,12)}`);for(let[a,o]of Object.entries(i.functionNames)){if(!o)continue;m(`Restoring ${a} (${o})`);let c=i.previousFunctionEnv?.[a]??i.functionEnv[a]??{};await F(n,o,c,i.previousCode);let u=i.previousFunctionVersions?.[a];if(u)await D(()=>n.updateAlias({FunctionName:o,Name:"live",FunctionVersion:u}))}await Re(s,r.artifactBucket,r.slug,t,{...i,sha:i.previousSha??i.sha,code:i.previousCode,functionEnv:i.previousFunctionEnv??i.functionEnv,functionVersions:i.previousFunctionVersions??i.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),V("Rollback complete")}async function Ye(e,t,r,s){let n=v(e,t),i=new b(n.region),a=`${n.slug}-${t}-http`,c={...(await i.getFunction(a)).Configuration?.Environment?.Variables??{}};if(c.MAINTENANCE_MODE=r?"1":"0",r&&s)c.MAINTENANCE_BYPASS_SECRET=s;if(!r)delete c.MAINTENANCE_BYPASS_SECRET;if(await D(()=>i.updateFunctionConfiguration({FunctionName:a,Environment:{Variables:c}})),(n.app.provisionedConcurrency??0)>0)await i.waitForFunctionActive(a,120),await z(i,a);V(r?"Application is now in maintenance mode (503)":"Application is live")}async function xe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(a.FunctionError)throw Error(`Command failed: ${a.Payload}`);return a.Payload??""}var ve=(e,t)=>`commands/${e}/${t}/history.json`,Ve=50;async function Ne(e,t,r,s){try{return(await e.getObjectJson(t,ve(r,s)))?.records??[]}catch{return[]}}async function Qe(e,t,r){let s=v(e,t),n=new b(s.region),i=`${s.slug}-${t}-cli`,a=await n.invoke({FunctionName:i,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"}),o=a.Payload??"",c=a.FunctionError?"error":"ok",u=-1;try{let p=new P(s.region);if(await p.bucketExists(s.artifactBucket)){let d=await Ne(p,s.artifactBucket,s.slug,t);u=d.reduce((y,C)=>Math.max(y,C.id),0)+1,d.push({id:u,command:r,timestamp:new Date().toISOString(),status:c,output:o.slice(0,4000)}),await p.putObjectJson(s.artifactBucket,ve(s.slug,t),{records:d.slice(-Ve)})}}catch{}if(a.FunctionError)throw Error(`Command failed${u>0?` (#${u})`:""}: ${o}`);return{id:u,status:c,output:o}}async function Be(e,t){let r=v(e,t),s=new P(r.region);return Ne(s,r.artifactBucket,r.slug,t)}async function Ze(e,t,r){let s=await Be(e,t);if(!s.length)return;return r==null?s[s.length-1]:s.find((n)=>n.id===r)}async function et(e,t,r){let s=Buffer.from(r,"utf-8").toString("base64");return xe(e,t,`tscloud:db-query --sql-base64=${s}`)}async function tt(e,t){let r=v(e,t),s=new Z(r.region),n=new b(r.region),i=new P(r.region),a="not deployed",o={};try{let{Stacks:A}=await s.describeStacks({stackName:r.stackName});a=A?.[0]?.StackStatus??a;for(let g of A?.[0]?.Outputs??[])if(g.OutputKey)o[g.OutputKey]=g.OutputValue??""}catch{}let c=de(r.app,r.slug,t),u=r.app.provisionedConcurrency??0,p=["http","cli",...c.length?["queue"]:[]],d=`${r.slug}-${t}`,y=[];for(let A of p){let g=`${d}-${A}`,k={mode:A,name:g,version:"$LATEST"};if(u>0){let N=await n.getAlias(g,"live").catch(()=>null);if(N?.FunctionVersion){k.version=N.FunctionVersion;let h=await n.getProvisionedConcurrencyConfig(g,"live").catch(()=>null);if(h)k.provisioned={status:h.Status??"-",allocated:h.AllocatedProvisionedConcurrentExecutions??0,requested:h.RequestedProvisionedConcurrentExecutions??0}}}y.push(k)}let C=await J(i,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:a,endpoint:o.HttpApiEndpoint,assetUrl:C?.assetUrl,scheduler:r.app.scheduler??"on",queues:c,provisionedConcurrency:u,functions:y,lastRelease:C?{sha:C.sha,timestamp:C.timestamp}:void 0}}function we(e,t){return`${e}-${t}-db`}async function rt(e,t,r,s){let n=v(e,t);if(n.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:i}=await import("./chunk-5jv4cpky.js"),a=new i(n.region),o=we(n.slug,t);m(`Scaling ${o} → ${r}–${s} ACUs`),await a.modifyDBCluster({DBClusterIdentifier:o,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:s},ApplyImmediately:!0}),V(`Scaling applied to ${o} (takes effect shortly).`)}async function st(e,t,r){let s=v(e,t);if(s.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!r.toTime&&!r.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:n}=await import("./chunk-5jv4cpky.js"),i=new n(s.region),a=we(s.slug,t),o=r.latest?"latest":r.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),c=r.target??`${a}-restore-${o}`;m(`Restoring ${a} → new cluster ${c} (${r.latest?"latest restorable time":r.toTime.toISOString()})`),await i.restoreDBClusterToPointInTime({DBClusterIdentifier:c,SourceDBClusterIdentifier:a,RestoreToTime:r.toTime,UseLatestRestorableTime:r.latest}),m("Waiting for the restored cluster to be ready");for(let u=0;u<120;u++){let{DBClusters:p}=await i.describeDBClusters({DBClusterIdentifier:c}),d=p?.[0]?.Status;if(d&&d!=="creating")break;await new Promise((y)=>setTimeout(y,15000))}return m("Adding a writer instance"),await i.createDBInstance({DBInstanceIdentifier:`${c}-1`,DBClusterIdentifier:c,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),V(`Restore complete → cluster ${c} with writer ${c}-1. Point an env's database at it once available.`),c}
3
3
  export{_ as Id,He as Jd,Ie as Kd,De as Ld,Y as Md,Oe as Nd,We as Od,Xe as Pd,Ge as Qd,Ye as Rd,xe as Sd,Qe as Td,Be as Ud,Ze as Vd,et as Wd,tt as Xd,rt as Yd,st as Zd};
@@ -1 +1 @@
1
- import{a as y,b as z,c as A,d as B,e as C,f as D,g as E,h as F,i as G,j as H,k as I,l as J,m as K,n as L,o as M}from"./chunk-xkfrqqcs.js";import{$e as u,Ze as s,_e as t,af as v,bf as w,cf as x}from"./chunk-8ewncfce.js";import{df as k,ef as l,ff as m,gf as n,hf as o,if as p,jf as q,kf as r}from"./chunk-9kf0np8j.js";import{Ao as c,Bo as d,Co as e,Do as f,Eo as g,Fo as h,Go as i,Ho as j,yo as a,zo as b}from"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{b as CHAIN_HEADER,H as DEFAULT_ATTACK_MODE_HOURS,k as DEFAULT_DDOS_THRESHOLDS,e as DEFAULT_RECURSION_LIMITS,a as DEPTH_HEADER,G as MAX_CONTROL_HOURS,F as PROTECTION_SETTING,I as ProtectionControlStore,y as RATE_LIMIT_KEY_SEPARATOR,C as RateLimiter,h as RecursionGuard,c as TRACE_HEADER,L as applyControlsToDdos,K as applyControlsToRateLimits,r as applyMitigationFactor,E as defaultRateLimitRules,J as describePosture,s as escapeSecLang,d as functionFingerprint,z as globMatches,u as globToRegex,g as inspectInvocation,t as isSafePattern,l as isValidCidr,M as mergeControlsIntoConfig,f as parseChain,q as planMitigation,i as propagationHeaders,D as rateLimitHeaders,B as rateLimitKey,j as recursionBlockedResponse,p as renderDdosInstallScript,o as renderNftablesRuleset,n as renderSysctlFile,v as renderWafConfig,w as renderWafInstallScript,A as ruleMatches,m as sysctlHardening,x as wafEventTelemetry};
1
+ import{a as y,b as z,c as A,d as B,e as C,f as D,g as E,h as F,i as G,j as H,k as I,l as J,m as K,n as L,o as M}from"./chunk-akwfvn5k.js";import{hf as s,if as t,jf as u,kf as v,lf as w,mf as x}from"./chunk-j2cb8we4.js";import{nf as k,of as l,pf as m,qf as n,rf as o,sf as p,tf as q,uf as r}from"./chunk-5gx38418.js";import{Ko as a,Lo as b,Mo as c,No as d,Oo as e,Po as f,Qo as g,Ro as h,So as i,To as j}from"./chunk-84703zpq.js";import"./chunk-re15e6p4.js";export{b as CHAIN_HEADER,H as DEFAULT_ATTACK_MODE_HOURS,k as DEFAULT_DDOS_THRESHOLDS,e as DEFAULT_RECURSION_LIMITS,a as DEPTH_HEADER,G as MAX_CONTROL_HOURS,F as PROTECTION_SETTING,I as ProtectionControlStore,y as RATE_LIMIT_KEY_SEPARATOR,C as RateLimiter,h as RecursionGuard,c as TRACE_HEADER,L as applyControlsToDdos,K as applyControlsToRateLimits,r as applyMitigationFactor,E as defaultRateLimitRules,J as describePosture,s as escapeSecLang,d as functionFingerprint,z as globMatches,u as globToRegex,g as inspectInvocation,t as isSafePattern,l as isValidCidr,M as mergeControlsIntoConfig,f as parseChain,q as planMitigation,i as propagationHeaders,D as rateLimitHeaders,B as rateLimitKey,j as recursionBlockedResponse,p as renderDdosInstallScript,o as renderNftablesRuleset,n as renderSysctlFile,v as renderWafConfig,w as renderWafInstallScript,A as ruleMatches,m as sysctlHardening,x as wafEventTelemetry};
@@ -0,0 +1 @@
1
+ import{_d as a}from"./chunk-tfmx17he.js";import"./chunk-mhrtx0p1.js";import"./chunk-re15e6p4.js";export{a as LambdaClient};