@geekmidas/cli 10.0.0-alpha.166 → 10.0.0-alpha.167
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GoDaddyProvider-mnY-cdD2.mjs → GoDaddyProvider-Dci0SlN5.mjs} +2 -2
- package/dist/{GoDaddyProvider-mnY-cdD2.mjs.map → GoDaddyProvider-Dci0SlN5.mjs.map} +1 -1
- package/dist/{GoDaddyProvider-DClFHezd.cjs → GoDaddyProvider-o6DJAsBZ.cjs} +2 -2
- package/dist/{GoDaddyProvider-DClFHezd.cjs.map → GoDaddyProvider-o6DJAsBZ.cjs.map} +1 -1
- package/dist/{HostingerProvider-BMyz2LnZ.cjs → HostingerProvider-BzHPhONW.cjs} +2 -2
- package/dist/{HostingerProvider-BMyz2LnZ.cjs.map → HostingerProvider-BzHPhONW.cjs.map} +1 -1
- package/dist/{HostingerProvider-39eSGyBa.mjs → HostingerProvider-Dd5x1zvF.mjs} +2 -2
- package/dist/{HostingerProvider-39eSGyBa.mjs.map → HostingerProvider-Dd5x1zvF.mjs.map} +1 -1
- package/dist/{LegacyStateStore-B2TBaSMq.mjs → LegacyStateStore-CpF6rmZc.mjs} +2 -2
- package/dist/{LegacyStateStore-B2TBaSMq.mjs.map → LegacyStateStore-CpF6rmZc.mjs.map} +1 -1
- package/dist/{LegacyStateStore-BJY7ntQk.cjs → LegacyStateStore-tqY0hM8z.cjs} +2 -2
- package/dist/{LegacyStateStore-BJY7ntQk.cjs.map → LegacyStateStore-tqY0hM8z.cjs.map} +1 -1
- package/dist/{LocalStateStore-8LFd-aMA.mjs → LocalStateStore-Adp96xPy.mjs} +2 -2
- package/dist/{LocalStateStore-8LFd-aMA.mjs.map → LocalStateStore-Adp96xPy.mjs.map} +1 -1
- package/dist/{LocalStateStore-BvoEjPi5.cjs → LocalStateStore-BYMUEGZN.cjs} +2 -2
- package/dist/{LocalStateStore-BvoEjPi5.cjs.map → LocalStateStore-BYMUEGZN.cjs.map} +1 -1
- package/dist/{S3StateStore-DMzsqfSa.mjs → S3StateStore-13Go3hfM.mjs} +4 -4
- package/dist/{S3StateStore-DMzsqfSa.mjs.map → S3StateStore-13Go3hfM.mjs.map} +1 -1
- package/dist/{S3StateStore-eeA5NXRa.cjs → S3StateStore-DjXyhGIP.cjs} +4 -4
- package/dist/{S3StateStore-eeA5NXRa.cjs.map → S3StateStore-DjXyhGIP.cjs.map} +1 -1
- package/dist/{SSMStateStore-CE2DTAtT.mjs → SSMStateStore-CQHUyH-c.mjs} +2 -2
- package/dist/{SSMStateStore-CE2DTAtT.mjs.map → SSMStateStore-CQHUyH-c.mjs.map} +1 -1
- package/dist/{SSMStateStore-BUv-du0T.cjs → SSMStateStore-DspMPho-.cjs} +2 -2
- package/dist/{SSMStateStore-BUv-du0T.cjs.map → SSMStateStore-DspMPho-.cjs.map} +1 -1
- package/dist/{add-Dp0KQNkQ.cjs → add-DsxJ0Knr.cjs} +6 -6
- package/dist/{add-Dp0KQNkQ.cjs.map → add-DsxJ0Knr.cjs.map} +1 -1
- package/dist/{add-BgCYGJpE.mjs → add-Dt8QKSOw.mjs} +6 -6
- package/dist/{add-BgCYGJpE.mjs.map → add-Dt8QKSOw.mjs.map} +1 -1
- package/dist/{apps-DkMR-qvD.cjs → apps-C6s-trVp.cjs} +66 -12
- package/dist/apps-C6s-trVp.cjs.map +1 -0
- package/dist/{apps-CJTOIaz3.mjs → apps-w2sRQKCr.mjs} +66 -13
- package/dist/apps-w2sRQKCr.mjs.map +1 -0
- package/dist/{bundler-CA7KimJ0.cjs → bundler-AzkSRAuu.cjs} +6 -6
- package/dist/{bundler-CA7KimJ0.cjs.map → bundler-AzkSRAuu.cjs.map} +1 -1
- package/dist/{bundler-Dt1ffXl6.mjs → bundler-BCWWne6N.mjs} +6 -6
- package/dist/{bundler-Dt1ffXl6.mjs.map → bundler-BCWWne6N.mjs.map} +1 -1
- package/dist/{cli-C-fdEb8N.mjs → cli-DSGw0Mw-.mjs} +4 -4
- package/dist/{cli-C-fdEb8N.mjs.map → cli-DSGw0Mw-.mjs.map} +1 -1
- package/dist/{cli-CY1Cp8yN.cjs → cli-OGss08bZ.cjs} +4 -4
- package/dist/{cli-CY1Cp8yN.cjs.map → cli-OGss08bZ.cjs.map} +1 -1
- package/dist/{compose-BIm9yNH7.cjs → compose-BqTuzitb.cjs} +5 -5
- package/dist/{compose-BIm9yNH7.cjs.map → compose-BqTuzitb.cjs.map} +1 -1
- package/dist/{compose-tX6YTa1U.mjs → compose-Csegtvq_.mjs} +62 -9
- package/dist/compose-Csegtvq_.mjs.map +1 -0
- package/dist/{compose-SmuCWWUh.cjs → compose-QSBmhr4V.cjs} +73 -8
- package/dist/compose-QSBmhr4V.cjs.map +1 -0
- package/dist/{compose-CZGeE6QJ.mjs → compose-RhuFQmZS.mjs} +5 -5
- package/dist/{compose-CZGeE6QJ.mjs.map → compose-RhuFQmZS.mjs.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{credentials-CS3Dr-pv.cjs → credentials-CORvhcrO.cjs} +6 -6
- package/dist/{credentials-CS3Dr-pv.cjs.map → credentials-CORvhcrO.cjs.map} +1 -1
- package/dist/{credentials-V3WgiKmZ.mjs → credentials-D4DUPPPP.mjs} +6 -6
- package/dist/{credentials-V3WgiKmZ.mjs.map → credentials-D4DUPPPP.mjs.map} +1 -1
- package/dist/deploy/public.cjs +11 -11
- package/dist/deploy/public.d.cts.map +1 -1
- package/dist/deploy/public.d.mts.map +1 -1
- package/dist/deploy/public.mjs +11 -11
- package/dist/{deploy--ia-CGMv.cjs → deploy-BwJ7uWXd.cjs} +107 -22
- package/dist/deploy-BwJ7uWXd.cjs.map +1 -0
- package/dist/{deploy-BWFFSN5p.mjs → deploy-DDfnQm8l.mjs} +107 -22
- package/dist/deploy-DDfnQm8l.mjs.map +1 -0
- package/dist/{destroy-ZNiKL3--.mjs → destroy-DKt8S051.mjs} +9 -9
- package/dist/{destroy-ZNiKL3--.mjs.map → destroy-DKt8S051.mjs.map} +1 -1
- package/dist/{destroy-CrxF8Dlk.cjs → destroy-nTNRfdy6.cjs} +9 -9
- package/dist/{destroy-CrxF8Dlk.cjs.map → destroy-nTNRfdy6.cjs.map} +1 -1
- package/dist/{docker-BtUjo-J_.cjs → docker-Dy1ZJUzV.cjs} +11 -7
- package/dist/docker-Dy1ZJUzV.cjs.map +1 -0
- package/dist/{docker-DhmU416x.mjs → docker-Ele34O8z.mjs} +12 -8
- package/dist/{docker-DhmU416x.mjs.map → docker-Ele34O8z.mjs.map} +1 -1
- package/dist/{dokploy-BszAUbbA.mjs → dokploy-BrfA2m5K.mjs} +2 -2
- package/dist/{dokploy-BszAUbbA.mjs.map → dokploy-BrfA2m5K.mjs.map} +1 -1
- package/dist/{dokploy-ComPiFLl.cjs → dokploy-DN2W1YIH.cjs} +2 -2
- package/dist/{dokploy-ComPiFLl.cjs.map → dokploy-DN2W1YIH.cjs.map} +1 -1
- package/dist/{eas-zxVAWY6c.cjs → eas-BRBdxmwe.cjs} +3 -3
- package/dist/{eas-zxVAWY6c.cjs.map → eas-BRBdxmwe.cjs.map} +1 -1
- package/dist/{eas-DQudP2g2.mjs → eas-CO3ogve5.mjs} +3 -3
- package/dist/{eas-DQudP2g2.mjs.map → eas-CO3ogve5.mjs.map} +1 -1
- package/dist/{encryption-CU5O0Y61.cjs → encryption-BZ1zgtF5.cjs} +3 -3
- package/dist/{encryption-CU5O0Y61.cjs.map → encryption-BZ1zgtF5.cjs.map} +1 -1
- package/dist/{encryption-BCaweYBJ.mjs → encryption-CHmfNBAy.mjs} +3 -3
- package/dist/{encryption-BCaweYBJ.mjs.map → encryption-CHmfNBAy.mjs.map} +1 -1
- package/dist/{engine-BzeCK6e8.mjs → engine-B3Gmu8-O.mjs} +13 -13
- package/dist/engine-B3Gmu8-O.mjs.map +1 -0
- package/dist/{engine-xrlcbr1g.cjs → engine-DewbDHOq.cjs} +12 -12
- package/dist/engine-DewbDHOq.cjs.map +1 -0
- package/dist/{github-Jcrqfzg0.cjs → github-DPNgIxdc.cjs} +7 -7
- package/dist/{github-Jcrqfzg0.cjs.map → github-DPNgIxdc.cjs.map} +1 -1
- package/dist/{github-CHClpJZS.mjs → github-DU3iEmJN.mjs} +7 -7
- package/dist/{github-CHClpJZS.mjs.map → github-DU3iEmJN.mjs.map} +1 -1
- package/dist/{googlePlay-e_tIBr4n.cjs → googlePlay-C2jnPqYn.cjs} +4 -4
- package/dist/{googlePlay-e_tIBr4n.cjs.map → googlePlay-C2jnPqYn.cjs.map} +1 -1
- package/dist/{googlePlay-Dk_pnif9.mjs → googlePlay-KPHn9H2f.mjs} +4 -4
- package/dist/{googlePlay-Dk_pnif9.mjs.map → googlePlay-KPHn9H2f.mjs.map} +1 -1
- package/dist/{iam-B6WLUf_x.cjs → iam-C2sf6AUi.cjs} +2 -2
- package/dist/{iam-B6WLUf_x.cjs.map → iam-C2sf6AUi.cjs.map} +1 -1
- package/dist/{iam-BKfO7u14.mjs → iam-CW61VcT3.mjs} +2 -2
- package/dist/{iam-BKfO7u14.mjs.map → iam-CW61VcT3.mjs.map} +1 -1
- package/dist/index.cjs +351 -112
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +351 -112
- package/dist/index.mjs.map +1 -1
- package/dist/{local-Dc2h2Ex3.cjs → local-BxjA0EXj.cjs} +2 -2
- package/dist/{local-Dc2h2Ex3.cjs.map → local-BxjA0EXj.cjs.map} +1 -1
- package/dist/{local-DUi3f-WB.mjs → local-CwR2DW6i.mjs} +2 -2
- package/dist/{local-DUi3f-WB.mjs.map → local-CwR2DW6i.mjs.map} +1 -1
- package/dist/{migrate-BU4eyd7z.cjs → migrate-B0a3WY4X.cjs} +5 -5
- package/dist/{migrate-BU4eyd7z.cjs.map → migrate-B0a3WY4X.cjs.map} +1 -1
- package/dist/{migrate-CIjcBr96.cjs → migrate-CYtM1UBH.cjs} +3 -3
- package/dist/{migrate-CIjcBr96.cjs.map → migrate-CYtM1UBH.cjs.map} +1 -1
- package/dist/{migrate-CbpeVxEW.mjs → migrate-DHWy64pc.mjs} +3 -3
- package/dist/{migrate-CbpeVxEW.mjs.map → migrate-DHWy64pc.mjs.map} +1 -1
- package/dist/{migrate-BxFCXc7M.mjs → migrate-vWy2CUoi.mjs} +5 -5
- package/dist/{migrate-BxFCXc7M.mjs.map → migrate-vWy2CUoi.mjs.map} +1 -1
- package/dist/next.cjs +59 -0
- package/dist/next.cjs.map +1 -0
- package/dist/next.d.cts +44 -0
- package/dist/next.d.cts.map +1 -0
- package/dist/next.d.mts +44 -0
- package/dist/next.d.mts.map +1 -0
- package/dist/next.mjs +58 -0
- package/dist/next.mjs.map +1 -0
- package/dist/{notes-TDHMzdVt.mjs → notes-9bOfe08J.mjs} +7 -7
- package/dist/notes-9bOfe08J.mjs.map +1 -0
- package/dist/{notes-DJyFkK13.cjs → notes-DRdlsCYV.cjs} +6 -6
- package/dist/notes-DRdlsCYV.cjs.map +1 -0
- package/dist/openapi.cjs +1 -1
- package/dist/openapi.mjs +1 -1
- package/dist/{projectBucket-BPzx0b0t.mjs → projectBucket-Cd7sEDhG.mjs} +2 -2
- package/dist/{projectBucket-BPzx0b0t.mjs.map → projectBucket-Cd7sEDhG.mjs.map} +1 -1
- package/dist/{projectBucket-CoskwJC5.cjs → projectBucket-gIQUuhGm.cjs} +2 -2
- package/dist/{projectBucket-CoskwJC5.cjs.map → projectBucket-gIQUuhGm.cjs.map} +1 -1
- package/dist/{publish-DB3-zkpm.cjs → publish-BgDFx08y.cjs} +2 -2
- package/dist/{publish-DB3-zkpm.cjs.map → publish-BgDFx08y.cjs.map} +1 -1
- package/dist/{publish-LZ1eb-MI.mjs → publish-DOxz4mxf.mjs} +2 -2
- package/dist/{publish-LZ1eb-MI.mjs.map → publish-DOxz4mxf.mjs.map} +1 -1
- package/dist/{resolve-B5_tOTJG.cjs → resolve-BhQd4IkT.cjs} +4 -4
- package/dist/{resolve-B5_tOTJG.cjs.map → resolve-BhQd4IkT.cjs.map} +1 -1
- package/dist/{resolve-jez3Y1S0.mjs → resolve-CdDyPOE8.mjs} +4 -4
- package/dist/{resolve-jez3Y1S0.mjs.map → resolve-CdDyPOE8.mjs.map} +1 -1
- package/dist/{rollback-BNo1bCLO.cjs → rollback-Brc-_HBJ.cjs} +6 -6
- package/dist/{rollback-BNo1bCLO.cjs.map → rollback-Brc-_HBJ.cjs.map} +1 -1
- package/dist/{rollback-BtOfxwo-.mjs → rollback-CLBKeSMl.mjs} +6 -6
- package/dist/{rollback-BtOfxwo-.mjs.map → rollback-CLBKeSMl.mjs.map} +1 -1
- package/dist/{s3-BlPwyu1L.cjs → s3-CuLmr6Q9.cjs} +3 -3
- package/dist/{s3-BlPwyu1L.cjs.map → s3-CuLmr6Q9.cjs.map} +1 -1
- package/dist/{s3-Bf_75vVl.mjs → s3-D0BIG_ml.mjs} +3 -3
- package/dist/{s3-Bf_75vVl.mjs.map → s3-D0BIG_ml.mjs.map} +1 -1
- package/dist/{serverSetup-D0Zor2i4.mjs → serverSetup-An1fE9nd.mjs} +6 -6
- package/dist/{serverSetup-D0Zor2i4.mjs.map → serverSetup-An1fE9nd.mjs.map} +1 -1
- package/dist/{serverSetup-D30vVD6t.cjs → serverSetup-BMpzrB1y.cjs} +6 -6
- package/dist/{serverSetup-D30vVD6t.cjs.map → serverSetup-BMpzrB1y.cjs.map} +1 -1
- package/dist/{sniffer-Bw00z3I8.cjs → sniffer-9a8wQeeD.cjs} +7 -7
- package/dist/{sniffer-Bw00z3I8.cjs.map → sniffer-9a8wQeeD.cjs.map} +1 -1
- package/dist/{sniffer-DdPDiNmc.mjs → sniffer-BObBXR5q.mjs} +7 -7
- package/dist/{sniffer-DdPDiNmc.mjs.map → sniffer-BObBXR5q.mjs.map} +1 -1
- package/dist/{snsSubscriptions-g7apv_fy.cjs → snsSubscriptions-BRmEdsks.cjs} +3 -3
- package/dist/{snsSubscriptions-g7apv_fy.cjs.map → snsSubscriptions-BRmEdsks.cjs.map} +1 -1
- package/dist/{snsSubscriptions-DBxVTR6Y.mjs → snsSubscriptions-oUTOkG-s.mjs} +3 -3
- package/dist/{snsSubscriptions-DBxVTR6Y.mjs.map → snsSubscriptions-oUTOkG-s.mjs.map} +1 -1
- package/dist/{sst-CEs0bMxj.cjs → sst-CJQI9GYW.cjs} +5 -5
- package/dist/{sst-CEs0bMxj.cjs.map → sst-CJQI9GYW.cjs.map} +1 -1
- package/dist/{sst-DJ22YDEq.mjs → sst-DVIeKWCH.mjs} +5 -5
- package/dist/{sst-DJ22YDEq.mjs.map → sst-DVIeKWCH.mjs.map} +1 -1
- package/dist/{stack-BmG-lKgD.cjs → stack-2jMvQfLo.cjs} +7 -7
- package/dist/{stack-BmG-lKgD.cjs.map → stack-2jMvQfLo.cjs.map} +1 -1
- package/dist/{stack-Ds9jjpE1.mjs → stack-kcxH-2tZ.mjs} +7 -7
- package/dist/{stack-Ds9jjpE1.mjs.map → stack-kcxH-2tZ.mjs.map} +1 -1
- package/dist/{stage-kGc9L3yB.cjs → stage-AHgVG7H8.cjs} +6 -6
- package/dist/{stage-kGc9L3yB.cjs.map → stage-AHgVG7H8.cjs.map} +1 -1
- package/dist/{stage-D9dfV1Ey.mjs → stage-BQSSMJL4.mjs} +6 -6
- package/dist/{stage-D9dfV1Ey.mjs.map → stage-BQSSMJL4.mjs.map} +1 -1
- package/dist/{stages-BL22BLJS.mjs → stages-BsK1Ro4s.mjs} +2 -2
- package/dist/{stages-BL22BLJS.mjs.map → stages-BsK1Ro4s.mjs.map} +1 -1
- package/dist/{stages-CN53nNOK.cjs → stages-DpF2K3PZ.cjs} +2 -2
- package/dist/{stages-CN53nNOK.cjs.map → stages-DpF2K3PZ.cjs.map} +1 -1
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.mjs +1 -1
- package/dist/{terminal-DVlIWcUb.cjs → terminal-BNjNr7BN.cjs} +2 -2
- package/dist/{terminal-DVlIWcUb.cjs.map → terminal-BNjNr7BN.cjs.map} +1 -1
- package/dist/{terminal-C0A7S7fB.mjs → terminal-DWROY7JE.mjs} +2 -2
- package/dist/{terminal-C0A7S7fB.mjs.map → terminal-DWROY7JE.mjs.map} +1 -1
- package/dist/workspace/index.cjs +1 -1
- package/dist/workspace/index.mjs +1 -1
- package/dist/{workspace-D4hzz6Xb.mjs → workspace-9q4TSHlM.mjs} +7 -8
- package/dist/workspace-9q4TSHlM.mjs.map +1 -0
- package/dist/{workspace-DPSdiv-b.cjs → workspace-Ciw3SnME.cjs} +6 -7
- package/dist/workspace-Ciw3SnME.cjs.map +1 -0
- package/package.json +25 -15
- package/dist/apps-CJTOIaz3.mjs.map +0 -1
- package/dist/apps-DkMR-qvD.cjs.map +0 -1
- package/dist/compose-SmuCWWUh.cjs.map +0 -1
- package/dist/compose-tX6YTa1U.mjs.map +0 -1
- package/dist/deploy--ia-CGMv.cjs.map +0 -1
- package/dist/deploy-BWFFSN5p.mjs.map +0 -1
- package/dist/docker-BtUjo-J_.cjs.map +0 -1
- package/dist/engine-BzeCK6e8.mjs.map +0 -1
- package/dist/engine-xrlcbr1g.cjs.map +0 -1
- package/dist/notes-DJyFkK13.cjs.map +0 -1
- package/dist/notes-TDHMzdVt.mjs.map +0 -1
- package/dist/workspace-D4hzz6Xb.mjs.map +0 -1
- package/dist/workspace-DPSdiv-b.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"destroy-CrxF8Dlk.cjs","names":["GkmError","defaultCdnClients","defaultClients","cdnName","awsEndpoint","awsClientConfig","GkmError","composeServer","secretsStoreFor","stackOverrideFile","join","stackDir","composeProject","deployIdentity","existsSync","dockerHost","resolve","loadWorkspaceConfig","canPrompt","createStateStore","prompt","dockerCompose","sshTarget","EDGE_PROJECT","removeEdgeRoutes","edgeRef","awsProvisioningCredentials","dnsResources","dnsRecordFqdn","normalizeDnsConfig","dnsCredentials","storedCredentials","pruneStackDns","findRootDomain","extractSubdomain","recordTtl"],"sources":["../src/providers/s3/destroy.ts","../src/compose/destroy.ts"],"sourcesContent":["/**\n * What `gkm compose --destroy` deletes in the stage's AWS account: each\n * resource a deploy recorded in the stage's state, and only once it is\n * proven gkm's own for this stage.\n *\n * A record alone proves nothing — a deploy records what it found and adopted\n * exactly as what it made (a certificate for the host, a bucket with no\n * tags). So each is checked against what gkm marks its own with: the\n * `gkm:project` and `gkm:stage` tags on a bucket, a user, a certificate, a\n * distribution, a topic or a queue; the stage's own name on an origin access\n * control and a headers policy, which take no tags. What fails the check is\n * left where it is, and said so.\n *\n * Nothing here runs on its own: `planAwsDestroy` reads, and returns a step\n * per resource whose `remove()` the command calls — after the person typed\n * the stage's name — in the order AWS needs: a distribution disabled and\n * gone before its certificate, a user's keys and policies before the user,\n * a bucket emptied before it is deleted.\n */\n\nimport type { ResourceRecord } from '../../deploy/StateStore.js';\nimport { GkmError } from '../../errors.js';\nimport { type AwsProvisioning, awsClientConfig, awsEndpoint } from '../aws.js';\nimport { TAG_PROJECT, TAG_STAGE } from '../iam.js';\nimport { type CdnClients, cdnName, defaultCdnClients } from './cdn.js';\nimport { defaultClients } from './index.js';\nimport { IAM_USER_PATH } from './naming.js';\n\n/** What a destroy step is about, as the person reads it. */\nexport interface AwsDestroyStep {\n\t/** The state record it is kept as: forgotten once it is gone. */\n\tkey: string;\n\tlabel: string;\n\t/** Why it is not deleted. Absent for one that will be. */\n\tleftAlone?: string;\n\t/** Already gone from the account: only its record is forgotten. */\n\tgone?: boolean;\n\t/** Deleted along with its user's step: only its record is forgotten here. */\n\twithUser?: boolean;\n\t/** Deletes it. Absent when it is left alone or already gone. */\n\tremove?: () => Promise<void>;\n}\n\n/** A DNS record a resource here needs, worked out from the resource. */\nexport interface AwsDnsRecord {\n\thost: string;\n\ttype: 'CNAME';\n\tvalue: string;\n}\n\nexport interface AwsDestroyPlan {\n\t/** In the order they are removed. */\n\tsteps: AwsDestroyStep[];\n\t/**\n\t * The records the s3 provider wrote for what it deletes — a CDN's name, a\n\t * certificate's validation — which no state record names.\n\t */\n\tdns: AwsDnsRecord[];\n}\n\nexport interface AwsDestroyInput {\n\tresources: Record<string, ResourceRecord>;\n\t/** `deployIdentity(…).key` — what `gkm:project` holds. */\n\tidentityKey: string;\n\t/** `deployIdentity(…).scope` — what CDN resource names start with. */\n\tscope: string;\n\tstage: string;\n\tcredential: AwsProvisioning;\n\t/** How long a disabled distribution is waited on, and how often asked. */\n\twait?: { timeoutMs: number; intervalMs: number };\n\t/** For tests: where the clients come from. */\n\tclients?: {\n\t\ts3?: typeof defaultClients;\n\t\tcdn?: (credential: AwsProvisioning) => Promise<CdnClients>;\n\t};\n}\n\n/** The record types this plans. Every other is the command's to report. */\nexport const AWS_RESOURCE_TYPES = [\n\t'cloudfront-distribution',\n\t'cloudfront-oac',\n\t'cloudfront-headers',\n\t'acm-certificate',\n\t'sns-subscription',\n\t'sns-topic',\n\t'sqs-queue',\n\t'iam-access-key',\n\t'iam-user',\n\t's3-bucket',\n] as const;\n\n/** A distribution disabled before it is deleted can take this long. */\nconst DISABLE_WAIT = { timeoutMs: 45 * 60_000, intervalMs: 20_000 };\n\n/** A disabled distribution that never finished deploying. */\nexport class DistributionStillDeploying extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly waitedMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`CloudFront distribution ${id} was disabled, and is still deploying after ` +\n\t\t\t\t`${Math.round(waitedMs / 60_000)} minutes. CloudFront deletes only a ` +\n\t\t\t\t'disabled distribution that has finished deploying. Run the destroy ' +\n\t\t\t\t'again later: everything deleted so far is forgotten, and it carries ' +\n\t\t\t\t'on from here.',\n\t\t);\n\t\tthis.name = 'DistributionStillDeploying';\n\t}\n}\n\n/** What an AWS SDK error is called, whichever field carries it. */\nfunction errorName(error: unknown): string {\n\tconst e = error as { name?: string; Code?: string };\n\treturn e?.Code ?? e?.name ?? '';\n}\n\n/** A read whose \"there is none\" answer is one of `missing`. */\nasync function readOr<T>(\n\tread: () => Promise<T>,\n\tmissing: readonly string[],\n): Promise<T | undefined> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (missing.includes(errorName(error))) return undefined;\n\t\tthrow error;\n\t}\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Whether a tag list says gkm made it for this project's stage. */\nfunction ours(\n\ttags: readonly { Key?: string; Value?: string }[] | undefined,\n\tinput: Pick<AwsDestroyInput, 'identityKey' | 'stage'>,\n): boolean {\n\tconst of = (key: string) => tags?.find((t) => t.Key === key)?.Value;\n\treturn of(TAG_PROJECT) === input.identityKey && of(TAG_STAGE) === input.stage;\n}\n\nconst NOT_TAGGED =\n\t\"not tagged as this stage's (gkm:project, gkm:stage): gkm found it, it did not make it\";\n\n/** The id after the type in a record's key: `cloudfront-oac:Uploads` → `Uploads`. */\nfunction keyId(record: ResourceRecord): string {\n\treturn record.key.slice(record.key.indexOf(':') + 1);\n}\n\n/** The file server a CDN record is for: `cloudfront-headers:Uploads:cors` → `Uploads`. */\nfunction serverOf(record: ResourceRecord): string {\n\treturn keyId(record).split(':')[0] ?? '';\n}\n\n/**\n * Each AWS resource the stage's state records, checked, in the order it is\n * deleted — and the DNS records the deleted ones were given.\n */\nexport async function planAwsDestroy(\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyPlan> {\n\tconst steps: AwsDestroyStep[] = [];\n\tconst dns: AwsDnsRecord[] = [];\n\tconst records = Object.values(input.resources);\n\tconst of = (type: string) => records.filter((r) => r.type === type);\n\tconst wait = input.wait ?? DISABLE_WAIT;\n\n\tconst cdnRecords = [\n\t\t...of('cloudfront-distribution'),\n\t\t...of('cloudfront-oac'),\n\t\t...of('cloudfront-headers'),\n\t\t...of('acm-certificate'),\n\t];\n\tif (cdnRecords.length > 0) {\n\t\tconst cdn = await (input.clients?.cdn ?? defaultCdnClients)(\n\t\t\tinput.credential,\n\t\t);\n\t\t// A distribution left alone keeps what it uses: deleting its origin\n\t\t// access control, a headers policy or its certificate would break it.\n\t\tconst kept = new Map<string, string>();\n\t\tfor (const record of of('cloudfront-distribution')) {\n\t\t\tconst step = await distributionStep(cdn, record, input, wait, dns);\n\t\t\tif (step.leftAlone) kept.set(serverOf(record), step.label);\n\t\t\tsteps.push(step);\n\t\t}\n\t\tconst usedBy = async (\n\t\t\trecord: ResourceRecord,\n\t\t\tstep: () => Promise<AwsDestroyStep>,\n\t\t): Promise<AwsDestroyStep> => {\n\t\t\tconst holder = kept.get(serverOf(record));\n\t\t\tif (!holder) return step();\n\t\t\tconst label = (await step()).label;\n\t\t\treturn {\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel,\n\t\t\t\tleftAlone: `used by ${holder}, which is left alone`,\n\t\t\t};\n\t\t};\n\t\tfor (const record of of('cloudfront-oac')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => originAccessControlStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('cloudfront-headers')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => headersPolicyStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('acm-certificate')) {\n\t\t\t// Its validation record goes only with the certificate itself.\n\t\t\tconst found: AwsDnsRecord[] = [];\n\t\t\tconst step = await usedBy(record, () =>\n\t\t\t\tcertificateStep(cdn, record, input, found),\n\t\t\t);\n\t\t\tif (!step.leftAlone) dns.push(...found);\n\t\t\tsteps.push(step);\n\t\t}\n\t}\n\n\tconst eventRecords = [\n\t\t...of('sns-subscription'),\n\t\t...of('sns-topic'),\n\t\t...of('sqs-queue'),\n\t];\n\tif (eventRecords.length > 0) {\n\t\tconst events = await eventClients(input.credential, records);\n\t\tfor (const record of of('sns-subscription')) {\n\t\t\tsteps.push(subscriptionStep(events, record));\n\t\t}\n\t\tfor (const record of of('sns-topic')) {\n\t\t\tsteps.push(await topicStep(events, record, input));\n\t\t}\n\t\tfor (const record of of('sqs-queue')) {\n\t\t\tsteps.push(await queueStep(events, record, input));\n\t\t}\n\t}\n\n\tconst users = of('iam-user');\n\tconst keys = of('iam-access-key');\n\tconst buckets = of('s3-bucket');\n\tif (users.length + keys.length + buckets.length > 0) {\n\t\tconst global = await (input.clients?.s3 ?? defaultClients)(\n\t\t\tinput.credential,\n\t\t\tregionOf(buckets[0]) ?? 'us-east-1',\n\t\t);\n\t\tconst userSteps = new Map<string, AwsDestroyStep>();\n\t\tfor (const record of users) {\n\t\t\tconst step = await userStep(global, record, input);\n\t\t\tuserSteps.set(record.id ?? '', step);\n\t\t\tsteps.push(step);\n\t\t}\n\t\t// A key goes with its user, and is checked through it.\n\t\tfor (const record of keys) {\n\t\t\tconst user = (record.data as { user?: string } | undefined)?.user;\n\t\t\tconst owner = user ? userSteps.get(user) : undefined;\n\t\t\tsteps.push({\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel: `IAM access key ${record.id ?? ''} of ${user ?? 'an unknown user'}`,\n\t\t\t\t...(owner?.leftAlone\n\t\t\t\t\t? { leftAlone: `its user is left alone: ${owner.leftAlone}` }\n\t\t\t\t\t: owner\n\t\t\t\t\t\t? { withUser: true }\n\t\t\t\t\t\t: { leftAlone: 'its user is not one this stage recorded' }),\n\t\t\t});\n\t\t}\n\t\tfor (const record of buckets) {\n\t\t\tconst region = regionOf(record) ?? global.region;\n\t\t\tconst clients =\n\t\t\t\tregion === global.region\n\t\t\t\t\t? global\n\t\t\t\t\t: await (input.clients?.s3 ?? defaultClients)(\n\t\t\t\t\t\t\tinput.credential,\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t);\n\t\t\tsteps.push(await bucketStep(clients, record, input));\n\t\t}\n\t}\n\n\treturn { steps, dns };\n}\n\nfunction regionOf(record: ResourceRecord | undefined): string | undefined {\n\treturn (record?.data as { region?: string } | undefined)?.region;\n}\n\n// ---------------------------------------------------------------------------\n// CloudFront and ACM\n// ---------------------------------------------------------------------------\n\nasync function distributionStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\twait: { timeoutMs: number; intervalMs: number },\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetDistributionCommand({ Id: id })),\n\t\t['NoSuchDistribution'],\n\t);\n\tconst distribution = found?.Distribution;\n\tconst aliases = distribution?.DistributionConfig?.Aliases?.Items ?? [];\n\tconst label = `CloudFront distribution ${id}${aliases.length ? ` (${aliases.join(', ')})` : ''}`;\n\tif (!distribution) return { key: record.key, label, gone: true };\n\n\t// Its tags, or the comment gkm writes on every distribution it makes —\n\t// `gkm <project> <stage> <file server>`, which nothing else writes.\n\tconst tags = await cloudfront.send(\n\t\tnew CF.ListTagsForResourceCommand({ Resource: distribution.ARN }),\n\t);\n\tconst comment = `gkm ${input.identityKey} ${input.stage} ${serverOf(record)}`;\n\tconst marked =\n\t\tdistribution.DistributionConfig?.Comment === comment.slice(0, 128);\n\tif (!ours(tags.Tags?.Items, input) && !marked) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `${NOT_TAGGED}, and its comment is not \"${comment}\"`,\n\t\t};\n\t}\n\tfor (const host of aliases) {\n\t\tdns.push({ host, type: 'CNAME', value: distribution.DomainName ?? '' });\n\t}\n\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tlet current = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tif (current.DistributionConfig?.Enabled) {\n\t\t\t\tawait cloudfront.send(\n\t\t\t\t\tnew CF.UpdateDistributionCommand({\n\t\t\t\t\t\tId: id,\n\t\t\t\t\t\tIfMatch: current.ETag,\n\t\t\t\t\t\tDistributionConfig: {\n\t\t\t\t\t\t\t...current.DistributionConfig,\n\t\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst started = Date.now();\n\t\t\tfor (;;) {\n\t\t\t\tconst state = await cloudfront.send(\n\t\t\t\t\tnew CF.GetDistributionCommand({ Id: id }),\n\t\t\t\t);\n\t\t\t\tif (state.Distribution?.Status === 'Deployed') break;\n\t\t\t\tif (Date.now() - started > wait.timeoutMs) {\n\t\t\t\t\tthrow new DistributionStillDeploying(id, Date.now() - started);\n\t\t\t\t}\n\t\t\t\tawait sleep(wait.intervalMs);\n\t\t\t}\n\t\t\tcurrent = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteDistributionCommand({ Id: id, IfMatch: current.ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function originAccessControlStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst expected = cdnName(input.scope, input.stage, keyId(record));\n\tconst label = `CloudFront origin access control ${expected}`;\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: id })),\n\t\t['NoSuchOriginAccessControl'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.OriginAccessControl?.OriginAccessControlConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetOriginAccessControlCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteOriginAccessControlCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function headersPolicyStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\t// `cloudfront-headers:<server>:<kind>`\n\tconst [server = '', kind = ''] = keyId(record).split(':');\n\tconst expected = `${cdnName(input.scope, input.stage, server)}-${kind}`;\n\tconst label = `CloudFront response headers policy ${expected}`;\n\tconst found = await readOr(\n\t\t() =>\n\t\t\tcloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id: id })),\n\t\t['NoSuchResponseHeadersPolicy'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.ResponseHeadersPolicyConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetResponseHeadersPolicyConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteResponseHeadersPolicyCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function certificateStep(\n\t{ ACM, acm }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst host = (record.data as { host?: string } | undefined)?.host ?? arn;\n\tconst label = `ACM certificate ${host} (us-east-1)`;\n\tconst found = await readOr(\n\t\t() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })),\n\t\t['ResourceNotFoundException'],\n\t);\n\tif (!found?.Certificate) return { key: record.key, label, gone: true };\n\tconst tags = await acm.send(\n\t\tnew ACM.ListTagsForCertificateCommand({ CertificateArn: arn }),\n\t);\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\tfor (const option of found.Certificate.DomainValidationOptions ?? []) {\n\t\tconst r = option.ResourceRecord;\n\t\tif (r?.Name && r.Value && r.Type === 'CNAME') {\n\t\t\tdns.push({ host: r.Name, type: 'CNAME', value: r.Value });\n\t\t}\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait acm.send(new ACM.DeleteCertificateCommand({ CertificateArn: arn }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// SNS and SQS\n// ---------------------------------------------------------------------------\n\ninterface EventClients {\n\tSNS: typeof import('@aws-sdk/client-sns');\n\tSQS: typeof import('@aws-sdk/client-sqs');\n\tsns: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sns')['SNSClient']>>;\n\tsqs: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sqs')['SQSClient']>>;\n}\n\nasync function eventClients(\n\tcredential: AwsProvisioning,\n\t_records: readonly ResourceRecord[],\n): Promise<EventClients> {\n\tconst SNS = await import('@aws-sdk/client-sns');\n\tconst SQS = await import('@aws-sdk/client-sqs');\n\tconst sns = new Map<string, InstanceType<typeof SNS.SNSClient>>();\n\tconst sqs = new Map<string, InstanceType<typeof SQS.SQSClient>>();\n\treturn {\n\t\tSNS,\n\t\tSQS,\n\t\tsns: async (region) => {\n\t\t\tif (!sns.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SNS');\n\t\t\t\tsns.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SNS.SNSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sns.get(region)!;\n\t\t},\n\t\tsqs: async (region) => {\n\t\t\tif (!sqs.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SQS');\n\t\t\t\tsqs.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SQS.SQSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sqs.get(region)!;\n\t\t},\n\t};\n}\n\n/** `arn:aws:sns:<region>:<account>:<name>` */\nfunction arnParts(arn: string) {\n\tconst [, , , region = '', account = '', ...rest] = arn.split(':');\n\treturn { region, account, name: rest.join(':') };\n}\n\nfunction subscriptionStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n): AwsDestroyStep {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS subscription ${keyId(record)}`;\n\t// Made by gkm, to its own push endpoint: a pending one has no ARN yet.\n\tif (!arn.startsWith('arn:')) return { key: record.key, label, gone: true };\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst client = await sns(arnParts(arn).region);\n\t\t\tawait readOr(\n\t\t\t\t() => client.send(new SNS.UnsubscribeCommand({ SubscriptionArn: arn })),\n\t\t\t\t['NotFound', 'NotFoundException'],\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function topicStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS topic ${arnParts(arn).name}`;\n\tconst client = await sns(arnParts(arn).region);\n\tconst tags = await readOr(\n\t\t() => client.send(new SNS.ListTagsForResourceCommand({ ResourceArn: arn })),\n\t\t[\n\t\t\t'NotFound',\n\t\t\t'NotFoundException',\n\t\t\t'ResourceNotFound',\n\t\t\t'ResourceNotFoundException',\n\t\t],\n\t);\n\tif (!tags) return { key: record.key, label, gone: true };\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SNS.DeleteTopicCommand({ TopicArn: arn }));\n\t\t},\n\t};\n}\n\nasync function queueStep(\n\t{ SQS, sqs }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst { region, account, name } = arnParts(arn);\n\tconst label = `SQS queue ${name}`;\n\tconst client = await sqs(region);\n\tconst url = await readOr(\n\t\t() =>\n\t\t\tclient.send(\n\t\t\t\tnew SQS.GetQueueUrlCommand({\n\t\t\t\t\tQueueName: name,\n\t\t\t\t\tQueueOwnerAWSAccountId: account,\n\t\t\t\t}),\n\t\t\t),\n\t\t['QueueDoesNotExist', 'AWS.SimpleQueueService.NonExistentQueue'],\n\t);\n\tif (!url?.QueueUrl) return { key: record.key, label, gone: true };\n\tconst queueUrl = url.QueueUrl;\n\tconst tags = await client.send(\n\t\tnew SQS.ListQueueTagsCommand({ QueueUrl: queueUrl }),\n\t);\n\tconst list = Object.entries(tags.Tags ?? {}).map(([Key, Value]) => ({\n\t\tKey,\n\t\tValue,\n\t}));\n\tif (!ours(list, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SQS.DeleteQueueCommand({ QueueUrl: queueUrl }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// IAM and S3\n// ---------------------------------------------------------------------------\n\ntype S3Clients = Awaited<ReturnType<typeof defaultClients>>;\n\nasync function userStep(\n\t{ IAM, iam }: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst name = record.id ?? '';\n\tconst label = `IAM user ${name}, its access keys and policies`;\n\tconst found = await readOr(\n\t\t() => iam.send(new IAM.GetUserCommand({ UserName: name })),\n\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t);\n\tif (!found?.User) return { key: record.key, label, gone: true };\n\tconst tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: name }));\n\tif (found.User.Path !== IAM_USER_PATH || !ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst keys = await iam.send(\n\t\t\t\tnew IAM.ListAccessKeysCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const key of keys.AccessKeyMetadata ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tAccessKeyId: key.AccessKeyId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst inline = await iam.send(\n\t\t\t\tnew IAM.ListUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of inline.PolicyNames ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyName: policy,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attached = await iam.send(\n\t\t\t\tnew IAM.ListAttachedUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of attached.AttachedPolicies ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DetachUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyArn: policy.PolicyArn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait iam.send(new IAM.DeleteUserCommand({ UserName: name }));\n\t\t},\n\t};\n}\n\n/** Every object version and delete marker in a bucket, a page at a time. */\nasync function* bucketVersions({ S3, s3 }: S3Clients, bucket: string) {\n\tlet KeyMarker: string | undefined;\n\tlet VersionIdMarker: string | undefined;\n\tfor (;;) {\n\t\tconst page = await s3.send(\n\t\t\tnew S3.ListObjectVersionsCommand({\n\t\t\t\tBucket: bucket,\n\t\t\t\t...(KeyMarker ? { KeyMarker } : {}),\n\t\t\t\t...(VersionIdMarker ? { VersionIdMarker } : {}),\n\t\t\t}),\n\t\t);\n\t\tconst objects = [...(page.Versions ?? []), ...(page.DeleteMarkers ?? [])]\n\t\t\t.filter((o) => o.Key)\n\t\t\t.map((o) => ({\n\t\t\t\tKey: o.Key!,\n\t\t\t\t// `null` is the one version an unversioned bucket's object has:\n\t\t\t\t// named or not, the same object is deleted.\n\t\t\t\t...(o.VersionId && o.VersionId !== 'null'\n\t\t\t\t\t? { VersionId: o.VersionId }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\tif (objects.length > 0) yield objects;\n\t\tif (!page.IsTruncated) return;\n\t\tKeyMarker = page.NextKeyMarker;\n\t\tVersionIdMarker = page.NextVersionIdMarker;\n\t}\n}\n\nasync function bucketStep(\n\tclients: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst { S3, s3 } = clients;\n\tconst bucket = record.id ?? '';\n\tconst tagging = await readOr(\n\t\t() => s3.send(new S3.GetBucketTaggingCommand({ Bucket: bucket })),\n\t\t['NoSuchBucket', 'NoSuchTagSet', 'NoSuchTagSetError'],\n\t);\n\tconst exists = await readOr(\n\t\t() => s3.send(new S3.HeadBucketCommand({ Bucket: bucket })),\n\t\t['NotFound', 'NoSuchBucket'],\n\t);\n\tconst base = `S3 bucket ${bucket}`;\n\tif (!exists) return { key: record.key, label: base, gone: true };\n\tif (!ours(tagging?.TagSet, input)) {\n\t\treturn { key: record.key, label: base, leftAlone: NOT_TAGGED };\n\t}\n\tlet count = 0;\n\tfor await (const page of bucketVersions(clients, bucket))\n\t\tcount += page.length;\n\treturn {\n\t\tkey: record.key,\n\t\tlabel: `${base}, emptied first: ${count} object version${count === 1 ? '' : 's'}`,\n\t\tremove: async () => {\n\t\t\t// Until it lists nothing: deleting a version-less object in a bucket\n\t\t\t// whose versioning was suspended leaves a delete marker behind.\n\t\t\tfor (let pass = 0; pass < 5; pass++) {\n\t\t\t\tlet deleted = 0;\n\t\t\t\tfor await (const page of bucketVersions(clients, bucket)) {\n\t\t\t\t\t// At most a thousand a call.\n\t\t\t\t\tfor (let i = 0; i < page.length; i += 1000) {\n\t\t\t\t\t\tawait s3.send(\n\t\t\t\t\t\t\tnew S3.DeleteObjectsCommand({\n\t\t\t\t\t\t\t\tBucket: bucket,\n\t\t\t\t\t\t\t\tDelete: { Objects: page.slice(i, i + 1000), Quiet: true },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tdeleted += page.length;\n\t\t\t\t}\n\t\t\t\tif (deleted === 0) break;\n\t\t\t}\n\t\t\tawait s3.send(new S3.DeleteBucketCommand({ Bucket: bucket }));\n\t\t},\n\t};\n}\n","/**\n * `gkm compose --stage <stage> --destroy`: everything a deploy made for the\n * stage, deleted for good.\n *\n * The one thing in gkm that deletes what a deploy created — a deploy itself\n * never does. So it is careful in three ways:\n *\n * - **Only what is provably gkm's.** Each AWS resource is checked against\n * what gkm marks its own with before it is deleted (see\n * `providers/s3/destroy.ts`); a DNS record only while it still holds the\n * value gkm wrote. What fails is listed, and left where it is.\n * - **Only with a person typing the stage.** The whole plan is printed\n * first, then the compose project's name — `<project>-<stage>` — has to be\n * typed back. Nothing skips that: there is no flag that answers it, and\n * with no terminal to ask at it refuses before reading anything.\n * - **Resumable.** Each resource's record is forgotten as soon as it is gone,\n * so a run that stops part way — a distribution still deploying — carries\n * on from there when it is run again.\n *\n * What other stages or projects share is never touched: the project bucket\n * that holds every stage's state, the shared Traefik edge, the server's own\n * setup (`gkm compose:server`). The stage's secrets are kept unless\n * `--secrets` is passed.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport {\n\ttype CredentialProvider,\n\tstoredCredentials,\n} from '../deploy/credentials.js';\nimport { dnsRecordFqdn, dnsResources } from '../deploy/dnsResources.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { createStateStore, type StateStore } from '../deploy/StateStore.js';\nimport { GkmError } from '../errors';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype AwsProvisioning,\n\tawsProvisioningCredentials,\n} from '../providers/aws.js';\nimport {\n\tAWS_RESOURCE_TYPES,\n\ttype AwsDestroyInput,\n\ttype AwsDestroyStep,\n\tplanAwsDestroy,\n} from '../providers/s3/destroy.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { stackOverrideFile } from '../target/compose/index';\nimport type { DnsProvider } from '../target/dokploy/dns/DnsProvider.js';\nimport {\n\textractSubdomain,\n\tfindRootDomain,\n\tnormalizeDnsConfig,\n} from '../target/dokploy/dns/index.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type {\n\tDnsProvider as DnsProviderConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\tdnsCredentials,\n\tpruneStackDns,\n\ttype RecordedDnsRecord,\n\trecordTtl,\n} from './dns';\nimport { type ComposeDocker, dockerCompose, type StackRef } from './docker';\nimport { edgeRef, removeEdgeRoutes } from './edge';\nimport { composeServer, dockerHost, sshTarget } from './server';\nimport { composeProject, stackDir } from './stack';\nimport { EDGE_PROJECT } from './traefik';\n\nexport interface ComposeDestroyOptions {\n\tcwd?: string;\n\tstage: string;\n\t/** Delete the stage's secrets too. Kept otherwise. */\n\tsecrets?: boolean;\n\t/** Print what would be deleted; delete nothing, ask nothing. */\n\tdryRun?: boolean;\n}\n\nexport interface ComposeDestroyDeps {\n\tdocker?: ComposeDocker;\n\t/** Whether a person is at a terminal to answer. */\n\tinteractive?: () => boolean;\n\t/** Ask the person, and resolve with what they typed. */\n\task?: (question: string) => Promise<string>;\n\t/** Where the DNS providers' tokens come from. */\n\tcredentials?: CredentialProvider;\n\t/** The provider for a domain — `createDnsProvider` by default. */\n\tdnsProviderFor?: (config: DnsProviderConfig) => Promise<DnsProvider | null>;\n\t/**\n\t * How the AWS account's credential is found — the machine's, as a deploy\n\t * finds it, by default.\n\t */\n\tawsCredentials?: () => Promise<AwsProvisioning | undefined>;\n\t/** For tests: the AWS clients and how long a distribution is waited on. */\n\taws?: Pick<AwsDestroyInput, 'clients' | 'wait'>;\n\tstate?: StateStore;\n\tenv?: NodeJS.ProcessEnv;\n\thome?: string;\n\tlog?: (line: string) => void;\n}\n\n/** A destroy with no terminal to type the stage's name at. */\nexport class ComposeDestroyNeedsTerminal extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Destroying '${stage}' deletes everything its deploys made, and asks you to ` +\n\t\t\t\t`type ${project} first — there is no terminal here to ask at, and no flag ` +\n\t\t\t\t'answers it. Run it yourself, from a terminal. `--dry-run` prints what it ' +\n\t\t\t\t'would delete, anywhere.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsTerminal';\n\t}\n}\n\n/** What was typed was not the project's name. */\nexport class ComposeDestroyNotConfirmed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Nothing was deleted: destroying '${stage}' needs ${project} typed exactly.`,\n\t\t);\n\t\tthis.name = 'ComposeDestroyNotConfirmed';\n\t}\n}\n\n/** AWS resources to delete, and no credentials to delete them with. */\nexport class ComposeDestroyNeedsAwsCredentials extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly resources: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has ${resources.length} AWS resource${resources.length === 1 ? '' : 's'} ` +\n\t\t\t\t`to delete (${resources.slice(0, 3).join(', ')}${resources.length > 3 ? ', …' : ''}), ` +\n\t\t\t\t\"and no AWS credentials were found to delete them with. Supply the stage's \" +\n\t\t\t\t'account the way a deploy does — AWS_PROFILE, or AWS_ACCESS_KEY_ID and ' +\n\t\t\t\t'AWS_SECRET_ACCESS_KEY — and run it again. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsAwsCredentials';\n\t}\n}\n\n/** `--secrets`, and a store that cannot delete. */\nexport class SecretsStoreCannotDelete extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`--secrets deletes '${stage}''s secrets, and its store (${store}) has no ` +\n\t\t\t\t'delete(stage). Give the custom store one, or run without --secrets and ' +\n\t\t\t\t'delete them where they are kept. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'SecretsStoreCannotDelete';\n\t}\n}\n\n/** One line of the plan, and how it is carried out. */\ninterface Step {\n\tlabel: string;\n\tleftAlone?: string;\n\t/** Forgotten from the stage's state once done. */\n\tkeys?: string[];\n\trun?: () => Promise<void>;\n}\n\n/** What a record of each type is to destroy. */\nconst KEPT_TYPES: Record<string, string> = {\n\t// The server's setup — its users, firewall, Docker — is the server's.\n\tserver:\n\t\t\"the server's setup is kept: gkm compose:server made it, for any stage\",\n};\n\n/** Records that name no resource of their own — a key in the secrets. */\nconst VALUE_TYPES = new Set(['url', 'email-from']);\n\n/**\n * The stage's stack: its project on the server (or this machine), as\n * `gkm compose --down` finds it.\n */\nexport async function composeStackRef(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): Promise<{\n\tref: StackRef;\n\tdir: string;\n\tserver?: ReturnType<typeof composeServer>;\n}> {\n\tconst local = stage === workspace.stages.local;\n\tconst server = local\n\t\t? undefined\n\t\t: composeServer({\n\t\t\t\tstage,\n\t\t\t\tlocal,\n\t\t\t\tconfig: workspace.deploy?.compose?.server,\n\t\t\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t\t\t?.custom,\n\t\t\t});\n\tconst override = stackOverrideFile(workspace.root, stage);\n\tconst dir = join(workspace.root, stackDir(stage));\n\tconst ref: StackRef = {\n\t\tproject: composeProject(deployIdentity(workspace, stage)),\n\t\tfile: join(dir, 'docker-compose.yml'),\n\t\t...(existsSync(override) ? { overrides: [override] } : {}),\n\t\tcwd: workspace.root,\n\t\t...(server ? { host: dockerHost(server) } : {}),\n\t};\n\treturn { ref, dir, ...(server ? { server } : {}) };\n}\n\n/** `gkm compose --stage <stage> --destroy`. */\nexport async function composeDestroyCommand(\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps = {},\n): Promise<void> {\n\tconst log = deps.log ?? ((line: string) => console.log(line));\n\tconst env = deps.env ?? process.env;\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst { stage } = options;\n\tconst local = stage === workspace.stages.local;\n\tif (!local) assertDeployedStage(workspace.stages, stage);\n\n\tconst identity = deployIdentity(workspace, stage);\n\tconst project = composeProject(identity);\n\tconst interactive = deps.interactive ?? canPrompt;\n\tif (!options.dryRun && !interactive()) {\n\t\tthrow new ComposeDestroyNeedsTerminal(stage, project);\n\t}\n\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: local ? undefined : workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\t// Held throughout: a deploy of the stage while it is torn down would\n\t// make what this is deleting.\n\tconst lock = options.dryRun\n\t\t? undefined\n\t\t: await state.lock(stage, { operation: 'destroy' });\n\ttry {\n\t\tconst steps = await plan(workspace, stage, options, deps, state, env);\n\t\tconst { ref } = await composeStackRef(workspace, stage);\n\n\t\tlog(\n\t\t\t`\\n🧨 ${options.dryRun ? 'Would delete' : 'This deletes'} stage '${stage}' of ${workspace.name} for good:\\n`,\n\t\t);\n\t\tconst doing = steps.filter((s) => !s.leftAlone);\n\t\tconst kept = steps.filter((s) => s.leftAlone);\n\t\tfor (const step of doing) log(` - ${step.label}`);\n\t\tif (kept.length > 0) {\n\t\t\tlog('\\n Left where it is:');\n\t\t\tfor (const step of kept) log(` · ${step.label} — ${step.leftAlone}`);\n\t\t}\n\t\tif (!options.secrets) {\n\t\t\tlog(\n\t\t\t\t\"\\n The stage's secrets are kept: a deploy of it again reuses them. --secrets deletes them too.\",\n\t\t\t);\n\t\t}\n\n\t\tif (options.dryRun) {\n\t\t\tlog('\\n--dry-run: nothing was deleted.');\n\t\t\treturn;\n\t\t}\n\n\t\tconst ask =\n\t\t\tdeps.ask ??\n\t\t\t((question: string) =>\n\t\t\t\tprompt(question, {\n\t\t\t\t\tinstead: 'Run it yourself, from a terminal.',\n\t\t\t\t}));\n\t\tconst typed = await ask(`\\n Type ${project} to destroy it: `);\n\t\tif (typed.trim() !== project) {\n\t\t\tthrow new ComposeDestroyNotConfirmed(stage, project);\n\t\t}\n\n\t\tlog('');\n\t\tfor (const step of doing) {\n\t\t\tawait step.run?.();\n\t\t\tfor (const key of step.keys ?? []) {\n\t\t\t\tawait state.deleteResource(stage, key);\n\t\t\t}\n\t\t\tlog(` ✓ ${step.label}`);\n\t\t}\n\t\tlog(`\\n💥 '${stage}' destroyed. ${ref.project} is gone.`);\n\t} finally {\n\t\tawait lock?.release();\n\t}\n}\n\n/** Every step, in the order it is carried out. */\nasync function plan(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps,\n\tstate: StateStore,\n\tenv: NodeJS.ProcessEnv,\n): Promise<Step[]> {\n\tconst steps: Step[] = [];\n\tconst resources = (await state.read(stage))?.resources ?? {};\n\tconst records = Object.values(resources);\n\n\t// ── The stack: containers, volumes, its routes on the edge ─────────────\n\tconst { ref, dir, server } = await composeStackRef(workspace, stage);\n\tconst docker = deps.docker ?? dockerCompose;\n\tsteps.push({\n\t\tlabel: `${server ? `on ${sshTarget(server)}: ` : ''}stack ${ref.project} — its containers, its volumes and their data, its routes on ${EDGE_PROJECT}`,\n\t\trun: async () => {\n\t\t\tconst edgeFile = join(dir, `${EDGE_PROJECT}.yml`);\n\t\t\tif (server || existsSync(edgeFile)) {\n\t\t\t\tawait removeEdgeRoutes(\n\t\t\t\t\tdocker,\n\t\t\t\t\tedgeRef(edgeFile, { host: ref.host }),\n\t\t\t\t\tref.project,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait docker.down(ref, { volumes: true });\n\t\t},\n\t});\n\n\t// ── AWS ─────────────────────────────────────────────────────────────────\n\tconst aws = records.filter((r) =>\n\t\t(AWS_RESOURCE_TYPES as readonly string[]).includes(r.type),\n\t);\n\tlet cdnDns: RecordedDnsRecord[] = [];\n\tif (aws.length > 0) {\n\t\tconst credential = await (\n\t\t\tdeps.awsCredentials ??\n\t\t\t(() =>\n\t\t\t\tawsProvisioningCredentials({\n\t\t\t\t\tstage,\n\t\t\t\t\tenv,\n\t\t\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t\t\t}))\n\t\t)();\n\t\tif (!credential) {\n\t\t\tthrow new ComposeDestroyNeedsAwsCredentials(\n\t\t\t\tstage,\n\t\t\t\taws.map((r) => r.key),\n\t\t\t);\n\t\t}\n\t\tconst identity = deployIdentity(workspace, stage);\n\t\tconst planned = await planAwsDestroy({\n\t\t\tresources,\n\t\t\tidentityKey: identity.key,\n\t\t\tscope: identity.scope,\n\t\t\tstage,\n\t\t\tcredential,\n\t\t\t...(deps.aws ?? {}),\n\t\t});\n\t\tfor (const step of planned.steps) steps.push(awsStep(step));\n\t\tcdnDns = providerDnsRecords(workspace, planned.dns);\n\t}\n\n\t// ── DNS: what the stage recorded, and what its CDN was given ───────────\n\tconst recorded = dnsResources(resources).map((r) => ({\n\t\t...r,\n\t\tfqdn: r.fqdn || dnsRecordFqdn(r.domain, r.name),\n\t}));\n\tconst seen = new Set(recorded.map((r) => `${r.fqdn} ${r.type}`));\n\tconst dnsRecords: RecordedDnsRecord[] = [\n\t\t...recorded,\n\t\t...cdnDns.filter((r) => !seen.has(`${r.fqdn} ${r.type}`)),\n\t];\n\tif (dnsRecords.length > 0) {\n\t\t// The providers' tokens are read now: a missing one stops the destroy\n\t\t// before anything is deleted, rather than after the stack is gone.\n\t\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\t\tconst domains = [...new Set(dnsRecords.map((r) => r.domain))]\n\t\t\t.filter((domain) => dns[domain])\n\t\t\t.map((domain) => ({ domain, config: dns[domain]! }));\n\t\tconst tokens = await dnsCredentials(\n\t\t\tstage,\n\t\t\tdomains,\n\t\t\tdeps.credentials ?? storedCredentials({ env }),\n\t\t);\n\t\tconst log = deps.log ?? ((line: string) => console.log(line));\n\t\tsteps.push({\n\t\t\tlabel: `DNS: ${dnsRecords.map((r) => `${r.type} ${r.fqdn}`).join(', ')} — each only while it holds the value gkm wrote`,\n\t\t\tkeys: recorded.map(\n\t\t\t\t(r) => `dns-record:${r.fqdn.toLowerCase()}:${r.type.toUpperCase()}`,\n\t\t\t),\n\t\t\trun: async () => {\n\t\t\t\tawait pruneStackDns(dnsRecords, {\n\t\t\t\t\tstage,\n\t\t\t\t\tdns: workspace.dns,\n\t\t\t\t\tlog,\n\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t...(tokens.godaddy ? { credential: tokens.godaddy } : {}),\n\t\t\t\t\t\tlog,\n\t\t\t\t\t},\n\t\t\t\t\t...(tokens.hostinger ? { hostinger: tokens.hostinger } : {}),\n\t\t\t\t\t...(deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}),\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\t// ── What gkm cannot delete, and what names nothing ──────────────────────\n\tconst handled = new Set<string>([\n\t\t...(AWS_RESOURCE_TYPES as readonly string[]),\n\t\t'dns-record',\n\t]);\n\tconst values = records.filter((r) => VALUE_TYPES.has(r.type));\n\tfor (const record of records) {\n\t\tif (handled.has(record.type) || VALUE_TYPES.has(record.type)) continue;\n\t\tsteps.push({\n\t\t\tlabel: `${record.type} ${record.id ?? record.key}`,\n\t\t\tleftAlone:\n\t\t\t\tKEPT_TYPES[record.type] ??\n\t\t\t\t`gkm does not delete a ${record.type} yet: delete it by hand`,\n\t\t});\n\t}\n\n\t// ── The stage's secrets ────────────────────────────────────────────────\n\tif (options.secrets) {\n\t\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t});\n\t\tif (!store.delete) throw new SecretsStoreCannotDelete(stage, store.name);\n\t\tsteps.push({\n\t\t\tlabel: `the stage's secrets, in its ${store.name} store`,\n\t\t\t// The keys the deleted resources were reached by go with them.\n\t\t\tkeys: values.map((r) => r.key),\n\t\t\trun: () => store.delete!(stage),\n\t\t});\n\t} else if (values.length > 0) {\n\t\t// Their resources are gone; the keys stay in the kept secrets, and a\n\t\t// deploy writes them again.\n\t\tsteps.push({\n\t\t\tlabel: `${values.length} record${values.length === 1 ? '' : 's'} of keys written into the secrets`,\n\t\t\tkeys: values.map((r) => r.key),\n\t\t});\n\t}\n\n\treturn steps;\n}\n\nfunction awsStep(step: AwsDestroyStep): Step {\n\tif (step.leftAlone) return { label: step.label, leftAlone: step.leftAlone };\n\treturn {\n\t\tlabel: step.gone\n\t\t\t? `${step.label} (already gone)`\n\t\t\t: step.withUser\n\t\t\t\t? `${step.label} — deleted with its user`\n\t\t\t\t: step.label,\n\t\tkeys: [step.key],\n\t\t...(step.remove ? { run: step.remove } : {}),\n\t};\n}\n\n/** The CDN's records, as the DNS prune takes them. */\nfunction providerDnsRecords(\n\tworkspace: NormalizedWorkspace,\n\trecords: readonly { host: string; type: 'CNAME'; value: string }[],\n): RecordedDnsRecord[] {\n\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\tconst out: RecordedDnsRecord[] = [];\n\tfor (const record of records) {\n\t\tconst host = record.host.toLowerCase().replace(/\\.$/, '');\n\t\tconst domain = findRootDomain(host, dns);\n\t\tif (!domain) continue;\n\t\tconst config = dns[domain]!;\n\t\tout.push({\n\t\t\tfqdn: host,\n\t\t\tdomain,\n\t\t\tname: extractSubdomain(host, domain),\n\t\t\ttype: record.type,\n\t\t\tvalue: record.value.replace(/\\.$/, ''),\n\t\t\tttl: recordTtl(config),\n\t\t\t...(typeof config.provider === 'string'\n\t\t\t\t? { provider: config.provider }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,eAAe;CAAE,WAAW;CAAa,YAAY;AAAO;;AAGlE,IAAa,6BAAb,cAAgDA,eAAAA,SAAS;CAE9C;CACA;CAFV,YACC,IACA,UACC;EACD,MACC,2BAA2B,GAAG,8CAC1B,KAAK,MAAM,WAAW,GAAM,EAAE,yLAInC;EATS,KAAA,KAAA;EACA,KAAA,WAAA;EAST,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,UAAU,OAAwB;CAC1C,MAAM,IAAI;CACV,OAAO,GAAG,QAAQ,GAAG,QAAQ;AAC9B;;AAGA,eAAe,OACd,MACA,SACyB;CACzB,IAAI;EACH,OAAO,MAAM,KAAK;CACnB,SAAS,OAAO;EACf,IAAI,QAAQ,SAAS,UAAU,KAAK,CAAC,GAAG,OAAO,KAAA;EAC/C,MAAM;CACP;AACD;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;;AAGlE,SAAS,KACR,MACA,OACU;CACV,MAAM,MAAM,QAAgB,MAAM,MAAM,MAAM,EAAE,QAAQ,GAAG,CAAC,EAAE;CAC9D,OAAO,GAAA,aAAc,MAAM,MAAM,eAAe,GAAA,WAAY,MAAM,MAAM;AACzE;AAEA,MAAM,aACL;;AAGD,SAAS,MAAM,QAAgC;CAC9C,OAAO,OAAO,IAAI,MAAM,OAAO,IAAI,QAAQ,GAAG,IAAI,CAAC;AACpD;;AAGA,SAAS,SAAS,QAAgC;CACjD,OAAO,MAAM,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAA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AM,OAAO,OAAO,KAAK,YAAY,CAAC,CAAC,QAAQ,OAAO,EAAE;EACxD,MAAM,SAASI,oBAAAA,eAAe,MAAM,GAAG;EACvC,IAAI,CAAC,QAAQ;EACb,MAAM,SAAS,IAAI;EACnB,IAAI,KAAK;GACR,MAAM;GACN;GACA,MAAMC,oBAAAA,iBAAiB,MAAM,MAAM;GACnC,MAAM,OAAO;GACb,OAAO,OAAO,MAAM,QAAQ,OAAO,EAAE;GACrC,KAAKC,yBAAAA,UAAU,MAAM;GACrB,GAAI,OAAO,OAAO,aAAa,WAC5B,EAAE,UAAU,OAAO,SAAS,IAC5B,CAAC;EACL,CAAC;CACF;CACA,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"destroy-nTNRfdy6.cjs","names":["GkmError","defaultCdnClients","defaultClients","cdnName","awsEndpoint","awsClientConfig","GkmError","composeServer","secretsStoreFor","stackOverrideFile","join","stackDir","composeProject","deployIdentity","existsSync","dockerHost","resolve","loadWorkspaceConfig","canPrompt","createStateStore","prompt","dockerCompose","sshTarget","EDGE_PROJECT","removeEdgeRoutes","edgeRef","awsProvisioningCredentials","dnsResources","dnsRecordFqdn","normalizeDnsConfig","dnsCredentials","storedCredentials","pruneStackDns","findRootDomain","extractSubdomain","recordTtl"],"sources":["../src/providers/s3/destroy.ts","../src/compose/destroy.ts"],"sourcesContent":["/**\n * What `gkm compose --destroy` deletes in the stage's AWS account: each\n * resource a deploy recorded in the stage's state, and only once it is\n * proven gkm's own for this stage.\n *\n * A record alone proves nothing — a deploy records what it found and adopted\n * exactly as what it made (a certificate for the host, a bucket with no\n * tags). So each is checked against what gkm marks its own with: the\n * `gkm:project` and `gkm:stage` tags on a bucket, a user, a certificate, a\n * distribution, a topic or a queue; the stage's own name on an origin access\n * control and a headers policy, which take no tags. What fails the check is\n * left where it is, and said so.\n *\n * Nothing here runs on its own: `planAwsDestroy` reads, and returns a step\n * per resource whose `remove()` the command calls — after the person typed\n * the stage's name — in the order AWS needs: a distribution disabled and\n * gone before its certificate, a user's keys and policies before the user,\n * a bucket emptied before it is deleted.\n */\n\nimport type { ResourceRecord } from '../../deploy/StateStore.js';\nimport { GkmError } from '../../errors.js';\nimport { type AwsProvisioning, awsClientConfig, awsEndpoint } from '../aws.js';\nimport { TAG_PROJECT, TAG_STAGE } from '../iam.js';\nimport { type CdnClients, cdnName, defaultCdnClients } from './cdn.js';\nimport { defaultClients } from './index.js';\nimport { IAM_USER_PATH } from './naming.js';\n\n/** What a destroy step is about, as the person reads it. */\nexport interface AwsDestroyStep {\n\t/** The state record it is kept as: forgotten once it is gone. */\n\tkey: string;\n\tlabel: string;\n\t/** Why it is not deleted. Absent for one that will be. */\n\tleftAlone?: string;\n\t/** Already gone from the account: only its record is forgotten. */\n\tgone?: boolean;\n\t/** Deleted along with its user's step: only its record is forgotten here. */\n\twithUser?: boolean;\n\t/** Deletes it. Absent when it is left alone or already gone. */\n\tremove?: () => Promise<void>;\n}\n\n/** A DNS record a resource here needs, worked out from the resource. */\nexport interface AwsDnsRecord {\n\thost: string;\n\ttype: 'CNAME';\n\tvalue: string;\n}\n\nexport interface AwsDestroyPlan {\n\t/** In the order they are removed. */\n\tsteps: AwsDestroyStep[];\n\t/**\n\t * The records the s3 provider wrote for what it deletes — a CDN's name, a\n\t * certificate's validation — which no state record names.\n\t */\n\tdns: AwsDnsRecord[];\n}\n\nexport interface AwsDestroyInput {\n\tresources: Record<string, ResourceRecord>;\n\t/** `deployIdentity(…).key` — what `gkm:project` holds. */\n\tidentityKey: string;\n\t/** `deployIdentity(…).scope` — what CDN resource names start with. */\n\tscope: string;\n\tstage: string;\n\tcredential: AwsProvisioning;\n\t/** How long a disabled distribution is waited on, and how often asked. */\n\twait?: { timeoutMs: number; intervalMs: number };\n\t/** For tests: where the clients come from. */\n\tclients?: {\n\t\ts3?: typeof defaultClients;\n\t\tcdn?: (credential: AwsProvisioning) => Promise<CdnClients>;\n\t};\n}\n\n/** The record types this plans. Every other is the command's to report. */\nexport const AWS_RESOURCE_TYPES = [\n\t'cloudfront-distribution',\n\t'cloudfront-oac',\n\t'cloudfront-headers',\n\t'acm-certificate',\n\t'sns-subscription',\n\t'sns-topic',\n\t'sqs-queue',\n\t'iam-access-key',\n\t'iam-user',\n\t's3-bucket',\n] as const;\n\n/** A distribution disabled before it is deleted can take this long. */\nconst DISABLE_WAIT = { timeoutMs: 45 * 60_000, intervalMs: 20_000 };\n\n/** A disabled distribution that never finished deploying. */\nexport class DistributionStillDeploying extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly waitedMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`CloudFront distribution ${id} was disabled, and is still deploying after ` +\n\t\t\t\t`${Math.round(waitedMs / 60_000)} minutes. CloudFront deletes only a ` +\n\t\t\t\t'disabled distribution that has finished deploying. Run the destroy ' +\n\t\t\t\t'again later: everything deleted so far is forgotten, and it carries ' +\n\t\t\t\t'on from here.',\n\t\t);\n\t\tthis.name = 'DistributionStillDeploying';\n\t}\n}\n\n/** What an AWS SDK error is called, whichever field carries it. */\nfunction errorName(error: unknown): string {\n\tconst e = error as { name?: string; Code?: string };\n\treturn e?.Code ?? e?.name ?? '';\n}\n\n/** A read whose \"there is none\" answer is one of `missing`. */\nasync function readOr<T>(\n\tread: () => Promise<T>,\n\tmissing: readonly string[],\n): Promise<T | undefined> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (missing.includes(errorName(error))) return undefined;\n\t\tthrow error;\n\t}\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Whether a tag list says gkm made it for this project's stage. */\nfunction ours(\n\ttags: readonly { Key?: string; Value?: string }[] | undefined,\n\tinput: Pick<AwsDestroyInput, 'identityKey' | 'stage'>,\n): boolean {\n\tconst of = (key: string) => tags?.find((t) => t.Key === key)?.Value;\n\treturn of(TAG_PROJECT) === input.identityKey && of(TAG_STAGE) === input.stage;\n}\n\nconst NOT_TAGGED =\n\t\"not tagged as this stage's (gkm:project, gkm:stage): gkm found it, it did not make it\";\n\n/** The id after the type in a record's key: `cloudfront-oac:Uploads` → `Uploads`. */\nfunction keyId(record: ResourceRecord): string {\n\treturn record.key.slice(record.key.indexOf(':') + 1);\n}\n\n/** The file server a CDN record is for: `cloudfront-headers:Uploads:cors` → `Uploads`. */\nfunction serverOf(record: ResourceRecord): string {\n\treturn keyId(record).split(':')[0] ?? '';\n}\n\n/**\n * Each AWS resource the stage's state records, checked, in the order it is\n * deleted — and the DNS records the deleted ones were given.\n */\nexport async function planAwsDestroy(\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyPlan> {\n\tconst steps: AwsDestroyStep[] = [];\n\tconst dns: AwsDnsRecord[] = [];\n\tconst records = Object.values(input.resources);\n\tconst of = (type: string) => records.filter((r) => r.type === type);\n\tconst wait = input.wait ?? DISABLE_WAIT;\n\n\tconst cdnRecords = [\n\t\t...of('cloudfront-distribution'),\n\t\t...of('cloudfront-oac'),\n\t\t...of('cloudfront-headers'),\n\t\t...of('acm-certificate'),\n\t];\n\tif (cdnRecords.length > 0) {\n\t\tconst cdn = await (input.clients?.cdn ?? defaultCdnClients)(\n\t\t\tinput.credential,\n\t\t);\n\t\t// A distribution left alone keeps what it uses: deleting its origin\n\t\t// access control, a headers policy or its certificate would break it.\n\t\tconst kept = new Map<string, string>();\n\t\tfor (const record of of('cloudfront-distribution')) {\n\t\t\tconst step = await distributionStep(cdn, record, input, wait, dns);\n\t\t\tif (step.leftAlone) kept.set(serverOf(record), step.label);\n\t\t\tsteps.push(step);\n\t\t}\n\t\tconst usedBy = async (\n\t\t\trecord: ResourceRecord,\n\t\t\tstep: () => Promise<AwsDestroyStep>,\n\t\t): Promise<AwsDestroyStep> => {\n\t\t\tconst holder = kept.get(serverOf(record));\n\t\t\tif (!holder) return step();\n\t\t\tconst label = (await step()).label;\n\t\t\treturn {\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel,\n\t\t\t\tleftAlone: `used by ${holder}, which is left alone`,\n\t\t\t};\n\t\t};\n\t\tfor (const record of of('cloudfront-oac')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => originAccessControlStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('cloudfront-headers')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => headersPolicyStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('acm-certificate')) {\n\t\t\t// Its validation record goes only with the certificate itself.\n\t\t\tconst found: AwsDnsRecord[] = [];\n\t\t\tconst step = await usedBy(record, () =>\n\t\t\t\tcertificateStep(cdn, record, input, found),\n\t\t\t);\n\t\t\tif (!step.leftAlone) dns.push(...found);\n\t\t\tsteps.push(step);\n\t\t}\n\t}\n\n\tconst eventRecords = [\n\t\t...of('sns-subscription'),\n\t\t...of('sns-topic'),\n\t\t...of('sqs-queue'),\n\t];\n\tif (eventRecords.length > 0) {\n\t\tconst events = await eventClients(input.credential, records);\n\t\tfor (const record of of('sns-subscription')) {\n\t\t\tsteps.push(subscriptionStep(events, record));\n\t\t}\n\t\tfor (const record of of('sns-topic')) {\n\t\t\tsteps.push(await topicStep(events, record, input));\n\t\t}\n\t\tfor (const record of of('sqs-queue')) {\n\t\t\tsteps.push(await queueStep(events, record, input));\n\t\t}\n\t}\n\n\tconst users = of('iam-user');\n\tconst keys = of('iam-access-key');\n\tconst buckets = of('s3-bucket');\n\tif (users.length + keys.length + buckets.length > 0) {\n\t\tconst global = await (input.clients?.s3 ?? defaultClients)(\n\t\t\tinput.credential,\n\t\t\tregionOf(buckets[0]) ?? 'us-east-1',\n\t\t);\n\t\tconst userSteps = new Map<string, AwsDestroyStep>();\n\t\tfor (const record of users) {\n\t\t\tconst step = await userStep(global, record, input);\n\t\t\tuserSteps.set(record.id ?? '', step);\n\t\t\tsteps.push(step);\n\t\t}\n\t\t// A key goes with its user, and is checked through it.\n\t\tfor (const record of keys) {\n\t\t\tconst user = (record.data as { user?: string } | undefined)?.user;\n\t\t\tconst owner = user ? userSteps.get(user) : undefined;\n\t\t\tsteps.push({\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel: `IAM access key ${record.id ?? ''} of ${user ?? 'an unknown user'}`,\n\t\t\t\t...(owner?.leftAlone\n\t\t\t\t\t? { leftAlone: `its user is left alone: ${owner.leftAlone}` }\n\t\t\t\t\t: owner\n\t\t\t\t\t\t? { withUser: true }\n\t\t\t\t\t\t: { leftAlone: 'its user is not one this stage recorded' }),\n\t\t\t});\n\t\t}\n\t\tfor (const record of buckets) {\n\t\t\tconst region = regionOf(record) ?? global.region;\n\t\t\tconst clients =\n\t\t\t\tregion === global.region\n\t\t\t\t\t? global\n\t\t\t\t\t: await (input.clients?.s3 ?? defaultClients)(\n\t\t\t\t\t\t\tinput.credential,\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t);\n\t\t\tsteps.push(await bucketStep(clients, record, input));\n\t\t}\n\t}\n\n\treturn { steps, dns };\n}\n\nfunction regionOf(record: ResourceRecord | undefined): string | undefined {\n\treturn (record?.data as { region?: string } | undefined)?.region;\n}\n\n// ---------------------------------------------------------------------------\n// CloudFront and ACM\n// ---------------------------------------------------------------------------\n\nasync function distributionStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\twait: { timeoutMs: number; intervalMs: number },\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetDistributionCommand({ Id: id })),\n\t\t['NoSuchDistribution'],\n\t);\n\tconst distribution = found?.Distribution;\n\tconst aliases = distribution?.DistributionConfig?.Aliases?.Items ?? [];\n\tconst label = `CloudFront distribution ${id}${aliases.length ? ` (${aliases.join(', ')})` : ''}`;\n\tif (!distribution) return { key: record.key, label, gone: true };\n\n\t// Its tags, or the comment gkm writes on every distribution it makes —\n\t// `gkm <project> <stage> <file server>`, which nothing else writes.\n\tconst tags = await cloudfront.send(\n\t\tnew CF.ListTagsForResourceCommand({ Resource: distribution.ARN }),\n\t);\n\tconst comment = `gkm ${input.identityKey} ${input.stage} ${serverOf(record)}`;\n\tconst marked =\n\t\tdistribution.DistributionConfig?.Comment === comment.slice(0, 128);\n\tif (!ours(tags.Tags?.Items, input) && !marked) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `${NOT_TAGGED}, and its comment is not \"${comment}\"`,\n\t\t};\n\t}\n\tfor (const host of aliases) {\n\t\tdns.push({ host, type: 'CNAME', value: distribution.DomainName ?? '' });\n\t}\n\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tlet current = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tif (current.DistributionConfig?.Enabled) {\n\t\t\t\tawait cloudfront.send(\n\t\t\t\t\tnew CF.UpdateDistributionCommand({\n\t\t\t\t\t\tId: id,\n\t\t\t\t\t\tIfMatch: current.ETag,\n\t\t\t\t\t\tDistributionConfig: {\n\t\t\t\t\t\t\t...current.DistributionConfig,\n\t\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst started = Date.now();\n\t\t\tfor (;;) {\n\t\t\t\tconst state = await cloudfront.send(\n\t\t\t\t\tnew CF.GetDistributionCommand({ Id: id }),\n\t\t\t\t);\n\t\t\t\tif (state.Distribution?.Status === 'Deployed') break;\n\t\t\t\tif (Date.now() - started > wait.timeoutMs) {\n\t\t\t\t\tthrow new DistributionStillDeploying(id, Date.now() - started);\n\t\t\t\t}\n\t\t\t\tawait sleep(wait.intervalMs);\n\t\t\t}\n\t\t\tcurrent = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteDistributionCommand({ Id: id, IfMatch: current.ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function originAccessControlStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst expected = cdnName(input.scope, input.stage, keyId(record));\n\tconst label = `CloudFront origin access control ${expected}`;\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: id })),\n\t\t['NoSuchOriginAccessControl'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.OriginAccessControl?.OriginAccessControlConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetOriginAccessControlCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteOriginAccessControlCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function headersPolicyStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\t// `cloudfront-headers:<server>:<kind>`\n\tconst [server = '', kind = ''] = keyId(record).split(':');\n\tconst expected = `${cdnName(input.scope, input.stage, server)}-${kind}`;\n\tconst label = `CloudFront response headers policy ${expected}`;\n\tconst found = await readOr(\n\t\t() =>\n\t\t\tcloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id: id })),\n\t\t['NoSuchResponseHeadersPolicy'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.ResponseHeadersPolicyConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetResponseHeadersPolicyConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteResponseHeadersPolicyCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function certificateStep(\n\t{ ACM, acm }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst host = (record.data as { host?: string } | undefined)?.host ?? arn;\n\tconst label = `ACM certificate ${host} (us-east-1)`;\n\tconst found = await readOr(\n\t\t() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })),\n\t\t['ResourceNotFoundException'],\n\t);\n\tif (!found?.Certificate) return { key: record.key, label, gone: true };\n\tconst tags = await acm.send(\n\t\tnew ACM.ListTagsForCertificateCommand({ CertificateArn: arn }),\n\t);\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\tfor (const option of found.Certificate.DomainValidationOptions ?? []) {\n\t\tconst r = option.ResourceRecord;\n\t\tif (r?.Name && r.Value && r.Type === 'CNAME') {\n\t\t\tdns.push({ host: r.Name, type: 'CNAME', value: r.Value });\n\t\t}\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait acm.send(new ACM.DeleteCertificateCommand({ CertificateArn: arn }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// SNS and SQS\n// ---------------------------------------------------------------------------\n\ninterface EventClients {\n\tSNS: typeof import('@aws-sdk/client-sns');\n\tSQS: typeof import('@aws-sdk/client-sqs');\n\tsns: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sns')['SNSClient']>>;\n\tsqs: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sqs')['SQSClient']>>;\n}\n\nasync function eventClients(\n\tcredential: AwsProvisioning,\n\t_records: readonly ResourceRecord[],\n): Promise<EventClients> {\n\tconst SNS = await import('@aws-sdk/client-sns');\n\tconst SQS = await import('@aws-sdk/client-sqs');\n\tconst sns = new Map<string, InstanceType<typeof SNS.SNSClient>>();\n\tconst sqs = new Map<string, InstanceType<typeof SQS.SQSClient>>();\n\treturn {\n\t\tSNS,\n\t\tSQS,\n\t\tsns: async (region) => {\n\t\t\tif (!sns.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SNS');\n\t\t\t\tsns.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SNS.SNSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sns.get(region)!;\n\t\t},\n\t\tsqs: async (region) => {\n\t\t\tif (!sqs.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SQS');\n\t\t\t\tsqs.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SQS.SQSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sqs.get(region)!;\n\t\t},\n\t};\n}\n\n/** `arn:aws:sns:<region>:<account>:<name>` */\nfunction arnParts(arn: string) {\n\tconst [, , , region = '', account = '', ...rest] = arn.split(':');\n\treturn { region, account, name: rest.join(':') };\n}\n\nfunction subscriptionStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n): AwsDestroyStep {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS subscription ${keyId(record)}`;\n\t// Made by gkm, to its own push endpoint: a pending one has no ARN yet.\n\tif (!arn.startsWith('arn:')) return { key: record.key, label, gone: true };\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst client = await sns(arnParts(arn).region);\n\t\t\tawait readOr(\n\t\t\t\t() => client.send(new SNS.UnsubscribeCommand({ SubscriptionArn: arn })),\n\t\t\t\t['NotFound', 'NotFoundException'],\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function topicStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS topic ${arnParts(arn).name}`;\n\tconst client = await sns(arnParts(arn).region);\n\tconst tags = await readOr(\n\t\t() => client.send(new SNS.ListTagsForResourceCommand({ ResourceArn: arn })),\n\t\t[\n\t\t\t'NotFound',\n\t\t\t'NotFoundException',\n\t\t\t'ResourceNotFound',\n\t\t\t'ResourceNotFoundException',\n\t\t],\n\t);\n\tif (!tags) return { key: record.key, label, gone: true };\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SNS.DeleteTopicCommand({ TopicArn: arn }));\n\t\t},\n\t};\n}\n\nasync function queueStep(\n\t{ SQS, sqs }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst { region, account, name } = arnParts(arn);\n\tconst label = `SQS queue ${name}`;\n\tconst client = await sqs(region);\n\tconst url = await readOr(\n\t\t() =>\n\t\t\tclient.send(\n\t\t\t\tnew SQS.GetQueueUrlCommand({\n\t\t\t\t\tQueueName: name,\n\t\t\t\t\tQueueOwnerAWSAccountId: account,\n\t\t\t\t}),\n\t\t\t),\n\t\t['QueueDoesNotExist', 'AWS.SimpleQueueService.NonExistentQueue'],\n\t);\n\tif (!url?.QueueUrl) return { key: record.key, label, gone: true };\n\tconst queueUrl = url.QueueUrl;\n\tconst tags = await client.send(\n\t\tnew SQS.ListQueueTagsCommand({ QueueUrl: queueUrl }),\n\t);\n\tconst list = Object.entries(tags.Tags ?? {}).map(([Key, Value]) => ({\n\t\tKey,\n\t\tValue,\n\t}));\n\tif (!ours(list, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SQS.DeleteQueueCommand({ QueueUrl: queueUrl }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// IAM and S3\n// ---------------------------------------------------------------------------\n\ntype S3Clients = Awaited<ReturnType<typeof defaultClients>>;\n\nasync function userStep(\n\t{ IAM, iam }: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst name = record.id ?? '';\n\tconst label = `IAM user ${name}, its access keys and policies`;\n\tconst found = await readOr(\n\t\t() => iam.send(new IAM.GetUserCommand({ UserName: name })),\n\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t);\n\tif (!found?.User) return { key: record.key, label, gone: true };\n\tconst tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: name }));\n\tif (found.User.Path !== IAM_USER_PATH || !ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst keys = await iam.send(\n\t\t\t\tnew IAM.ListAccessKeysCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const key of keys.AccessKeyMetadata ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tAccessKeyId: key.AccessKeyId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst inline = await iam.send(\n\t\t\t\tnew IAM.ListUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of inline.PolicyNames ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyName: policy,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attached = await iam.send(\n\t\t\t\tnew IAM.ListAttachedUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of attached.AttachedPolicies ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DetachUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyArn: policy.PolicyArn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait iam.send(new IAM.DeleteUserCommand({ UserName: name }));\n\t\t},\n\t};\n}\n\n/** Every object version and delete marker in a bucket, a page at a time. */\nasync function* bucketVersions({ S3, s3 }: S3Clients, bucket: string) {\n\tlet KeyMarker: string | undefined;\n\tlet VersionIdMarker: string | undefined;\n\tfor (;;) {\n\t\tconst page = await s3.send(\n\t\t\tnew S3.ListObjectVersionsCommand({\n\t\t\t\tBucket: bucket,\n\t\t\t\t...(KeyMarker ? { KeyMarker } : {}),\n\t\t\t\t...(VersionIdMarker ? { VersionIdMarker } : {}),\n\t\t\t}),\n\t\t);\n\t\tconst objects = [...(page.Versions ?? []), ...(page.DeleteMarkers ?? [])]\n\t\t\t.filter((o) => o.Key)\n\t\t\t.map((o) => ({\n\t\t\t\tKey: o.Key!,\n\t\t\t\t// `null` is the one version an unversioned bucket's object has:\n\t\t\t\t// named or not, the same object is deleted.\n\t\t\t\t...(o.VersionId && o.VersionId !== 'null'\n\t\t\t\t\t? { VersionId: o.VersionId }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\tif (objects.length > 0) yield objects;\n\t\tif (!page.IsTruncated) return;\n\t\tKeyMarker = page.NextKeyMarker;\n\t\tVersionIdMarker = page.NextVersionIdMarker;\n\t}\n}\n\nasync function bucketStep(\n\tclients: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst { S3, s3 } = clients;\n\tconst bucket = record.id ?? '';\n\tconst tagging = await readOr(\n\t\t() => s3.send(new S3.GetBucketTaggingCommand({ Bucket: bucket })),\n\t\t['NoSuchBucket', 'NoSuchTagSet', 'NoSuchTagSetError'],\n\t);\n\tconst exists = await readOr(\n\t\t() => s3.send(new S3.HeadBucketCommand({ Bucket: bucket })),\n\t\t['NotFound', 'NoSuchBucket'],\n\t);\n\tconst base = `S3 bucket ${bucket}`;\n\tif (!exists) return { key: record.key, label: base, gone: true };\n\tif (!ours(tagging?.TagSet, input)) {\n\t\treturn { key: record.key, label: base, leftAlone: NOT_TAGGED };\n\t}\n\tlet count = 0;\n\tfor await (const page of bucketVersions(clients, bucket))\n\t\tcount += page.length;\n\treturn {\n\t\tkey: record.key,\n\t\tlabel: `${base}, emptied first: ${count} object version${count === 1 ? '' : 's'}`,\n\t\tremove: async () => {\n\t\t\t// Until it lists nothing: deleting a version-less object in a bucket\n\t\t\t// whose versioning was suspended leaves a delete marker behind.\n\t\t\tfor (let pass = 0; pass < 5; pass++) {\n\t\t\t\tlet deleted = 0;\n\t\t\t\tfor await (const page of bucketVersions(clients, bucket)) {\n\t\t\t\t\t// At most a thousand a call.\n\t\t\t\t\tfor (let i = 0; i < page.length; i += 1000) {\n\t\t\t\t\t\tawait s3.send(\n\t\t\t\t\t\t\tnew S3.DeleteObjectsCommand({\n\t\t\t\t\t\t\t\tBucket: bucket,\n\t\t\t\t\t\t\t\tDelete: { Objects: page.slice(i, i + 1000), Quiet: true },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tdeleted += page.length;\n\t\t\t\t}\n\t\t\t\tif (deleted === 0) break;\n\t\t\t}\n\t\t\tawait s3.send(new S3.DeleteBucketCommand({ Bucket: bucket }));\n\t\t},\n\t};\n}\n","/**\n * `gkm compose --stage <stage> --destroy`: everything a deploy made for the\n * stage, deleted for good.\n *\n * The one thing in gkm that deletes what a deploy created — a deploy itself\n * never does. So it is careful in three ways:\n *\n * - **Only what is provably gkm's.** Each AWS resource is checked against\n * what gkm marks its own with before it is deleted (see\n * `providers/s3/destroy.ts`); a DNS record only while it still holds the\n * value gkm wrote. What fails is listed, and left where it is.\n * - **Only with a person typing the stage.** The whole plan is printed\n * first, then the compose project's name — `<project>-<stage>` — has to be\n * typed back. Nothing skips that: there is no flag that answers it, and\n * with no terminal to ask at it refuses before reading anything.\n * - **Resumable.** Each resource's record is forgotten as soon as it is gone,\n * so a run that stops part way — a distribution still deploying — carries\n * on from there when it is run again.\n *\n * What other stages or projects share is never touched: the project bucket\n * that holds every stage's state, the shared Traefik edge, the server's own\n * setup (`gkm compose:server`). The stage's secrets are kept unless\n * `--secrets` is passed.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport {\n\ttype CredentialProvider,\n\tstoredCredentials,\n} from '../deploy/credentials.js';\nimport { dnsRecordFqdn, dnsResources } from '../deploy/dnsResources.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { createStateStore, type StateStore } from '../deploy/StateStore.js';\nimport { GkmError } from '../errors';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype AwsProvisioning,\n\tawsProvisioningCredentials,\n} from '../providers/aws.js';\nimport {\n\tAWS_RESOURCE_TYPES,\n\ttype AwsDestroyInput,\n\ttype AwsDestroyStep,\n\tplanAwsDestroy,\n} from '../providers/s3/destroy.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { stackOverrideFile } from '../target/compose/index';\nimport type { DnsProvider } from '../target/dokploy/dns/DnsProvider.js';\nimport {\n\textractSubdomain,\n\tfindRootDomain,\n\tnormalizeDnsConfig,\n} from '../target/dokploy/dns/index.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type {\n\tDnsProvider as DnsProviderConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\tdnsCredentials,\n\tpruneStackDns,\n\ttype RecordedDnsRecord,\n\trecordTtl,\n} from './dns';\nimport { type ComposeDocker, dockerCompose, type StackRef } from './docker';\nimport { edgeRef, removeEdgeRoutes } from './edge';\nimport { composeServer, dockerHost, sshTarget } from './server';\nimport { composeProject, stackDir } from './stack';\nimport { EDGE_PROJECT } from './traefik';\n\nexport interface ComposeDestroyOptions {\n\tcwd?: string;\n\tstage: string;\n\t/** Delete the stage's secrets too. Kept otherwise. */\n\tsecrets?: boolean;\n\t/** Print what would be deleted; delete nothing, ask nothing. */\n\tdryRun?: boolean;\n}\n\nexport interface ComposeDestroyDeps {\n\tdocker?: ComposeDocker;\n\t/** Whether a person is at a terminal to answer. */\n\tinteractive?: () => boolean;\n\t/** Ask the person, and resolve with what they typed. */\n\task?: (question: string) => Promise<string>;\n\t/** Where the DNS providers' tokens come from. */\n\tcredentials?: CredentialProvider;\n\t/** The provider for a domain — `createDnsProvider` by default. */\n\tdnsProviderFor?: (config: DnsProviderConfig) => Promise<DnsProvider | null>;\n\t/**\n\t * How the AWS account's credential is found — the machine's, as a deploy\n\t * finds it, by default.\n\t */\n\tawsCredentials?: () => Promise<AwsProvisioning | undefined>;\n\t/** For tests: the AWS clients and how long a distribution is waited on. */\n\taws?: Pick<AwsDestroyInput, 'clients' | 'wait'>;\n\tstate?: StateStore;\n\tenv?: NodeJS.ProcessEnv;\n\thome?: string;\n\tlog?: (line: string) => void;\n}\n\n/** A destroy with no terminal to type the stage's name at. */\nexport class ComposeDestroyNeedsTerminal extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Destroying '${stage}' deletes everything its deploys made, and asks you to ` +\n\t\t\t\t`type ${project} first — there is no terminal here to ask at, and no flag ` +\n\t\t\t\t'answers it. Run it yourself, from a terminal. `--dry-run` prints what it ' +\n\t\t\t\t'would delete, anywhere.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsTerminal';\n\t}\n}\n\n/** What was typed was not the project's name. */\nexport class ComposeDestroyNotConfirmed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Nothing was deleted: destroying '${stage}' needs ${project} typed exactly.`,\n\t\t);\n\t\tthis.name = 'ComposeDestroyNotConfirmed';\n\t}\n}\n\n/** AWS resources to delete, and no credentials to delete them with. */\nexport class ComposeDestroyNeedsAwsCredentials extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly resources: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has ${resources.length} AWS resource${resources.length === 1 ? '' : 's'} ` +\n\t\t\t\t`to delete (${resources.slice(0, 3).join(', ')}${resources.length > 3 ? ', …' : ''}), ` +\n\t\t\t\t\"and no AWS credentials were found to delete them with. Supply the stage's \" +\n\t\t\t\t'account the way a deploy does — AWS_PROFILE, or AWS_ACCESS_KEY_ID and ' +\n\t\t\t\t'AWS_SECRET_ACCESS_KEY — and run it again. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsAwsCredentials';\n\t}\n}\n\n/** `--secrets`, and a store that cannot delete. */\nexport class SecretsStoreCannotDelete extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`--secrets deletes '${stage}''s secrets, and its store (${store}) has no ` +\n\t\t\t\t'delete(stage). Give the custom store one, or run without --secrets and ' +\n\t\t\t\t'delete them where they are kept. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'SecretsStoreCannotDelete';\n\t}\n}\n\n/** One line of the plan, and how it is carried out. */\ninterface Step {\n\tlabel: string;\n\tleftAlone?: string;\n\t/** Forgotten from the stage's state once done. */\n\tkeys?: string[];\n\trun?: () => Promise<void>;\n}\n\n/** What a record of each type is to destroy. */\nconst KEPT_TYPES: Record<string, string> = {\n\t// The server's setup — its users, firewall, Docker — is the server's.\n\tserver:\n\t\t\"the server's setup is kept: gkm compose:server made it, for any stage\",\n};\n\n/** Records that name no resource of their own — a key in the secrets. */\nconst VALUE_TYPES = new Set(['url', 'email-from']);\n\n/**\n * The stage's stack: its project on the server (or this machine), as\n * `gkm compose --down` finds it.\n */\nexport async function composeStackRef(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): Promise<{\n\tref: StackRef;\n\tdir: string;\n\tserver?: ReturnType<typeof composeServer>;\n}> {\n\tconst local = stage === workspace.stages.local;\n\tconst server = local\n\t\t? undefined\n\t\t: composeServer({\n\t\t\t\tstage,\n\t\t\t\tlocal,\n\t\t\t\tconfig: workspace.deploy?.compose?.server,\n\t\t\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t\t\t?.custom,\n\t\t\t});\n\tconst override = stackOverrideFile(workspace.root, stage);\n\tconst dir = join(workspace.root, stackDir(stage));\n\tconst ref: StackRef = {\n\t\tproject: composeProject(deployIdentity(workspace, stage)),\n\t\tfile: join(dir, 'docker-compose.yml'),\n\t\t...(existsSync(override) ? { overrides: [override] } : {}),\n\t\tcwd: workspace.root,\n\t\t...(server ? { host: dockerHost(server) } : {}),\n\t};\n\treturn { ref, dir, ...(server ? { server } : {}) };\n}\n\n/** `gkm compose --stage <stage> --destroy`. */\nexport async function composeDestroyCommand(\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps = {},\n): Promise<void> {\n\tconst log = deps.log ?? ((line: string) => console.log(line));\n\tconst env = deps.env ?? process.env;\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst { stage } = options;\n\tconst local = stage === workspace.stages.local;\n\tif (!local) assertDeployedStage(workspace.stages, stage);\n\n\tconst identity = deployIdentity(workspace, stage);\n\tconst project = composeProject(identity);\n\tconst interactive = deps.interactive ?? canPrompt;\n\tif (!options.dryRun && !interactive()) {\n\t\tthrow new ComposeDestroyNeedsTerminal(stage, project);\n\t}\n\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: local ? undefined : workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\t// Held throughout: a deploy of the stage while it is torn down would\n\t// make what this is deleting.\n\tconst lock = options.dryRun\n\t\t? undefined\n\t\t: await state.lock(stage, { operation: 'destroy' });\n\ttry {\n\t\tconst steps = await plan(workspace, stage, options, deps, state, env);\n\t\tconst { ref } = await composeStackRef(workspace, stage);\n\n\t\tlog(\n\t\t\t`\\n🧨 ${options.dryRun ? 'Would delete' : 'This deletes'} stage '${stage}' of ${workspace.name} for good:\\n`,\n\t\t);\n\t\tconst doing = steps.filter((s) => !s.leftAlone);\n\t\tconst kept = steps.filter((s) => s.leftAlone);\n\t\tfor (const step of doing) log(` - ${step.label}`);\n\t\tif (kept.length > 0) {\n\t\t\tlog('\\n Left where it is:');\n\t\t\tfor (const step of kept) log(` · ${step.label} — ${step.leftAlone}`);\n\t\t}\n\t\tif (!options.secrets) {\n\t\t\tlog(\n\t\t\t\t\"\\n The stage's secrets are kept: a deploy of it again reuses them. --secrets deletes them too.\",\n\t\t\t);\n\t\t}\n\n\t\tif (options.dryRun) {\n\t\t\tlog('\\n--dry-run: nothing was deleted.');\n\t\t\treturn;\n\t\t}\n\n\t\tconst ask =\n\t\t\tdeps.ask ??\n\t\t\t((question: string) =>\n\t\t\t\tprompt(question, {\n\t\t\t\t\tinstead: 'Run it yourself, from a terminal.',\n\t\t\t\t}));\n\t\tconst typed = await ask(`\\n Type ${project} to destroy it: `);\n\t\tif (typed.trim() !== project) {\n\t\t\tthrow new ComposeDestroyNotConfirmed(stage, project);\n\t\t}\n\n\t\tlog('');\n\t\tfor (const step of doing) {\n\t\t\tawait step.run?.();\n\t\t\tfor (const key of step.keys ?? []) {\n\t\t\t\tawait state.deleteResource(stage, key);\n\t\t\t}\n\t\t\tlog(` ✓ ${step.label}`);\n\t\t}\n\t\tlog(`\\n💥 '${stage}' destroyed. ${ref.project} is gone.`);\n\t} finally {\n\t\tawait lock?.release();\n\t}\n}\n\n/** Every step, in the order it is carried out. */\nasync function plan(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps,\n\tstate: StateStore,\n\tenv: NodeJS.ProcessEnv,\n): Promise<Step[]> {\n\tconst steps: Step[] = [];\n\tconst resources = (await state.read(stage))?.resources ?? {};\n\tconst records = Object.values(resources);\n\n\t// ── The stack: containers, volumes, its routes on the edge ─────────────\n\tconst { ref, dir, server } = await composeStackRef(workspace, stage);\n\tconst docker = deps.docker ?? dockerCompose;\n\tsteps.push({\n\t\tlabel: `${server ? `on ${sshTarget(server)}: ` : ''}stack ${ref.project} — its containers, its volumes and their data, its routes on ${EDGE_PROJECT}`,\n\t\trun: async () => {\n\t\t\tconst edgeFile = join(dir, `${EDGE_PROJECT}.yml`);\n\t\t\tif (server || existsSync(edgeFile)) {\n\t\t\t\tawait removeEdgeRoutes(\n\t\t\t\t\tdocker,\n\t\t\t\t\tedgeRef(edgeFile, { host: ref.host }),\n\t\t\t\t\tref.project,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait docker.down(ref, { volumes: true });\n\t\t},\n\t});\n\n\t// ── AWS ─────────────────────────────────────────────────────────────────\n\tconst aws = records.filter((r) =>\n\t\t(AWS_RESOURCE_TYPES as readonly string[]).includes(r.type),\n\t);\n\tlet cdnDns: RecordedDnsRecord[] = [];\n\tif (aws.length > 0) {\n\t\tconst credential = await (\n\t\t\tdeps.awsCredentials ??\n\t\t\t(() =>\n\t\t\t\tawsProvisioningCredentials({\n\t\t\t\t\tstage,\n\t\t\t\t\tenv,\n\t\t\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t\t\t}))\n\t\t)();\n\t\tif (!credential) {\n\t\t\tthrow new ComposeDestroyNeedsAwsCredentials(\n\t\t\t\tstage,\n\t\t\t\taws.map((r) => r.key),\n\t\t\t);\n\t\t}\n\t\tconst identity = deployIdentity(workspace, stage);\n\t\tconst planned = await planAwsDestroy({\n\t\t\tresources,\n\t\t\tidentityKey: identity.key,\n\t\t\tscope: identity.scope,\n\t\t\tstage,\n\t\t\tcredential,\n\t\t\t...(deps.aws ?? {}),\n\t\t});\n\t\tfor (const step of planned.steps) steps.push(awsStep(step));\n\t\tcdnDns = providerDnsRecords(workspace, planned.dns);\n\t}\n\n\t// ── DNS: what the stage recorded, and what its CDN was given ───────────\n\tconst recorded = dnsResources(resources).map((r) => ({\n\t\t...r,\n\t\tfqdn: r.fqdn || dnsRecordFqdn(r.domain, r.name),\n\t}));\n\tconst seen = new Set(recorded.map((r) => `${r.fqdn} ${r.type}`));\n\tconst dnsRecords: RecordedDnsRecord[] = [\n\t\t...recorded,\n\t\t...cdnDns.filter((r) => !seen.has(`${r.fqdn} ${r.type}`)),\n\t];\n\tif (dnsRecords.length > 0) {\n\t\t// The providers' tokens are read now: a missing one stops the destroy\n\t\t// before anything is deleted, rather than after the stack is gone.\n\t\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\t\tconst domains = [...new Set(dnsRecords.map((r) => r.domain))]\n\t\t\t.filter((domain) => dns[domain])\n\t\t\t.map((domain) => ({ domain, config: dns[domain]! }));\n\t\tconst tokens = await dnsCredentials(\n\t\t\tstage,\n\t\t\tdomains,\n\t\t\tdeps.credentials ?? storedCredentials({ env }),\n\t\t);\n\t\tconst log = deps.log ?? ((line: string) => console.log(line));\n\t\tsteps.push({\n\t\t\tlabel: `DNS: ${dnsRecords.map((r) => `${r.type} ${r.fqdn}`).join(', ')} — each only while it holds the value gkm wrote`,\n\t\t\tkeys: recorded.map(\n\t\t\t\t(r) => `dns-record:${r.fqdn.toLowerCase()}:${r.type.toUpperCase()}`,\n\t\t\t),\n\t\t\trun: async () => {\n\t\t\t\tawait pruneStackDns(dnsRecords, {\n\t\t\t\t\tstage,\n\t\t\t\t\tdns: workspace.dns,\n\t\t\t\t\tlog,\n\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t...(tokens.godaddy ? { credential: tokens.godaddy } : {}),\n\t\t\t\t\t\tlog,\n\t\t\t\t\t},\n\t\t\t\t\t...(tokens.hostinger ? { hostinger: tokens.hostinger } : {}),\n\t\t\t\t\t...(deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}),\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\t// ── What gkm cannot delete, and what names nothing ──────────────────────\n\tconst handled = new Set<string>([\n\t\t...(AWS_RESOURCE_TYPES as readonly string[]),\n\t\t'dns-record',\n\t]);\n\tconst values = records.filter((r) => VALUE_TYPES.has(r.type));\n\tfor (const record of records) {\n\t\tif (handled.has(record.type) || VALUE_TYPES.has(record.type)) continue;\n\t\tsteps.push({\n\t\t\tlabel: `${record.type} ${record.id ?? record.key}`,\n\t\t\tleftAlone:\n\t\t\t\tKEPT_TYPES[record.type] ??\n\t\t\t\t`gkm does not delete a ${record.type} yet: delete it by hand`,\n\t\t});\n\t}\n\n\t// ── The stage's secrets ────────────────────────────────────────────────\n\tif (options.secrets) {\n\t\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t});\n\t\tif (!store.delete) throw new SecretsStoreCannotDelete(stage, store.name);\n\t\tsteps.push({\n\t\t\tlabel: `the stage's secrets, in its ${store.name} store`,\n\t\t\t// The keys the deleted resources were reached by go with them.\n\t\t\tkeys: values.map((r) => r.key),\n\t\t\trun: () => store.delete!(stage),\n\t\t});\n\t} else if (values.length > 0) {\n\t\t// Their resources are gone; the keys stay in the kept secrets, and a\n\t\t// deploy writes them again.\n\t\tsteps.push({\n\t\t\tlabel: `${values.length} record${values.length === 1 ? '' : 's'} of keys written into the secrets`,\n\t\t\tkeys: values.map((r) => r.key),\n\t\t});\n\t}\n\n\treturn steps;\n}\n\nfunction awsStep(step: AwsDestroyStep): Step {\n\tif (step.leftAlone) return { label: step.label, leftAlone: step.leftAlone };\n\treturn {\n\t\tlabel: step.gone\n\t\t\t? `${step.label} (already gone)`\n\t\t\t: step.withUser\n\t\t\t\t? `${step.label} — deleted with its user`\n\t\t\t\t: step.label,\n\t\tkeys: [step.key],\n\t\t...(step.remove ? { run: step.remove } : {}),\n\t};\n}\n\n/** The CDN's records, as the DNS prune takes them. */\nfunction providerDnsRecords(\n\tworkspace: NormalizedWorkspace,\n\trecords: readonly { host: string; type: 'CNAME'; value: string }[],\n): RecordedDnsRecord[] {\n\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\tconst out: RecordedDnsRecord[] = [];\n\tfor (const record of records) {\n\t\tconst host = record.host.toLowerCase().replace(/\\.$/, '');\n\t\tconst domain = findRootDomain(host, dns);\n\t\tif (!domain) continue;\n\t\tconst config = dns[domain]!;\n\t\tout.push({\n\t\t\tfqdn: host,\n\t\t\tdomain,\n\t\t\tname: extractSubdomain(host, domain),\n\t\t\ttype: record.type,\n\t\t\tvalue: record.value.replace(/\\.$/, ''),\n\t\t\tttl: recordTtl(config),\n\t\t\t...(typeof config.provider === 'string'\n\t\t\t\t? { provider: config.provider }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,eAAe;CAAE,WAAW;CAAa,YAAY;AAAO;;AAGlE,IAAa,6BAAb,cAAgDA,eAAAA,SAAS;CAE9C;CACA;CAFV,YACC,IACA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AC;EACL,CAAC;CACF;CACA,OAAO;AACR"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const require_errors = require("./errors-DMC4Umsb.cjs");
|
|
2
|
-
const require_credentials = require("./credentials-
|
|
3
|
-
const require_workspace = require("./workspace-
|
|
4
|
-
const require_apps = require("./apps-
|
|
5
|
-
const require_compose = require("./compose-
|
|
2
|
+
const require_credentials = require("./credentials-CORvhcrO.cjs");
|
|
3
|
+
const require_workspace = require("./workspace-Ciw3SnME.cjs");
|
|
4
|
+
const require_apps = require("./apps-C6s-trVp.cjs");
|
|
5
|
+
const require_compose = require("./compose-BqTuzitb.cjs");
|
|
6
6
|
const require_SubscriberGenerator = require("./SubscriberGenerator-mZpSuSU7.cjs");
|
|
7
7
|
const require_EndpointGenerator = require("./EndpointGenerator-DxrRqfJ3.cjs");
|
|
8
8
|
const require_discover = require("./discover-CRywE7yc.cjs");
|
|
@@ -1330,13 +1330,17 @@ function processorDockerfile(unit, host, options) {
|
|
|
1330
1330
|
* A site's Dockerfile, with an `ARG` for every key its bundler inlines.
|
|
1331
1331
|
*
|
|
1332
1332
|
* The keys come from the site's declaration where there is one — every
|
|
1333
|
-
* public key its edges give it, `
|
|
1333
|
+
* public key its edges give it, `VITE_UPLOADS_URL` included — and an
|
|
1334
1334
|
* `ARG` the Dockerfile does not declare is a build argument the build drops,
|
|
1335
1335
|
* leaving the bundle with an empty URL.
|
|
1336
1336
|
*/
|
|
1337
1337
|
function siteDockerfile(appName, app, options) {
|
|
1338
1338
|
const declared = options.manifest ? Object.entries(options.manifest).find(([id, d]) => d.kind === "site" && require_workspace.appKey(id) === appName)?.[1] : void 0;
|
|
1339
|
-
const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? [
|
|
1339
|
+
const publicUrlArgs = options.publicUrlArgs ?? (declared?.kind === "site" && options.manifest ? [
|
|
1340
|
+
(0, _geekmidas_manifest.provideKey)(declared.id, "url"),
|
|
1341
|
+
...Object.keys((0, _geekmidas_manifest.publicEnvFor)(declared, options.manifest)),
|
|
1342
|
+
...(0, _geekmidas_manifest.imageOriginSources)(declared, options.manifest).length > 0 ? [`${_geekmidas_manifest.PUBLIC_PREFIX[declared.variant]}${_geekmidas_manifest.IMAGE_ORIGINS_KEY}`] : []
|
|
1343
|
+
] : require_compose.getPublicUrlArgNames(app));
|
|
1340
1344
|
const webOpts = {
|
|
1341
1345
|
...options.image,
|
|
1342
1346
|
publicUrlArgs,
|
|
@@ -1513,4 +1517,4 @@ Object.defineProperty(exports, "workerEntryDir", {
|
|
|
1513
1517
|
}
|
|
1514
1518
|
});
|
|
1515
1519
|
|
|
1516
|
-
//# sourceMappingURL=docker-
|
|
1520
|
+
//# sourceMappingURL=docker-Dy1ZJUzV.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docker-Dy1ZJUzV.cjs","names":["GkmError","join","processorUnitName","ConstructGenerator","Processor","mkdir","relative","dirname","writeFile","PROCESSORS_DEV_PREFIX","writeTelemetryModule","startTelemetryCode","PROCESSOR_ORIGIN_SECRET_ENV","ORIGIN_VERIFY_HEADER","ConstructGenerator","join","mkdir","relative","Cron","writeFile","dirname","runtimeFor","ConstructGenerator","Queue","join","mkdir","relative","dirname","runtimeFor","writeFile","provideKey","GkmError","join","appKey","SubscriberGenerator","mkdir","writeFile","writeTelemetryModule","runtimeFor","startTelemetryCode","output","GkmError","loadWorkspaceConfig","resolveDockerConfig","run","relative","imageLayout","dockerfileOf","join","mkdir","dirname","writeFile","workerUnits","processorUnits","COMPOSE_PATH","appImageOptions","siteClientTelemetry","generateEntryDockerfile","generateBackendDockerfile","generateWorkerDockerfile","WORKER_PORT","generateProcessorDockerfile","PROCESSOR_PORT","appKey","provideKey","publicEnvFor","imageOriginSources","PUBLIC_PREFIX","IMAGE_ORIGINS_KEY","getPublicUrlArgNames","generateViteStaticDockerfile","generateNodeWebDockerfile","generateNextjsDockerfile","existsSync","generateDockerignore","readFile","appendFile","reconcileWorkspace"],"sources":["../src/docker/imageRef.ts","../src/generators/ProcessorGenerator.ts","../src/generators/CronGenerator.ts","../src/generators/QueueGenerator.ts","../src/generators/WorkerGenerator.ts","../src/docker/index.ts"],"sourcesContent":["/**\n * An image reference, checked before it reaches `docker`.\n *\n * The parts come from the workspace — a registry in `gkm.config.ts`, an image\n * name from the project, a tag from `--tag` — and an argument array already\n * keeps them out of a shell. What it cannot do is stop `docker` reading a value\n * that starts with `-` as one of its own flags, so a ref is held to Docker's\n * own grammar (distribution/reference) and anything else is refused by name\n * before a build starts.\n */\n\nimport { GkmError } from '../errors';\n\nconst DOMAIN_COMPONENT = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])';\nconst DOMAIN = `${DOMAIN_COMPONENT}(?:\\\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;\nconst PATH_COMPONENT = '[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*';\nconst TAG = '[\\\\w][\\\\w.-]{0,127}';\nconst DIGEST =\n\t'[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}';\n\nconst REFERENCE = new RegExp(\n\t`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`,\n);\n\n/** Docker refuses a repository name longer than this. */\nconst MAX_NAME_LENGTH = 255;\n\n/** A value that is not an image reference was about to be built or pushed. */\nexport class ImageRefInvalid extends GkmError {\n\tconstructor(readonly ref: string) {\n\t\tsuper(\n\t\t\t`'${ref}' is not a valid image reference. An image is \\`[registry/]name[:tag]\\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`,\n\t\t);\n\t\tthis.name = 'ImageRefInvalid';\n\t}\n}\n\n/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */\nexport function validateImageRef(ref: string): string {\n\tconst name = ref.split('@')[0]!.replace(/:[\\w][\\w.-]*$/, '');\n\tif (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) {\n\t\tthrow new ImageRefInvalid(ref);\n\t}\n\treturn ref;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Processor } from '@geekmidas/constructs/processors';\nimport type { ProcessorInfo } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport { processorUnitName } from '../build/workers';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n} from '../providers/processorOrigin';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport { PROCESSORS_DEV_PREFIX } from './processorRoute';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\ntype AnyProcessor = Processor<string, any, any, any>;\n\n/** Where a file server's processor entry lives, under an app's `.gkm/server`. */\nexport function processorEntryDir(\n\tserverDir: string,\n\tfileServerId: string,\n): string {\n\treturn join(serverDir, 'processors', processorUnitName(fileServerId));\n}\n\n/** The file its bundle is written to, beside the server's. */\nexport function processorBundleName(fileServerId: string): string {\n\treturn `${processorUnitName(fileServerId)}.mjs`;\n}\n\n/**\n * A file server's processors, as the build generates them.\n *\n * On AWS each is a Lambda behind a function URL — the CDN's origin for its\n * pattern. On a server they are one process per file server, the processor\n * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target\n * generates nothing per processor here.\n */\nexport class ProcessorGenerator extends ConstructGenerator<\n\tAnyProcessor,\n\tProcessorInfo[]\n> {\n\tisConstruct(value: unknown): value is AnyProcessor {\n\t\treturn Processor.isProcessor(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<AnyProcessor>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<ProcessorInfo[]> {\n\t\tif ((options?.target ?? 'aws') !== 'aws' || constructs.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst dir = join(outputDir, 'processors');\n\t\tawait mkdir(dir, { recursive: true });\n\n\t\tconst infos: ProcessorInfo[] = [];\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst file = join(dir, `${key}.ts`);\n\t\t\tconst importPath = relative(dirname(file), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tawait writeFile(\n\t\t\t\tfile,\n\t\t\t\t`import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';\nimport { ${key} } from '${importPath}';\n${context.storageDrivers?.imports ?? ''}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaProcessor(${key});\n\nexport const handler = adapter.handler;\n`,\n\t\t\t);\n\t\t\tinfos.push(\n\t\t\t\tawait processorInfo(\n\t\t\t\t\tkey,\n\t\t\t\t\tconstruct,\n\t\t\t\t\trelative(options?.root ?? process.cwd(), file).replace(\n\t\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t\t'.handler',\n\t\t\t\t\t),\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn infos;\n\t}\n\n\t/**\n\t * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting\n\t * each file server's processors under `/__gkm/processors/<FileServer>`.\n\t * The local edge sends each pattern on the file server's host there, so\n\t * `processedUrl()` answers locally as it does deployed.\n\t *\n\t * In the dev server's own process rather than a unit of its own: locally\n\t * there is no CPU to protect, and the dev server already reloads on change.\n\t */\n\tasync buildDev(\n\t\toutputDir: string,\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst file = join(outputDir, 'processors.ts');\n\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\t\tconst byServer = new Map<string, string[]>();\n\t\tfor (const { key, construct } of processors) {\n\t\t\tbyServer.set(construct.surfaceId, [\n\t\t\t\t...(byServer.get(construct.surfaceId) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst units = [...byServer.entries()]\n\t\t\t.map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(', ')}],`)\n\t\t\t.join('\\n');\n\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\t`/**\n * Generated processors setup for \\`gkm dev\\`.\n *\n * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the\n * local edge rewrites each processor pattern on the file server's host here.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${imports}\n\nexport function setupProcessors(\n app: { all: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n): void {\n const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(\n Object.entries({\n${units}\n }).map(([id, processors]) => [id, processorServer(processors, envParser)]),\n );\n\n app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {\n const server = c.req.param('server') as string;\n const serve = units[server];\n if (!serve) return c.notFound();\n const path = c.req.path.slice(\\`${PROCESSORS_DEV_PREFIX}\\${server}\\`.length) || '/';\n const response = await serve({ method: c.req.method, path });\n if (!response) {\n return new Response(null, {\n status: 404,\n headers: { 'cache-control': 'public, max-age=60' },\n });\n }\n return new Response(c.req.method === 'HEAD' ? null : response.body, {\n status: response.status,\n headers: response.headers,\n });\n });\n}\n`,\n\t\t);\n\t\treturn file;\n\t}\n\n\t/**\n\t * A file server's processor unit: one process answering each of its\n\t * processors' patterns, and `/health`. Returns its entry, `processors.ts`.\n\t *\n\t * Its own process because making a derivative is CPU-bound — a resize\n\t * spike in the API's process would be every request's latency.\n\t */\n\tasync buildEntry(input: {\n\t\tcontext: BuildContext;\n\t\tfileServerId: string;\n\t\toutputDir: string;\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[];\n\t\t/** From the file server's edge to a `Telemetry` node, when it has one. */\n\t\ttelemetry?: TelemetryContext;\n\t}): Promise<string> {\n\t\tconst { context, outputDir, processors } = input;\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\t// The file server's own edge decides; without one the module loads\n\t\t// nothing, and the entry's start-up is the same shape either way.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst healthCheck = context.production?.healthCheck ?? '/health';\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\tconst entry = join(outputDir, 'processors.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\t`#!/usr/bin/env node\n/**\n * Production entry for ${input.fileServerId}'s processors.\n * Generated by 'gkm build --production'.\n *\n * Answers each processor's pattern, and ${healthCheck} on PORT. The edge\n * routes only those patterns here; everything else on the file server's\n * domain is the bucket.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${context.storageDrivers?.imports ?? ''}\n${imports}\n\n${startTelemetryCode([healthCheck])}\n${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};\n\nconst processors = [${processors.map(({ key }) => key).join(', ')}];\nconst serve = processorServer(processors);\nconst port = Number(process.env.PORT) || 3000;\nlet stopping = false;\n\n${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}\n// Where the CDN fronts this unit, the secret it adds to every request: one\n// without it is refused here, whatever the edge in front did or could not.\nconst originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}\n ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})\n : undefined;\nconst fromOrigin = (header: string | string[] | undefined) => {\n if (!originSecret) return true;\n const given = Buffer.from(typeof header === 'string' ? header : '');\n return given.length === originSecret.length && timingSafeEqual(given, originSecret);\n};\n\nconst server = createServer(async (req, res) => {\n const method = req.method ?? 'GET';\n const path = (req.url ?? '/').split('?')[0] ?? '/';\n if (path === ${JSON.stringify(healthCheck)}) {\n res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));\n return;\n }\n if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {\n res.writeHead(403, { 'cache-control': 'no-store' }).end();\n return;\n }\n await traced(method, path, async () => {\n try {\n const response = await serve({ method, path });\n if (!response) {\n res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();\n return 404;\n }\n res.writeHead(response.status, response.headers);\n res.end(method === 'HEAD' ? undefined : response.body);\n return response.status;\n } catch (error) {\n console.error(error);\n res.writeHead(500, { 'cache-control': 'no-store' }).end();\n return 500;\n }\n });\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();\n server.close();\n await runShutdownHooks((error) => console.error(error));\n process.exit(0);\n};\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n`,\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * A SERVER span per request, once telemetry has started — opened by the unit\n * rather than by hooking node:http, which sees nothing inside a bundle. Named\n * after the processor's pattern, never the key, which has no bound.\n *\n * Only in an entry whose file server has a `Telemetry` node: the bundle\n * follows the import, and an app without one need not install the API.\n */\nconst REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;\nconst routeOf = (path: string) =>\n processors.find((processor) => path.startsWith(processor.prefix))?.pattern;\n\nasync function traced(\n method: string,\n path: string,\n run: () => Promise<number>,\n): Promise<void> {\n if (!tracing) {\n await run();\n return;\n }\n const route = routeOf(path);\n await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(\n route ? \\`\\${method} \\${route}\\` : method,\n {\n kind: tracing.SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': path,\n ...(route ? { 'http.route': route } : {}),\n },\n },\n async (span) => {\n try {\n const status = await run();\n span.setAttribute('http.response.status_code', status);\n if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });\n } finally {\n span.end();\n }\n },\n );\n}\n`;\n\n/** The same shape without telemetry: each request just runs. */\nconst NO_REQUEST_SPANS = `async function traced(\n _method: string,\n _path: string,\n run: () => Promise<number>,\n): Promise<void> {\n await run();\n}\n`;\n\n/** What the manifest records of one processor. */\nexport async function processorInfo(\n\tname: string,\n\tprocessor: AnyProcessor,\n\thandler: string,\n\tcontext: Pick<BuildContext, 'markOptional'>,\n): Promise<ProcessorInfo> {\n\treturn {\n\t\tname,\n\t\thandler,\n\t\tfileServer: processor.surfaceId,\n\t\tpath: processor.pattern,\n\t\tprefix: processor.prefix,\n\t\t...(processor.native.length ? { native: [...processor.native] } : {}),\n\t\t...(processor.timeout !== undefined ? { timeout: processor.timeout } : {}),\n\t\t...(processor.memorySize !== undefined\n\t\t\t? { memorySize: processor.memorySize }\n\t\t\t: {}),\n\t\tenvironment: await processor.getEnvironment({\n\t\t\tmarkOptional: context.markOptional,\n\t\t}),\n\t\tdependencies: processor.constructs,\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Cron } from '@geekmidas/constructs/crons';\nimport type { BuildContext } from '../build/types';\nimport type { CronInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\nexport class CronGenerator extends ConstructGenerator<\n\tCron<any, any, any, any, any, any>,\n\tCronInfo[]\n> {\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<CronInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst cronInfos: CronInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// A server runs its crons itself, the way it already runs its\n\t\t\t// subscribers: one file, wired into the generated entry. Written even\n\t\t\t// when there are none, so the entry can import it unconditionally.\n\t\t\tawait this.generateServerCronsFile(outputDir, constructs);\n\n\t\t\tlogger.log(`Generated server crons file with ${constructs.length} crons`);\n\n\t\t\t// A server cron has no individual handler to point infra at — the\n\t\t\t// process schedules it.\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\t// Create crons subdirectory\n\t\tconst cronsDir = join(outputDir, 'crons');\n\t\tawait mkdir(cronsDir, { recursive: true });\n\n\t\t// Generate cron handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateCronHandler(\n\t\t\t\tcronsDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tcronInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tschedule: construct.schedule || 'rate(1 hour)',\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated cron handler: ${key}`);\n\t\t}\n\n\t\treturn cronInfos;\n\t}\n\n\tisConstruct(value: any): value is Cron<any, any, any, any, any, any> {\n\t\treturn Cron.isCron(value);\n\t}\n\n\t/**\n\t * The crons file a server entry imports.\n\t *\n\t * Shaped after `generateServerSubscribersFile`: one module, every cron, a\n\t * `setupCrons` the generated entry calls beside `setupSubscribers`.\n\t *\n\t * It picks its scheduler from what the process can reach. With a Postgres it\n\t * uses pg-boss, whose schedules live in the database — so a deployment\n\t * running four replicas fires each job once, which is the thing a timer in\n\t * every process gets wrong and does not report. With no database it falls\n\t * back to timers and says plainly that it is doing so.\n\t */\n\tprivate async generateServerCronsFile(\n\t\toutputDir: string,\n\t\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst cronsPath = join(outputDir, 'crons.ts');\n\n\t\t// Nothing to schedule, so nothing to import — the entry imports this file\n\t\t// whatever the app declares, and a project with no events must not have\n\t\t// to resolve `@geekmidas/events`.\n\t\tif (crons.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tcronsPath,\n\t\t\t\t`/**\n * Generated cron setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupCrons(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function cronsStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopCrons(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn cronsPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of crons) {\n\t\t\tconst relativePath = relative(dirname(cronsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) importsByFile.set(importPath, []);\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst entries = crons\n\t\t\t.map(({ key }) => ` { name: '${key}', cron: ${key} }`)\n\t\t\t.join(',\\n');\n\n\t\tconst content = `/**\n * Generated cron setup.\n *\n * Schedules every cron this app declares, in the process that serves it.\n *\n * The schedule lives in Postgres, through pg-boss, in the database the worker\n * named with \\`.database(db)\\`. That is what makes running several replicas\n * safe: each job fires once, where a timer in every process fires it once per\n * replica and reports nothing.\n *\n * No connection string appears here. The construct that owns the database is\n * the only thing that knows its key, and it is resolved through service\n * discovery like any other dependency.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst crons = [\n${entries}\n];\n\ntype Stoppable = { stop: () => Promise<void> | void };\nconst running: Stoppable[] = [];\n// What a worker's health check reads: the crons that cannot be scheduled, and\n// the broker connection the schedule is kept through.\nconst failed: string[] = [];\nconst connections: import('@geekmidas/events').EventConnection[] = [];\n\nexport async function setupCrons(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n if (crons.length === 0) {\n return;\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Resolved once per cron rather than per firing: registering services on\n // every tick would reconnect a database every minute.\n const prepared = [];\n for (const { name, cron } of crons) {\n try {\n const schedule = toCronExpression(cron.schedule);\n const services = cron.services.length > 0\n ? await serviceDiscovery.register(cron.services)\n : {};\n\n prepared.push({ name, cron, schedule, services });\n } catch (error) {\n // An unrepresentable schedule is a build-time mistake, and failing the\n // process for it would take the HTTP server down with it.\n logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');\n failed.push(name);\n }\n }\n\n const run = async (entry: (typeof prepared)[number]) => {\n try {\n // The cron's own function, the way its Lambda would run it — services,\n // the worker's database as \\`db\\`, its events. It used to call a\n // \\`handler\\` a Cron does not have, so every firing logged a failure.\n await runCron(entry.cron, serviceDiscovery, entry.name);\n } catch (error) {\n logger.error({ err: error, cron: entry.name }, 'Cron failed');\n }\n };\n\n // The app's one pg-boss: the events broker's, as the broker's role, in the\n // broker's schema. A server fires its own crons, and a process scheduling in\n // memory fires each job once per replica — so the schedule lives in\n // Postgres. It used to be a second pg-boss on the worker's database, as the\n // runtime role, which can neither create a schema nor use the broker's.\n const { url, devPid } = envParser\n .create((get) => ({\n url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),\n // Set by \\`gkm dev\\` on the server it starts, and by nothing deployed.\n devPid: get('GKM_DEV_PID').string().optional(),\n }))\n .parse();\n\n if (!url?.startsWith('pgboss://')) {\n // \\`gkm dev\\` on a target whose crons are infrastructure once deployed —\n // EventBridge rules on AWS — has no broker to keep a schedule in. It is one\n // process, so a timer fires each job once, which is all pg-boss is for\n // here. Only there: a deployed server firing by timer fires once per\n // replica, so outside dev this stays the error below.\n if (devPid) {\n for (const entry of prepared) {\n running.push(scheduleInProcess(entry.schedule, () => run(entry)));\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');\n }\n return;\n }\n\n logger.error(\n { crons: prepared.map(({ name }) => name) },\n 'These crons have nowhere to keep their schedule. On a server they are ' +\n 'scheduled through the pg-boss events broker ' +\n '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +\n (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),\n );\n failed.push(...prepared.map(({ name }) => name));\n return;\n }\n\n // Through the registered pg-boss driver, which the entry registers for a\n // server whose broker is pg-boss. Naming \\`@geekmidas/events/pgboss\\` here\n // made every bundle with a cron resolve pg-boss, whatever its broker.\n const { EventConnectionFactory } = await import('@geekmidas/events');\n const connection = (await EventConnectionFactory.fromConnectionString(\n url,\n )) as import('@geekmidas/events').EventConnection & { instance?: any };\n const boss = connection.instance!;\n\n // What this app declares now. Anything else under the prefix belonged to a\n // cron since renamed or deleted, and would keep firing at a handler that has\n // gone.\n //\n // The prefix is \\`cron.\\` rather than \\`cron:\\`: pg-boss accepts\n // alphanumerics, underscores, hyphens, periods and slashes in a queue name,\n // and rejects a colon outright.\n const declared = new Set(prepared.map(({ name }) => \\`cron.\\${name}\\`));\n for (const existing of await boss.getSchedules()) {\n if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {\n await boss.unschedule(existing.name);\n logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');\n }\n }\n\n for (const entry of prepared) {\n const queue = \\`cron.\\${entry.name}\\`;\n await boss.createQueue(queue);\n // UTC, so this agrees with the schedule a deploy target would have made.\n await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });\n await boss.work(queue, () => run(entry));\n\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');\n }\n\n running.push({ stop: () => connection.close() });\n connections.push(connection);\n logger.info({ count: prepared.length }, 'Crons scheduled');\n}\n\n/** The crons that cannot be scheduled, and the connection that schedules the rest. */\nexport function cronsStatus(): {\n failed: string[];\n connections: import('@geekmidas/events').EventConnection[];\n} {\n return { failed: [...failed], connections: [...connections] };\n}\n\n/**\n * Stop scheduling, let a firing in flight finish, and close the broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopCrons(): Promise<void> {\n const open = [...running];\n running.length = 0;\n connections.length = 0;\n await Promise.all(open.map((r) => r.stop()));\n}\n`;\n\n\t\tawait writeFile(cronsPath, content);\n\n\t\treturn cronsPath;\n\t}\n\n\tprivate async generateCronHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSScheduledFunction(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Queue } from '@geekmidas/constructs/queue';\nimport { provideKey } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport type { QueueInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\n/**\n * Generates the runtime for queue consumers (`worker.queue(…)`).\n *\n * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that\n * polls each queue in-process, alongside the Hono server, through the queue's\n * own connection string — pg-boss by default, SQS on the AWS emulator.\n * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed\n * by an SQS event-source mapping.\n */\nexport class QueueGenerator extends ConstructGenerator<\n\tQueue<any, any, any, any, any, any>,\n\tQueueInfo[]\n> {\n\tisConstruct(value: any): value is Queue<any, any, any, any, any, any> {\n\t\treturn Queue.isQueue(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<QueueInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst queueInfos: QueueInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// Generate queues.ts for in-process polling (even if empty, so the\n\t\t\t// server entry can always import setupQueues).\n\t\t\tawait this.generateServerQueuesFile(outputDir, constructs);\n\t\t\tlogger.log(\n\t\t\t\t`Generated server queues file with ${constructs.length} queues (polling mode)`,\n\t\t\t);\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tconst queuesDir = join(outputDir, 'queues');\n\t\tawait mkdir(queuesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateQueueHandler(\n\t\t\t\tqueuesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tqueueInfos.push({\n\t\t\t\tname: construct.name,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tbatchSize: construct.batchSize,\n\t\t\t\tfifo: construct.fifo,\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated queue handler: ${key}`);\n\t\t}\n\n\t\treturn queueInfos;\n\t}\n\n\tprivate async generateQueueHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\t\tconst importPath = relative(dirname(handlerPath), sourceFile).replace(\n\t\t\t/\\.ts$/,\n\t\t\t'.js',\n\t\t);\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaQueue(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerQueuesFile(\n\t\toutputDir: string,\n\t\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst queuesPath = join(outputDir, 'queues.ts');\n\n\t\t// Nothing to poll, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (queues.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tqueuesPath,\n\t\t\t\t`/**\n * Generated queues setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupQueues(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function queuesStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopQueues(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn queuesPath;\n\t\t}\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of queues) {\n\t\t\tconst importPath = relative(dirname(queuesPath), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each queue's consumer reaches its own queue, by the queue's own key.\n\t\tconst entries = queues\n\t\t\t.map(\n\t\t\t\t({ key, construct }) =>\n\t\t\t\t\t` { queue: ${key}, connectionKey: '${provideKey(\n\t\t\t\t\t\tconstruct.id,\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)}' },`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst content = `/**\n * Generated queue consumers setup.\n *\n * Each queue's one consumer polls its own queue, through the queue's own\n * connection string — the one its producers publish on. SQS cannot push, so\n * this is a poller on every transport: pg-boss locally by default, the SQS\n * queue on the AWS emulator.\n *\n * Deployed on Lambda, a queue's consumer is an SQS event source instead.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst queues = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\nexport async function setupQueues(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n for (const { queue, connectionKey } of queues) {\n const connectionString = process.env[connectionKey];\n if (!connectionString) {\n logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');\n failed.push(queue.name);\n continue;\n }\n\n try {\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n const eventSubscriber = await Subscriber.fromConnection(connection);\n const services = queue.services.length > 0\n ? await serviceDiscovery.register(queue.services)\n : {};\n // The queue's database — the worker's, or its own — handed over as \\`db\\`.\n const db = queue.databaseService\n ? (await serviceDiscovery.register([queue.databaseService]))[\n queue.databaseService.serviceName\n ]\n : undefined;\n\n // A queue's messages carry one type — its own name.\n await eventSubscriber.subscribe([queue.name], async (message) => {\n try {\n const validation = await queue.messageSchema['~standard'].validate(message.payload);\n if (validation.issues) {\n logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');\n return;\n }\n\n await queue.handler({\n messages: [validation.value],\n services: services,\n logger: queue.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');\n // Rethrown so the transport keeps the message for a retry.\n throw error;\n }\n });\n logger.info({ queue: queue.name }, 'Queue consumer started polling');\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');\n failed.push(queue.name);\n }\n }\n}\n\n/** The consumers that could not start, and the connections that did. */\nexport function queuesStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the messages in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopQueues(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(queuesPath, content);\n\t\treturn queuesPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Cron } from '@geekmidas/constructs/crons';\nimport type { Queue } from '@geekmidas/constructs/queue';\nimport type { Subscriber } from '@geekmidas/constructs/subscribers';\nimport type { BuildContext } from '../build/types';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport { CronGenerator } from './CronGenerator';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport type { GeneratedConstruct } from './Generator';\nimport { QueueGenerator } from './QueueGenerator';\nimport { SubscriberGenerator } from './SubscriberGenerator';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * A worker whose topic subscribers would have to be pushed to over HTTP.\n *\n * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's\n * process serves nothing but its health check. A server target's broker is\n * pg-boss, where each subscriber polls a queue of its own, so this is only\n * reached by building server images for a project that deploys to AWS — where\n * a subscriber is a Lambda instead.\n */\nexport class WorkerSubscribersNeedPush extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly subscribers: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs topic subscribers (${subscribers.join(', ')}), ` +\n\t\t\t\t`and this build's broker is SNS, which pushes each event to its ` +\n\t\t\t\t`subscriber over HTTP. A worker image serves only its health check. ` +\n\t\t\t\t`Deploy to a server target, whose broker is pg-boss and whose ` +\n\t\t\t\t`subscribers poll, or to AWS, where each subscriber is a Lambda.`,\n\t\t);\n\t\tthis.name = 'WorkerSubscribersNeedPush';\n\t}\n}\n\n/** Where a worker's generated entry lives, under an app's `.gkm/server`. */\nexport function workerEntryDir(serverDir: string, workerId: string): string {\n\treturn join(serverDir, 'workers', appKey(workerId));\n}\n\n/** The file a worker's bundle is written to, beside the server's. */\nexport function workerBundleName(workerId: string): string {\n\treturn `worker-${appKey(workerId)}.mjs`;\n}\n\nexport interface WorkerEntryInput {\n\tcontext: BuildContext;\n\t/** The worker's construct id, `Jobs`. */\n\tworkerId: string;\n\t/** The worker's own directory — see `workerEntryDir`. */\n\toutputDir: string;\n\t/** Everything built from this worker, and nothing built from another. */\n\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[];\n\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[];\n\tsubscribers: GeneratedConstruct<\n\t\tSubscriber<any, any, any, any, any, any, any>\n\t>[];\n\t/** What its process starts OpenTelemetry with — none without an edge. */\n\ttelemetry?: TelemetryContext;\n}\n\n/**\n * A Worker's production entry: the process that runs its crons, its queue\n * consumers and its topic subscribers, and answers nothing but a health check.\n *\n * It is the server's runtime without the server. The `crons.ts`, `queues.ts`\n * and `subscribers.ts` it starts are the files `gkm dev` starts — written by\n * the same generators, given only this worker's constructs — so a consumer\n * runs the same code in development and in the image. What it adds is the\n * process around them: drivers, a health check that says when a consumer or\n * the broker is down, and a shutdown that drains.\n */\nexport class WorkerGenerator {\n\tconstructor(\n\t\tprivate readonly generators = {\n\t\t\tcron: new CronGenerator(),\n\t\t\tqueue: new QueueGenerator(),\n\t\t\tsubscriber: new SubscriberGenerator(),\n\t\t},\n\t) {}\n\n\t/** Write the worker's files; returns its entry, `worker.ts`. */\n\tasync build(input: WorkerEntryInput): Promise<string> {\n\t\tconst { context, workerId, outputDir } = input;\n\n\t\tif (\n\t\t\tinput.subscribers.length > 0 &&\n\t\t\tcontext.eventsBackends?.includes('sns')\n\t\t) {\n\t\t\tthrow new WorkerSubscribersNeedPush(\n\t\t\t\tworkerId,\n\t\t\t\tinput.subscribers.map(({ key }) => key),\n\t\t\t);\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst options = { target: 'server' as const };\n\t\tawait Promise.all([\n\t\t\tthis.generators.cron.build(context, input.crons, outputDir, options),\n\t\t\tthis.generators.queue.build(context, input.queues, outputDir, options),\n\t\t\tthis.generators.subscriber.build(\n\t\t\t\tcontext,\n\t\t\t\tinput.subscribers,\n\t\t\t\toutputDir,\n\t\t\t\toptions,\n\t\t\t),\n\t\t]);\n\n\t\tawait writeFile(\n\t\t\tjoin(outputDir, 'app.ts'),\n\t\t\tworkerApp(context, workerId, outputDir),\n\t\t);\n\t\t// The worker's own edge decides, not the app's that carries it.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst entry = join(outputDir, 'worker.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\tworkerEntry(context.production?.healthCheck ?? '/health'),\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * `app.ts`: the worker's runtime — its logger and environment parser off the\n * Worker construct, the drivers its target needs, and a `startWorker` that\n * starts every cron, consumer and subscriber it owns.\n */\nfunction workerApp(\n\tcontext: BuildContext,\n\tworkerId: string,\n\toutputDir: string,\n): string {\n\tconst runtime = runtimeFor(context, outputDir, workerId);\n\n\treturn `/**\n * Generated worker runtime for ${workerId}.\n * Generated by 'gkm build --production'.\n */\nimport { setupCrons, cronsStatus, stopCrons } from './crons.js';\nimport { setupQueues, queuesStatus, stopQueues } from './queues.js';\nimport { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n// Who this worker is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};\n\nexport { logger };\n\n/** What the health check answers, and why. */\nexport interface WorkerHealth {\n healthy: boolean;\n /** The crons, queues and subscribers that could not start. */\n failed: string[];\n /** How many broker connections did not answer. */\n down: number;\n}\n\n/** Whether one broker connection answers: open, and — on pg-boss — a query. */\nasync function answers(connection: unknown): Promise<boolean> {\n const c = connection as {\n isConnected?: () => boolean;\n instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };\n };\n if (c.isConnected && !c.isConnected()) return false;\n const db = c.instance?.getDb?.();\n if (!db) return true;\n try {\n await Promise.race([\n db.executeSql('select 1'),\n new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A request to a route this worker mounted, and what it answered. */\nexport interface WorkerRequest {\n headers: Record<string, string | string[] | undefined>;\n body: string;\n /** The request's query — Mailpit's webhook carries its token there. */\n query?: URLSearchParams;\n}\nexport interface WorkerAnswer {\n status: number;\n body: unknown;\n}\n\n// The routes something pushes to: an SNS subscriber's, and the one a local\n// object store posts a bucket's events to. Mounted by the subscribers, served\n// by the entry's HTTP server beside the health check.\nconst routes = new Map<string, (c: any) => unknown>();\nconst app = {\n post: (path: string, handler: (c: any) => unknown) => {\n routes.set(path, handler);\n },\n};\n\n/** Run one mounted route, as the subscribers' handlers expect to be called. */\nasync function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {\n const handler = routes.get(path);\n if (!handler) return undefined;\n let answer: WorkerAnswer | undefined;\n const c = {\n req: {\n text: async () => request.body,\n query: (name: string) => request.query?.get(name) ?? undefined,\n header: (name: string) => {\n const value = request.headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n },\n },\n json: (body: unknown, status = 200) => {\n answer = { status, body };\n return answer;\n },\n };\n await handler(c);\n return answer ?? { status: 204, body: null };\n}\n\n/** Start everything this worker runs. */\nexport async function startWorker(): Promise<{\n health: () => Promise<WorkerHealth>;\n stop: () => Promise<void>;\n route: typeof route;\n /** Subscribe the pushed routes, once the server answers on \\`port\\`. */\n subscribeForPush: (port: number) => Promise<void>;\n}> {\n const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue consumers');\n });\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];\n\n return {\n route,\n subscribeForPush,\n async health() {\n const all = statuses();\n const failed = all.flatMap((s) => s.failed);\n const alive = await Promise.all(\n all.flatMap((s) => s.connections as unknown[]).map(answers),\n );\n const down = alive.filter((ok) => !ok).length;\n return { healthy: failed.length === 0 && down === 0, failed, down };\n },\n // Each stops pulling, waits for what it has in flight, and closes its\n // broker connection. Together, so one slow handler does not hold the\n // others' connections open.\n async stop() {\n await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);\n },\n };\n}\n`;\n}\n\n/**\n * `worker.ts`: the process. Health first, so the container answers while the\n * consumers connect; then the worker; then a shutdown that drains.\n */\nfunction workerEntry(healthCheck: string): string {\n\treturn `#!/usr/bin/env node\n/**\n * Production worker entry point.\n * Generated by 'gkm build --production'.\n *\n * Runs this worker's crons, queue consumers and topic subscribers, and serves\n * its health check: ${healthCheck}, on PORT — 200 when every consumer started\n * and every broker connection answers, 503 otherwise. Beside it, on the same\n * port, the POST routes its subscribers mounted: where a local object store\n * posts a bucket's events.\n *\n * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers\n * in flight finish, closes its broker connections and database pools, and\n * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's\n * 10s stop timeout).\n */\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\n\n${startTelemetryCode([healthCheck])}\nconst { startWorker, logger } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nlet worker: Awaited<ReturnType<typeof startWorker>> | undefined;\nlet stopping = false;\n\nconst server = createServer((req, res) => {\n // Parsed once: the path routes, the query goes to the route.\n const url = new URL(req.url ?? '/', 'http://localhost');\n const path = url.pathname;\n const answer = (status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json' });\n res.end(JSON.stringify(body));\n };\n\n // A route a subscriber mounted: what SNS pushes to, or what a local object\n // store posts a bucket's events to. Refused while starting or stopping, so\n // the sender keeps the message and sends it again.\n if (req.method === 'POST') {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk) => {\n body += chunk;\n });\n req.on('end', () => {\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(\n (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),\n (error) => {\n logger.error({ err: error, path }, 'Route failed');\n answer(500, { status: 'failed' });\n },\n );\n });\n return;\n }\n\n if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {\n res.writeHead(404).end();\n return;\n }\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.health().then(\n (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),\n (error) => answer(503, { status: 'unhealthy', error: String(error) }),\n );\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n\n // Nothing new is pulled or scheduled; what is in flight finishes.\n await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));\n // Then what the handlers used: database pools.\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n server.close();\n logger.info('Worker stopped');\n process.exit(0);\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nworker = await startWorker();\nlogger.info({ port }, 'Worker started');\nawait worker.subscribeForPush(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n});\n`;\n}\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport {\n\ttype ConstructManifest,\n\tIMAGE_ORIGINS_KEY,\n\timageOriginSources,\n\tPUBLIC_PREFIX,\n\tprovideKey,\n\tpublicEnvFor,\n} from '@geekmidas/manifest';\nimport {\n\ttype ProcessorUnit,\n\tprocessorUnits,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadWorkspaceConfig } from '../config';\nimport { GkmError } from '../errors';\nimport { processorBundleName } from '../generators/ProcessorGenerator.js';\nimport { workerBundleName } from '../generators/WorkerGenerator.js';\nimport { output } from '../output';\nimport { dockerfileOf } from '../reconcile/apps.js';\nimport { COMPOSE_PATH } from '../reconcile/index.js';\nimport { reconcileWorkspace } from '../reconcile/workspace.js';\nimport { run } from '../run';\nimport { getPublicUrlArgNames } from '../target/dokploy/domain.js';\nimport { siteClientTelemetry } from '../telemetry/edges.js';\nimport type { CacheBackend, GkmConfig } from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport { validateImageRef } from './imageRef';\nimport { appImageOptions, type ImageLayout, imageLayout } from './layout';\nimport {\n\tgenerateBackendDockerfile,\n\tgenerateDockerignore,\n\tgenerateEntryDockerfile,\n\tgenerateNextjsDockerfile,\n\tgenerateNodeWebDockerfile,\n\tgenerateProcessorDockerfile,\n\tgenerateViteStaticDockerfile,\n\tgenerateWorkerDockerfile,\n\tPROCESSOR_PORT,\n\tresolveDockerConfig,\n\tWORKER_PORT,\n} from './templates';\n\nexport { ImageRefInvalid, validateImageRef } from './imageRef';\nexport {\n\tappImageOptions,\n\tcomposeBuildPaths,\n\tfromBuildRoot,\n\ttype ImageLayout,\n\timageLayout,\n\tMonorepoNeedsTurbo,\n} from './layout';\nexport {\n\tdetectPackageManager,\n\tfindBuildRoot,\n\tfindLockfilePath,\n\thasTurboConfig,\n\tisMonorepo,\n} from './templates';\n\n// Through `output`, so a deploy run that generates a Dockerfile hears it.\nconst logger = output;\n\n/** `docker build` failed; what docker printed above says why. */\nexport class DockerBuildFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerBuildFailed';\n\t}\n}\n\n/** `docker push` failed — usually the registry login or its permissions. */\nexport class DockerPushFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerPushFailed';\n\t}\n}\n\n/** `gkm docker --push` was asked for with nowhere to push to. */\nexport class PushNeedsRegistry extends GkmError {\n\tconstructor(readonly imageName: string) {\n\t\tsuper(\n\t\t\t`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`,\n\t\t);\n\t\tthis.name = 'PushNeedsRegistry';\n\t}\n}\n\nexport interface DockerOptions {\n\t/** Build each app's image after generating files */\n\tbuild?: boolean;\n\t/** Push the images to the registry after building */\n\tpush?: boolean;\n\t/** Image tag (default: 'latest') */\n\ttag?: string;\n\t/** Container registry URL */\n\tregistry?: string;\n\t/**\n\t * The directory to generate for — an app's own, when a deploy builds it.\n\t * Defaults to the process's working directory.\n\t */\n\tcwd?: string;\n\t/**\n\t * The stage the images are for: a site's clients trace at its sample\n\t * rate. The local stage when absent.\n\t */\n\tstage?: string;\n}\n\n/**\n * Docker command implementation: one Dockerfile per deployable app, each\n * building its image inside Docker from a turbo-pruned slice of the build\n * root — nothing is built on the host — plus the build root's\n * `.dockerignore` and `docker-compose.constructs.yml`.\n */\nexport async function dockerCommand(\n\toptions: DockerOptions,\n): Promise<WorkspaceDockerResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst loaded = await loadWorkspaceConfig(cwd);\n\n\t// A single-app config is a workspace of one app at its root; the image is\n\t// named the way its `docker` block says.\n\tconst names: Record<string, string> =\n\t\tloaded.type === 'single'\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.keys(loaded.workspace.apps).map((name) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tresolveDockerConfig(loaded.raw as GkmConfig).imageName,\n\t\t\t\t\t]),\n\t\t\t\t)\n\t\t\t: {};\n\n\tconst result = await workspaceDockerCommand(\n\t\tloaded.workspace,\n\t\tloaded.manifest,\n\t\tnames,\n\t\tloaded.background,\n\t\toptions.stage,\n\t);\n\n\tif (options.build) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait buildDockerImage(app, result.buildRoot, options);\n\t\t}\n\t}\n\tif (options.push) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait pushDockerImage(app.imageName, options, result.buildRoot);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Build one app's image, from the build root.\n * Uses BuildKit for cache mount support\n */\nasync function buildDockerImage(\n\tapp: AppDockerResult,\n\tbuildRoot: string,\n\toptions: DockerOptions,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\t// Before anything runs: a ref docker would misread is refused by name.\n\tconst fullImageName = validateImageRef(\n\t\tregistry\n\t\t\t? `${registry}/${app.imageName}:${tag}`\n\t\t\t: `${app.imageName}:${tag}`,\n\t);\n\n\tlogger.log(`\\n🐳 Building Docker image: ${fullImageName}`);\n\n\ttry {\n\t\t// An argument array, so nothing in the ref is read by a shell, and\n\t\t// `--tag=` so it cannot be read as a flag.\n\t\tawait run(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'build',\n\t\t\t\t`--file=${relative(buildRoot, app.dockerfile)}`,\n\t\t\t\t`--tag=${fullImageName}`,\n\t\t\t\t'.',\n\t\t\t],\n\t\t\t{\n\t\t\t\tcwd: buildRoot,\n\t\t\t\t// BuildKit, for the templates' `RUN --mount=type=cache`.\n\t\t\t\tenv: { ...process.env, DOCKER_BUILDKIT: '1' },\n\t\t\t},\n\t\t);\n\t\tlogger.log(`✅ Docker image built: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerBuildFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Push Docker image to registry\n */\nasync function pushDockerImage(\n\timageName: string,\n\toptions: DockerOptions,\n\tcwd: string,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\tif (!registry) {\n\t\tthrow new PushNeedsRegistry(imageName);\n\t}\n\n\tconst fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);\n\n\tlogger.log(`\\n🚀 Pushing Docker image: ${fullImageName}`);\n\n\ttry {\n\t\tawait run('docker', ['push', fullImageName], { cwd });\n\t\tlogger.log(`✅ Docker image pushed: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerPushFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Result of generating Docker files for a single app in a workspace.\n */\nexport interface AppDockerResult {\n\tappName: string;\n\ttype: 'backend' | 'web' | 'mobile';\n\t/** The Dockerfile, absolute. */\n\tdockerfile: string;\n\timageName: string;\n}\n\n/**\n * Result of workspace docker command.\n */\nexport interface WorkspaceDockerResult {\n\tapps: AppDockerResult[];\n\tdockerCompose: string;\n\tdockerignore: string;\n\t/** Every image's build context, absolute. */\n\tbuildRoot: string;\n}\n\n/**\n * Generate Dockerfiles for all apps in a workspace.\n * @internal Exported for testing\n */\nexport async function workspaceDockerCommand(\n\tworkspace: NormalizedWorkspace,\n\t/** What the workspace declares — where a site's public keys come from. */\n\tmanifest?: ConstructManifest,\n\t/** Image names other than the app's own. */\n\timageNames: Readonly<Record<string, string>> = {},\n\t/** Each Worker's files, from discovery — which app each is built from. */\n\tbackground: Readonly<Record<string, readonly string[]>> = {},\n\t/** The stage a site's clients trace at the rate of — local when absent. */\n\tstage?: string,\n): Promise<WorkspaceDockerResult> {\n\tconst results: AppDockerResult[] = [];\n\tconst layout = imageLayout(workspace);\n\n\tlogger.log(`\\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);\n\tlogger.log(` Build root: ${layout.buildRoot}`);\n\tlogger.log(\n\t\t` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ''}, turbo@${layout.tools.turboVersion}`,\n\t);\n\n\tfor (const [appName, app] of Object.entries(workspace.apps)) {\n\t\t// Mobile apps deploy via their own toolchain (e.g. EAS Build for Expo)\n\t\t// — no Docker image is produced.\n\t\tif (app.type === 'mobile') {\n\t\t\tlogger.log(\n\t\t\t\t`\\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst buildType = app.entry ? 'entry' : app.type;\n\t\tlogger.log(`\\n 📄 Generating Dockerfile for ${appName} (${buildType})`);\n\n\t\tconst dockerfile = appDockerfile(appName, app, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tapps: workspace.apps,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t\tworkspace,\n\t\t\t...(stage ? { stage } : {}),\n\t\t});\n\n\t\tconst path = dockerfileOf(appName, app.path);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName,\n\t\t\ttype: app.type,\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[appName] ?? appName,\n\t\t});\n\t}\n\n\t// Each Worker with background work: an image of its own, built from the\n\t// app whose build writes its entry.\n\tfor (const worker of manifest\n\t\t? workerUnits(workspace, manifest, background)\n\t\t: []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`,\n\t\t);\n\t\tconst dockerfile = workerDockerfile(worker, workspace.apps[worker.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\t// Always named for the worker: an app at the root has the bare\n\t\t// `Dockerfile`, which this must not overwrite.\n\t\tconst path = workerDockerfileOf(worker.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: worker.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[worker.name] ?? worker.name,\n\t\t});\n\t}\n\n\t// Each file server's processors: an image of their own, built from the\n\t// app whose build writes their entry.\n\tfor (const unit of manifest ? processorUnits(workspace, manifest) : []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`,\n\t\t);\n\t\tconst dockerfile = processorDockerfile(unit, workspace.apps[unit.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\tconst path = workerDockerfileOf(unit.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: unit.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[unit.name] ?? unit.name,\n\t\t});\n\t}\n\n\tconst dockerignorePath = await ensureDockerignore(layout.buildRoot);\n\tlogger.log(`\\n Ensured: ${dockerignorePath}`);\n\n\tconst composePath = await writeConstructsCompose(workspace);\n\n\t// Summary\n\tlogger.log(\n\t\t`\\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`,\n\t);\n\tlogger.log(`\\n📋 Build commands (from ${layout.buildRoot}):`);\n\tfor (const result of results) {\n\t\tconst icon =\n\t\t\tresult.type === 'backend' ? '⚙️' : result.type === 'mobile' ? '📱' : '🌐';\n\t\tlogger.log(\n\t\t\t` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`,\n\t\t);\n\t}\n\tprintRunInstructions(workspace);\n\n\treturn {\n\t\tapps: results,\n\t\tdockerCompose: composePath,\n\t\tdockerignore: dockerignorePath,\n\t\tbuildRoot: layout.buildRoot,\n\t};\n}\n\n/**\n * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,\n * a backend with its own entry bundled by esbuild, or a site by its\n * framework. The one choice every builder of images makes.\n */\nexport function appDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/**\n\t\t * Every app in the workspace, so a site's image knows the backends whose\n\t\t * clients it generates.\n\t\t */\n\t\tapps?: Readonly<Record<string, NormalizedAppConfig>>;\n\t\tmanifest?: ConstructManifest;\n\t\t/** The workspace's stages and `deploy.telemetry`, for a site's clients. */\n\t\tworkspace?: Pick<NormalizedWorkspace, 'stages' | 'deploy'>;\n\t\t/** A site's public keys, when the caller resolved them itself. */\n\t\tpublicUrlArgs?: string[];\n\t\t/**\n\t\t * The cache backend a gkm backend's entry registers, where it is not the\n\t\t * deploy target's — the compose stack's own Redis.\n\t\t */\n\t\tcache?: CacheBackend;\n\t\t/**\n\t\t * The stage whose sample rate a site's clients trace at — the local\n\t\t * stage when absent.\n\t\t */\n\t\tstage?: string;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tappName,\n\t\tapp,\n\t\toptions.workspaceRoot,\n\t\toptions.apps,\n\t\tapp.type === 'web' && options.manifest && options.workspace\n\t\t\t? siteClientTelemetry(\n\t\t\t\t\toptions.manifest,\n\t\t\t\t\tappName,\n\t\t\t\t\toptions.workspace,\n\t\t\t\t\toptions.stage,\n\t\t\t\t)\n\t\t\t: undefined,\n\t);\n\n\tif (app.type === 'web') {\n\t\treturn siteDockerfile(appName, app, {\n\t\t\timage,\n\t\t\t...(options.manifest ? { manifest: options.manifest } : {}),\n\t\t\t...(options.publicUrlArgs\n\t\t\t\t? { publicUrlArgs: options.publicUrlArgs }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\tif (app.entry) {\n\t\treturn generateEntryDockerfile({\n\t\t\t...image,\n\t\t\tentry: app.entry,\n\t\t\thealthCheckPath: '/health',\n\t\t});\n\t}\n\treturn generateBackendDockerfile({\n\t\t...image,\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/** Where `gkm docker` writes a worker's Dockerfile. */\nexport function workerDockerfileOf(worker: string): string {\n\treturn `.gkm/docker/Dockerfile.${worker}`;\n}\n\n/**\n * A Worker's Dockerfile: its host app's build, and the worker's bundle as the\n * runner — see `generateWorkerDockerfile`.\n */\nexport function workerDockerfile(\n\tworker: WorkerUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/** As {@link appDockerfile}'s: the cache backend its entry registers. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tworker.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateWorkerDockerfile({\n\t\t...image,\n\t\timageName: worker.name,\n\t\tport: WORKER_PORT,\n\t\tworker: worker.id,\n\t\tbundle: workerBundleName(worker.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A file server's processor unit's Dockerfile: its host app's build, and the\n * unit's bundle as the runner, with its processors' native packages\n * installed beside it — see `generateProcessorDockerfile`.\n */\nexport function processorDockerfile(\n\tunit: ProcessorUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tunit.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateProcessorDockerfile({\n\t\t...image,\n\t\timageName: unit.name,\n\t\tport: PROCESSOR_PORT,\n\t\tfileServer: unit.id,\n\t\tbundle: processorBundleName(unit.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A site's Dockerfile, with an `ARG` for every key its bundler inlines.\n *\n * The keys come from the site's declaration where there is one — every\n * public key its edges give it, `VITE_UPLOADS_URL` included — and an\n * `ARG` the Dockerfile does not declare is a build argument the build drops,\n * leaving the bundle with an empty URL.\n */\nexport function siteDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\timage: ReturnType<typeof appImageOptions>;\n\t\tmanifest?: ConstructManifest;\n\t\tpublicUrlArgs?: string[];\n\t},\n): string {\n\tconst declared = options.manifest\n\t\t? Object.entries(options.manifest).find(\n\t\t\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t\t\t)?.[1]\n\t\t: undefined;\n\tconst publicUrlArgs =\n\t\toptions.publicUrlArgs ??\n\t\t(declared?.kind === 'site' && options.manifest\n\t\t\t? [\n\t\t\t\t\t// Its own address under its own name, for server code that runs\n\t\t\t\t\t// at build — what `publicBuildValues` hands every image build.\n\t\t\t\t\tprovideKey(declared.id, 'url'),\n\t\t\t\t\t...Object.keys(publicEnvFor(declared, options.manifest)),\n\t\t\t\t\t// The origins its pages load files from, where it has any.\n\t\t\t\t\t...(imageOriginSources(declared, options.manifest).length > 0\n\t\t\t\t\t\t? [`${PUBLIC_PREFIX[declared.variant]}${IMAGE_ORIGINS_KEY}`]\n\t\t\t\t\t\t: []),\n\t\t\t\t]\n\t\t\t: getPublicUrlArgNames(app));\n\n\tconst webOpts = {\n\t\t...options.image,\n\t\tpublicUrlArgs,\n\t\t// Built against its stage's running APIs, so not offline.\n\t\t...(declared?.kind === 'site' && declared.prerender === 'stage'\n\t\t\t? { prerender: true }\n\t\t\t: {}),\n\t};\n\n\tswitch (app.framework) {\n\t\tcase 'vite':\n\t\t\treturn generateViteStaticDockerfile(webOpts);\n\t\tcase 'tanstack-start':\n\t\tcase 'remix':\n\t\t\treturn generateNodeWebDockerfile(webOpts);\n\t\tdefault:\n\t\t\t// nextjs (and any unspecified web framework — schema requires a valid\n\t\t\t// framework, so this is just a default).\n\t\t\treturn generateNextjsDockerfile(webOpts);\n\t}\n}\n\n/**\n * What a build root's `.dockerignore` must leave out of every image's\n * context: dependencies installed for another platform, anything built on the\n * host (every image builds from source), git, and gkm's own output —\n * `.gkm/compose`'s env files hold a stage's secrets.\n */\nconst REQUIRED_IGNORES = [\n\t'**/node_modules',\n\t'.git',\n\t'**/dist',\n\t'**/.next',\n\t'**/.turbo',\n\t'**/.gkm',\n\t'**/.gkm/compose',\n];\n\n/**\n * Make sure the build root's `.dockerignore` leaves out what no image may\n * hold: written whole where there is none, and each missing line appended to\n * one the project keeps.\n */\nexport async function ensureDockerignore(buildRoot: string): Promise<string> {\n\tconst path = join(buildRoot, '.dockerignore');\n\tif (!existsSync(path)) {\n\t\tawait writeFile(path, generateDockerignore());\n\t\treturn path;\n\t}\n\n\tconst current = await readFile(path, 'utf-8');\n\tconst lines = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n\tconst missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));\n\tif (missing.length === 0) return path;\n\n\tawait appendFile(\n\t\tpath,\n\t\t`${current.endsWith('\\n') || current === '' ? '' : '\\n'}\\n# gkm: images build from source, and a stack's env files hold its secrets\\n${missing.join('\\n')}\\n`,\n\t);\n\treturn path;\n}\n\n/**\n * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with\n * the apps beside the containers their constructs derive.\n *\n * Through reconcile rather than a second generator, so what `gkm docker`\n * describes and what `gkm dev` runs cannot disagree. Nothing is started.\n */\nasync function writeConstructsCompose(\n\tworkspace: NormalizedWorkspace,\n): Promise<string> {\n\tawait reconcileWorkspace(workspace, {\n\t\tstage: workspace.stages.local,\n\t\tstart: false,\n\t});\n\tlogger.log(` Generated: ${COMPOSE_PATH} (project root)`);\n\treturn join(workspace.root, COMPOSE_PATH);\n}\n\nfunction printRunInstructions(workspace: NormalizedWorkspace): void {\n\tconst project = existsSync(join(workspace.root, 'docker-compose.yml'))\n\t\t? ' -f docker-compose.yml'\n\t\t: '';\n\tlogger.log('\\n📋 Run everything (the apps sit behind the \"apps\" profile):');\n\tlogger.log(\n\t\t' gkm setup # starts the containers and creates what they hold',\n\t);\n\tlogger.log(\n\t\t` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,mBAAmB;AACzB,MAAM,SAAS,GAAG,iBAAiB,QAAQ,iBAAiB;AAC5D,MAAM,iBAAiB;AAKvB,MAAM,YAAY,IAAI,OACrB,OAAO,OAAO,KAAK,eAAe,MAAM,eAAe,uGACxD;;AAGA,MAAM,kBAAkB;;AAGxB,IAAa,kBAAb,cAAqCA,eAAAA,SAAS;CACxB;CAArB,YAAY,KAAsB;EACjC,MACC,IAAI,IAAI,0QACT;EAHoB,KAAA,MAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,iBAAiB,KAAqB;CACrD,MAAM,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,QAAQ,iBAAiB,EAAE;CAC3D,IAAI,CAAC,UAAU,KAAK,GAAG,KAAK,KAAK,SAAS,iBACzC,MAAM,IAAI,gBAAgB,GAAG;CAE9B,OAAO;AACR;;;;ACnBA,SAAgB,kBACf,WACA,cACS;CACT,QAAA,GAAOC,UAAAA,KAAAA,CAAK,WAAW,cAAcC,aAAAA,kBAAkB,YAAY,CAAC;AACrE;;AAGA,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