@geekmidas/cli 10.0.0-alpha.17 → 10.0.0-alpha.171
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/README.md +323 -380
- package/bin/adjacent-tsconfig.mjs +46 -8
- package/bin/gkm.mjs +11 -3
- package/bin/owning-tsconfig-jsx-register.mjs +18 -0
- package/bin/owning-tsconfig-jsx.mjs +108 -0
- package/dist/EndpointGenerator-C1h_wExz.cjs +1098 -0
- package/dist/EndpointGenerator-C1h_wExz.cjs.map +1 -0
- package/dist/EndpointGenerator-CSKhAD6W.mjs +1039 -0
- package/dist/EndpointGenerator-CSKhAD6W.mjs.map +1 -0
- package/dist/GoDaddyProvider-Cs32wo6I.cjs +412 -0
- package/dist/GoDaddyProvider-Cs32wo6I.cjs.map +1 -0
- package/dist/GoDaddyProvider-D7CTqN0f.mjs +412 -0
- package/dist/GoDaddyProvider-D7CTqN0f.mjs.map +1 -0
- package/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-B_3Qs9mT.mjs} +23 -9
- package/dist/HostingerProvider-B_3Qs9mT.mjs.map +1 -0
- package/dist/{HostingerProvider-BZFGYYVA.cjs → HostingerProvider-D0515Stf.cjs} +23 -9
- package/dist/HostingerProvider-D0515Stf.cjs.map +1 -0
- package/dist/LegacyStateStore-Bv_2L86H.cjs +124 -0
- package/dist/LegacyStateStore-Bv_2L86H.cjs.map +1 -0
- package/dist/LegacyStateStore-CUjKKENQ.mjs +124 -0
- package/dist/LegacyStateStore-CUjKKENQ.mjs.map +1 -0
- package/dist/LocalStateStore-DXuj1BDq.mjs +167 -0
- package/dist/LocalStateStore-DXuj1BDq.mjs.map +1 -0
- package/dist/LocalStateStore-PQ2qJ5VF.cjs +178 -0
- package/dist/LocalStateStore-PQ2qJ5VF.cjs.map +1 -0
- package/dist/OpenApiTsGenerator-5xPn-p65.mjs +534 -0
- package/dist/OpenApiTsGenerator-5xPn-p65.mjs.map +1 -0
- package/dist/OpenApiTsGenerator-CzrLGzC0.cjs +539 -0
- package/dist/OpenApiTsGenerator-CzrLGzC0.cjs.map +1 -0
- package/dist/{Route53Provider-Cvj40A8I.mjs → Route53Provider-Di_SD9CF.mjs} +3 -3
- package/dist/Route53Provider-Di_SD9CF.mjs.map +1 -0
- package/dist/{Route53Provider-DVILBsvV.cjs → Route53Provider-emLuQHVw.cjs} +3 -3
- package/dist/Route53Provider-emLuQHVw.cjs.map +1 -0
- package/dist/S3StateStore-BGnOwqUp.mjs +223 -0
- package/dist/S3StateStore-BGnOwqUp.mjs.map +1 -0
- package/dist/S3StateStore-cmS6iUZn.cjs +222 -0
- package/dist/S3StateStore-cmS6iUZn.cjs.map +1 -0
- package/dist/SSMStateStore-BqXzPBbu.mjs +205 -0
- package/dist/SSMStateStore-BqXzPBbu.mjs.map +1 -0
- package/dist/SSMStateStore-BtNGbg8Z.cjs +204 -0
- package/dist/SSMStateStore-BtNGbg8Z.cjs.map +1 -0
- package/dist/SubscriberGenerator-CfZWX0lT.mjs +783 -0
- package/dist/SubscriberGenerator-CfZWX0lT.mjs.map +1 -0
- package/dist/SubscriberGenerator-DMi4siph.cjs +848 -0
- package/dist/SubscriberGenerator-DMi4siph.cjs.map +1 -0
- package/dist/add-DW2KLCY0.mjs +711 -0
- package/dist/add-DW2KLCY0.mjs.map +1 -0
- package/dist/add-Dp5xRn-u.cjs +713 -0
- package/dist/add-Dp5xRn-u.cjs.map +1 -0
- package/dist/appPorts-BoXMwolc.mjs +249 -0
- package/dist/appPorts-BoXMwolc.mjs.map +1 -0
- package/dist/appPorts-IW-OZmRi.cjs +296 -0
- package/dist/appPorts-IW-OZmRi.cjs.map +1 -0
- package/dist/apps-DYGKg5SP.cjs +5535 -0
- package/dist/apps-DYGKg5SP.cjs.map +1 -0
- package/dist/apps-DrXwv-0A.mjs +4986 -0
- package/dist/apps-DrXwv-0A.mjs.map +1 -0
- package/dist/aws-C5LAU_Ii.mjs +97 -0
- package/dist/aws-C5LAU_Ii.mjs.map +1 -0
- package/dist/aws-DKC2m3sT.cjs +108 -0
- package/dist/aws-DKC2m3sT.cjs.map +1 -0
- package/dist/awsStore-Bx5nCFnS.mjs +121 -0
- package/dist/awsStore-Bx5nCFnS.mjs.map +1 -0
- package/dist/awsStore-u3ehhMoY.cjs +138 -0
- package/dist/awsStore-u3ehhMoY.cjs.map +1 -0
- package/dist/{backup-provisioner-DIVCbfee.mjs → backup-provisioner-C8DnCmxK.mjs} +2 -2
- package/dist/backup-provisioner-C8DnCmxK.mjs.map +1 -0
- package/dist/{backup-provisioner-BmhIO_Yr.cjs → backup-provisioner-oDEsPj02.cjs} +2 -2
- package/dist/backup-provisioner-oDEsPj02.cjs.map +1 -0
- package/dist/backups/runner.cjs +519 -0
- package/dist/backups/runner.cjs.map +1 -0
- package/dist/backups/runner.d.cts +102 -0
- package/dist/backups/runner.d.cts.map +1 -0
- package/dist/backups/runner.d.mts +102 -0
- package/dist/backups/runner.d.mts.map +1 -0
- package/dist/backups/runner.mjs +506 -0
- package/dist/backups/runner.mjs.map +1 -0
- package/dist/{bundler-mjqGAvu1.cjs → bundler-BIfEe05e.cjs} +59 -14
- package/dist/bundler-BIfEe05e.cjs.map +1 -0
- package/dist/{bundler-mwH7WOb1.mjs → bundler-Swt8wHG9.mjs} +59 -14
- package/dist/bundler-Swt8wHG9.mjs.map +1 -0
- package/dist/cli-C9wdKQy_.mjs +80 -0
- package/dist/cli-C9wdKQy_.mjs.map +1 -0
- package/dist/cli-ohJToj0E.cjs +80 -0
- package/dist/cli-ohJToj0E.cjs.map +1 -0
- package/dist/compose-BLOnkeaJ.mjs +2432 -0
- package/dist/compose-BLOnkeaJ.mjs.map +1 -0
- package/dist/compose-Br3SQ2bW.cjs +3293 -0
- package/dist/compose-Br3SQ2bW.cjs.map +1 -0
- package/dist/compose-SNYBstbO.cjs +2929 -0
- package/dist/compose-SNYBstbO.cjs.map +1 -0
- package/dist/compose-iUOeazjW.mjs +3192 -0
- package/dist/compose-iUOeazjW.mjs.map +1 -0
- package/dist/config-CsCYzlVO.d.mts +291 -0
- package/dist/config-CsCYzlVO.d.mts.map +1 -0
- package/dist/config-D-gHQXhi.d.cts +291 -0
- package/dist/config-D-gHQXhi.d.cts.map +1 -0
- package/dist/config.cjs +457 -9
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +4 -117
- package/dist/config.d.mts +4 -117
- package/dist/config.mjs +441 -3
- package/dist/config.mjs.map +1 -0
- package/dist/credentialSchemas-BzJiK1nQ.mjs +236 -0
- package/dist/credentialSchemas-BzJiK1nQ.mjs.map +1 -0
- package/dist/credentialSchemas-OVXofU-r.cjs +271 -0
- package/dist/credentialSchemas-OVXofU-r.cjs.map +1 -0
- package/dist/credentials-BdZhygvW.cjs +2293 -0
- package/dist/credentials-BdZhygvW.cjs.map +1 -0
- package/dist/credentials-C2VfI-uf.mjs +1838 -0
- package/dist/credentials-C2VfI-uf.mjs.map +1 -0
- package/dist/databases-CuTL1e7s.cjs +703 -0
- package/dist/databases-CuTL1e7s.cjs.map +1 -0
- package/dist/databases-zN-gEox0.mjs +588 -0
- package/dist/databases-zN-gEox0.mjs.map +1 -0
- package/dist/define-6poNqm5O.mjs +106 -0
- package/dist/define-6poNqm5O.mjs.map +1 -0
- package/dist/define-crmMcXFS.cjs +153 -0
- package/dist/define-crmMcXFS.cjs.map +1 -0
- package/dist/deploy/public.cjs +211 -0
- package/dist/deploy/public.cjs.map +1 -0
- package/dist/deploy/public.d.cts +658 -0
- package/dist/deploy/public.d.cts.map +1 -0
- package/dist/deploy/public.d.mts +658 -0
- package/dist/deploy/public.d.mts.map +1 -0
- package/dist/deploy/public.mjs +144 -0
- package/dist/deploy/public.mjs.map +1 -0
- package/dist/deploy/sniffer-envparser-worker.cjs +54 -0
- package/dist/deploy/sniffer-envparser-worker.cjs.map +1 -0
- package/dist/deploy/sniffer-envparser-worker.d.cts +1 -0
- package/dist/deploy/sniffer-envparser-worker.d.mts +1 -0
- package/dist/deploy/sniffer-envparser-worker.mjs +55 -0
- package/dist/deploy/sniffer-envparser-worker.mjs.map +1 -0
- package/dist/deploy/sniffer-hooks.cjs +1 -1
- package/dist/deploy/sniffer-hooks.mjs +1 -1
- package/dist/deploy/sniffer-loader.cjs +2 -2
- package/dist/deploy/sniffer-loader.mjs +1 -1
- package/dist/deploy/sniffer-routes-worker.cjs +2 -2
- package/dist/deploy/sniffer-routes-worker.mjs +1 -1
- package/dist/deploy-CYyf-Q8N.cjs +3902 -0
- package/dist/deploy-CYyf-Q8N.cjs.map +1 -0
- package/dist/deploy-DqH8QReb.mjs +3846 -0
- package/dist/deploy-DqH8QReb.mjs.map +1 -0
- package/dist/destroy-B9myEYFT.mjs +788 -0
- package/dist/destroy-B9myEYFT.mjs.map +1 -0
- package/dist/destroy-Bp5iHtLf.cjs +789 -0
- package/dist/destroy-Bp5iHtLf.cjs.map +1 -0
- package/dist/discover-39VKSE2i.cjs +1085 -0
- package/dist/discover-39VKSE2i.cjs.map +1 -0
- package/dist/discover-B_PDDaVj.mjs +940 -0
- package/dist/discover-B_PDDaVj.mjs.map +1 -0
- package/dist/docker-BezTRGxN.cjs +1520 -0
- package/dist/docker-BezTRGxN.cjs.map +1 -0
- package/dist/docker-De_-Ll-A.mjs +1413 -0
- package/dist/docker-De_-Ll-A.mjs.map +1 -0
- package/dist/dokploy-CWCIqro_.cjs +38 -0
- package/dist/dokploy-CWCIqro_.cjs.map +1 -0
- package/dist/dokploy-EsBgWO8W.mjs +38 -0
- package/dist/dokploy-EsBgWO8W.mjs.map +1 -0
- package/dist/drivers-BhdC9Efj.cjs +248 -0
- package/dist/drivers-BhdC9Efj.cjs.map +1 -0
- package/dist/drivers-wcDnzf7l.mjs +213 -0
- package/dist/drivers-wcDnzf7l.mjs.map +1 -0
- package/dist/eas-8t6PJRni.cjs +337 -0
- package/dist/eas-8t6PJRni.cjs.map +1 -0
- package/dist/eas-BalvsiH5.mjs +334 -0
- package/dist/eas-BalvsiH5.mjs.map +1 -0
- package/dist/emit-C4KSXOeS.mjs +153 -0
- package/dist/emit-C4KSXOeS.mjs.map +1 -0
- package/dist/emit-DiW0kbue.cjs +164 -0
- package/dist/emit-DiW0kbue.cjs.map +1 -0
- package/dist/encryption-B4mWxt4G.mjs +89 -0
- package/dist/encryption-B4mWxt4G.mjs.map +1 -0
- package/dist/encryption-CKBmU66R.cjs +90 -0
- package/dist/encryption-CKBmU66R.cjs.map +1 -0
- package/dist/engine-BTG46RG-.cjs +3329 -0
- package/dist/engine-BTG46RG-.cjs.map +1 -0
- package/dist/engine-y8iWIXuv.mjs +3216 -0
- package/dist/engine-y8iWIXuv.mjs.map +1 -0
- package/dist/errors-D8Gwp5kU.mjs +23 -0
- package/dist/errors-D8Gwp5kU.mjs.map +1 -0
- package/dist/errors-DMC4Umsb.cjs +34 -0
- package/dist/errors-DMC4Umsb.cjs.map +1 -0
- package/dist/github-CeXlzWWA.cjs +978 -0
- package/dist/github-CeXlzWWA.cjs.map +1 -0
- package/dist/github-DvGoKoQO.mjs +977 -0
- package/dist/github-DvGoKoQO.mjs.map +1 -0
- package/dist/googlePlay-CfzG7jOJ.cjs +931 -0
- package/dist/googlePlay-CfzG7jOJ.cjs.map +1 -0
- package/dist/googlePlay-DWv6CUgM.mjs +931 -0
- package/dist/googlePlay-DWv6CUgM.mjs.map +1 -0
- package/dist/iam-BE0qX5Lb.mjs +442 -0
- package/dist/iam-BE0qX5Lb.mjs.map +1 -0
- package/dist/iam-FA95ku7l.cjs +521 -0
- package/dist/iam-FA95ku7l.cjs.map +1 -0
- package/dist/{index-RCUizGxL.d.cts → index-QxGYzGEN.d.mts} +38 -14
- package/dist/index-QxGYzGEN.d.mts.map +1 -0
- package/dist/{index-B4H4XF7A.d.mts → index-tFzoro1V.d.cts} +38 -14
- package/dist/index-tFzoro1V.d.cts.map +1 -0
- package/dist/index.cjs +15142 -13470
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +14959 -13285
- package/dist/index.mjs.map +1 -1
- package/dist/local-CvRvfktv.mjs +224 -0
- package/dist/local-CvRvfktv.mjs.map +1 -0
- package/dist/local-DH9at_0c.cjs +241 -0
- package/dist/local-DH9at_0c.cjs.map +1 -0
- package/dist/migrate-B1lHo2K2.cjs +272 -0
- package/dist/migrate-B1lHo2K2.cjs.map +1 -0
- package/dist/migrate-D1iCmQgc.mjs +267 -0
- package/dist/migrate-D1iCmQgc.mjs.map +1 -0
- package/dist/migrate-DzOWCnRR.cjs +181 -0
- package/dist/migrate-DzOWCnRR.cjs.map +1 -0
- package/dist/migrate-NmW2Su8s.mjs +181 -0
- package/dist/migrate-NmW2Su8s.mjs.map +1 -0
- 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-BdIY7IoB.mjs +409 -0
- package/dist/notes-BdIY7IoB.mjs.map +1 -0
- package/dist/notes-ikElBCC8.cjs +510 -0
- package/dist/notes-ikElBCC8.cjs.map +1 -0
- package/dist/openapi.cjs +213 -7
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +32 -8
- package/dist/openapi.d.cts.map +1 -1
- package/dist/openapi.d.mts +32 -8
- package/dist/openapi.d.mts.map +1 -1
- package/dist/openapi.mjs +208 -2
- package/dist/openapi.mjs.map +1 -0
- package/dist/projectBucket-C-FOIic4.mjs +222 -0
- package/dist/projectBucket-C-FOIic4.mjs.map +1 -0
- package/dist/projectBucket-uidxz03Q.cjs +263 -0
- package/dist/projectBucket-uidxz03Q.cjs.map +1 -0
- package/dist/provider-BqpjG9QM.cjs +57 -0
- package/dist/provider-BqpjG9QM.cjs.map +1 -0
- package/dist/provider-CEOKk8NS.mjs +46 -0
- package/dist/provider-CEOKk8NS.mjs.map +1 -0
- package/dist/publish-Ujng6o63.mjs +123 -0
- package/dist/publish-Ujng6o63.mjs.map +1 -0
- package/dist/publish-oO_8elIf.cjs +124 -0
- package/dist/publish-oO_8elIf.cjs.map +1 -0
- package/dist/ready-COJHr1Yi.mjs +375 -0
- package/dist/ready-COJHr1Yi.mjs.map +1 -0
- package/dist/ready-DcD0SCnV.cjs +404 -0
- package/dist/ready-DcD0SCnV.cjs.map +1 -0
- package/dist/reconcile/public.cjs +3 -5
- package/dist/reconcile/public.d.cts +33 -89
- package/dist/reconcile/public.d.cts.map +1 -1
- package/dist/reconcile/public.d.mts +33 -89
- package/dist/reconcile/public.d.mts.map +1 -1
- package/dist/reconcile/public.mjs +3 -3
- package/dist/reconcile--I7V4Klj.mjs +34 -0
- package/dist/reconcile--I7V4Klj.mjs.map +1 -0
- package/dist/reconcile-CuCQBa5-.cjs +34 -0
- package/dist/reconcile-CuCQBa5-.cjs.map +1 -0
- package/dist/resolve-CTb1gsTO.cjs +316 -0
- package/dist/resolve-CTb1gsTO.cjs.map +1 -0
- package/dist/resolve-Lk7fd8Kb.mjs +263 -0
- package/dist/resolve-Lk7fd8Kb.mjs.map +1 -0
- package/dist/rollback-B2DhSX-I.mjs +136 -0
- package/dist/rollback-B2DhSX-I.mjs.map +1 -0
- package/dist/rollback-PK4pSOLd.cjs +165 -0
- package/dist/rollback-PK4pSOLd.cjs.map +1 -0
- package/dist/runtime-BpGIXfYr.d.mts +82 -0
- package/dist/runtime-BpGIXfYr.d.mts.map +1 -0
- package/dist/runtime-DLV0CNZ4.d.cts +82 -0
- package/dist/runtime-DLV0CNZ4.d.cts.map +1 -0
- package/dist/s3-BY5ry__M.mjs +240 -0
- package/dist/s3-BY5ry__M.mjs.map +1 -0
- package/dist/s3-FG9qIgEB.cjs +240 -0
- package/dist/s3-FG9qIgEB.cjs.map +1 -0
- package/dist/sandbox/config-worker.cjs +43 -0
- package/dist/sandbox/config-worker.cjs.map +1 -0
- package/dist/sandbox/config-worker.d.cts +1 -0
- package/dist/sandbox/config-worker.d.mts +1 -0
- package/dist/sandbox/config-worker.mjs +44 -0
- package/dist/sandbox/config-worker.mjs.map +1 -0
- package/dist/sandbox/credentials-worker.cjs +53 -0
- package/dist/sandbox/credentials-worker.cjs.map +1 -0
- package/dist/sandbox/credentials-worker.d.cts +1 -0
- package/dist/sandbox/credentials-worker.d.mts +1 -0
- package/dist/sandbox/credentials-worker.mjs +54 -0
- package/dist/sandbox/credentials-worker.mjs.map +1 -0
- package/dist/sandbox/discover-worker.cjs +47 -0
- package/dist/sandbox/discover-worker.cjs.map +1 -0
- package/dist/sandbox/discover-worker.d.cts +1 -0
- package/dist/sandbox/discover-worker.d.mts +1 -0
- package/dist/sandbox/discover-worker.mjs +48 -0
- package/dist/sandbox/discover-worker.mjs.map +1 -0
- package/dist/sandbox/migrate-worker.cjs +75 -0
- package/dist/sandbox/migrate-worker.cjs.map +1 -0
- package/dist/sandbox/migrate-worker.d.cts +1 -0
- package/dist/sandbox/migrate-worker.d.mts +1 -0
- package/dist/sandbox/migrate-worker.mjs +76 -0
- package/dist/sandbox/migrate-worker.mjs.map +1 -0
- package/dist/{workspace-B8NLb54N.cjs → schemas-BCwKKA42.mjs} +399 -1173
- package/dist/schemas-BCwKKA42.mjs.map +1 -0
- package/dist/{workspace-DI-M3BnN.mjs → schemas-BQ_v0lEX.cjs} +487 -982
- package/dist/schemas-BQ_v0lEX.cjs.map +1 -0
- package/dist/secretsManager-CJyxFcBH.mjs +113 -0
- package/dist/secretsManager-CJyxFcBH.mjs.map +1 -0
- package/dist/secretsManager-D8on44WI.cjs +124 -0
- package/dist/secretsManager-D8on44WI.cjs.map +1 -0
- package/dist/seeds-Bc3niNVb.cjs +382 -0
- package/dist/seeds-Bc3niNVb.cjs.map +1 -0
- package/dist/seeds-Ccn0Ru2T.mjs +299 -0
- package/dist/seeds-Ccn0Ru2T.mjs.map +1 -0
- package/dist/serverSetup-BL1sHzRr.mjs +685 -0
- package/dist/serverSetup-BL1sHzRr.mjs.map +1 -0
- package/dist/serverSetup-C7fDKGiN.cjs +685 -0
- package/dist/serverSetup-C7fDKGiN.cjs.map +1 -0
- package/dist/sniffer-BvhDRsgI.mjs +1824 -0
- package/dist/sniffer-BvhDRsgI.mjs.map +1 -0
- package/dist/sniffer-DJp9a2Pg.cjs +1997 -0
- package/dist/sniffer-DJp9a2Pg.cjs.map +1 -0
- package/dist/snsSubscriptions-7y2XBXde.mjs +1053 -0
- package/dist/snsSubscriptions-7y2XBXde.mjs.map +1 -0
- package/dist/snsSubscriptions-8t1XFvoc.cjs +1184 -0
- package/dist/snsSubscriptions-8t1XFvoc.cjs.map +1 -0
- package/dist/sst-8HZe83-M.cjs +501 -0
- package/dist/sst-8HZe83-M.cjs.map +1 -0
- package/dist/sst-CzFd-1om.mjs +478 -0
- package/dist/sst-CzFd-1om.mjs.map +1 -0
- package/dist/stack-3tvhk7SU.cjs +2568 -0
- package/dist/stack-3tvhk7SU.cjs.map +1 -0
- package/dist/stack-j2e8ddGl.mjs +2381 -0
- package/dist/stack-j2e8ddGl.mjs.map +1 -0
- package/dist/stage-DCSJii_y.cjs +313 -0
- package/dist/stage-DCSJii_y.cjs.map +1 -0
- package/dist/stage-DMv-IfSD.mjs +302 -0
- package/dist/stage-DMv-IfSD.mjs.map +1 -0
- package/dist/stages-CCAAe1tP.mjs +190 -0
- package/dist/stages-CCAAe1tP.mjs.map +1 -0
- package/dist/stages-D49CUpBY.cjs +190 -0
- package/dist/stages-D49CUpBY.cjs.map +1 -0
- package/dist/target/public.cjs +15 -0
- package/dist/target/public.d.cts +28 -0
- package/dist/target/public.d.cts.map +1 -0
- package/dist/target/public.d.mts +28 -0
- package/dist/target/public.d.mts.map +1 -0
- package/dist/target/public.mjs +4 -0
- package/dist/terminal-DIEj2Nap.cjs +85 -0
- package/dist/terminal-DIEj2Nap.cjs.map +1 -0
- package/dist/terminal-VLmWgL_N.mjs +85 -0
- package/dist/terminal-VLmWgL_N.mjs.map +1 -0
- package/dist/{types-N7c2O2m7.d.cts → types-Bj1A1wkS.d.mts} +2146 -428
- package/dist/types-Bj1A1wkS.d.mts.map +1 -0
- package/dist/types-Bl_CwZC9.cjs +90 -0
- package/dist/types-Bl_CwZC9.cjs.map +1 -0
- package/dist/{types-7R81hu0i.d.mts → types-CV4AzwC_.d.cts} +2148 -428
- package/dist/types-CV4AzwC_.d.cts.map +1 -0
- package/dist/types-Y1NfWlyG.mjs +61 -0
- package/dist/types-Y1NfWlyG.mjs.map +1 -0
- package/dist/utils-D2Nk1Nv2.cjs +205 -0
- package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
- package/dist/utils-D_fxUqvU.mjs +156 -0
- package/dist/utils-D_fxUqvU.mjs.map +1 -0
- package/dist/vitest.cjs +65 -0
- package/dist/vitest.cjs.map +1 -0
- package/dist/vitest.d.cts +29 -0
- package/dist/vitest.d.cts.map +1 -0
- package/dist/vitest.d.mts +29 -0
- package/dist/vitest.d.mts.map +1 -0
- package/dist/vitest.mjs +65 -0
- package/dist/vitest.mjs.map +1 -0
- package/dist/workerRuntime-BXfhbe13.cjs +108 -0
- package/dist/workerRuntime-BXfhbe13.cjs.map +1 -0
- package/dist/workerRuntime-CsOyBRx2.mjs +79 -0
- package/dist/workerRuntime-CsOyBRx2.mjs.map +1 -0
- package/dist/workspace/index.cjs +6 -2
- package/dist/workspace/index.d.cts +3 -3
- package/dist/workspace/index.d.mts +3 -3
- package/dist/workspace/index.mjs +2 -2
- package/dist/workspace-B0PI9k9p.mjs +3013 -0
- package/dist/workspace-B0PI9k9p.mjs.map +1 -0
- package/dist/workspace-LR9DFjU8.cjs +3563 -0
- package/dist/workspace-LR9DFjU8.cjs.map +1 -0
- package/package.json +75 -13
- package/dist/HostingerProvider-BY26bWwB.mjs.map +0 -1
- package/dist/HostingerProvider-BZFGYYVA.cjs.map +0 -1
- package/dist/LocalStateProvider-7HR6SS2t.cjs +0 -48
- package/dist/LocalStateProvider-7HR6SS2t.cjs.map +0 -1
- package/dist/LocalStateProvider-D7QyJoLM.mjs +0 -48
- package/dist/LocalStateProvider-D7QyJoLM.mjs.map +0 -1
- package/dist/Route53Provider-Cvj40A8I.mjs.map +0 -1
- package/dist/Route53Provider-DVILBsvV.cjs.map +0 -1
- package/dist/SSMStateProvider-B0Hu1MKZ.mjs +0 -75
- package/dist/SSMStateProvider-B0Hu1MKZ.mjs.map +0 -1
- package/dist/SSMStateProvider-VrQ-yeqd.cjs +0 -74
- package/dist/SSMStateProvider-VrQ-yeqd.cjs.map +0 -1
- package/dist/backup-provisioner-BmhIO_Yr.cjs.map +0 -1
- package/dist/backup-provisioner-DIVCbfee.mjs.map +0 -1
- package/dist/bundler-mjqGAvu1.cjs.map +0 -1
- package/dist/bundler-mwH7WOb1.mjs.map +0 -1
- package/dist/config-CdTMeMU_.cjs +0 -467
- package/dist/config-CdTMeMU_.cjs.map +0 -1
- package/dist/config-DPnPkWyH.mjs +0 -414
- package/dist/config-DPnPkWyH.mjs.map +0 -1
- package/dist/config.d.cts.map +0 -1
- package/dist/config.d.mts.map +0 -1
- package/dist/credentials-fJP5-fa1.mjs +0 -2780
- package/dist/credentials-fJP5-fa1.mjs.map +0 -1
- package/dist/credentials-tvyReUAd.cjs +0 -2917
- package/dist/credentials-tvyReUAd.cjs.map +0 -1
- package/dist/discover-BERGFg8v.cjs +0 -288
- package/dist/discover-BERGFg8v.cjs.map +0 -1
- package/dist/discover-CK-n3w6b.mjs +0 -244
- package/dist/discover-CK-n3w6b.mjs.map +0 -1
- package/dist/emit-BdoPFjZf.cjs +0 -253
- package/dist/emit-BdoPFjZf.cjs.map +0 -1
- package/dist/emit-Bzq7JsMP.mjs +0 -224
- package/dist/emit-Bzq7JsMP.mjs.map +0 -1
- package/dist/generator-LfZU7NlU.mjs +0 -247
- package/dist/generator-LfZU7NlU.mjs.map +0 -1
- package/dist/generator-Wdfp0jCS.cjs +0 -282
- package/dist/generator-Wdfp0jCS.cjs.map +0 -1
- package/dist/github-CAfKyYPN.mjs +0 -216
- package/dist/github-CAfKyYPN.mjs.map +0 -1
- package/dist/github-DVE8Gg_F.cjs +0 -216
- package/dist/github-DVE8Gg_F.cjs.map +0 -1
- package/dist/index-B4H4XF7A.d.mts.map +0 -1
- package/dist/index-RCUizGxL.d.cts.map +0 -1
- package/dist/openapi-BeckoaP9.cjs +0 -2038
- package/dist/openapi-BeckoaP9.cjs.map +0 -1
- package/dist/openapi-DolhBm6r.mjs +0 -1991
- package/dist/openapi-DolhBm6r.mjs.map +0 -1
- package/dist/reconcile-Cq4cO83R.cjs +0 -136
- package/dist/reconcile-Cq4cO83R.cjs.map +0 -1
- package/dist/reconcile-fmoluZmZ.mjs +0 -113
- package/dist/reconcile-fmoluZmZ.mjs.map +0 -1
- package/dist/ssm-BKN1Cg4z.mjs +0 -60
- package/dist/ssm-BKN1Cg4z.mjs.map +0 -1
- package/dist/ssm-FxeSAt35.cjs +0 -60
- package/dist/ssm-FxeSAt35.cjs.map +0 -1
- package/dist/storage-DgypfSD6.cjs +0 -351
- package/dist/storage-DgypfSD6.cjs.map +0 -1
- package/dist/storage-TP0x118M.mjs +0 -304
- package/dist/storage-TP0x118M.mjs.map +0 -1
- package/dist/transfer-4A4S2hcw.mjs +0 -122
- package/dist/transfer-4A4S2hcw.mjs.map +0 -1
- package/dist/transfer-DdmtKLzi.cjs +0 -151
- package/dist/transfer-DdmtKLzi.cjs.map +0 -1
- package/dist/types-7R81hu0i.d.mts.map +0 -1
- package/dist/types-N7c2O2m7.d.cts.map +0 -1
- package/dist/workspace-B8NLb54N.cjs.map +0 -1
- package/dist/workspace-DI-M3BnN.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps-DrXwv-0A.mjs","names":["hostFor","connect"],"sources":["../src/providers/dns.ts","../src/backups/config.ts","../src/reconcile/signedOrigins.ts","../src/reconcile/env.ts","../src/providers/s3/lifecycle.ts","../src/reconcile/provision.ts","../src/backups/service.ts","../src/build/workers.ts","../src/compose/siteBuild.ts","../src/exec/imageBuild.ts","../src/docker/templates.ts","../src/docker/layout.ts","../src/providers/processorOrigin.ts","../src/secrets/stackKeys.ts","../src/trust/authority.ts","../src/reconcile/clients.ts","../src/reconcile/docker.ts","../src/reconcile/lan.ts","../src/reconcile/logins.ts","../src/reconcile/ports.ts","../src/reconcile/state.ts","../src/reconcile/index.ts","../src/reconcile/workspace.ts","../src/reconcile/apps.ts"],"sourcesContent":["/**\n * What the deploy's DNS step needs to know about a workspace before its\n * stack is run: whether it deploys with compose.\n *\n * The step itself is `stageDns` in `compose/dns.ts`, run by every deploy\n * (`gkm deploy`, and `gkm compose`, the same run) where the deploy runs — a\n * CI runner or a developer's machine, which hold the DNS provider's token.\n * The server never does.\n */\n\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/** Whether the workspace deploys through the compose target. */\nexport function deploysWithCompose(workspace: NormalizedWorkspace): boolean {\n\treturn (\n\t\tworkspace.deploy?.default === 'compose' ||\n\t\tObject.values(workspace.apps).some(\n\t\t\t(app) => app.resolvedDeployTarget === 'compose',\n\t\t)\n\t);\n}\n","/**\n * Which stages take backups, and where they are kept.\n *\n * A deployed compose stage whose stack runs Postgres is backed up by\n * default — every day at 02:00 UTC, kept 30 days — unless\n * `deploy.backups.<stage>` says otherwise. The local stage never is.\n *\n * Every backup is kept in the project bucket (`providers/projectBucket.ts`),\n * beside the stage's deploy state, one folder per run and one file per\n * database:\n *\n * ```\n * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/database.sql.gz\n * gkm/<project>/<stage>/backups/2026-10-10/02-00-00Z/auth-database.sql.gz\n * ```\n *\n * Beside the runs, `imports/` holds files prepared by hand for\n * `gkm backup:restore --from` — never listed as a run, never expired.\n *\n * The file is named after the database's construct, the way its migrations\n * folder is: `AuthDatabase` is `db/auth-database`, and `auth-database.sql.gz`.\n */\n\nimport { type ConstructManifest, kebabCase } from '@geekmidas/manifest';\nimport { deploysWithCompose } from '../providers/dns.js';\nimport type { PrefixExpiry } from '../providers/projectBucket.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { checkStageBackups, type StageBackups } from './schedule.js';\n\n/** What a stage's backups come to. */\nexport type StageBackupsChoice =\n\t| {\n\t\t\tmode: 'on';\n\t\t\tbackups: StageBackups;\n\t\t\t/** Whether the stage named it, or took the default. */\n\t\t\tsource: 'config' | 'default';\n\t }\n\t/** `deploy.backups.<stage>: false`. */\n\t| { mode: 'disabled' }\n\t/** Nothing to back up, or nowhere it applies. */\n\t| { mode: 'none'; reason: 'local' | 'not-compose' | 'no-postgres' };\n\n/** The workspace parts {@link stageBackups} reads. */\nexport type BackupsWorkspace = Pick<\n\tNormalizedWorkspace,\n\t'name' | 'apps' | 'deploy' | 'stages' | 'state'\n>;\n\n/** Whether the stack runs Postgres: some construct is a database. */\nexport function runsPostgres(manifest: ConstructManifest): boolean {\n\treturn Object.values(manifest).some((d) => d.kind === 'database');\n}\n\n/**\n * What `stage`'s backups are: on — by its entry or the default — off by\n * `false`, or none, for the local stage, a stage compose does not deploy,\n * and a stack with no database.\n */\nexport function stageBackups(\n\tworkspace: BackupsWorkspace,\n\tmanifest: ConstructManifest,\n\tstage: string,\n): StageBackupsChoice {\n\tif (stage === workspace.stages?.local) {\n\t\treturn { mode: 'none', reason: 'local' };\n\t}\n\tif (!deploysWithCompose(workspace as NormalizedWorkspace)) {\n\t\treturn { mode: 'none', reason: 'not-compose' };\n\t}\n\tif (!runsPostgres(manifest)) return { mode: 'none', reason: 'no-postgres' };\n\tconst value = (\n\t\tworkspace.deploy?.backups as Record<string, unknown> | undefined\n\t)?.[stage];\n\tconst checked = checkStageBackups(stage, value ?? {});\n\tif (checked === false) return { mode: 'disabled' };\n\treturn {\n\t\tmode: 'on',\n\t\tbackups: checked,\n\t\tsource: value === undefined ? 'default' : 'config',\n\t};\n}\n\n/**\n * Where a stage's backups are, in the project bucket — under the same\n * `<prefix>/<project>/<stage>` its deploy state is: `gkm/shop/production/backups`.\n */\nexport function backupsPrefix(\n\tworkspace: Pick<NormalizedWorkspace, 'name' | 'state'>,\n\tstage: string,\n): string {\n\tconst state = workspace.state;\n\tconst prefix =\n\t\tstate?.provider === 's3' && state.prefix !== undefined\n\t\t\t? state.prefix.replace(/\\/+$/, '')\n\t\t\t: 'gkm';\n\treturn `${prefix ? `${prefix}/` : ''}${workspace.name}/${stage}/backups`;\n}\n\n/**\n * What every run folder's key starts with, under the stage's backups prefix:\n * the first digit of its year. What the expiry rule matches — `imports/`\n * does not.\n */\nexport const RUNS_PREFIX = '2';\n\n/** One run's folder: `2026-10-10/02-00-00Z`, for the time it started. */\nexport function runFolder(at: Date): string {\n\tconst iso = at.toISOString();\n\treturn `${iso.slice(0, 10)}/${iso.slice(11, 19).replace(/:/g, '-')}Z`;\n}\n\n/** A run folder's time back, or `undefined` for a key that is not one. */\nexport function runTime(folder: string): Date | undefined {\n\tconst match = /^(\\d{4}-\\d{2}-\\d{2})\\/(\\d{2})-(\\d{2})-(\\d{2})Z$/.exec(folder);\n\tif (!match) return undefined;\n\tconst at = new Date(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);\n\treturn Number.isNaN(at.getTime()) ? undefined : at;\n}\n\n/** One database the stack backs up. */\nexport interface BackupDatabase {\n\t/** Its construct: `AuthDatabase`. */\n\tid: string;\n\t/** Its file in a run's folder, less `.sql.gz`: `auth-database`. */\n\tfile: string;\n\t/** Its name in the stack's Postgres: `auth_database_production`. */\n\tname: string;\n}\n\n/** A database's file in a run's folder: `auth-database.sql.gz`. */\nexport function backupFile(database: Pick<BackupDatabase, 'file'>): string {\n\treturn `${database.file}.sql.gz`;\n}\n\n/** Each database the stack runs, by its construct and its name in Postgres. */\nexport function backupDatabases(\n\tresources: readonly { id: string; kind: string; name: string }[],\n): BackupDatabase[] {\n\treturn resources\n\t\t.filter((r) => r.kind === 'database')\n\t\t.map((r) => ({ id: r.id, file: kebabCase(r.id), name: r.name }))\n\t\t.sort((a, b) => a.file.localeCompare(b.file));\n}\n\n/**\n * The expiry of every stage's backups, by each stage's own entry — what the\n * project bucket's lifecycle carries beside its own rule.\n *\n * A put replaces a bucket's whole lifecycle, so this is built from every\n * deployed stage each time, never from the stage being deployed alone: one\n * stage's deploy keeps every other's rule. A stage set to `false` has none,\n * and its backups are kept until someone deletes them.\n *\n * The rule covers the runs and nothing else beside them: a lifecycle filter\n * cannot leave a folder out, so it matches what every run folder starts\n * with — its year, `2…` — and the stage's `imports/` is never expired.\n */\nexport function backupExpiries(\n\tworkspace: BackupsWorkspace,\n\tmanifest: ConstructManifest,\n): PrefixExpiry[] {\n\tconst expiries: PrefixExpiry[] = [];\n\tfor (const stage of [...(workspace.stages?.deployed ?? [])].sort()) {\n\t\tconst choice = stageBackups(workspace, manifest, stage);\n\t\tif (choice.mode !== 'on') continue;\n\t\texpiries.push({\n\t\t\tid: `gkm-backups-${stage}`,\n\t\t\tprefix: `${backupsPrefix(workspace, stage)}/${RUNS_PREFIX}`,\n\t\t\tdays: choice.backups.keepDays,\n\t\t\tabortIncompleteDays: 1,\n\t\t});\n\t}\n\treturn expiries;\n}\n","/**\n * Where each bucket's presigned links point, derived from its connection.\n *\n * Not stored and not provisioned: the origin is a function of the connection\n * string (`s3Url.signedOrigin`), so it is computed wherever the connection is\n * resolved — a stage's secrets, MinIO locally — and can never disagree with\n * the links the bucket's client signs.\n */\n\nimport { providedKeyFor } from '@geekmidas/manifest';\nimport * as s3Url from '@geekmidas/storage/s3-url';\n\n/**\n * `<ID>_SIGNED_ORIGIN` for each bucket whose connection `lookup` resolves to\n * an `s3://` URL with a knowable host. A bucket with none, or another scheme,\n * gets nothing rather than a guess.\n */\nexport function signedOrigins(\n\tbuckets: Iterable<string>,\n\tlookup: (key: string) => string | undefined,\n): Record<string, string> {\n\tconst origins: Record<string, string> = {};\n\tfor (const id of buckets) {\n\t\tconst connection = lookup(\n\t\t\tprovidedKeyFor(id, 'objects', 'connectionString'),\n\t\t);\n\t\tif (!connection?.startsWith('s3:')) continue;\n\t\tlet origin: string | undefined;\n\t\ttry {\n\t\t\torigin = s3Url.signedOrigin(s3Url.parse(connection));\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (origin) origins[providedKeyFor(id, 'objects', 'signedOrigin')] = origin;\n\t}\n\treturn origins;\n}\n","/**\n * The URLs a reconciled stage injects.\n *\n * One `<NAME>_URL` per construct, and the protocol picks the driver. This is the\n * seam between the target that writes a URL and the client that parses it, so\n * every component of it is read off the resource — never inherited from ambient\n * environment. A bucket can live in a different region than the function reading\n * it, and `AWS_REGION` in a Lambda is the *function's* region, so a URL that\n * omits `?region=` breaks cross-region silently at runtime.\n *\n * Locally that self-containment is what lets the port be whatever was free: the\n * app reads `ORDERS_URL` and never sees a host or a port.\n */\n\nimport { createHash } from 'node:crypto';\nimport { formatKeyring } from '@geekmidas/constructs/encryption';\nimport { ownerRole, readerRole } from '@geekmidas/db/pg/roles';\nimport * as snsUrl from '@geekmidas/events/sns/url';\nimport * as sqsUrl from '@geekmidas/events/sqs/url';\nimport {\n\tcacheTable,\n\tcookieDomain,\n\tdrawSecret,\n\tEDGE_TOKEN_KEY,\n\texternalApiUrl,\n\timageOrigins,\n\tmobileOrigins,\n\tprovidedKeyFor,\n\tschemeBase,\n\tsenderAddress,\n\twildcardDomainOf,\n} from '@geekmidas/manifest';\nimport { LOGS_ORG, otlpHeaders } from '../compose/logs.js';\nimport { GkmError } from '../errors';\nimport { telemetryEnv } from '../telemetry/config.js';\nimport { hostFor, hostsFor } from './caddyfile';\nimport { primaryPortKey } from './containers';\nimport {\n\tEMULATOR_REGION,\n\temulatorEndpoint,\n\temulatorQueueUrl,\n\temulatorTopicArn,\n} from './emulator';\nimport { INBOX_RELAY_TOKEN_KEY, inboxRelayToken } from './inboxRelay';\nimport type { ContainerCredentials } from './localCredentials';\nimport { objectsWebhookToken } from './objectEvents';\nimport { PgBossNeedsDatabase, type Plan, type PlannedResource } from './plan';\nimport type { PortAssignments } from './ports';\nimport { signedOrigins } from './signedOrigins';\n\n/** The host containers are published on. */\nconst LOCAL_HOST = 'localhost';\n\n/** The region local buckets claim, so the client has one to sign with. */\nconst LOCAL_REGION = 'us-east-1';\n\n/**\n * The credentials the S3 client resolves for MinIO.\n *\n * An `s3://` URL deliberately carries none: deployed, the SDK reads them from\n * the execution role, so a URL that embedded a key would be one more thing to\n * rotate and one more thing to leak into a log. Locally there is no role, and\n * the same chain reads these — which is why they are injected beside the URL\n * rather than written into it.\n */\nfunction storageCredentials(\n\tcredentials: ContainerCredentials,\n): Record<string, string> {\n\treturn {\n\t\tAWS_ACCESS_KEY_ID: credentials.minio.user,\n\t\tAWS_SECRET_ACCESS_KEY: credentials.minio.password,\n\t\tAWS_REGION: LOCAL_REGION,\n\t};\n}\n\n/** The port Mailpit's inbox — its web UI and HTTP API — is published under. */\nconst MAILPIT_INBOX_PORT = 'mailpit-web';\n\n/** The schema pg-boss keeps its tables in, inside the declared database. */\nconst PGBOSS_SCHEMA = 'pgboss';\n\n/** The exchange every local topic and queue shares on RabbitMQ. */\nconst RABBITMQ_EXCHANGE = 'gkm.events';\n\nexport interface EnvOptions {\n\t/** Assigned ports, keyed by port key. */\n\tports: PortAssignments;\n\t/**\n\t * The buckets, by construct id, whose MinIO posts their events to be\n\t * relayed onto the broker — see `objectEvents.ts`. Only these resolve an\n\t * events key and a token: a bucket nothing watches has neither.\n\t */\n\trelayedBuckets?: readonly string[];\n\t/**\n\t * The project, which seeds any secret this stage derives.\n\t *\n\t * Derived rather than random so it survives a restart -- a signing key that\n\t * changed on every `gkm dev` would invalidate every session you were in the\n\t * middle of -- and seeded by the project so two checkouts do not share one.\n\t */\n\tproject?: string;\n\t/**\n\t * Where each address-owning construct answers, keyed by id — surfaces and\n\t * sites, e.g. `{ Api: 'http://localhost:3000', Console: 'http://localhost:5173' }`\n\t * — and a file server a target placed at a host of its own (`gkm compose`'s\n\t * edge).\n\t *\n\t * Not container addresses: `gkm dev` assigns these, which is why they arrive\n\t * here rather than being read off a published port. Keyed by id rather than\n\t * being one `surface` string because there is more than one address in a\n\t * workspace and the difference between them is exactly what CORS is about.\n\t */\n\taddresses?: Readonly<Record<string, string>>;\n\t/**\n\t * The other addresses each construct answers on, keyed by id: its\n\t * `aliases`, as a target placed them (`gkm compose`'s edge). Absent, a\n\t * construct behind the local edge answers its aliases under the project,\n\t * as `hostsFor` names them. A site's are origins every surface it calls\n\t * trusts; its `redirects` are not, since the browser never runs there.\n\t */\n\taliasAddresses?: Readonly<Record<string, readonly string[]>>;\n\t/**\n\t * This machine's address on the local network — what a phone running the\n\t * app reaches it on. Only a local stage has one, and only a project with a\n\t * mobile app reads it: its `exp://` origins, and the address sign-in links\n\t * for the app are built on.\n\t */\n\tlanAddress?: string;\n\t/** Each mobile app's Metro port, by id — the exact port its `exp://` origins name. */\n\tmetroPorts?: Readonly<Record<string, number>>;\n\t/**\n\t * The domain mail is sent from, `localhost` by default. Each mail\n\t * construct sends as its own local part at it (`senderAddress`).\n\t *\n\t * Stage config, exactly as it is deployed — the difference is only that here\n\t * nobody had to verify it.\n\t */\n\tmailDomain?: string;\n\t/**\n\t * The stage's random seed, salting every derived role password.\n\t *\n\t * The local stages' is generated once per machine with their logins; a\n\t * stack that serves a deployed stage passes the seed its store keeps, so\n\t * its passwords are the ones a deploy derives. Either way they are not\n\t * computable from the repo.\n\t */\n\tseed?: string;\n\t/**\n\t * What every container was brought up with — the cluster's superuser,\n\t * MinIO's root, the cache's token, the emulator's key pair.\n\t *\n\t * pg-boss and a `roles: false` database connect as the superuser, so its\n\t * login is in their URLs.\n\t */\n\tcredentials: ContainerCredentials;\n}\n\n/**\n * The credentials a stage's URLs carry: the containers' logins and the seed\n * role passwords are salted with.\n */\ninterface StageCredential {\n\tcontainers: ContainerCredentials;\n\tseed?: string;\n}\n\n/** The credential `options` describe. */\nfunction credentialOf(options: {\n\tseed?: string;\n\tcredentials: ContainerCredentials;\n}): StageCredential {\n\treturn {\n\t\tcontainers: options.credentials,\n\t\t...(options.seed ? { seed: options.seed } : {}),\n\t};\n}\n\n/**\n * What project code run against a stage is handed — a migration, a seed, an\n * app under `gkm dev`, `gkm exec`'s command, `gkm compose`'s seeds: the\n * stage's stored secrets, under every value the stage resolved.\n *\n * One merge for every command, so a seed sees the same keys whichever one\n * runs it. Each command supplies only what is its own — the ports it reaches\n * the containers on, their logins — as inputs to {@link envFor}.\n *\n * The resolved values win: they are the statement of what exists, and a\n * stored URL naming an old port is the drift resolution replaces. A command\n * whose stage says a value by hand (a deployed stack's) leaves that key out\n * of `resolved`.\n */\nexport function stageEnv(\n\tstored: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n): Record<string, string> {\n\treturn { ...stored, ...resolved };\n}\n\n/**\n * The token a stack's own services prove themselves with at its edge\n * (`EDGE_TOKEN_HEADER`): derived from the stage's seed, as a bucket's webhook\n * token is, so every process, the edge and the auth server agree on it with\n * nothing stored.\n */\nexport function edgeToken(project: string, seed?: string): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:edge-token`)\n\t\t.digest('base64url')\n\t\t.slice(0, 43);\n}\n\n/**\n * Every env key a reconciled plan resolves, and its value.\n *\n * Keys come from the declaration rather than being re-derived, so what the build\n * publishes and what the app reads cannot drift.\n */\nexport function envFor(\n\tplan: Plan,\n\toptions: EnvOptions,\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\tconst credential = credentialOf(options);\n\n\t// Resolved once, up front, because a surface's cookie domain and origin list\n\t// are derived from *other constructs'* addresses — and reading them as the\n\t// loop happened to reach them would make the answer depend on the order the\n\t// manifest was keyed in.\n\tconst resolved: Record<string, string> = {};\n\tconst devices = options.lanAddress ? deviceBuckets(plan) : new Set<string>();\n\tfor (const resource of plan.resources) {\n\t\tconst url = urlFor(\n\t\t\tresource,\n\t\t\tplan,\n\t\t\toptions.ports,\n\t\t\toptions.project ?? '',\n\t\t\toptions.addresses,\n\t\t\tcredential,\n\t\t\tdevices.has(resource.id) ? options.lanAddress : undefined,\n\t\t);\n\t\tif (url) resolved[resource.id] = url;\n\t}\n\tconst aliased = aliasAddressesFor(plan, options);\n\n\tfor (const resource of plan.resources) {\n\t\tconst url = resolved[resource.id];\n\n\t\t// A surface carries the origins its callers may come from, and they are\n\t\t// its inbound edges — nothing more. Better Auth's CSRF check applies to\n\t\t// every caller and not only to browsers, so a sibling service calling it\n\t\t// is rejected unless its origin is listed; that this list is now the\n\t\t// graph rather than every app the workspace happens to run is what makes\n\t\t// it the same list deployed, where no workspace is watching.\n\t\tif (resource.kind === 'rest-api') {\n\t\t\tObject.assign(\n\t\t\t\tenv,\n\t\t\t\tsurfaceEnv(resource, url, resolved, {\n\t\t\t\t\tplan,\n\t\t\t\t\taliased,\n\t\t\t\t\t...(options.addresses ? { addresses: options.addresses } : {}),\n\t\t\t\t\t...(options.lanAddress ? { lanAddress: options.lanAddress } : {}),\n\t\t\t\t\t...(options.metroPorts ? { metroPorts: options.metroPorts } : {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tif (resource.kind === 'websocket-api') {\n\t\t\t// Who may open it from a browser, read off its inbound edges as a\n\t\t\t// REST surface's are. A socket carries no cookie scope of its own.\n\t\t\tconst origins = surfaceEnv(resource, url, resolved, { aliased })[\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'trustedOrigins')\n\t\t\t];\n\t\t\tif (origins !== undefined) {\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'trustedOrigins')] =\n\t\t\t\t\torigins;\n\t\t\t}\n\t\t\tconst publisher = webSocketPublisher(\n\t\t\t\tresource,\n\t\t\t\toptions.ports,\n\t\t\t\toptions.project ?? '',\n\t\t\t\tcredential,\n\t\t\t);\n\t\t\tif (publisher) {\n\t\t\t\tenv[\n\t\t\t\t\tprovidedKeyFor(\n\t\t\t\t\t\tresource.id,\n\t\t\t\t\t\tresource.kind,\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)\n\t\t\t\t] = publisher;\n\t\t\t}\n\t\t}\n\t\tif (url) env[resource.envKey] = url;\n\n\t\t// A wildcard site's tenant is the leading label of the host it is\n\t\t// reached on: the domain under its `*` is what that label comes off,\n\t\t// and the protected labels are the ones no tenant can be.\n\t\tif (resource.kind === 'site' && resource.protectedSubdomains && url) {\n\t\t\tconst domain = wildcardDomainOf(new URL(url).hostname);\n\t\t\tif (domain) {\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'domain')] = domain;\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'protectedSubdomains')] =\n\t\t\t\t\tresource.protectedSubdomains.join(',');\n\t\t\t}\n\t\t}\n\n\t\t// A database owns a second key, and it is deliberately not in `provides`:\n\t\t// the owner URL is what a migrator connects with, so no edge in any\n\t\t// manifest can name it and nothing can be granted DDL rights by mistake.\n\t\t// `gkm exec` injects it; a handler never sees it.\n\t\tif (isDatabase(resource.kind) && resource.roles !== false) {\n\t\t\tconst owner = ownerUrl(\n\t\t\t\tresource,\n\t\t\t\tplan,\n\t\t\t\toptions.ports,\n\t\t\t\toptions.project ?? '',\n\t\t\t\tcredential,\n\t\t\t);\n\t\t\tif (owner)\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'ownerUrl')] = owner;\n\t\t}\n\n\t\t// An external API owns a second key. Faked, it is the fake's; otherwise\n\t\t// it is the stage's own, from its secrets like any value it was given.\n\t\tif (resource.kind === 'external-api' && url && resource.fake) {\n\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'credentials')] =\n\t\t\t\tresource.fake.credentials;\n\t\t}\n\n\t\t// A credential resolves nothing (see `urlFor`) — unless the plan was\n\t\t// made with fakes and it has one: then the stage is handed the fake's\n\t\t// value in place of its own, as an external API is handed its fake's.\n\t\tif (\n\t\t\tresource.kind === 'credential' &&\n\t\t\tresource.fakeCredentials !== undefined\n\t\t) {\n\t\t\tenv[resource.envKey] = resource.fakeCredentials;\n\t\t}\n\n\t\t// Telemetry owns the rest of OpenTelemetry's keys: how to sign in to\n\t\t// OpenObserve, and the sampler — every trace, locally. The service's\n\t\t// name is each process's own, so it is not resolved here.\n\t\tif (resource.kind === 'telemetry' && url) {\n\t\t\tconst login = options.credentials.logs;\n\t\t\tObject.assign(\n\t\t\t\tenv,\n\t\t\t\ttelemetryEnv(\n\t\t\t\t\t{ endpoint: url, headers: otlpHeaders(login.email, login.password) },\n\t\t\t\t\t1,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Mail owns a second key. It is the sending identity, which is the one\n\t\t// thing about mail that differs per stage — so it travels with the URL\n\t\t// rather than being written into the construct.\n\t\t// An inbox owns two more. Its domain, as a wildcard site's is locally:\n\t\t// the project's own under `localhost`, with a label for any stage but\n\t\t// the local one — `test.shop.localhost` — so `gkm test` never receives\n\t\t// what `gkm dev` does; a tenant is a label under it, as deployed. And,\n\t\t// locally, where mail is delivered to it: Mailpit's SMTP, which a test\n\t\t// sends through as any sender would.\n\t\tif (resource.kind === 'inbox' && url) {\n\t\t\tconst base = resource.id.toLowerCase();\n\t\t\tconst stage =\n\t\t\t\tresource.name === base\n\t\t\t\t\t? undefined\n\t\t\t\t\t: resource.name.slice(base.length + 1);\n\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'domain')] = [\n\t\t\t\tstage,\n\t\t\t\toptions.project,\n\t\t\t\tLOCAL_HOST,\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join('.');\n\t\t\tconst smtp = options.ports[primaryPortKey('mailpit')];\n\t\t\tif (smtp !== undefined) {\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'smtpUrl')] =\n\t\t\t\t\t`smtp://${LOCAL_HOST}:${smtp}`;\n\t\t\t}\n\t\t}\n\n\t\tif (resource.kind === 'email' && url) {\n\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'from')] = senderAddress(\n\t\t\t\tresource,\n\t\t\t\toptions.mailDomain ?? LOCAL_HOST,\n\t\t\t);\n\n\t\t\t// And, locally, a third: where the mail it sent can be read back.\n\t\t\t// Mailpit answers SMTP on one port and its inbox on another; a feature\n\t\t\t// test signs in by opening the email that was actually sent, and this\n\t\t\t// is how it finds it. Deployed mail has no inbox, so nothing deployed\n\t\t\t// publishes this key.\n\t\t\tconst inbox = options.ports[MAILPIT_INBOX_PORT];\n\t\t\tif (inbox !== undefined) {\n\t\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'inboxUrl')] =\n\t\t\t\t\t`http://${LOCAL_HOST}:${inbox}`;\n\t\t\t}\n\t\t}\n\t}\n\n\t// After the loop, and deliberately: a site's keys are renames of values the\n\t// constructs it depends on resolved, so every source has to exist before any\n\t// of them can be read. Doing it inline would make the result depend on the\n\t// order the manifest happened to be keyed in.\n\tObject.assign(\n\t\tenv,\n\t\tsignedOrigins(\n\t\t\tplan.resources.filter((r) => r.kind === 'objects').map((r) => r.id),\n\t\t\t(key) => env[key],\n\t\t),\n\t);\n\tObject.assign(env, publicEnv(plan, env, options.addresses));\n\n\tObject.assign(env, brokerEnv(plan, options.ports, credential));\n\n\t// A bucket in MinIO has no topic of its own to publish its events to:\n\t// MinIO posts them to the process that runs the bucket's subscribers, which\n\t// relays them onto the one broker — so that broker is where they are\n\t// delivered from, and the token is what MinIO presents. On SNS a bucket's\n\t// events come from a topic the storage publishes to instead.\n\tconst relay = env.EVENT_PUBLISHER_CONNECTION_STRING;\n\tif (relay && options.relayedBuckets?.length) {\n\t\tfor (const resource of plan.resources) {\n\t\t\tif (resource.kind !== 'objects' || resource.container !== 'minio') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!options.relayedBuckets.includes(resource.id)) continue;\n\t\t\tif (!env[resource.envKey]) continue;\n\t\t\tenv[\n\t\t\t\tprovidedKeyFor(resource.id, resource.kind, 'eventsConnectionString')\n\t\t\t] = relay;\n\t\t\tenv[providedKeyFor(resource.id, resource.kind, 'eventsToken')] =\n\t\t\t\tobjectsWebhookToken(\n\t\t\t\t\toptions.project ?? '',\n\t\t\t\t\tresource.id,\n\t\t\t\t\tcredential.seed,\n\t\t\t\t);\n\t\t}\n\t}\n\n\t// The token Mailpit's webhook presents to the worker that receives for\n\t// every inbox — derived beside its URL, so the two cannot disagree.\n\tif (plan.resources.some((r) => r.kind === 'inbox' && env[r.envKey])) {\n\t\tenv[INBOX_RELAY_TOKEN_KEY] = inboxRelayToken(\n\t\t\toptions.project ?? '',\n\t\t\tcredential.seed,\n\t\t);\n\t}\n\n\t// The stack's token, which its services send when they call a sibling\n\t// through the edge — and which the edge and the auth server know it by.\n\t// Only where a surface resolved: with none, there is no sibling to call.\n\tif (\n\t\tplan.resources.some(\n\t\t\t(r) =>\n\t\t\t\t(r.kind === 'rest-api' || r.kind === 'websocket-api') && env[r.envKey],\n\t\t)\n\t) {\n\t\tenv[EDGE_TOKEN_KEY] = edgeToken(options.project ?? '', credential.seed);\n\t}\n\n\t// Only once a bucket actually resolved: an unresolvable plan resolves\n\t// nothing, and credentials for a container that is not running are noise.\n\tif (plan.resources.some((r) => r.kind === 'objects' && env[r.envKey])) {\n\t\tObject.assign(env, storageCredentials(options.credentials));\n\t}\n\n\treturn env;\n}\n\n/**\n * The values a site's bundler inlines, under the names it inlines them by.\n *\n * A rename and nothing more. `API_URL` was resolved once, by the same code that\n * resolved it for the server; a site reads the same value under `VITE_API_URL`\n * because that prefix is how its bundler is told to ship it. Nothing is derived\n * twice, so a site and its API cannot come to disagree about where the API is.\n *\n * A source that resolved to nothing is skipped rather than written empty: an\n * inlined empty string is a frontend that builds and then fails at runtime\n * against `http:///`, where a missing variable fails at build with the name of\n * the thing that is missing.\n */\nfunction publicEnv(\n\tplan: Plan,\n\tresolved: Record<string, string>,\n\t/** Where each surface answers on its own port — what a mobile app is given. */\n\taddresses: Readonly<Record<string, string>> = {},\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\t// Which construct each key belongs to, so a mobile app can be handed the\n\t// surface's own port rather than the edge's hostname.\n\tconst owners = new Map(plan.resources.map((r) => [r.envKey, r.id]));\n\n\tfor (const resource of plan.resources) {\n\t\tfor (const [key, source] of Object.entries(resource.publicEnv ?? {})) {\n\t\t\t// A phone cannot open `https://api-dev.shop.localhost` — the hostname\n\t\t\t// resolves only on this machine, and the edge routes by it, so no LAN\n\t\t\t// address can stand in for it. The surface's own port can: the app\n\t\t\t// swaps `localhost` for the host Metro was served from, and reaches it.\n\t\t\tconst direct =\n\t\t\t\tresource.kind === 'mobile-app'\n\t\t\t\t\t? addresses[owners.get(source) ?? '']\n\t\t\t\t\t: undefined;\n\t\t\tconst value = direct ?? resolved[source];\n\t\t\tif (value) env[key] = value;\n\t\t}\n\t\tif (resource.imageOrigins) {\n\t\t\tconst origins = imageOrigins(\n\t\t\t\tresource.imageOrigins.sources,\n\t\t\t\t(key) => resolved[key],\n\t\t\t);\n\t\t\tif (origins) env[resource.imageOrigins.key] = origins;\n\t\t}\n\t}\n\n\treturn env;\n}\n\n/**\n * What a surface publishes beyond its own address: who may call it, and where\n * a cookie set by it is readable.\n *\n * Both are read off the same list — the constructs that declared an edge to\n * this surface — which is why neither appears in application code. A surface\n * that listed its own callers would be edited every time something new called\n * it, and the thing being edited is already recorded in the graph.\n *\n * An empty origin list is written, and a surface with no address writes nothing\n * at all. The two cases look alike and are not: \"nothing depends on this yet\" is\n * a real state a target should publish, while \"this surface has no address here\"\n * means it is not running in this stage, and keys belong with the address they\n * describe.\n */\nfunction surfaceEnv(\n\tresource: PlannedResource,\n\turl: string | undefined,\n\t/**\n\t * Every construct's *resolved* address, keyed by id — not the raw ones the\n\t * workspace assigned.\n\t *\n\t * The difference is the feature. Behind the edge a surface and its callers\n\t * are `api.shop.localhost` and `console.shop.localhost`, which share a\n\t * parent and therefore a cookie; the addresses they were assigned are\n\t * `localhost:3000` and `localhost:5173`, which are one host with two ports\n\t * and share nothing. Deriving from the wrong one produces a local cookie\n\t * model that is *different* from the deployed one rather than matching it.\n\t */\n\tresolved: Readonly<Record<string, string>> = {},\n\tlocal: {\n\t\tplan?: Plan;\n\t\t/** Each caller's alias addresses — origins beside its own. */\n\t\taliased?: Readonly<Record<string, readonly string[]>>;\n\t\taddresses?: Readonly<Record<string, string>>;\n\t\tlanAddress?: string;\n\t\tmetroPorts?: Readonly<Record<string, number>>;\n\t} = {},\n): Record<string, string> {\n\tif (!url) return {};\n\n\tconst origins = [\n\t\t...new Set(\n\t\t\t(resource.callers ?? [])\n\t\t\t\t.flatMap((caller) =>\n\t\t\t\t\tresolved[caller]\n\t\t\t\t\t\t? [resolved[caller], ...(local.aliased?.[caller] ?? [])]\n\t\t\t\t\t\t: [],\n\t\t\t\t)\n\t\t\t\t.map(originOf)\n\t\t\t\t.filter((origin): origin is string => Boolean(origin)),\n\t\t),\n\t].sort();\n\n\t// Its own address belongs in the cookie derivation but not in the origin\n\t// list: a surface does not need permission to call itself, and adding it\n\t// would make every surface trust every other one that shares a port.\n\tconst domain = cookieDomain([url, ...origins]);\n\n\t// A mobile caller is reached by its scheme, not an address, so it adds its\n\t// scheme — and, on this local stage, the `exp://` hosts Expo Go sends from —\n\t// rather than an origin read off a URL. After the cookie domain on purpose:\n\t// a scheme is not a host anything shares a cookie with.\n\tconst mobile = (resource.callers ?? [])\n\t\t.map((caller) =>\n\t\t\tlocal.plan?.resources.find(\n\t\t\t\t(r) => r.id === caller && r.kind === 'mobile-app',\n\t\t\t),\n\t\t)\n\t\t.filter((caller): caller is PlannedResource => Boolean(caller));\n\tconst hosts = [...(local.lanAddress ? [local.lanAddress] : []), LOCAL_HOST];\n\tconst schemes = mobile.flatMap((caller) => {\n\t\tconst scheme = resolved[caller.id];\n\t\tconst port = local.metroPorts?.[caller.id];\n\t\treturn scheme\n\t\t\t? mobileOrigins(scheme, { hosts, ...(port ? { port } : {}) })\n\t\t\t: [];\n\t});\n\n\t// Where a phone reaches this surface: its own port on the LAN address. What\n\t// the auth server builds a sign-in link on when the app asked for it — the\n\t// link is opened on the phone, which cannot resolve the edge's hostname.\n\tconst own = local.addresses?.[resource.id];\n\tconst device =\n\t\tmobile.length > 0 && local.lanAddress && own\n\t\t\t? own.replace(\n\t\t\t\t\t/\\/\\/(localhost|127\\.0\\.0\\.1)(?=[:/]|$)/,\n\t\t\t\t\t`//${local.lanAddress}`,\n\t\t\t\t)\n\t\t\t: undefined;\n\n\treturn {\n\t\t[providedKeyFor(resource.id, resource.kind, 'trustedOrigins')]: [\n\t\t\t...origins,\n\t\t\t...new Set(schemes),\n\t\t].join(','),\n\t\t...(domain\n\t\t\t? { [providedKeyFor(resource.id, resource.kind, 'cookieDomain')]: domain }\n\t\t\t: {}),\n\t\t...(device\n\t\t\t? { [providedKeyFor(resource.id, resource.kind, 'deviceUrl')]: device }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Every construct's alias addresses: where a target placed them, and\n * otherwise — behind the local edge — each alias under the project, on the\n * edge's port, as {@link hostsFor} names it. Never a redirect's.\n */\nfunction aliasAddressesFor(\n\tplan: Plan,\n\toptions: EnvOptions,\n): Record<string, readonly string[]> {\n\tif (options.aliasAddresses) return { ...options.aliasAddresses };\n\tconst edge = plan.containers.includes('caddy')\n\t\t? options.ports[primaryPortKey('caddy')]\n\t\t: undefined;\n\tif (edge === undefined) return {};\n\tconst aliased: Record<string, readonly string[]> = {};\n\tfor (const resource of plan.resources) {\n\t\tif (!resource.aliases?.length) continue;\n\t\tif (!options.addresses?.[resource.id]) continue;\n\t\taliased[resource.id] = hostsFor(\n\t\t\tresource,\n\t\t\toptions.project ?? '',\n\t\t).aliases.map((host) => `https://${host}:${edge}`);\n\t}\n\treturn aliased;\n}\n\n/**\n * The buckets whose links a phone opens: those a surface a mobile app calls\n * depends on.\n *\n * The surface hands the app a URL it built — a file server's public link, a\n * bucket's presigned one — and the phone cannot resolve `*.localhost`, or\n * reach `localhost` at all. A presigned URL's signature covers its host, so\n * nothing downstream can move it either: the bucket has to be resolved on the\n * LAN address in the first place.\n */\nfunction deviceBuckets(plan: Plan): Set<string> {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tconst fromApp = (id: string): boolean => {\n\t\tconst caller = byId.get(id);\n\t\tif (caller?.kind === 'mobile-app') return true;\n\t\treturn (\n\t\t\t(caller?.kind === 'rest-api' || caller?.kind === 'websocket-api') &&\n\t\t\t(caller.callers ?? []).some((c) => byId.get(c)?.kind === 'mobile-app')\n\t\t);\n\t};\n\n\tconst buckets = new Set(\n\t\tplan.resources\n\t\t\t.filter((r) => r.kind === 'objects' || r.kind === 'file-server')\n\t\t\t.filter((r) => (r.callers ?? []).some(fromApp))\n\t\t\t.map((r) => r.id),\n\t);\n\t// A `FileServer` is one construct declaring two nodes, and a handler's\n\t// edge is to the bucket — so the server fronting a bucket a phone's links\n\t// come from serves the phone too.\n\tfor (const r of plan.resources) {\n\t\tif (r.kind === 'file-server' && r.of && buckets.has(r.of)) {\n\t\t\tbuckets.add(r.id);\n\t\t}\n\t}\n\treturn buckets;\n}\n\n/**\n * Where a WebSocket surface's publisher meets its sockets: the local Redis,\n * on channels named for the project and the surface, so two projects sharing\n * one Redis never see each other's frames.\n */\nexport function webSocketPublisher(\n\tresource: PlannedResource,\n\tports: PortAssignments,\n\tproject: string,\n\tcredential: StageCredential,\n): string | undefined {\n\tconst port = ports[primaryPortKey('redis')];\n\tif (port === undefined) return undefined;\n\n\tconst channel = encodeURIComponent(\n\t\t`gkm:ws:${project ? `${project}:` : ''}${resource.id}`,\n\t);\n\treturn `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}?channel=${channel}`;\n}\n\n/**\n * An address reduced to the origin a browser compares against.\n *\n * A WebSocket surface's address is `wss://`, but its host is served over\n * HTTPS like any other: its origin is that one, and a non-web scheme among the\n * origins means a mobile app to whoever reads the list.\n */\nfunction originOf(address: string): string | undefined {\n\ttry {\n\t\treturn new URL(address.replace(/^ws(s?):/, 'http$1:')).origin;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The runtime role of whatever a derived node hangs off.\n *\n * A reader's parent may itself be a schema tenant, so this follows `of` by one\n * hop rather than assuming the cluster — the reader of a tenant reads that\n * tenant's schema, not the database's.\n */\nfunction parentRole(resource: PlannedResource, plan: Plan): string {\n\tconst parent = plan.resources.find((r) => r.id === resource.of);\n\n\treturn parent ? localRole(parent) : resource.name;\n}\n\n/** Whether a kind connects to Postgres and therefore has an owner role. */\nfunction isDatabase(kind: PlannedResource['kind']): boolean {\n\treturn kind === 'database' || kind === 'database-schema';\n}\n\n/**\n * The URL a migrator connects with — the owner role, which can create, alter\n * and drop.\n *\n * Never in `provides`, which is the whole point. A handler that could reach this\n * could `DROP TABLE`, and the security property the role split exists for is\n * that it cannot: the value is injected by `gkm exec` for the migrate step and\n * by nothing else.\n */\nfunction ownerUrl(\n\tresource: PlannedResource,\n\tplan: Plan,\n\tports: PortAssignments,\n\tproject: string,\n\tcredential: StageCredential,\n): string | undefined {\n\tif (!resource.container) return undefined;\n\n\tconst port = ports[primaryPortKey(resource.container)];\n\tif (port === undefined) return undefined;\n\n\tconst owner = ownerRole(localRole(resource));\n\n\treturn postgres(port, rootDatabase(resource, plan), {\n\t\tuser: owner,\n\t\tpassword: localRolePassword(project, plan, owner, credential.seed),\n\t});\n}\n\n/**\n * The shared broker keys, when anything is published or consumed.\n *\n * A queue's own key is the producer's. These two are the *connection* itself,\n * which locally is one broker for every queue and topic in the project: the\n * generated pollers open a single connection and subscribe each worker by name\n * on it. Deployed there is no such thing — a Lambda is handed its own event\n * source — so this pair exists for the local target and says so.\n */\nfunction brokerEnv(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredential: StageCredential,\n): Record<string, string> {\n\tconst carrier = plan.resources.find(\n\t\t(r) => r.kind === 'queue' || r.kind === 'topic',\n\t);\n\n\tconst publisher = carrier\n\t\t? urlFor(carrier, plan, ports, '', {}, credential)\n\t\t: plan.workerBroker\n\t\t\t? workerBroker(plan, ports, credential)\n\t\t\t: undefined;\n\tif (!publisher) return {};\n\n\t// One broker address only where there is one broker: pg-boss and RabbitMQ.\n\t// On SNS every topic and queue is its own address, carried by its own\n\t// `<ID>_PUBLISHER_CONNECTION_STRING`, and no single string stands for them.\n\tif (plan.events === 'sns') return {};\n\n\treturn { EVENT_PUBLISHER_CONNECTION_STRING: publisher };\n}\n\n/**\n * The broker a worker schedules its crons through, when nothing else declared\n * one — pg-boss in the declared database, on that database's port.\n */\nfunction workerBroker(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredential: StageCredential,\n): string | undefined {\n\tconst database = plan.resources.find((r) => r.kind === 'database');\n\tif (!database?.container) return undefined;\n\n\tconst port = ports[primaryPortKey(database.container)];\n\treturn port === undefined ? undefined : broker(plan, port, credential);\n}\n\n/**\n * The URL for one planned resource.\n *\n * Every part of it comes from the resource and the port it was published on.\n */\nfunction urlFor(\n\tresource: PlannedResource,\n\tplan: Plan,\n\tports: PortAssignments,\n\tproject: string,\n\taddresses: Readonly<Record<string, string>> | undefined,\n\tcredential: StageCredential,\n\t/**\n\t * The LAN address, for a bucket whose links a phone opens — see\n\t * `deviceBuckets`. Undefined for everything else.\n\t */\n\tlan?: string,\n): string | undefined {\n\t// A secret has no address, so there is no port to wait for.\n\tif (resource.kind === 'secret') return localSecret(project, plan, resource);\n\n\t// Nor has an encryption key: a keyring derived the way a secret is.\n\tif (resource.kind === 'encryption') {\n\t\treturn localKeyring(project, plan, resource);\n\t}\n\n\t// A mobile app resolves its scheme — the same on every stage.\n\tif (resource.kind === 'mobile-app') {\n\t\treturn schemeBase(project, resource.scheme);\n\t}\n\n\t// A credential resolves to nothing here, deliberately. A secret is derived\n\t// because the platform owns it; a credential was issued by a third party, so\n\t// inventing a value would produce a Stripe key that is not a Stripe key and\n\t// fail at the first call rather than at the first read. It comes from\n\t// `gkm secrets` or `.env` like any other supplied value, and the construct's\n\t// own schema is what reports it missing — or, on a stage that fakes, from\n\t// its fake (`envFor`).\n\tif (resource.kind === 'credential') return undefined;\n\n\t// An external API is the provider, at its URL for this stage — unless the\n\t// plan was made with fakes (`gkm test`, `gkm dev --fake`), and then it is\n\t// its fake, on the port its key was assigned.\n\tif (resource.kind === 'external-api') {\n\t\tif (!resource.fake) {\n\t\t\treturn resource.url === undefined\n\t\t\t\t? undefined\n\t\t\t\t: externalApiUrl({ id: resource.id, url: resource.url }, plan.stage);\n\t\t}\n\t\tconst port = ports[resource.fake.key];\n\t\treturn port === undefined ? undefined : `http://${LOCAL_HOST}:${port}`;\n\t}\n\n\t// A surface answers on the app's own port, and a site on its dev server's —\n\t// both assigned by the workspace, neither published by a container.\n\t//\n\t// Behind the edge when there is one, which is what gives them a hostname and\n\t// a certificate rather than a port on localhost. The application cannot tell\n\t// the difference: it reads whichever address was injected and composes none,\n\t// so this is the target's decision alone.\n\tif (resource.kind === 'rest-api' || resource.kind === 'site') {\n\t\tconst address = addresses?.[resource.id];\n\t\tconst edge = plan.containers.includes('caddy')\n\t\t\t? ports[primaryPortKey('caddy')]\n\t\t\t: undefined;\n\n\t\treturn address && edge !== undefined\n\t\t\t? `https://${hostFor(resource, project)}:${edge}`\n\t\t\t: address;\n\t}\n\n\t// The same address, in the scheme a WebSocket client opens.\n\tif (resource.kind === 'websocket-api') {\n\t\tconst address = addresses?.[resource.id];\n\t\tconst edge = plan.containers.includes('caddy')\n\t\t\t? ports[primaryPortKey('caddy')]\n\t\t\t: undefined;\n\n\t\treturn address && edge !== undefined\n\t\t\t? `wss://${hostFor(resource, project)}:${edge}`\n\t\t\t: address?.replace(/^http/, 'ws');\n\t}\n\n\tif (!resource.container) return undefined;\n\n\tconst port = ports[primaryPortKey(resource.container)];\n\tif (port === undefined) return undefined;\n\n\tswitch (resource.kind) {\n\t\tcase 'database':\n\t\tcase 'database-schema':\n\t\tcase 'database-reader': {\n\t\t\t// A tenant and a reader both live in the *parent's* database; what\n\t\t\t// separates them is the role's grants and the `search_path` pinned on\n\t\t\t// that role, never a database of their own.\n\t\t\tconst database = rootDatabase(resource, plan);\n\n\t\t\t// The runtime role, which can read and write rows and create nothing.\n\t\t\t// `search_path` is pinned on the role by the DDL rather than carried\n\t\t\t// here, so a connection string cannot forget it — and forgetting it\n\t\t\t// looks like an empty database rather than an error.\n\t\t\t//\n\t\t\t// `roles: false` is the documented downgrade: both URLs fall back to\n\t\t\t// the cluster's master credential, and the schema goes back into the\n\t\t\t// URL because there is no role to pin it on.\n\t\t\tif (resource.roles === false) {\n\t\t\t\tconst schema = schemaOf(resource, plan);\n\n\t\t\t\tconst master = credential.containers.postgres;\n\t\t\t\treturn schema\n\t\t\t\t\t? `${postgres(port, database, master)}?search_path=${schema}`\n\t\t\t\t\t: postgres(port, database, master);\n\t\t\t}\n\n\t\t\t// A reader connects as the read-only role on its parent, not as a role\n\t\t\t// of its own: read-only is enforced by the grants, which is what makes\n\t\t\t// falling back to the writer's endpoint safe where no replica exists.\n\t\t\tconst role =\n\t\t\t\tresource.kind === 'database-reader'\n\t\t\t\t\t? readerRole(parentRole(resource, plan))\n\t\t\t\t\t: localRole(resource);\n\n\t\t\treturn postgres(port, database, {\n\t\t\t\tuser: role,\n\t\t\t\tpassword: localRolePassword(project, plan, role, credential.seed),\n\t\t\t});\n\t\t}\n\n\t\tcase 'telemetry':\n\t\t\t// OpenObserve takes OTLP/HTTP under its organisation's API.\n\t\t\treturn `http://${LOCAL_HOST}:${port}/api/${LOGS_ORG}`;\n\n\t\tcase 'email':\n\t\t\t// The same scheme the deployed target writes; only host and credentials\n\t\t\t// differ, which is what lets the client never branch on provider.\n\t\t\treturn `smtp://${LOCAL_HOST}:${port}`;\n\n\t\tcase 'inbox': {\n\t\t\t// Where its raw messages are read from: Mailpit's API, which keeps\n\t\t\t// every message it receives. Deployed it is the bucket SES stores\n\t\t\t// them in; the decoder reads by key from whichever this names.\n\t\t\tconst api = ports[MAILPIT_INBOX_PORT];\n\t\t\treturn api === undefined ? undefined : `http://${LOCAL_HOST}:${api}`;\n\t\t}\n\n\t\tcase 'objects':\n\t\t\t// `?endpoint=` is what points the same S3 client at MinIO — the client\n\t\t\t// is identical, only the URL differs. Path-style addressing goes with\n\t\t\t// it: virtual-host style resolves `bucket.localhost`, which is not\n\t\t\t// MinIO and not anything.\n\t\t\t//\n\t\t\t// On the LAN address when a phone opens its links: a presigned URL is\n\t\t\t// signed for the endpoint's host, so it is the endpoint that moves.\n\t\t\t// MinIO answers on it from this machine too.\n\t\t\treturn `s3://${resource.name}?region=${LOCAL_REGION}&endpoint=http://${lan ?? LOCAL_HOST}:${port}&forcePathStyle=true`;\n\n\t\tcase 'file-server': {\n\t\t\t// A host of its own, over TLS — the shape it has deployed, and the one\n\t\t\t// MinIO alone cannot produce: its virtual-host mode reads the leading\n\t\t\t// label *as the bucket name*, so it matches only when the server's id\n\t\t\t// and the bucket's agree and never for a server fronting two buckets.\n\t\t\t// The local edge in front of it does the mapping instead, and issues\n\t\t\t// the certificate. An AWS emulator supplies neither: CloudFront\n\t\t\t// emulation is control plane only, and this is the data plane.\n\t\t\t//\n\t\t\t// The port is in the address because ports are assigned rather than\n\t\t\t// fixed, so two projects can run at once. Nothing that reads a\n\t\t\t// hostname — a cookie domain, a CORS origin — looks at it.\n\t\t\tconst origin = plan.resources.find((r) => r.id === resource.of);\n\t\t\tif (!origin) return undefined;\n\n\t\t\t// Where a target put it — a stack's edge, at the host its links are\n\t\t\t// built on — which is the one address a link stored by a seed stays\n\t\t\t// right at.\n\t\t\tconst placed = addresses?.[resource.id];\n\t\t\tif (placed) return placed;\n\n\t\t\t// A phone resolves no `*.localhost` host, and the edge routes on it,\n\t\t\t// so a file server whose links reach one is the path under MinIO on\n\t\t\t// the LAN address — the one address that needs no Host routing.\n\t\t\t// Not with processors: they answer only through the edge, and a link\n\t\t\t// past it would serve the original rather than what was asked for.\n\t\t\tconst objects = origin.container\n\t\t\t\t? ports[primaryPortKey(origin.container)]\n\t\t\t\t: undefined;\n\t\t\tif (lan && !resource.processors?.length && objects !== undefined) {\n\t\t\t\treturn `http://${lan}:${objects}/${origin.name}`;\n\t\t\t}\n\n\t\t\t// With the edge off, the honest local answer is the address that\n\t\t\t// works: a path under the object store. It is not the deployed shape,\n\t\t\t// and the application still cannot tell — it reads the key it was\n\t\t\t// given and never composes one.\n\t\t\treturn plan.containers.includes('caddy')\n\t\t\t\t? `https://${hostFor(resource, project)}:${port}`\n\t\t\t\t: `http://${LOCAL_HOST}:${port}/${origin.name}`;\n\t\t}\n\n\t\tcase 'cache':\n\t\t\t// The scheme is the backend, and the backend is the same one deployed —\n\t\t\t// which is what lets a driver registered at build time match the URL\n\t\t\t// resolved at run time.\n\t\t\t//\n\t\t\t// A cache in a database has no address of its own: no second host and\n\t\t\t// no second credential, just its parent's URL. Reached by following\n\t\t\t// `of` and nothing else — `planFor` has already resolved a\n\t\t\t// `cache: 'db'` backend into that edge, so there is one way a cache\n\t\t\t// lands in a database and one way to find out.\n\t\t\tif (resource.of) {\n\t\t\t\tconst parent = plan.resources.find((r) => r.id === resource.of);\n\t\t\t\tconst url = parent\n\t\t\t\t\t? urlFor(parent, plan, ports, project, addresses, credential)\n\t\t\t\t\t: undefined;\n\n\t\t\t\t// The parent's address plus the one thing that distinguishes this\n\t\t\t\t// cache from another in the same database: its table. Two caches on\n\t\t\t\t// one database resolve the same connection string, so without it a\n\t\t\t\t// client built from the URL cannot tell them apart.\n\t\t\t\treturn url\n\t\t\t\t\t? withTable(url, resource.table ?? cacheTable(resource.id))\n\t\t\t\t\t: undefined;\n\t\t\t}\n\n\t\t\tswitch (plan.cache) {\n\t\t\t\tcase 'elasticache':\n\t\t\t\tcase 'redis':\n\t\t\t\t\t// The wire protocol, with the password the container requires.\n\t\t\t\t\t// Deployed it is `rediss://` inside a VPC; the client is the\n\t\t\t\t\t// same either way.\n\t\t\t\t\treturn `redis://:${encodeURIComponent(credential.containers.redis.password)}@${LOCAL_HOST}:${port}`;\n\n\t\t\t\tdefault:\n\t\t\t\t\t// The token in the userinfo, because an address and the credential\n\t\t\t\t\t// that opens it are one fact. Deployed the scheme is https and the\n\t\t\t\t\t// host is the provider's; nothing else differs.\n\t\t\t\t\treturn `http://:${encodeURIComponent(credential.containers.cacheToken)}@${LOCAL_HOST}:${port}`;\n\t\t\t}\n\n\t\tcase 'queue':\n\t\tcase 'topic':\n\t\t\treturn broker(plan, port, credential, resource);\n\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * The producer's connection string, composed from the backend the plan chose.\n *\n * The protocol is what picks the transport, so a producer never branches: the\n * same `.publish()` reaches pg-boss here and SQS deployed because the string it\n * was handed said so.\n */\nfunction broker(\n\tplan: Plan,\n\tport: number,\n\tcredential: StageCredential,\n\t/** The topic or queue — needed where each is its own address (SNS/SQS). */\n\tresource?: PlannedResource,\n): string {\n\tswitch (plan.events) {\n\t\tcase 'pgboss': {\n\t\t\t// A schema tenant of the database the app already declared, which is\n\t\t\t// why nothing here invents a Postgres of its own.\n\t\t\tconst database = plan.resources.find((r) => r.kind === 'database');\n\t\t\tif (!database) throw new PgBossNeedsDatabase([]);\n\n\t\t\tconst { user, password } = credential.containers.postgres;\n\t\t\treturn `pgboss://${user}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}/${database.name}?schema=${PGBOSS_SCHEMA}`;\n\t\t}\n\n\t\tcase 'rabbitmq': {\n\t\t\t// The exchange is declared by whichever client connects first, so\n\t\t\t// naming it here is the whole of the setup.\n\t\t\tconst { user, password } = credential.containers.rabbitmq;\n\t\t\treturn `rabbitmq://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${LOCAL_HOST}:${port}?exchange=${RABBITMQ_EXCHANGE}`;\n\t\t}\n\n\t\tcase 'sns': {\n\t\t\t// The emulator's ARNs and queue URLs are deterministic, so the address\n\t\t\t// is composed here and the topic or queue is created beside it by the\n\t\t\t// applier (`applyCarriers`). Credentials ride in the string: the\n\t\t\t// emulator's are not the developer's AWS profile, and must not be\n\t\t\t// picked up from it.\n\t\t\tif (!resource) throw new UnprovisionedEventsBackend('sns');\n\t\t\tconst endpoint = emulatorEndpoint(port);\n\t\t\tconst address =\n\t\t\t\tresource.kind === 'topic'\n\t\t\t\t\t? snsUrl.build({\n\t\t\t\t\t\t\ttopicArn: emulatorTopicArn(resource.name),\n\t\t\t\t\t\t\tregion: EMULATOR_REGION,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t})\n\t\t\t\t\t: sqsUrl.build({\n\t\t\t\t\t\t\tqueueUrl: emulatorQueueUrl(resource.name, port),\n\t\t\t\t\t\t\tregion: EMULATOR_REGION,\n\t\t\t\t\t\t\tendpoint,\n\t\t\t\t\t\t});\n\t\t\tconst url = new URL(address);\n\t\t\tconst { accessKeyId, secretAccessKey } = credential.containers.emulator;\n\t\t\turl.searchParams.set('accessKeyId', accessKeyId);\n\t\t\turl.searchParams.set('secretAccessKey', secretAccessKey);\n\t\t\treturn url.toString();\n\t\t}\n\t}\n}\n\n/** A local Postgres URL, with the login it connects as. */\nfunction postgres(\n\tport: number,\n\tdatabase: string,\n\tcredential: { user: string; password: string },\n): string {\n\treturn `postgres://${credential.user}:${encodeURIComponent(credential.password)}@${LOCAL_HOST}:${port}/${database}`;\n}\n\n/**\n * The role a handler connects as, for one database or tenant.\n *\n * The construct's id, lowercased and stage-scoped exactly as its database or\n * schema is — so `Orders` in the `test` stage connects as `orders_test`, and two\n * stages sharing one cluster cannot share a credential. Roles are cluster-scoped\n * in Postgres, which is why the suffix is not optional here the way it is for a\n * schema.\n */\nexport function localRole(resource: PlannedResource): string {\n\treturn resource.name;\n}\n\n/**\n * The password for a derived local role.\n *\n * Derived rather than random, for the same reason the local secret is: a\n * password that changed on every `gkm dev` would lock a developer out of the\n * data they had a moment ago. Seeded by the project so two checkouts do not\n * share one, and by the stage so `test` and `development` do not.\n *\n * Without a seed it is a *local* credential by construction — the cluster is\n * on loopback and everything it is derived from is in the repo. `gkm compose`\n * serving a deployed stage passes that stage's random seed, which is what\n * makes the same derivation a secret.\n */\nexport function localRolePassword(\n\tproject: string,\n\tplan: Plan,\n\trole: string,\n\t/**\n\t * A deployed stage's random seed. Given, the derivation is the one a\n\t * deploy makes — the seed first — so a stack serving that stage connects\n\t * with the passwords its roles were created with.\n\t */\n\tseed?: string,\n): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:${plan.stage}:role:${role}`)\n\t\t.digest('base64url')\n\t\t.slice(0, 32);\n}\n\n/**\n * A cache's address: its database's URL, carrying the table it reads.\n *\n * Appended rather than kept beside the URL as a second key, for the reason the\n * design gives everywhere else — an address and what it opens are one fact, and\n * two keys are one more thing to keep in step.\n */\nfunction withTable(url: string, table: string): string {\n\tconst parsed = new URL(url);\n\tparsed.searchParams.set('table', table);\n\n\treturn parsed.toString();\n}\n\n/**\n * The physical database a derived resource lives in.\n *\n * Walks `of` to the top rather than reading the immediate parent, because a\n * reader's parent may itself be a schema tenant — two hops from the database\n * that actually exists.\n */\nexport function rootDatabase(resource: PlannedResource, plan: Plan): string {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tlet current = resource;\n\n\twhile (current.of) {\n\t\tconst parent = byId.get(current.of);\n\t\tif (!parent) break;\n\t\tcurrent = parent;\n\t}\n\n\treturn current.name;\n}\n\n/** The schema a derived resource puts on its search path, if it has one. */\nfunction schemaOf(resource: PlannedResource, plan: Plan): string | undefined {\n\tconst byId = new Map(plan.resources.map((r) => [r.id, r]));\n\tlet current: PlannedResource | undefined = resource;\n\n\t// A reader has no schema of its own; it reads whatever its parent addresses.\n\twhile (current) {\n\t\tif (current.kind === 'database-schema') return current.schema;\n\t\tcurrent = current.of ? byId.get(current.of) : undefined;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A broker address asked for without the topic or queue it would name.\n *\n * On SNS each topic and queue is its own address, so there is no project-wide\n * one to hand out — a cron's schedule store, say, cannot live there.\n */\nexport class UnprovisionedEventsBackend extends GkmError {\n\tconstructor(readonly backend: string) {\n\t\tsuper(\n\t\t\t`'${backend}' has no single broker address: each topic and queue is ` +\n\t\t\t\t`addressed by its own ARN. Something asked for one without naming ` +\n\t\t\t\t`the topic or queue.`,\n\t\t);\n\t\tthis.name = 'UnprovisionedEventsBackend';\n\t}\n}\n\n/**\n * The keyring an `Encryption` construct resolves to locally.\n *\n * Derived like a secret — stable across restarts, distinct per project, stage\n * and construct, never written to disk — so what `gkm dev` encrypted yesterday\n * still opens today. One key, because nothing local is worth rotating: a\n * server stage's keyring is generated and rotated in its secrets instead.\n */\nfunction localKeyring(\n\tproject: string,\n\tplan: Plan,\n\tresource: PlannedResource,\n): string {\n\tconst derive = (purpose: string) =>\n\t\tcreateHash('sha256')\n\t\t\t.update(`${project}:${plan.stage}:${resource.id}:${purpose}`)\n\t\t\t.digest();\n\n\treturn formatKeyring({\n\t\tkeys: [{ id: 'k1', key: derive('k1') }],\n\t\tindex: derive('index'),\n\t});\n}\n\n/**\n * The value a secret resolves to locally.\n *\n * A hash of what identifies it, so it is stable, distinct per project, stage\n * and construct, and never written to disk as a literal. Deployed this is the\n * one kind whose value does *not* come from here — a secret manager generates\n * it once and the target reads it back. Drawn in the format the deploy draws\n * it in, so a value that passes a third party's rules here passes them there.\n */\nfunction localSecret(\n\tproject: string,\n\tplan: Plan,\n\tresource: PlannedResource,\n): string {\n\treturn drawSecret(\n\t\thashStream(`${project}:${plan.stage}:${resource.id}`),\n\t\tresource.format,\n\t);\n}\n\n/**\n * Integers in `[0, n)` drawn from a hash of `seed`, the same every time —\n * what a local secret is drawn with instead of `crypto`, so `gkm dev` and\n * `gkm test` need nothing stored. Rejection-sampled, so no character is\n * likelier than another.\n */\nfunction hashStream(seed: string): (n: number) => number {\n\tlet block = 0;\n\tlet bytes = Buffer.alloc(0);\n\tlet offset = 0;\n\n\tconst next = (): number => {\n\t\tif (offset === bytes.length) {\n\t\t\tbytes = createHash('sha256').update(`${seed}:${block++}`).digest();\n\t\t\toffset = 0;\n\t\t}\n\t\treturn bytes[offset++] as number;\n\t};\n\n\treturn (n) => {\n\t\tconst limit = 256 - (256 % n);\n\t\tfor (;;) {\n\t\t\tconst byte = next();\n\t\t\tif (byte < limit) return byte % n;\n\t\t}\n\t};\n}\n","/**\n * A bucket's lifecycle, as the constructs declare it: one expiry rule per\n * prefix, merged into whatever else the bucket's lifecycle already holds.\n *\n * S3 — and MinIO, which speaks the same API — keeps one lifecycle document\n * per bucket, and a write replaces all of it. So gkm owns only the rules it\n * names (`gkm-…`): every other rule is read and put back as it was, a rule of\n * gkm's that is no longer declared is dropped, and nothing is written when\n * gkm's rules already say what the manifest does.\n *\n * Shared by the `s3` provider and the MinIO a local or compose stack runs,\n * so a prefix expires the same way on both.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { LifecycleRule } from '@aws-sdk/client-s3';\n\n/** The id every rule gkm writes starts with — and the only ones it touches. */\nexport const GKM_RULE_PREFIX = 'gkm-';\n\n/**\n * The rule id for one prefix: readable, and unique however the prefix is\n * spelled — `a/b` and `a-b` read alike once sanitised, so a short hash of the\n * prefix itself follows.\n */\nexport function expireRuleId(prefix: string): string {\n\tconst readable = prefix\n\t\t.replace(/[^A-Za-z0-9._-]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.slice(0, 200);\n\tconst hash = createHash('sha256').update(prefix).digest('hex').slice(0, 8);\n\treturn `${GKM_RULE_PREFIX}expire-${readable ? `${readable}-` : ''}${hash}`;\n}\n\n/** The rules a bucket's expiry asks for, in a stable order. */\nexport function expireRules(\n\texpire: Readonly<Record<string, number>> | undefined,\n): LifecycleRule[] {\n\treturn Object.entries(expire ?? {})\n\t\t.map(\n\t\t\t([prefix, days]): LifecycleRule => ({\n\t\t\t\tID: expireRuleId(prefix),\n\t\t\t\tStatus: 'Enabled',\n\t\t\t\tFilter: { Prefix: prefix },\n\t\t\t\tExpiration: { Days: days },\n\t\t\t}),\n\t\t)\n\t\t.sort((a, b) => a.ID!.localeCompare(b.ID!));\n}\n\n/** What to do to a bucket's lifecycle, if anything. */\nexport interface LifecycleMerge {\n\t/** Whether gkm's rules differ from what the bucket holds. */\n\tchanged: boolean;\n\t/** The whole document to write: the bucket's other rules, then gkm's. */\n\trules: LifecycleRule[];\n\t/** What changes, said for a plan or a log line. */\n\tdescribe: string;\n}\n\n/**\n * Merge the declared expiry into the bucket's current rules.\n *\n * @param current the bucket's rules, or nothing when it has no lifecycle\n */\nexport function mergeLifecycle(\n\tcurrent: readonly LifecycleRule[] | undefined,\n\texpire: Readonly<Record<string, number>> | undefined,\n): LifecycleMerge {\n\tconst wanted = expireRules(expire);\n\tconst rules = current ?? [];\n\tconst others = rules.filter((r) => !r.ID?.startsWith(GKM_RULE_PREFIX));\n\tconst ours = rules.filter((r) => r.ID?.startsWith(GKM_RULE_PREFIX));\n\n\tconst changed =\n\t\tcanonical(ours) !== canonical(wanted) ||\n\t\t// A second rule under one of gkm's ids is drift too.\n\t\tnew Set(ours.map((r) => r.ID)).size !== ours.length;\n\n\treturn {\n\t\tchanged,\n\t\trules: [...others, ...wanted],\n\t\tdescribe: describeExpiry(expire),\n\t};\n}\n\n/** `expire quotes/ after 30 days, tmp/ after 1 day` — or what removing says. */\nfunction describeExpiry(\n\texpire: Readonly<Record<string, number>> | undefined,\n): string {\n\tconst entries = Object.entries(expire ?? {}).sort(([a], [b]) =>\n\t\ta.localeCompare(b),\n\t);\n\tif (entries.length === 0) return 'remove expiry rules';\n\treturn `expire ${entries\n\t\t.map(\n\t\t\t([prefix, days]) => `${prefix} after ${days} day${days === 1 ? '' : 's'}`,\n\t\t)\n\t\t.join(', ')}`;\n}\n\n/** gkm's rules as the fields it sets, order-free. */\nfunction canonical(rules: readonly LifecycleRule[]): string {\n\treturn JSON.stringify(\n\t\trules\n\t\t\t.map((r) => ({\n\t\t\t\tid: r.ID,\n\t\t\t\tstatus: r.Status,\n\t\t\t\t// The legacy top-level `Prefix` reads the same as a filter's.\n\t\t\t\tprefix: r.Filter?.Prefix ?? r.Prefix ?? '',\n\t\t\t\tdays: r.Expiration?.Days ?? null,\n\t\t\t}))\n\t\t\t.sort((a, b) => (a.id ?? '').localeCompare(b.id ?? '')),\n\t);\n}\n","/**\n * Creating what the URLs name.\n *\n * Convergent and idempotent: every statement asks whether the thing exists\n * first, so reconciling repeatedly is free and a half-applied run recovers by\n * being run again. That property is what lets `gkm dev` do this on every start.\n *\n * The line the design draws is at data, not at side effects — this creates\n * databases, schemas, and buckets, and it never seeds, resets, or drops. A\n * developer who wants their data gone asks for it explicitly.\n *\n * Statement generation is separated from application for the reason the design\n * gives: the same DDL has to run in-process locally and from a provisioner in a\n * VPC, and one implementation is what stops \"works locally, fails deployed\".\n * When the role DDL lands in `@geekmidas/db` this delegates to it rather than\n * growing its own.\n */\n\nimport type { LifecycleRule } from '@aws-sdk/client-s3';\nimport { cacheTableStatements } from '@geekmidas/cache/postgres';\nimport { ownerRole, readerRole, roleStatements } from '@geekmidas/db/pg/roles';\nimport { cacheTable } from '@geekmidas/manifest';\nimport { mergeLifecycle } from '../providers/s3/lifecycle';\nimport { localRole, localRolePassword, rootDatabase } from './env';\nimport {\n\tminioNotificationRule,\n\tNOTIFICATION_RULE_PREFIX,\n} from './objectEvents';\nimport type { Plan, PlannedResource } from './plan';\n\n/** One thing to create, and how to tell whether it already exists. */\nexport interface Statement {\n\t/** The construct this is for, so a failure can name it. */\n\tid: string;\n\t/** What it does, in the line reconcile prints. */\n\tdescribe: string;\n\t/** The database to connect to. Absent means the cluster's default. */\n\tdatabase?: string;\n\t/**\n\t * Answers \"does this already exist\", parameterised.\n\t *\n\t * Absent for a statement that is idempotent in itself — a `GRANT` re-granting\n\t * what is already granted is a no-op, and checking would cost a round trip to\n\t * learn nothing. Those run every time and report unchanged.\n\t */\n\texists?: { sql: string; values: unknown[] };\n\t/**\n\t * The DDL, run only when `exists` returns nothing.\n\t *\n\t * Not parameterised, because identifiers cannot be — which is why\n\t * {@link quoteIdentifier} exists and why names are canonicalised long before\n\t * they reach here.\n\t */\n\tcreate: string;\n}\n\n/**\n * The Postgres work a plan implies.\n *\n * Databases before the schemas inside them, which `provisionOrder` already\n * guarantees by putting parents first.\n */\nexport function postgresStatements(\n\tplan: Plan,\n\t/**\n\t * Seeds the derived role passwords. The same project seeds the same\n\t * passwords, so a restart does not lock a developer out of their own data —\n\t * and two checkouts do not share a credential.\n\t */\n\tproject = '',\n\t/**\n\t * A deployed stage's random seed, salting the role passwords the way a\n\t * deploy does — see `localRolePassword`. Absent for the local stages.\n\t */\n\tseed?: string,\n): Statement[] {\n\tconst statements: Statement[] = [];\n\t// A cache's table, run once every database and its roles exist: a cache\n\t// can sort before the database it lives in (`Cache`, `Database`), and its\n\t// table cannot be looked for in a database not yet created.\n\tconst cacheTables: Statement[] = [];\n\n\tfor (const resource of plan.resources) {\n\t\tif (!resource.provisions || resource.container !== 'postgres') continue;\n\n\t\tif (resource.kind === 'database') {\n\t\t\tstatements.push({\n\t\t\t\tid: resource.id,\n\t\t\t\tdescribe: `database ${resource.name}`,\n\t\t\t\texists: {\n\t\t\t\t\tsql: 'SELECT 1 FROM pg_database WHERE datname = $1',\n\t\t\t\t\tvalues: [resource.name],\n\t\t\t\t},\n\t\t\t\t// `CREATE DATABASE` cannot run inside a transaction, which is why\n\t\t\t\t// each statement is applied on its own rather than batched.\n\t\t\t\tcreate: `CREATE DATABASE ${quoteIdentifier(resource.name)}`,\n\t\t\t});\n\n\t\t\t// After the database, never before: roles are cluster-scoped but their\n\t\t\t// grants are not, so every statement after the first two has to run\n\t\t\t// against a database that exists.\n\t\t\tif (resource.schema) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t...rolesFor(resource, resource.schema, plan, project, seed),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (resource.kind === 'database-schema' && resource.schema) {\n\t\t\t// The schema *and* the roles that reach it, from one generator shared\n\t\t\t// with the deploy target — the same DDL has to run in-process here and\n\t\t\t// from a provisioner in a VPC, and one implementation is what stops\n\t\t\t// \"works locally, fails deployed\".\n\t\t\tstatements.push(\n\t\t\t\t...rolesFor(resource, resource.schema, plan, project, seed),\n\t\t\t);\n\t\t}\n\n\t\t// A cache that lives in a database is a table in it, and a table is DDL —\n\t\t// so the owner creates it, not the handler's role, which may not create\n\t\t// anything. The same reason the driver does not do it lazily.\n\t\t//\n\t\t// `of` is the whole test: `planFor` resolves a `cache: 'db'` backend into\n\t\t// that edge before anything reads the plan, so a cache lands in a\n\t\t// database exactly one way and this does not have to know the config\n\t\t// existed.\n\t\tconst cacheHome =\n\t\t\tresource.kind === 'cache' && resource.of\n\t\t\t\t? plan.resources.find((r) => r.id === resource.of)\n\t\t\t\t: undefined;\n\n\t\tif (cacheHome) {\n\t\t\tcacheTables.push(...cacheTableDdl(resource, cacheHome, plan));\n\t\t}\n\n\t\t// A reader provisions nothing: it is a set of grants on an endpoint that\n\t\t// already exists, and falling back to the writer where no replica exists\n\t\t// stays safe because read-only is enforced by the role.\n\t}\n\n\treturn [...statements, ...cacheTables];\n}\n\n/**\n * A cache's table, in the schema the role that reads it resolves names in.\n *\n * Two things have to line up, and neither is the table's contents. The driver\n * names the table unqualified and lets the connection's `search_path` place it\n * — which the role carries — so creating it from the master connection, whose\n * path is `public`, leaves a table the application cannot see and a\n * `relation \"cache\" does not exist` on the first request. And the default\n * privileges that make a tenant's tables reachable are granted *for the owner\n * role*, so nothing covers a table the master created.\n *\n * Hence: qualified with the tenant's schema, handed to its owner, and granted\n * explicitly — `roleStatements` grants what exists at the time it runs, and\n * this table does not exist yet.\n *\n * A database that opted out of roles needs none of it: everything connects as\n * the master, whose `search_path` finds `public`, and the table it creates\n * there is the table it reads.\n */\nfunction cacheTableDdl(\n\tcache: PlannedResource,\n\thome: PlannedResource,\n\tplan: Plan,\n): Statement[] {\n\tconst database = rootDatabase(home, plan);\n\tconst schema = home.roles === false ? undefined : home.schema;\n\t// The same default the URL carries — `cacheTable` is read by both, so the\n\t// table a client reads and the table a target creates cannot drift.\n\tconst name = cache.table ?? cacheTable(cache.id);\n\tconst table = schema ? `${schema}.${name}` : name;\n\n\tconst created = cacheTableStatements({ table }).map((statement) => ({\n\t\tid: cache.id,\n\t\tdescribe: statement.describe,\n\t\tdatabase,\n\t\t...(statement.exists ? { exists: statement.exists } : {}),\n\t\tcreate: statement.sql,\n\t}));\n\n\tif (!schema) return created;\n\n\tconst runtime = localRole(home);\n\tconst owner = ownerRole(runtime);\n\tconst qualified = table\n\t\t.split('.')\n\t\t.map((part) => quoteIdentifier(part))\n\t\t.join('.');\n\n\treturn [\n\t\t...created,\n\t\t{\n\t\t\tid: cache.id,\n\t\t\tdescribe: `cache table ${table} is owned by ${owner}`,\n\t\t\tdatabase,\n\t\t\tcreate: `ALTER TABLE ${qualified} OWNER TO ${quoteIdentifier(owner)}`,\n\t\t},\n\t\t{\n\t\t\tid: cache.id,\n\t\t\tdescribe: `${runtime} may read and write ${table}`,\n\t\t\tdatabase,\n\t\t\tcreate:\n\t\t\t\t`GRANT SELECT, INSERT, UPDATE, DELETE ON ${qualified} ` +\n\t\t\t\t`TO ${quoteIdentifier(runtime)}`,\n\t\t},\n\t];\n}\n\n/**\n * The roles and schema for one database or tenant.\n *\n * Skipped entirely when the construct declared `roles: false` — the documented\n * downgrade, where both URLs fall back to the cluster's master credential. It\n * is a choice someone made rather than a default they got.\n */\nfunction rolesFor(\n\tresource: PlannedResource,\n\tschema: string,\n\tplan: Plan,\n\tproject: string,\n\tseed?: string,\n): Statement[] {\n\tif (resource.roles === false) return [];\n\n\tconst runtime = localRole(resource);\n\tconst owner = ownerRole(runtime);\n\n\t// A reader role only where something reads through one. Creating roles\n\t// nothing connects as is noise in `\\du` and one more thing to explain.\n\tconst reader = plan.resources.some(\n\t\t(r) => r.kind === 'database-reader' && r.of === resource.id,\n\t)\n\t\t? readerRole(runtime)\n\t\t: undefined;\n\n\treturn roleStatements({\n\t\truntime,\n\t\towner,\n\t\t...(reader ? { reader } : {}),\n\t\tschema,\n\t\t// A database's owner may create in it — trusted extensions; a tenant's\n\t\t// stays confined to its schema.\n\t\t...(resource.kind === 'database'\n\t\t\t? { database: rootDatabase(resource, plan) }\n\t\t\t: {}),\n\t\t...(resource.extensions ? { extensions: resource.extensions } : {}),\n\t\tpasswords: {\n\t\t\truntime: localRolePassword(project, plan, runtime, seed),\n\t\t\towner: localRolePassword(project, plan, owner, seed),\n\t\t\t...(reader\n\t\t\t\t? { reader: localRolePassword(project, plan, reader, seed) }\n\t\t\t\t: {}),\n\t\t},\n\t}).map((statement) => ({\n\t\tid: resource.id,\n\t\tdescribe: statement.describe,\n\t\t// Inside the parent's database — a tenant is a schema, never a database\n\t\t// of its own. Roles are cluster-scoped, but the grants are not, so all of\n\t\t// it has to run against the database the objects live in.\n\t\tdatabase: rootDatabase(resource, plan),\n\t\t...(statement.exists ? { exists: statement.exists } : {}),\n\t\tcreate: statement.sql,\n\t}));\n}\n\n/** The buckets a plan implies. */\nexport function bucketNames(plan: Plan): string[] {\n\treturn plan.resources\n\t\t.filter((r) => r.provisions && r.kind === 'objects')\n\t\t.map((r) => r.name);\n}\n\n/**\n * Quote an identifier for use in DDL.\n *\n * Names reaching here are already canonical and stage-suffixed, so this is\n * defence rather than sanitisation — but DDL cannot be parameterised, and an\n * unquoted identifier is the one place a name could ever be more than a name.\n */\nexport function quoteIdentifier(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** What applying a statement did. */\nexport interface Applied {\n\tid: string;\n\tdescribe: string;\n\t/** False when it already existed — the converged case. */\n\tcreated: boolean;\n}\n\n/** The database operations the applier needs, so it can be run against a fake. */\nexport interface SqlClient {\n\t/** Run a query against one database, returning its rows. */\n\tquery(\n\t\tdatabase: string | undefined,\n\t\tsql: string,\n\t\tvalues?: unknown[],\n\t): Promise<unknown[]>;\n}\n\n/**\n * Apply the plan's Postgres statements.\n *\n * Each is checked before it is run, so this converges rather than erroring on a\n * second pass.\n */\nexport async function applyPostgres(\n\tclient: SqlClient,\n\tstatements: readonly Statement[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const statement of statements) {\n\t\t// No check means the statement is idempotent in itself — a GRANT\n\t\t// re-granting what is already granted is a no-op — so it runs and\n\t\t// reports unchanged, and a converged reconcile still says converged.\n\t\tif (!statement.exists) {\n\t\t\tawait client.query(statement.database, statement.create);\n\t\t\tapplied.push({\n\t\t\t\tid: statement.id,\n\t\t\t\tdescribe: statement.describe,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst rows = await client.query(\n\t\t\tstatement.database,\n\t\t\tstatement.exists.sql,\n\t\t\tstatement.exists.values,\n\t\t);\n\n\t\tif (rows.length > 0) {\n\t\t\tapplied.push({\n\t\t\t\tid: statement.id,\n\t\t\t\tdescribe: statement.describe,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.query(statement.database, statement.create);\n\t\tapplied.push({\n\t\t\tid: statement.id,\n\t\t\tdescribe: statement.describe,\n\t\t\tcreated: true,\n\t\t});\n\t}\n\n\treturn applied;\n}\n\n/**\n * What each bucket's open paths are, if anything serves it.\n *\n * Keyed by the *origin*, because that is where the policy lives: two servers\n * over one bucket contribute to one policy, so the patterns are unioned rather\n * than the last one winning.\n */\nexport function bucketPolicies(\n\tplan: Plan,\n): { bucket: string; open: string[] }[] {\n\tconst byBucket = new Map<string, Set<string>>();\n\n\tfor (const resource of plan.resources) {\n\t\tif (resource.kind !== 'file-server' || !resource.open?.length) continue;\n\n\t\tconst origin = plan.resources.find((r) => r.id === resource.of);\n\t\tif (!origin) continue;\n\n\t\tconst patterns = byBucket.get(origin.name) ?? new Set<string>();\n\t\tfor (const pattern of resource.open) patterns.add(pattern);\n\t\tbyBucket.set(origin.name, patterns);\n\t}\n\n\treturn [...byBucket]\n\t\t.map(([bucket, open]) => ({ bucket, open: [...open].sort() }))\n\t\t.sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\n/**\n * What each bucket keeps, and for how long: the buckets that declare an\n * expiry, by their stage-scoped name.\n *\n * Every bucket in the plan, not only those that declare one, is what a\n * removed expiry needs — its rules are dropped from a bucket that no longer\n * asks for them — so a bucket with none is listed with an empty expiry.\n */\nexport function bucketLifecycles(\n\tplan: Plan,\n): { bucket: string; expire: Readonly<Record<string, number>> }[] {\n\treturn plan.resources\n\t\t.filter((r) => r.kind === 'objects' && r.provisions)\n\t\t.map((r) => ({ bucket: r.name, expire: r.expire ?? {} }))\n\t\t.sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\n/**\n * One bucket's open paths as an S3 bucket policy.\n *\n * Anonymous `s3:GetObject` on the named prefixes and nothing else — which is\n * what \"open\" means everywhere: the server serves that path without a\n * signature, and the bucket stays private for everything else.\n *\n * One fidelity note, stated rather than discovered: an S3 policy resource's `*`\n * crosses `/`, so a single-star pattern is *wider* here than the construct's own\n * runtime check, which stops at a segment boundary. The construct is the\n * stricter of the two, so a key it refuses to serve unsigned is never one this\n * policy was relied on to refuse — but a key fetched directly, bypassing the\n * client, can be admitted by the policy where the client would have said no.\n * Prefer `**` where crossing segments is what you meant.\n */\nexport function bucketPolicy(bucket: string, open: readonly string[]): string {\n\treturn JSON.stringify({\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tSid: 'GkmOpenPaths',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tPrincipal: { AWS: ['*'] },\n\t\t\t\tAction: ['s3:GetObject'],\n\t\t\t\tResource: open.map(\n\t\t\t\t\t(pattern) =>\n\t\t\t\t\t\t`arn:aws:s3:::${bucket}/${pattern.replace(/\\*\\*/g, '*')}`,\n\t\t\t\t),\n\t\t\t},\n\t\t],\n\t});\n}\n\n/**\n * The topics and queues to create on the AWS emulator.\n *\n * Only on the `sns` backend: pg-boss makes its own tables on first connect and\n * a RabbitMQ exchange is declared by the client, but an SNS topic and an SQS\n * queue must exist before anything can publish to them.\n */\nexport function carrierNames(plan: Plan): {\n\ttopics: string[];\n\tqueues: string[];\n} {\n\tif (plan.events !== 'sns') return { topics: [], queues: [] };\n\n\tconst named = (kind: 'topic' | 'queue') =>\n\t\tplan.resources.filter((r) => r.kind === kind).map((r) => r.name);\n\n\treturn { topics: named('topic'), queues: named('queue') };\n}\n\n/** The emulator operations the applier needs. Both creates are idempotent. */\nexport interface CarrierClient {\n\ttopicExists(name: string): Promise<boolean>;\n\tcreateTopic(name: string): Promise<void>;\n\tqueueExists(name: string): Promise<boolean>;\n\tcreateQueue(name: string): Promise<void>;\n}\n\n/** Create each topic and queue the plan names, skipping those that exist. */\nexport async function applyCarriers(\n\tclient: CarrierClient,\n\tcarriers: { topics: readonly string[]; queues: readonly string[] },\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const name of carriers.topics) {\n\t\tconst created = !(await client.topicExists(name));\n\t\tif (created) await client.createTopic(name);\n\t\tapplied.push({ id: name, describe: `topic ${name}`, created });\n\t}\n\tfor (const name of carriers.queues) {\n\t\tconst created = !(await client.queueExists(name));\n\t\tif (created) await client.createQueue(name);\n\t\tapplied.push({ id: name, describe: `queue ${name}`, created });\n\t}\n\n\treturn applied;\n}\n\n/** The Postgres databases the plan creates — each is a `CREATE DATABASE`. */\nexport function postgresDatabaseNames(plan: Plan): string[] {\n\treturn plan.resources\n\t\t.filter(\n\t\t\t(resource) =>\n\t\t\t\tresource.kind === 'database' &&\n\t\t\t\tresource.provisions &&\n\t\t\t\tresource.container === 'postgres',\n\t\t)\n\t\t.map((resource) => resource.name);\n}\n\n/**\n * Whether every one of these databases exists. A database dropped behind the\n * recorded state's back — by another checkout's test teardown, against the\n * same container — makes the state a lie, and only asking Postgres finds out.\n * Unreachable counts as missing: applying again is what finds out why.\n */\nexport async function databasesExist(\n\tclient: SqlClient,\n\tnames: readonly string[],\n): Promise<boolean> {\n\tif (names.length === 0) return true;\n\ttry {\n\t\tconst rows = (await client.query(\n\t\t\tundefined,\n\t\t\t'SELECT datname FROM pg_catalog.pg_database WHERE datname = ANY($1)',\n\t\t\t[names],\n\t\t)) as { datname: string }[];\n\t\treturn new Set(rows.map((row) => row.datname)).size === names.length;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** The object-storage operations the applier needs. */\nexport interface BucketClient {\n\texists(bucket: string): Promise<boolean>;\n\tcreate(bucket: string): Promise<void>;\n\t/** The bucket's current policy, or `undefined` where it has none. */\n\tpolicy(bucket: string): Promise<string | undefined>;\n\tsetPolicy(bucket: string, policy: string): Promise<void>;\n\t/** The bucket's notification configuration — empty where it has none. */\n\tnotification(bucket: string): Promise<BucketNotification>;\n\tsetNotification(\n\t\tbucket: string,\n\t\tnotification: BucketNotification,\n\t): Promise<void>;\n\t/** The bucket's lifecycle rules, or `undefined` where it has none. */\n\tlifecycle(bucket: string): Promise<LifecycleRule[] | undefined>;\n\t/** Replace its lifecycle with these rules — none removes it. */\n\tsetLifecycle(bucket: string, rules: LifecycleRule[]): Promise<void>;\n}\n\n/** A queue rule of a bucket's notification, as the S3 API shapes it. */\nexport interface BucketNotificationRule {\n\tId?: string;\n\tQueueArn?: string;\n\tEvents?: string[];\n\tFilter?: unknown;\n}\n\n/**\n * A bucket's notification configuration, as the S3 API shapes it. The topic\n * and function rules are carried through untouched: gkm writes queue rules —\n * which is what a MinIO webhook target is — and keeps whatever else is there.\n */\nexport interface BucketNotification {\n\tQueueConfigurations?: BucketNotificationRule[];\n\tTopicConfigurations?: unknown[];\n\tLambdaFunctionConfigurations?: unknown[];\n}\n\n/**\n * Point each watched bucket's events at its webhook target, and stop sending\n * an unwatched one's.\n *\n * Merged rather than written whole: only the rule gkm owns on a bucket\n * (`gkm-<Bucket>`) is added or removed, and every other rule — one somebody\n * added by hand — is kept. Compared before writing, so a converged reconcile\n * changes nothing.\n *\n * @param buckets - each bucket the plan names, by construct id and name\n * @param watched - the construct ids whose events are relayed\n */\nexport async function applyNotifications(\n\tclient: BucketClient,\n\tbuckets: readonly { id: string; name: string }[],\n\twatched: ReadonlySet<string>,\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { id, name } of buckets) {\n\t\tconst current = await client.notification(name);\n\t\tconst queues = current.QueueConfigurations ?? [];\n\t\tconst others = queues.filter(\n\t\t\t(rule) => !rule.Id?.startsWith(NOTIFICATION_RULE_PREFIX),\n\t\t);\n\t\tconst wanted = watched.has(id)\n\t\t\t? [...others, minioNotificationRule(id)]\n\t\t\t: others;\n\n\t\t// Nothing of gkm's there, and nothing to add: not this bucket's concern.\n\t\tif (!watched.has(id) && others.length === queues.length) continue;\n\n\t\tconst describe = `object events from ${name}`;\n\t\tconst ours = queues.filter((rule) =>\n\t\t\trule.Id?.startsWith(NOTIFICATION_RULE_PREFIX),\n\t\t);\n\t\tconst converged = watched.has(id)\n\t\t\t? ours.length === 1 && sameRule(ours[0]!, minioNotificationRule(id))\n\t\t\t: ours.length === 0;\n\t\tif (converged) {\n\t\t\tapplied.push({ id: `${name}:events`, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setNotification(name, {\n\t\t\t...current,\n\t\t\tQueueConfigurations: wanted,\n\t\t});\n\t\tapplied.push({ id: `${name}:events`, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/**\n * Whether a rule read back says what gkm wrote: the same target, the same\n * events in any order, and no filter — the store may hand back an empty one.\n */\nfunction sameRule(\n\tcurrent: BucketNotificationRule,\n\twanted: BucketNotificationRule,\n): boolean {\n\tconst filter = current.Filter as\n\t\t| { Key?: { FilterRules?: unknown[] } }\n\t\t| undefined;\n\treturn (\n\t\tcurrent.Id === wanted.Id &&\n\t\tcurrent.QueueArn === wanted.QueueArn &&\n\t\tJSON.stringify([...(current.Events ?? [])].sort()) ===\n\t\t\tJSON.stringify([...(wanted.Events ?? [])].sort()) &&\n\t\t(filter?.Key?.FilterRules?.length ?? 0) === 0\n\t);\n}\n\n/**\n * Apply each bucket's expiry, beside whatever other rules it has, skipping\n * those already correct — the same merge the `s3` provider makes deployed.\n */\nexport async function applyLifecycles(\n\tclient: BucketClient,\n\tlifecycles: readonly {\n\t\tbucket: string;\n\t\texpire: Readonly<Record<string, number>>;\n\t}[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { bucket, expire } of lifecycles) {\n\t\tconst merge = mergeLifecycle(await client.lifecycle(bucket), expire);\n\t\tconst id = `${bucket}:lifecycle`;\n\t\tconst describe = `${merge.describe} on ${bucket}`;\n\n\t\t// Nothing declared and nothing of gkm's there: not worth a line.\n\t\tif (!merge.changed && Object.keys(expire).length === 0) continue;\n\t\tif (!merge.changed) {\n\t\t\tapplied.push({ id, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setLifecycle(bucket, merge.rules);\n\t\tapplied.push({ id, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/**\n * Apply each served bucket's open-path policy, skipping those already correct.\n *\n * Compared as parsed JSON rather than as text: the same policy re-serialised\n * with different key order is the same policy, and rewriting it every reconcile\n * would report a change on every start.\n */\nexport async function applyPolicies(\n\tclient: BucketClient,\n\tpolicies: readonly { bucket: string; open: string[] }[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const { bucket, open } of policies) {\n\t\tconst wanted = bucketPolicy(bucket, open);\n\t\tconst describe = `open paths on ${bucket}`;\n\n\t\tif (equivalent(await client.policy(bucket), wanted)) {\n\t\t\tapplied.push({ id: `${bucket}:policy`, describe, created: false });\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.setPolicy(bucket, wanted);\n\t\tapplied.push({ id: `${bucket}:policy`, describe, created: true });\n\t}\n\n\treturn applied;\n}\n\n/** Whether two policy documents say the same thing. */\nfunction equivalent(current: string | undefined, wanted: string): boolean {\n\tif (!current) return false;\n\n\ttry {\n\t\treturn (\n\t\t\tJSON.stringify(JSON.parse(current)) === JSON.stringify(JSON.parse(wanted))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Create every bucket the plan names, skipping those that exist. */\nexport async function applyBuckets(\n\tclient: BucketClient,\n\tbuckets: readonly string[],\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tfor (const bucket of buckets) {\n\t\tif (await client.exists(bucket)) {\n\t\t\tapplied.push({\n\t\t\t\tid: bucket,\n\t\t\t\tdescribe: `bucket ${bucket}`,\n\t\t\t\tcreated: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait client.create(bucket);\n\t\tapplied.push({ id: bucket, describe: `bucket ${bucket}`, created: true });\n\t}\n\n\treturn applied;\n}\n","/**\n * The stack's `backups` service: what a deployed compose stage with Postgres\n * runs beside its apps, unless `deploy.backups.<stage>` is `false`.\n *\n * - **The image** is built from the stack's own Postgres image —\n * `postgres:<major>-alpine`, already on the server for the stack, and with\n * the `pg_dump` that matches the server — with Node added and gkm's runner\n * (`runner.ts`) copied in. Nothing is pulled that the stack does not have,\n * and nothing is mounted from the host: the build context is two files.\n * - **Its key** is `BACKUPS_URL`, from the stage's secrets, like any app's:\n * allowed to put objects under the stage's backups prefix and nothing else.\n * The server holds no AWS credentials of its own.\n * - **Its login** is a role of its own, `<project>_backups`, granted\n * `pg_read_all_data` — it can read every database and write none. Postgres\n * before 14 has no such role, and there it signs in as the stack's\n * superuser.\n * - **Its health** is the last good run: unhealthy once that is more than\n * twice the schedule's longest gap old, after a startup grace.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { DEFAULT_POSTGRES_VERSION } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { postgresImage } from '../reconcile/containers.js';\nimport { localRolePassword } from '../reconcile/env.js';\nimport { postgresRoleSlug } from '../reconcile/localCredentials.js';\nimport type { Plan } from '../reconcile/plan.js';\nimport { quoteIdentifier, type Statement } from '../reconcile/provision.js';\nimport {\n\ttype BackupDatabase,\n\ttype BackupsWorkspace,\n\tbackupDatabases,\n\tbackupsPrefix,\n} from './config.js';\nimport type { StageBackups } from './schedule.js';\n\n/** The service's name in the stack. */\nexport const BACKUPS_SERVICE = 'backups';\n\n/** The secret its key is written to. */\nexport const BACKUPS_URL_KEY = 'BACKUPS_URL';\n\n/** Where the runner is, in the image. */\nexport const RUNNER_PATH = '/gkm/backup.mjs';\n\n/** The first Postgres with `pg_read_all_data`. */\nconst READ_ALL_DATA_SINCE = 14;\n\n/** A stage that backs up, and no key to back up with. */\nexport class BackupsUrlMissing extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`'${stage}' runs Postgres, so its stack backs it up, and its secrets ` +\n\t\t\t\t`hold no ${BACKUPS_URL_KEY} to back up with. The deploy writes it — ` +\n\t\t\t\t\"the IAM user and key it creates in the stage's AWS account — so \" +\n\t\t\t\t'run the deploy with the ' +\n\t\t\t\t\"account's credentials. To take no backups on this stage, set \" +\n\t\t\t\t`deploy.backups.${stage}: false.`,\n\t\t);\n\t\tthis.name = 'BackupsUrlMissing';\n\t}\n}\n\n/** The backups role: `<project>_backups`, as the superuser is `<project>_admin`. */\nexport function backupsRole(project: string): string {\n\treturn `${postgresRoleSlug(project)}_backups`;\n}\n\n/** The stack's backups, as its compose file and env file have them. */\nexport interface StackBackups {\n\tbackups: StageBackups;\n\tdatabases: BackupDatabase[];\n\t/** `gkm/<project>/<stage>/backups`. */\n\tprefix: string;\n\t/** The Postgres image it is built from. */\n\tfrom: string;\n\t/** `<project>-backups:pg18-<hash>`: built on the server, never pushed. */\n\timage: string;\n\t/** Its build context: the Dockerfile and the runner. */\n\tfiles: { Dockerfile: string; 'backup.mjs': string };\n\t/** What it signs in to Postgres as. */\n\tlogin: { user: string; password: string };\n\t/** Whether that is its own read-only role (else the superuser). */\n\treadOnly: boolean;\n\t/** Its environment — empty in a stack that only builds. */\n\tenv: Record<string, string>;\n}\n\n/**\n * The runner's source, as JavaScript: the built `backups/runner.mjs` beside\n * the CLI's bundle, or — run from source — `runner.ts`, with its types\n * stripped by esbuild.\n */\nexport function runnerSource(): string {\n\tconst here = dirname(fileURLToPath(import.meta.url));\n\tfor (const path of [\n\t\tjoin(here, 'backups', 'runner.mjs'),\n\t\tjoin(here, 'runner.mjs'),\n\t\tjoin(here, '..', 'backups', 'runner.mjs'),\n\t]) {\n\t\tif (existsSync(path)) return readFileSync(path, 'utf-8');\n\t}\n\tconst { transformSync } = createRequire(import.meta.url)(\n\t\t'esbuild',\n\t) as typeof import('esbuild');\n\treturn transformSync(readFileSync(join(here, 'runner.ts'), 'utf-8'), {\n\t\tloader: 'ts',\n\t\tformat: 'esm',\n\t\ttarget: 'node22',\n\t}).code;\n}\n\n/** The image's Dockerfile: the stack's Postgres, Node, and the runner. */\nexport function backupsDockerfile(from: string): string {\n\treturn `# Generated by gkm — the stage's backups: pg_dump from ${from}, and gkm's uploader.\nFROM ${from}\nRUN apk add --no-cache nodejs\nCOPY backup.mjs ${RUNNER_PATH}\nUSER postgres\nENTRYPOINT []\nCMD [\"node\", \"${RUNNER_PATH}\", \"serve\"]\n`;\n}\n\nexport interface StackBackupsInput {\n\tworkspace: BackupsWorkspace;\n\tstage: string;\n\tproject: string;\n\tplan: Plan;\n\tbackups: StageBackups;\n\t/** The stage's secrets, by key. */\n\tcustom: Readonly<Record<string, string>>;\n\tseed: string;\n\t/** The stack's superuser. */\n\tsuperuser: { user: string; password: string };\n\t/** What the stage's telemetry hands a process, when it is on. */\n\ttelemetry?: Readonly<Record<string, string>>;\n\t/** The stack only builds: no environment, no key needed. */\n\tbuildOnly?: boolean;\n}\n\n/**\n * The stack's backups service, for a stage whose backups are on.\n *\n * @throws {BackupsUrlMissing} when the stage's secrets hold no key\n */\nexport function stackBackups(input: StackBackupsInput): StackBackups {\n\tconst { plan, stage } = input;\n\tconst version =\n\t\tplan.resources.find((r) => r.version)?.version ?? DEFAULT_POSTGRES_VERSION;\n\tconst from = postgresImage(version);\n\tconst script = runnerSource();\n\tconst dockerfile = backupsDockerfile(from);\n\tconst hash = createHash('sha256')\n\t\t.update(dockerfile)\n\t\t.update(script)\n\t\t.digest('hex')\n\t\t.slice(0, 12);\n\n\tconst readOnly = version >= READ_ALL_DATA_SINCE;\n\tconst role = backupsRole(input.workspace.name);\n\tconst login = readOnly\n\t\t? {\n\t\t\t\tuser: role,\n\t\t\t\tpassword: localRolePassword(\n\t\t\t\t\tinput.workspace.name,\n\t\t\t\t\tplan,\n\t\t\t\t\trole,\n\t\t\t\t\tinput.seed,\n\t\t\t\t),\n\t\t\t}\n\t\t: input.superuser;\n\n\tconst databases = backupDatabases(plan.resources);\n\tconst prefix = backupsPrefix(input.workspace, stage);\n\tconst { kind, ...schedule } = input.backups.schedule;\n\n\tlet env: Record<string, string> = {};\n\tif (!input.buildOnly) {\n\t\tconst url = input.custom[BACKUPS_URL_KEY];\n\t\tif (!url) throw new BackupsUrlMissing(stage);\n\t\tenv = {\n\t\t\tBACKUPS_URL: url,\n\t\t\tBACKUPS_PREFIX: prefix,\n\t\t\tBACKUPS_DATABASES: JSON.stringify(\n\t\t\t\tdatabases.map(({ file, name }) => ({ file, name })),\n\t\t\t),\n\t\t\tBACKUPS_SCHEDULE: JSON.stringify(\n\t\t\t\tkind === 'cron'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tminutes: input.backups.schedule.minutes,\n\t\t\t\t\t\t\thours: input.backups.schedule.hours,\n\t\t\t\t\t\t\tdays: input.backups.schedule.days,\n\t\t\t\t\t\t\tmonths: input.backups.schedule.months,\n\t\t\t\t\t\t\tweekdays: input.backups.schedule.weekdays,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { kind, ...schedule },\n\t\t\t),\n\t\t\tBACKUPS_MAX_GAP_SECONDS: String(input.backups.maxGapSeconds),\n\t\t\tPGHOST: 'postgres',\n\t\t\tPGPORT: '5432',\n\t\t\tPGUSER: login.user,\n\t\t\tPGPASSWORD: login.password,\n\t\t\t...(input.telemetry?.OTEL_EXPORTER_OTLP_ENDPOINT\n\t\t\t\t? {\n\t\t\t\t\t\tOTEL_EXPORTER_OTLP_ENDPOINT:\n\t\t\t\t\t\t\tinput.telemetry.OTEL_EXPORTER_OTLP_ENDPOINT,\n\t\t\t\t\t\t...(input.telemetry.OTEL_EXPORTER_OTLP_HEADERS\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tOTEL_EXPORTER_OTLP_HEADERS:\n\t\t\t\t\t\t\t\t\t\tinput.telemetry.OTEL_EXPORTER_OTLP_HEADERS,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tOTEL_SERVICE_NAME: BACKUPS_SERVICE,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\tbackups: input.backups,\n\t\tdatabases,\n\t\tprefix,\n\t\tfrom,\n\t\timage: `${input.project}-backups:pg${version}-${hash}`,\n\t\tfiles: { Dockerfile: dockerfile, 'backup.mjs': script },\n\t\tlogin,\n\t\treadOnly,\n\t\tenv,\n\t};\n}\n\n/** The service in the stack's compose file. */\nexport function backupsService(backups: StackBackups, envFiles: boolean) {\n\treturn {\n\t\timage: backups.image,\n\t\t// Built on the server from two files; there is nothing to pull.\n\t\tbuild: { context: `./${BACKUPS_SERVICE}`, dockerfile: 'Dockerfile' },\n\t\tpull_policy: 'build' as const,\n\t\trestart: 'unless-stopped',\n\t\t...(envFiles\n\t\t\t? {\n\t\t\t\t\tenv_file: [\n\t\t\t\t\t\t{ path: `./${BACKUPS_SERVICE}.env`, format: 'raw' as const },\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t: {}),\n\t\tdepends_on: { postgres: { condition: 'service_healthy' as const } },\n\t\thealthcheck: {\n\t\t\ttest: ['CMD', 'node', RUNNER_PATH, 'health'],\n\t\t\tinterval: '1m',\n\t\t\ttimeout: '10s',\n\t\t\tretries: 3,\n\t\t\tstart_period: '30s',\n\t\t},\n\t};\n}\n\n/**\n * The backups role, created and kept: able to sign in and read every\n * database, and nothing else. None when it signs in as the superuser.\n */\nexport function backupsRoleStatements(backups: StackBackups): Statement[] {\n\tif (!backups.readOnly) return [];\n\tconst role = quoteIdentifier(backups.login.user);\n\tconst password = `'${backups.login.password.replace(/'/g, \"''\")}'`;\n\treturn [\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}`,\n\t\t\texists: {\n\t\t\t\tsql: 'SELECT 1 FROM pg_roles WHERE rolname = $1',\n\t\t\t\tvalues: [backups.login.user],\n\t\t\t},\n\t\t\tcreate: `CREATE ROLE ${role} LOGIN PASSWORD ${password}`,\n\t\t},\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}: its password`,\n\t\t\tcreate: `ALTER ROLE ${role} WITH LOGIN PASSWORD ${password}`,\n\t\t},\n\t\t{\n\t\t\tid: BACKUPS_SERVICE,\n\t\t\tdescribe: `role ${backups.login.user}: read every database`,\n\t\t\tcreate: `GRANT pg_read_all_data TO ${role}`,\n\t\t},\n\t];\n}\n","import { isAbsolute, join, relative, sep } from 'node:path';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport { fileServerLabel } from '../workspace/fileServerLabel.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/**\n * A Worker as a deploy unit: one process, one image, one service.\n *\n * A worker declares no app — it names a process, not a directory — so the\n * image is built from the app whose code holds its work: `gkm build` there\n * writes the worker's entry beside the server's, and the worker's image\n * copies that bundle out instead.\n */\nexport interface WorkerUnit {\n\t/** The construct, `Jobs`. */\n\tid: string;\n\t/** Its service and image name, `jobs`. */\n\tname: string;\n\t/** The backend app whose build writes its entry, `api`. */\n\tapp: string;\n}\n\n/** A worker with background work and no backend app to build it from. */\nexport class WorkerHasNoApp extends GkmError {\n\tconstructor(readonly worker: string) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' has crons, queues or subscribers, and the ` +\n\t\t\t\t`workspace has no backend app that builds a server to carry its ` +\n\t\t\t\t`entry. Declare a RestApi whose app holds the worker's code.`,\n\t\t);\n\t\tthis.name = 'WorkerHasNoApp';\n\t}\n}\n\n/** A worker whose service name an app already has. */\nexport class WorkerNameTaken extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly service: string,\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs as the service '${service}', and an app is ` +\n\t\t\t\t`already called that. Rename the worker — new Worker('${worker}Worker') ` +\n\t\t\t\t`— so each container has a name of its own.`,\n\t\t);\n\t\tthis.name = 'WorkerNameTaken';\n\t}\n}\n\n/**\n * The workers a workspace deploys — each one that has background work — and\n * the app each is built from.\n *\n * The host is the backend app whose directory holds the most of the worker's\n * files; one whose work sits outside every app (a shared `jobs/` directory)\n * is built by the first backend, by name, that generates a server. An app\n * with its own entry is never one — gkm's generators do not build it — and a\n * surface that serves itself, an auth server, only when it holds the work.\n *\n * @param background Each worker's files, from discovery's `background`.\n */\nexport function workerUnits(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tbackground: Readonly<Record<string, readonly string[]>>,\n): WorkerUnit[] {\n\tconst hosts = hostApps(workspace, manifest);\n\n\tconst units: WorkerUnit[] = [];\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration.kind !== 'worker') continue;\n\t\tconst files = background[id] ?? [];\n\t\tif (files.length === 0) continue;\n\n\t\tconst name = appKey(id);\n\t\tif (workspace.apps[name]) throw new WorkerNameTaken(id, name);\n\n\t\tconst host = hostFor(hosts, files);\n\t\tif (!host) throw new WorkerHasNoApp(id);\n\n\t\tunits.push({ id, name, app: host.name });\n\t}\n\n\treturn units.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/** The service and image name of a file server's processors: `assets-processors`. */\nexport function processorUnitName(fileServerId: string): string {\n\treturn `${fileServerLabel(fileServerId)}-processors`;\n}\n\n/** A file server's processors as a deploy unit: one process, one image. */\nexport interface ProcessorUnit {\n\t/** The file server's surface, `AssetsServer`. */\n\tid: string;\n\t/** Its service and image name, `assets-processors`. */\n\tname: string;\n\t/** The backend app whose build writes its entry, `api`. */\n\tapp: string;\n}\n\n/** A file server with processors and no backend app to build them from. */\nexport class ProcessorsHaveNoApp extends GkmError {\n\tconstructor(readonly fileServer: string) {\n\t\tsuper(\n\t\t\t`The file server '${fileServer}' has processors, and the workspace has ` +\n\t\t\t\t`no backend app that builds a server to carry their entry. Declare a ` +\n\t\t\t\t`RestApi whose app holds the processors' code.`,\n\t\t);\n\t\tthis.name = 'ProcessorsHaveNoApp';\n\t}\n}\n\n/**\n * The processor units a workspace deploys — each file server with processors\n * — and the app each is built from, chosen as a worker's is: the backend app\n * holding the most of its processors' files.\n */\nexport function processorUnits(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): ProcessorUnit[] {\n\tconst hosts = hostApps(workspace, manifest);\n\n\tconst units: ProcessorUnit[] = [];\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'file-server') continue;\n\t\tconst processors = declaration.processors ?? [];\n\t\tif (processors.length === 0) continue;\n\n\t\t// Each handler is its source, `apps/api/processors/thumbs.ts#thumbs`,\n\t\t// until a build replaces it.\n\t\tconst files = processors.map(({ handler }) => {\n\t\t\tconst file = handler.split('#')[0] ?? handler;\n\t\t\treturn isAbsolute(file) ? file : join(workspace.root, file);\n\t\t});\n\t\tconst host = hostFor(hosts, files);\n\t\tif (!host) throw new ProcessorsHaveNoApp(declaration.id);\n\n\t\tconst name = processorUnitName(declaration.id);\n\t\tif (workspace.apps[name]) throw new WorkerNameTaken(declaration.id, name);\n\t\tunits.push({ id: declaration.id, name, app: host.name });\n\t}\n\n\treturn units.sort((a, b) => a.name.localeCompare(b.name));\n}\n\ninterface HostApp {\n\tname: string;\n\troot: string;\n\tgenerated: boolean;\n}\n\n/** The backend apps whose builds generate a server, each where it lives. */\nfunction hostApps(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): HostApp[] {\n\treturn Object.entries(workspace.apps)\n\t\t.filter(([, app]) => app.type === 'backend' && !app.entry)\n\t\t.map(([name, app]) => {\n\t\t\tconst surface = Object.entries(manifest).find(\n\t\t\t\t([id, d]) =>\n\t\t\t\t\t(d.kind === 'rest-api' || d.kind === 'websocket-api') &&\n\t\t\t\t\tappKey(id) === name,\n\t\t\t)?.[1];\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\troot: isAbsolute(app.path) ? app.path : join(workspace.root, app.path),\n\t\t\t\t// A surface that serves itself — an auth server — has a build that\n\t\t\t\t// generates no server. A WebSocket surface always serves itself.\n\t\t\t\tgenerated: !(\n\t\t\t\t\tsurface?.kind === 'websocket-api' ||\n\t\t\t\t\t(surface?.kind === 'rest-api' && surface.servesItself === true)\n\t\t\t\t),\n\t\t\t};\n\t\t})\n\t\t.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * The app holding the most of these files; then one that generates a server;\n * then by name. None when no app holds any and none generates a server.\n */\nfunction hostFor(\n\thosts: readonly HostApp[],\n\tfiles: readonly string[],\n): HostApp | undefined {\n\tconst ranked = hosts\n\t\t.map((host) => ({\n\t\t\thost,\n\t\t\tholds: files.filter((file) => isUnder(file, host.root)).length,\n\t\t}))\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.holds - a.holds ||\n\t\t\t\tNumber(b.host.generated) - Number(a.host.generated),\n\t\t);\n\tconst host = ranked[0]?.host;\n\tif (!host || (ranked[0]!.holds === 0 && !host.generated)) return undefined;\n\treturn host;\n}\n\n/** Whether `file` is inside `dir`. */\nexport function isUnder(file: string, dir: string): boolean {\n\tconst rel = relative(dir, file);\n\treturn rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n\t\t? !rel.startsWith(`..${sep}`)\n\t\t: false;\n}\n","import {\n\ttype ConstructManifest,\n\tIMAGE_ORIGINS_KEY,\n\timageOriginSources,\n\timageOrigins,\n\tPUBLIC_PREFIX,\n\ttype PublicDeclaration,\n\tprovidedKeyFor,\n\tpublicEnvFor,\n\tpublicValues,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { GkmError } from '../errors.js';\nimport { signedOrigins } from '../reconcile/signedOrigins.js';\nimport { appKey } from '../workspace/derive.js';\n\n/**\n * A site's build inlines where it loads files from — a file server's URL, a\n * bucket's signed origin — and the stage has not resolved it yet: a provider\n * writes it on the stage's first deploy. Built anyway, the bundle would ship\n * without its own asset host, and every image from it would be refused.\n */\nexport class SiteBuildValueUnresolved extends GkmError {\n\tconstructor(\n\t\treadonly site: string,\n\t\treadonly key: string,\n\t\treadonly stage: string,\n\t\t/** The stored key it is derived from, where it is derived. */\n\t\treadonly from?: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${site}' inlines ${key} into its build, and the stage '${stage}' ` +\n\t\t\t\t`has ${from ? `no ${from} to derive it from` : 'no value for it'} yet. ` +\n\t\t\t\t`A provider writes it on the stage's first deploy: deploy the stage ` +\n\t\t\t\t`first (gkm deploy --stage ${stage}), then build. Or set it: ` +\n\t\t\t\t`gkm secrets:set ${from ?? key} '…' --stage ${stage}`,\n\t\t);\n\t\tthis.name = 'SiteBuildValueUnresolved';\n\t}\n}\n\n/** How {@link publicBuildValues} treats a value it inlines that is missing. */\nexport interface PublicBuildOptions {\n\t/**\n\t * Refuse a build whose file origins — each file server's URL, each\n\t * bucket's signed origin — the stage has not resolved, naming the stage.\n\t * A deployed stage's build; locally every one resolves.\n\t */\n\trequireFileOrigins?: { stage: string };\n}\n\n/**\n * What a site's image is built with — or a mobile app's EAS build: every\n * value its build reads, resolved for the stage, and so every `ARG` a site's\n * Dockerfile declares.\n *\n * - **Its edges' public values and its own address**, under the variant's\n * public prefix (`publicEnvFor`): what the bundler inlines.\n * - **Its own address under its own name** (`WEB_URL`). Server code runs at\n * build too — `next build` prerenders, and a page's `metadataBase` is read\n * then — and `gkm exec -- next build` has it locally, so the image build\n * must, or a site that builds locally fails in CI. A mobile app has no\n * address: its own value is its scheme (`APP_SCHEME`), which its\n * `app.config.ts` reads when EAS builds it.\n * - **Every stage secret already named for the bundle**: a key carrying the\n * variant's public prefix (`NEXT_PUBLIC_APP_STORE_URL` on a `next` site) was\n * declared public by whoever named it, so it is passed. Anything else is\n * not: a secret without the prefix never reaches a site's build.\n *\n * A value the stage resolves to nothing is left out rather than passed empty\n * — except, with `requireFileOrigins`, where its pages load files from.\n * A derived value wins over a stage secret of the same name: the site's\n * addresses are the construct's, not a copy someone set.\n */\nexport function publicBuildValues(\n\tsite: PublicDeclaration,\n\tmanifest: ConstructManifest,\n\tresolve: (key: string) => string | undefined,\n\tsecrets: Readonly<Record<string, string>>,\n\toptions: PublicBuildOptions = {},\n): Record<string, string> {\n\tconst args: Record<string, string> = {};\n\n\tconst own = providedKeyFor(\n\t\tsite.id,\n\t\tsite.kind,\n\t\tsite.kind === 'site' ? 'url' : 'scheme',\n\t);\n\tconst ownValue = resolve(own);\n\tif (ownValue) args[own] = ownValue;\n\n\t// A bucket's signed origin is derived from its connection, wherever that\n\t// resolved — so it is resolved here too, rather than looked up.\n\tconst derived = signedOrigins(\n\t\tObject.keys(manifest).filter((id) => manifest[id]?.kind === 'objects'),\n\t\tresolve,\n\t);\n\tfor (const [key, source] of Object.entries(publicEnvFor(site, manifest))) {\n\t\tconst value = resolve(source) ?? derived[source];\n\t\tif (value) args[key] = value;\n\t}\n\n\tconst prefix = PUBLIC_PREFIX[site.variant];\n\tconst required = options.requireFileOrigins;\n\tif (required) {\n\t\tfor (const value of publicValues(site, manifest)) {\n\t\t\tif (value.kind === 'file-server' && value.role === 'url') {\n\t\t\t\tif (!resolve(value.key)) {\n\t\t\t\t\tthrow new SiteBuildValueUnresolved(\n\t\t\t\t\t\tsite.id,\n\t\t\t\t\t\tvalue.key,\n\t\t\t\t\t\trequired.stage,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A signed origin is derived: what has to resolve is the connection.\n\t\t\t// One that resolved to no knowable host is not a missing value.\n\t\t\tif (value.kind === 'objects' && value.role === 'signedOrigin') {\n\t\t\t\tconst connection = providedKeyFor(\n\t\t\t\t\tvalue.id,\n\t\t\t\t\t'objects',\n\t\t\t\t\t'connectionString',\n\t\t\t\t);\n\t\t\t\tif (!resolve(value.key) && !resolve(connection)) {\n\t\t\t\t\tthrow new SiteBuildValueUnresolved(\n\t\t\t\t\t\tsite.id,\n\t\t\t\t\t\tvalue.key,\n\t\t\t\t\t\trequired.stage,\n\t\t\t\t\t\tconnection,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconst origins = imageOrigins(\n\t\timageOriginSources(site, manifest),\n\t\t(source) => resolve(source) ?? derived[source],\n\t);\n\tif (origins) args[`${prefix}${IMAGE_ORIGINS_KEY}`] = origins;\n\n\tfor (const [key, value] of Object.entries(secrets)) {\n\t\tif (key.startsWith(prefix) && args[key] === undefined && value) {\n\t\t\targs[key] = value;\n\t\t}\n\t}\n\n\treturn args;\n}\n\n/**\n * Where a site's own hosts point during its image build: this loopback\n * address, on which nothing in a build container listens — so a request to\n * one is refused at once instead of waiting on a host that is not up yet.\n */\nexport const OFFLINE_BUILD_ADDRESS = '127.0.0.1';\n\n/**\n * The hosts a site's image build must not wait on: its own and those of the\n * constructs its `.dependsOn()` names, as this stage serves them.\n *\n * None of them answers while the image is built — the stack the site belongs\n * to is started after it — and a fetch to a public host that does not answer\n * yet can stall until the framework's prerender limit (Next's 60s). Mapped to\n * {@link OFFLINE_BUILD_ADDRESS} in the build's `/etc/hosts`, each is refused\n * at once, and the page renders on its first request instead.\n *\n * The mapping is the build's only: the URLs the bundle inlines are the real\n * ones, and the running container resolves them as anything else does. A\n * stage secret named for the bundle is someone else's host (an analytics\n * service, a store) and is left alone, as are `localhost` and an address.\n *\n * None for a site that pre-renders against its stage (`prerender: 'stage'`):\n * it is built once those hosts answer, and has to reach them.\n */\nexport function offlineBuildHosts(\n\tsite: SiteDeclaration,\n\tmanifest: ConstructManifest,\n\tresolve: (key: string) => string | undefined,\n): string[] {\n\tif (site.prerender === 'stage') return [];\n\tconst sources = [\n\t\tprovidedKeyFor(site.id, site.kind, 'url'),\n\t\t...Object.values(publicEnvFor(site, manifest)),\n\t];\n\tconst hosts = new Set<string>();\n\tfor (const source of sources) {\n\t\tconst host = hostOf(resolve(source));\n\t\tif (host) hosts.add(host);\n\t}\n\treturn [...hosts].sort();\n}\n\n/** A URL's host, where it is a name `/etc/hosts` can map. */\nfunction hostOf(value: string | undefined): string | undefined {\n\tif (!value || !URL.canParse(value)) return undefined;\n\tconst { protocol, hostname } = new URL(value);\n\tif (!/^(https?|wss?):$/.test(protocol)) return undefined;\n\t// A wildcard is no one name: `/etc/hosts` maps names, not patterns.\n\tif (hostname === 'localhost' || hostname.includes('*')) return undefined;\n\t// An address is reached as it is; only a name is looked up.\n\tif (/^[\\d.]+$/.test(hostname) || hostname.startsWith('[')) return undefined;\n\treturn hostname;\n}\n\n/**\n * {@link offlineBuildHosts} for a target that knows each app's public URL by\n * its app key rather than by construct key — the site's own, and each app it\n * calls. None, for an app that declares no site.\n */\nexport function siteOfflineHosts(\n\tmanifest: ConstructManifest,\n\tappName: string,\n\townUrl: string,\n\turls: Readonly<Record<string, string>>,\n): string[] {\n\tconst entries = Object.entries(manifest);\n\tconst site = entries.find(\n\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t)?.[1];\n\tif (site?.kind !== 'site') return [];\n\n\tconst byKey = new Map<string, string>();\n\tfor (const [id] of entries) {\n\t\tconst name = appKey(id);\n\t\tconst url = name === appName ? ownUrl : urls[name];\n\t\tif (url) byKey.set(providedKeyFor(id, manifest[id]!.kind, 'url'), url);\n\t}\n\treturn offlineBuildHosts(site, manifest, (key) => byKey.get(key));\n}\n\n/**\n * Whether a site runs a server of its own — Next's, TanStack Start's — which\n * reads an environment at runtime as a backend does: its edges' public URLs\n * and the stage's secrets. A `static` site is a finished bundle, and reads\n * nothing once it is built.\n */\nexport function runsServer(site: Pick<SiteDeclaration, 'variant'>): boolean {\n\treturn site.variant !== 'static';\n}\n","import { PUBLIC_ENV_PREFIXES } from '../workspace/publicEnv.js';\n\n/**\n * Set by a site's Dockerfile in its builder stage: this process is building\n * an image.\n *\n * Inside an image there is no stage to load secrets for and no local\n * container to resolve an address from — the public URLs the bundle inlines\n * arrived as the Dockerfile's build args, already in the environment. So\n * `gkm exec -- next build` there injects exactly those, and never the\n * `localhost` addresses a workspace resolves on a developer's machine.\n */\nexport const IMAGE_BUILD_ENV = 'GKM_IMAGE_BUILD';\n\n/** Whether this process is building an image. */\nexport function isImageBuild(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn env[IMAGE_BUILD_ENV] === '1';\n}\n\n/**\n * Set by a site's Dockerfile in its builder stage: this build is offline —\n * no stage is reachable from it.\n *\n * A site's image is built before the stack it belongs to runs, so the APIs\n * its `.dependsOn()` names do not answer yet: data a page fetches while the\n * framework prerenders it would be none, cached as the page. A site tests\n * `process.env.GKM_BUILD_OFFLINE === '1'` to skip that fetch, and renders the\n * page on its first request instead — which gkm's warm-up after a deploy\n * makes before any visitor does.\n *\n * Separate from {@link IMAGE_BUILD_ENV}, which says what `gkm exec` injects:\n * this says what the build can reach. Only the builder stage sets it; the\n * running container never has it.\n */\nexport const BUILD_OFFLINE_ENV = 'GKM_BUILD_OFFLINE';\n\n/** Whether this process is a build that no stage is reachable from. */\nexport function isOfflineBuild(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn env[BUILD_OFFLINE_ENV] === '1';\n}\n\n/**\n * What `gkm exec` injects inside an image build: the public values its build\n * args set — every `NEXT_PUBLIC_*`, `VITE_*` and `EXPO_PUBLIC_*` — and\n * nothing read from a secrets store, a file or a container.\n */\nexport function imageBuildCredentials(\n\tenv: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n\tconst credentials: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (value === undefined) continue;\n\t\tif (PUBLIC_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))) {\n\t\t\tcredentials[key] = value;\n\t\t}\n\t}\n\treturn credentials;\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, parse, posix } from 'node:path';\nimport { externalsManifestName } from '../build/native';\nimport { BUILD_OFFLINE_ENV, IMAGE_BUILD_ENV } from '../exec/imageBuild';\nimport {\n\ttype ClientTelemetryDefault,\n\ttelemetryArgs,\n} from '../generators/clientTelemetry';\nimport type { CacheBackend, DockerConfig, GkmConfig } from '../types';\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';\n\n/**\n * The turbo every image prunes and builds with when the build root resolves\n * none of its own: a repository without turbo still needs `turbo prune` to\n * cut its slice of the workspace, and an unpinned `turbo` is whatever the\n * registry says on the day of the build.\n */\nexport const TURBO_VERSION = '2.5.4';\n\n/**\n * Caddy, which serves a static site's files. A 2.x tag, so a rebuild picks\n * up patch releases and never a major.\n */\nexport const STATIC_SITE_IMAGE = 'caddy:2.10-alpine';\n\n/**\n * The image generated Dockerfiles build on unless one is configured. Pinned to\n * a Node security release, not the floating `node:22-alpine` tag, so a cached\n * or older image can't put a build below the patched version — and the\n * Dockerfile says which version it runs.\n */\nexport const DEFAULT_BASE_IMAGE = 'node:22.23.4-alpine';\n\n/**\n * How an image is built: every template prunes the build root to the app's\n * slice, installs it, builds it and copies the result into a runner.\n *\n * Every path is relative to the build root — the directory that holds the\n * lockfile, which is the gkm workspace's root in a project of its own and the\n * monorepo's root when the workspace is nested inside one.\n */\nexport interface ImageTemplateOptions {\n\t/** The image the Dockerfile builds; informational. */\n\timageName?: string;\n\tbaseImage: string;\n\tport: number;\n\t/** The app's directory, relative to the build root. */\n\tappPath: string;\n\t/** The app's package, which turbo prunes to. */\n\tturboPackage: string;\n\t/** Detected package manager */\n\tpackageManager: PackageManager;\n\t/**\n\t * The exact version the build root's `packageManager` field names. Absent,\n\t * the image installs the package manager's latest.\n\t */\n\tpackageManagerVersion?: string;\n\t/** The turbo the build root resolves; `TURBO_VERSION` otherwise. */\n\tturboVersion?: string;\n\t/**\n\t * Whether the build root is a workspace of packages, which turbo prunes. A\n\t * single package is copied whole. Defaults to true.\n\t */\n\tmonorepo?: boolean;\n\t/**\n\t * Other packages the slice keeps: a gkm workspace nested in a monorepo is a\n\t * package of its own, holding the config and constructs the app is built\n\t * from.\n\t */\n\tprunePackages?: string[];\n\t/** The gkm workspace's root, relative to the build root. Defaults to `.` */\n\tgkmRoot?: string;\n\t/**\n\t * What under the gkm root the build reads besides the app — its config and\n\t * the directories its construct globs start in. `turbo prune` keeps\n\t * packages; these are copied beside them.\n\t */\n\tgkmPaths?: string[];\n\t/**\n\t * A site's: the backends whose typed clients it imports, each generated\n\t * in the builder — `gkm openapi --app <app>` from the backend's directory\n\t * (relative to the build root) — before the site is built.\n\t */\n\tclients?: {\n\t\tapp: string;\n\t\tpath: string;\n\t\t/**\n\t\t * Whether this client propagates trace context by default — passed as\n\t\t * `--telemetry [rate]`. Off when absent; the site's edge to a\n\t\t * `Telemetry` construct is what sets it.\n\t\t */\n\t\ttelemetry?: ClientTelemetryDefault;\n\t}[];\n}\n\nexport interface FrontendDockerfileOptions extends ImageTemplateOptions {\n\t/**\n\t * Public URL build args to include in the Dockerfile.\n\t * These will be declared as ARG and converted to ENV for the build.\n\t * Example: ['NEXT_PUBLIC_API_URL', 'NEXT_PUBLIC_AUTH_URL']\n\t */\n\tpublicUrlArgs?: string[];\n\t/**\n\t * The site pre-renders against its stage (`prerender: 'stage'`): its\n\t * build is not offline — it runs once the site's APIs are up, and reaches\n\t * them — so `GKM_BUILD_OFFLINE` is not set, and the build trusts the root\n\t * {@link LOCAL_CA_BUILD_SECRET} hands it, where it is handed one.\n\t */\n\tprerender?: boolean;\n}\n\n/**\n * The build secret a site that pre-renders against its stage reads the root\n * certificate of the stage's edge from — gkm's local CA, on the local stage,\n * whose hosts no public root vouches for. A certificate, not a key; a secret\n * only because a build has no other way to be handed a file it should not\n * keep. Absent on a deployed stage, whose certificates are public ones.\n */\nexport const LOCAL_CA_BUILD_SECRET = 'gkm_local_ca';\n\n/**\n * The build argument naming the deploy a site that pre-renders against its\n * stage is built for — new on every deploy, so the layer that fetches the\n * stage's data is never served from Docker's cache.\n */\nexport const PRERENDER_RUN_ARG = 'GKM_PRERENDER_RUN';\n\nconst LOCKFILES: [string, PackageManager][] = [\n\t['pnpm-lock.yaml', 'pnpm'],\n\t['bun.lockb', 'bun'],\n\t['yarn.lock', 'yarn'],\n\t['package-lock.json', 'npm'],\n];\n\n/**\n * Detect package manager from lockfiles\n * Walks up the directory tree to find lockfile (for monorepos)\n */\nexport function detectPackageManager(\n\tcwd: string = process.cwd(),\n): PackageManager {\n\tconst lockfile = findLockfilePath(cwd);\n\tif (!lockfile) return 'pnpm';\n\tconst name = lockfile.slice(dirname(lockfile).length + 1);\n\treturn LOCKFILES.find(([file]) => file === name)?.[1] ?? 'pnpm';\n}\n\n/**\n * Find the lockfile path by walking up the directory tree\n * Returns the full path to the lockfile, or null if not found\n */\nexport function findLockfilePath(cwd: string = process.cwd()): string | null {\n\tfor (const dir of upFrom(cwd)) {\n\t\tfor (const [lockfile] of LOCKFILES) {\n\t\t\tconst lockfilePath = join(dir, lockfile);\n\t\t\tif (existsSync(lockfilePath)) {\n\t\t\t\treturn lockfilePath;\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The directory every image is built from: the nearest at or above `cwd`\n * holding a lockfile or a `pnpm-workspace.yaml` — the package manager's root,\n * which is what an install resolves the workspace's dependencies against.\n *\n * In a project of its own that is the gkm workspace's root. A gkm workspace\n * nested inside a monorepo, whose dependencies are the monorepo's\n * `workspace:*` packages, is built from the monorepo's root. `cwd` itself\n * when neither is found.\n */\nexport function findBuildRoot(cwd: string = process.cwd()): string {\n\tfor (const dir of upFrom(cwd)) {\n\t\tif (existsSync(join(dir, 'pnpm-workspace.yaml'))) return dir;\n\t\tfor (const [lockfile] of LOCKFILES) {\n\t\t\tif (existsSync(join(dir, lockfile))) return dir;\n\t\t}\n\t}\n\treturn cwd;\n}\n\n/** `cwd` and every directory above it, the filesystem root last. */\nfunction upFrom(cwd: string): string[] {\n\tconst dirs: string[] = [];\n\tconst root = parse(cwd).root;\n\tlet dir = cwd;\n\twhile (dir !== root) {\n\t\tdirs.push(dir);\n\t\tdir = dirname(dir);\n\t}\n\tdirs.push(root);\n\treturn dirs;\n}\n\n/** What a build root builds its images with. */\nexport interface BuildTools {\n\tpackageManager: PackageManager;\n\t/** From `packageManager` in the build root's package.json, if set. */\n\tpackageManagerVersion?: string;\n\t/** The turbo the build root resolves, or `TURBO_VERSION`. */\n\tturboVersion: string;\n\t/** Whether the build root is a workspace of packages. */\n\tmonorepo: boolean;\n}\n\n/** The package manager, its version, turbo's and the shape of a build root. */\nexport function resolveBuildTools(buildRoot: string): BuildTools {\n\tconst pkg = readJson(join(buildRoot, 'package.json'));\n\tconst packageManager = detectPackageManager(buildRoot);\n\tconst field =\n\t\ttypeof pkg?.packageManager === 'string' ? pkg.packageManager : '';\n\t// `pnpm@10.30.1+sha512.…` — the hash is corepack's, the version is ours.\n\tconst match = /^([a-z]+)@(\\d[^+\\s]*)/.exec(field);\n\tconst packageManagerVersion =\n\t\tmatch && match[1] === packageManager ? match[2] : undefined;\n\n\treturn {\n\t\tpackageManager,\n\t\t...(packageManagerVersion ? { packageManagerVersion } : {}),\n\t\tturboVersion: resolveTurboVersion(buildRoot) ?? TURBO_VERSION,\n\t\tmonorepo:\n\t\t\texistsSync(join(buildRoot, 'pnpm-workspace.yaml')) ||\n\t\t\tpkg?.workspaces !== undefined,\n\t};\n}\n\n/**\n * The turbo version a build root resolves: what is installed, or what its\n * lockfile pins. Undefined when it has none.\n */\nexport function resolveTurboVersion(buildRoot: string): string | undefined {\n\tconst installed = readJson(\n\t\tjoin(buildRoot, 'node_modules', 'turbo', 'package.json'),\n\t);\n\tif (typeof installed?.version === 'string') return installed.version;\n\n\tconst read = (file: string) => {\n\t\ttry {\n\t\t\treturn readFileSync(join(buildRoot, file), 'utf-8');\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t};\n\n\tconst pnpm = read('pnpm-lock.yaml');\n\tconst fromPnpm = pnpm && /^ {2}'?turbo@(\\d[^:'(\\s]*)'?:/m.exec(pnpm);\n\tif (fromPnpm) return fromPnpm[1];\n\n\tconst npm = read('package-lock.json');\n\tif (npm) {\n\t\tconst lock = safeParse(npm) as {\n\t\t\tpackages?: Record<string, { version?: string }>;\n\t\t};\n\t\tconst version = lock?.packages?.['node_modules/turbo']?.version;\n\t\tif (version) return version;\n\t}\n\n\tconst yarn = read('yarn.lock');\n\tconst fromYarn =\n\t\tyarn && /^\"?turbo@[^\\n]*:\\n\\s+version:? \"?(\\d[^\"\\s]*)\"?/m.exec(yarn);\n\tif (fromYarn) return fromYarn[1];\n\n\treturn undefined;\n}\n\nfunction readJson(path: string): Record<string, unknown> | undefined {\n\ttry {\n\t\treturn safeParse(readFileSync(path, 'utf-8'));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction safeParse(text: string): Record<string, unknown> | undefined {\n\ttry {\n\t\tconst value = JSON.parse(text);\n\t\treturn value && typeof value === 'object' ? value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Get the lockfile name for a package manager\n */\nexport function getLockfileName(pm: PackageManager): string {\n\tconst lockfileMap: Record<PackageManager, string> = {\n\t\tpnpm: 'pnpm-lock.yaml',\n\t\tnpm: 'package-lock.json',\n\t\tyarn: 'yarn.lock',\n\t\tbun: 'bun.lockb',\n\t};\n\treturn lockfileMap[pm];\n}\n\n/**\n * Check if we're in a monorepo (lockfile is in a parent directory)\n */\nexport function isMonorepo(cwd: string = process.cwd()): boolean {\n\tconst lockfilePath = findLockfilePath(cwd);\n\tif (!lockfilePath) {\n\t\treturn false;\n\t}\n\n\t// Check if lockfile is in a parent directory (not in cwd)\n\tconst lockfileDir = dirname(lockfilePath);\n\treturn lockfileDir !== cwd;\n}\n\n/**\n * Check if turbo.json exists (walks up directory tree)\n */\nexport function hasTurboConfig(cwd: string = process.cwd()): boolean {\n\treturn upFrom(cwd).some((dir) => existsSync(join(dir, 'turbo.json')));\n}\n\n/**\n * Package manager specific commands. `version` pins what corepack (or npm,\n * for bun) installs; without it, the latest.\n */\nfunction getPmConfig(pm: PackageManager, version?: string) {\n\tconst configs = {\n\t\tpnpm: {\n\t\t\tinstall: `corepack enable && corepack prepare pnpm@${version ?? 'latest'} --activate`,\n\t\t\tlockfile: 'pnpm-lock.yaml',\n\t\t\t// turbo prune writes a lockfile for the slice, not the repository's,\n\t\t\t// so the install cannot be frozen to it.\n\t\t\tinstallCmd: 'pnpm install',\n\t\t\tcacheTarget: '/root/.local/share/pnpm/store',\n\t\t\tcacheId: 'pnpm',\n\t\t\trun: 'pnpm run',\n\t\t\tdlx: 'pnpm dlx',\n\t\t},\n\t\tnpm: {\n\t\t\tinstall: version ? `npm install -g npm@${version}` : '',\n\t\t\tlockfile: 'package-lock.json',\n\t\t\tinstallCmd: 'npm install',\n\t\t\tcacheTarget: '/root/.npm',\n\t\t\tcacheId: 'npm',\n\t\t\trun: 'npm run',\n\t\t\tdlx: 'npx --yes',\n\t\t},\n\t\tyarn: {\n\t\t\tinstall: `corepack enable && corepack prepare yarn@${version ?? 'stable'} --activate`,\n\t\t\tlockfile: 'yarn.lock',\n\t\t\tinstallCmd: 'yarn install',\n\t\t\tcacheTarget: '/root/.yarn/cache',\n\t\t\tcacheId: 'yarn',\n\t\t\trun: 'yarn run',\n\t\t\tdlx: 'yarn dlx',\n\t\t},\n\t\tbun: {\n\t\t\tinstall: `npm install -g bun@${version ?? 'latest'}`,\n\t\t\tlockfile: 'bun.lockb',\n\t\t\tinstallCmd: 'bun install',\n\t\t\tcacheTarget: '/root/.bun/install/cache',\n\t\t\tcacheId: 'bun',\n\t\t\trun: 'bun run',\n\t\t\tdlx: 'bunx',\n\t\t},\n\t};\n\treturn configs[pm];\n}\n\n/** What every template's first three stages need, resolved from options. */\nfunction layout(options: ImageTemplateOptions) {\n\tconst pm = getPmConfig(options.packageManager, options.packageManagerVersion);\n\tconst turbo = `${pm.dlx} turbo@${options.turboVersion ?? TURBO_VERSION}`;\n\tconst gkmRoot = options.gkmRoot ?? '.';\n\treturn {\n\t\tpm,\n\t\tturbo,\n\t\tinstallPm: pm.install ? `RUN ${pm.install}` : '',\n\t\tmonorepo: options.monorepo ?? true,\n\t\tgkmRoot,\n\t\t/** The app, absolute inside the image. */\n\t\tapp: `/app/${options.appPath}`.replace(/\\/\\.$/, ''),\n\t};\n}\n\n/**\n * The pruner stage: the build context cut to the app's slice, in turbo's\n * `out/` layout — `out/json` for the install, `out/full` for the build.\n *\n * `turbo prune` keeps the packages the app depends on and nothing else at\n * the root, so the root's own files (a `tsconfig.base.json` the packages\n * extend, the config their build reads) and what the gkm workspace keeps\n * outside any package are copied in beside them. A single package is copied\n * whole.\n */\n/**\n * The Node image every stage builds on, as a build argument: declared before\n * the first `FROM`, so each stage can read it, and defaulted to the configured\n * image. A compose file's `build.args`, or `docker build --build-arg`, picks\n * another version without regenerating the Dockerfile.\n */\nfunction nodeImageArg(options: ImageTemplateOptions): string {\n\treturn `# The Node image; override with --build-arg NODE_IMAGE=node:<version>-alpine\nARG NODE_IMAGE=${options.baseImage}`;\n}\n\nfunction prunerStage(options: ImageTemplateOptions): string {\n\tconst { pm, turbo, installPm, monorepo, gkmRoot } = layout(options);\n\tconst scopes = [options.turboPackage, ...(options.prunePackages ?? [])].join(\n\t\t' ',\n\t);\n\n\tif (!monorepo) {\n\t\treturn `${nodeImageArg(options)}\n\n# Stage 1: The build context, in the layout the stages below read\nFROM \\${NODE_IMAGE} AS pruner\nWORKDIR /app\nCOPY . .\nRUN mkdir -p /tmp/out/json /tmp/out/full && \\\\\n cp package.json /tmp/out/json/ && \\\\\n cp ${pm.lockfile} /tmp/out/ && \\\\\n cp -a . /tmp/out/full/ && \\\\\n mv /tmp/out ./out`;\n\t}\n\n\tconst gkmPaths = options.gkmPaths ?? [];\n\tconst nested = gkmRoot !== '.';\n\tconst dest = nested ? `/app/out/full/${gkmRoot}` : '/app/out/full';\n\tconst copyGkm = gkmPaths.length\n\t\t? `\n\n# What the gkm workspace keeps outside any package — its config, the\n# directories its constructs are declared in — beside the slice.\nRUN ${nested ? `cd ${gkmRoot} && ` : ''}for path in ${gkmPaths.join(' ')}; do \\\\\n if [ -e \"$path\" ]; then \\\\\n mkdir -p \"${dest}\" && cp -rn \"$path\" \"${dest}/\"; \\\\\n fi; \\\\\n done`\n\t\t: '';\n\n\treturn `${nodeImageArg(options)}\n\n# Stage 1: Prune the monorepo to the app's slice\nFROM \\${NODE_IMAGE} AS pruner\nWORKDIR /app\n${installPm}\nCOPY . .\nRUN ${turbo} prune ${scopes} --docker\n\n# The root's own files — the tsconfig the packages extend, the config their\n# build reads — which turbo prune leaves out. What the install itself reads\n# (registry config, local tarballs) goes beside the manifests too.\nRUN find . -maxdepth 1 -type f ! -name '${pm.lockfile}' ! -name package.json \\\\\n -exec cp -n {} out/full/ \\\\; && \\\\\n for file in .npmrc .yarnrc.yml .pnpmfile.cjs bunfig.toml *.tgz; do \\\\\n if [ -f \"$file\" ]; then cp \"$file\" out/json/; fi; \\\\\n done${copyGkm}`;\n}\n\n/** The deps stage: the slice's dependencies, installed from its lockfile. */\nfunction depsStage(options: ImageTemplateOptions): string {\n\tconst { pm, installPm } = layout(options);\n\treturn `# Stage 2: Install dependencies\nFROM \\${NODE_IMAGE} AS deps\nWORKDIR /app\n${installPm}\nCOPY --from=pruner /app/out/${pm.lockfile} ./\nCOPY --from=pruner /app/out/json/ ./\nRUN --mount=type=cache,id=${pm.cacheId},target=${pm.cacheTarget} \\\\\n ${pm.installCmd}`;\n}\n\n/**\n * The start of the builder stage: the slice's source over its dependencies,\n * and every workspace package the app depends on built from it.\n *\n * Nothing built on the host reaches the image — `.dockerignore` keeps every\n * `dist` out — so a workspace package (a CLI that is a sibling package) is\n * built here: turbo's build of the app's dependencies (`^build`) and nothing\n * else. The root's own `build` script is never run: the slice holds one app,\n * and a root `build` that is `gkm build` (what `gkm init` scaffolds) builds\n * every app the workspace declares, most of which are not in it. The app\n * itself is built after this, by `gkm build` or its framework.\n */\nfunction builderStage(\n\toptions: ImageTemplateOptions,\n\textra: { args?: string[] } = {},\n): string {\n\tconst { turbo, monorepo } = layout(options);\n\tconst args = extra.args ?? [];\n\tconst argLines = args.length\n\t\t? `\\n# Build-time args: public values the bundler inlines\\n${args.map((a) => `ARG ${a}=\"\"`).join('\\n')}\\n${args.map((a) => `ENV ${a}=$${a}`).join('\\n')}\\n`\n\t\t: '';\n\tconst scopes = [options.turboPackage, ...(options.prunePackages ?? [])];\n\tconst dependencies = monorepo\n\t\t? `\\n# The workspace packages the app depends on, built from source.\\nRUN ${turbo} run build ${scopes.map((s) => `--filter='${s}^...'`).join(' ')}`\n\t\t: '';\n\n\treturn `# Stage 3: Build\nFROM deps AS builder\nWORKDIR /app\n${argLines}\nCOPY --from=pruner /app/out/full/ ./${dependencies}`;\n}\n\n/**\n * The PATH a command in the app's directory runs with: the app's binaries,\n * then the gkm workspace's, then the root's — a nested workspace's apps\n * declare nothing, and its CLI is installed where its config is.\n */\nfunction binPath(options: ImageTemplateOptions): string {\n\tconst { app, gkmRoot } = layout(options);\n\tconst dirs = [\n\t\t`${app}/node_modules/.bin`,\n\t\tgkmRoot === '.' ? '' : `/app/${gkmRoot}/node_modules/.bin`,\n\t\t'/app/node_modules/.bin',\n\t].filter(Boolean);\n\treturn `PATH=\"${[...new Set(dirs)].join(':')}:$PATH\"`;\n}\n\n/**\n * Run the gkm CLI the app resolves, from the app's directory: node on its\n * `bin/gkm.mjs`, found the way Node resolves a package — up from the app.\n *\n * Not through `node_modules/.bin`: a CLI that is a workspace package has no\n * bin linked, since its files were not there when the slice's dependencies\n * were installed.\n */\nfunction gkmCommand(args: string): string {\n\treturn `GKM_BIN=\"$(node -e '${FIND_GKM_BIN}')\" && node \"$GKM_BIN\" ${args}`;\n}\n\n/** Prints the `bin/gkm.mjs` Node resolves from the cwd, or fails saying so. */\nconst FIND_GKM_BIN = `let d=process.cwd();const{existsSync:e}=require(\"fs\"),{dirname:u,join:j}=require(\"path\");for(;;){const p=j(d,\"node_modules/@geekmidas/cli/bin/gkm.mjs\");if(e(p)){console.log(p);break}if(u(d)===d){console.error(\"@geekmidas/cli is not installed where the app can resolve it\");process.exit(1)}d=u(d)}`;\n\n/**\n * What a site's builder does with the gkm workspace it carries, before its\n * framework builds it — all of it inside the image, nothing from the host:\n *\n * - `gkm` on the PATH: the CLI the workspace installs, so a build script that\n * is `gkm exec -- next build` runs. Resolved from the gkm root rather than\n * through `node_modules/.bin`, where a CLI that is a workspace package has\n * no bin linked.\n * - `GKM_IMAGE_BUILD`, which has `gkm exec` inject the build args above — the\n * stage's public URLs — and never load a secret or resolve a local address.\n * - `GKM_BUILD_OFFLINE`, which tells the site's own code that no stage is\n * reachable from this build: its APIs are not up yet, so a page that\n * fetches from them renders on request rather than at build.\n * - each backend's typed client, generated from its endpoints at the\n * workspace root's `.gkm/client/`, where the site's tsconfig paths point.\n */\nfunction siteWorkspaceSteps(options: FrontendDockerfileOptions): string {\n\tconst { gkmRoot } = layout(options);\n\tconst root = `/app/${gkmRoot}`.replace(/\\/\\.$/, '');\n\tconst clients = options.clients ?? [];\n\tconst generate = clients.length\n\t\t? `\n\n# The typed client of each API this site calls, generated from its endpoints\n# into ${gkmRoot === '.' ? '' : `${gkmRoot}/`}.gkm/client/ — offline, with no secret and no container.\nRUN ${clients.map(({ app, path, telemetry }) => ['cd', `/app/${path}`, '&&', 'gkm', 'openapi', '--app', app, ...telemetryArgs(telemetry)].join(' ')).join(' && \\\\\\n ')}`\n\t\t: '';\n\n\treturn `# The gkm CLI the workspace installs, as \\`gkm\\`\nRUN cd ${root} && GKM_BIN=\"$(node -e '${FIND_GKM_BIN}')\" && \\\\\n { echo '#!/bin/sh'; echo \"exec node \\\\\"$GKM_BIN\\\\\" \\\\\"\\\\$@\\\\\"\"; } > /usr/local/bin/gkm && \\\\\n chmod +x /usr/local/bin/gkm\n\n# \\`gkm exec\\` in this build injects the build args, never a stage's secrets\nENV ${IMAGE_BUILD_ENV}=1\n${\n\toptions.prerender\n\t\t? `# Built once the site's APIs are up on its stage: it pre-renders from them`\n\t\t: `# No stage is reachable from this build: the site's APIs are not up yet\nENV ${BUILD_OFFLINE_ENV}=1`\n}${generate}`;\n}\n\n/**\n * Build the site with turbo. Loose env mode, so the task sees what the\n * Dockerfile set — the build args, `GKM_IMAGE_BUILD` and `GKM_BUILD_OFFLINE`\n * — whatever the project's turbo.json declares: the image's environment\n * holds nothing else.\n */\nfunction siteBuild(options: FrontendDockerfileOptions): string {\n\tconst { turbo } = layout(options);\n\tconst build = `${turbo} run build --filter='${options.turboPackage}' --env-mode=loose`;\n\tif (!options.prerender) return `RUN ${build}`;\n\t// Its APIs answer at their public hosts, behind the stage's certificate:\n\t// on the local stage that chains to gkm's own root, handed in as a secret.\n\t// What they answer changes with no change to the source, so each deploy's\n\t// run is part of the cache key: a cached layer would ship the last data.\n\tconst ca = `/run/secrets/${LOCAL_CA_BUILD_SECRET}`;\n\treturn `ARG ${PRERENDER_RUN_ARG}=\"\"\nRUN --mount=type=secret,id=${LOCAL_CA_BUILD_SECRET},required=false \\\\\n echo \"prerendered for: \\${${PRERENDER_RUN_ARG}:-any run}\" && \\\\\n if [ -s ${ca} ]; then export NODE_EXTRA_CA_CERTS=${ca}; fi && \\\\\n ${build}`;\n}\n\n/**\n * The encrypted credentials, from a build secret — never an ARG, which is\n * recorded in the image history — written where the build embeds them from.\n * Two lines, ciphertext then IV; absent when the app has no secrets.\n *\n * A BuildKit secret is not part of the cache key, so `GKM_CIPHERTEXT_HASH`\n * (a hash of the ciphertext, not a secret) is: credentials encrypted under a\n * new key rebuild the layer that embeds them.\n */\nfunction credentialsStep(appDir: string, then: string): string {\n\treturn `ARG GKM_CIPHERTEXT_HASH=\"\"\nRUN --mount=type=secret,id=gkm_credentials,required=false \\\\\n echo \"credentials: \\${GKM_CIPHERTEXT_HASH:-none}\" && \\\\\n if [ -s /run/secrets/gkm_credentials ]; then \\\\\n mkdir -p ${appDir}/.gkm && \\\\\n sed -n 1p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.enc && \\\\\n sed -n 2p /run/secrets/gkm_credentials > ${appDir}/.gkm/credentials.iv; \\\\\n fi && \\\\\n ${then} && \\\\\n rm -f ${appDir}/.gkm/credentials.enc ${appDir}/.gkm/credentials.iv`;\n}\n\n/**\n * The packages a bundle left out — its native ones, which load a binary built\n * for the platform they were installed on — installed for Linux beside it.\n * `gkm build` records them, at the versions it resolved, in a `package.json`\n * beside the bundle (`externalsManifestName`), so the image installs exactly\n * what the build left out: nothing, for most apps.\n */\nfunction externalsStages(\n\tappDir: string,\n\tbundle: string,\n): { stage: string; copy: string } {\n\treturn {\n\t\tstage: `\n# The packages the bundle leaves out, installed for Linux at the versions the\n# build resolved — and nothing else.\nFROM \\${NODE_IMAGE} AS externals\nWORKDIR /externals\nCOPY --from=builder ${appDir}/.gkm/server/dist/${externalsManifestName(bundle)} ./package.json\nRUN --mount=type=cache,id=npm,target=/root/.npm \\\\\n npm install --omit=dev --no-package-lock --no-audit --no-fund && \\\\\n mkdir -p node_modules\n`,\n\t\tcopy: `\\nCOPY --from=externals --chown=hono:nodejs /externals/node_modules ./node_modules`,\n\t};\n}\n\n/**\n * Generate .dockerignore file\n *\n * Written at the build root. Nothing built on the host may reach an image —\n * every image builds its packages from source — and nothing secret may reach\n * a build context.\n */\nexport function generateDockerignore(): string {\n\treturn `# Dependencies: installed in the image, for Linux\n**/node_modules\n.pnpm-store\n\n# Build output: every image builds from source, never from the host's\n**/dist\n**/.next\n**/.turbo\n**/.gkm\n\n# The key gkm build --stage encrypted secrets with: runtime env only, never\n# the build context\n**/master.key\n\n# gkm compose's stacks: each app's env file holds its stage's secrets\n**/.gkm/compose\n\n# IDE and editor\n.idea\n.vscode\n*.swp\n*.swo\n\n# Git\n.git\n\n# Logs\n*.log\nnpm-debug.log*\npnpm-debug.log*\n\n# Test files\ncoverage\n\n# Environment files (handle secrets separately)\n**/.env\n**/.env.*\n!**/.env.example\n\n# Docker files (don't copy recursively)\nDockerfile*\ndocker-compose*\n.dockerignore\n`;\n}\n\n/**\n * Generate docker-entrypoint.sh for custom startup logic\n */\nexport function generateDockerEntrypoint(): string {\n\treturn `#!/bin/sh\nset -e\n\n# Run any custom startup scripts here\n# Example: wait for database\n# until nc -z $DB_HOST $DB_PORT; do\n# echo \"Waiting for database...\"\n# sleep 1\n# done\n\n# Execute the main command\nexec \"$@\"\n`;\n}\n\n/**\n * Resolve Docker configuration from GkmConfig with defaults\n */\nexport function resolveDockerConfig(config: GkmConfig): Required<DockerConfig> {\n\tconst docker = config.docker ?? {};\n\n\treturn {\n\t\tregistry: docker.registry ?? '',\n\t\t// The project's name, from the config — what somebody types after\n\t\t// `docker pull` — never whatever the directory's package.json is called.\n\t\timageName: docker.imageName ?? config.name ?? 'api',\n\t\tbaseImage: docker.baseImage ?? DEFAULT_BASE_IMAGE,\n\t\tport: docker.port ?? 3000,\n\t};\n}\n\n/** A site's root answers its health check. */\nfunction siteHealthcheck(port: number): string {\n\treturn `# A site answers at its root; Docker, and Dokploy, read the container's\n# health from it rather than from the process merely running. 127.0.0.1, not\n# localhost: the server listens on IPv4, and localhost can resolve to ::1.\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://127.0.0.1:${port}/ > /dev/null 2>&1 || exit 1`;\n}\n\n/**\n * Generate a Dockerfile for Next.js frontend apps using standalone output.\n *\n * Pruned at the build root, Next traces from there, so the standalone\n * server lands at `<appPath>/server.js` under `.next/standalone`.\n * @internal Exported for testing\n */\nexport function generateNextjsDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst {\n\t\tport,\n\t\tappPath,\n\t\tpublicUrlArgs = ['NEXT_PUBLIC_API_URL', 'NEXT_PUBLIC_AUTH_URL'],\n\t} = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Next.js standalone Dockerfile, built from a turbo-pruned slice\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: publicUrlArgs })}\n\n${siteWorkspaceSteps(options)}\n\n# Ensure public directory exists (may be empty for scaffolded projects)\nRUN mkdir -p ${appPath}/public\n\nENV NEXT_TELEMETRY_DISABLED=1\n\n# Build the application\n${siteBuild(options)}\n\n# The runner needs the standalone server; without it there is nothing to run.\nRUN if [ ! -d ${appPath}/.next/standalone ]; then \\\\\n echo \"${appPath}/.next/standalone was not built: set output: 'standalone' in next.config so the image can run the app without node_modules.\" >&2; \\\\\n exit 1; \\\\\n fi\n\n# Stage 4: Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\n# Install tini for proper signal handling\nRUN apk add --no-cache tini\n\n# Create non-root user\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 nextjs\n\n# Set environment\nENV NODE_ENV=production\nENV NEXT_TELEMETRY_DISABLED=1\nENV PORT=${port}\nENV HOSTNAME=\"0.0.0.0\"\n\n# The standalone server, with its static files and public directory beside it\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/.next/static ./${appPath}/.next/static\nCOPY --from=builder --chown=nextjs:nodejs /app/${appPath}/public ./${appPath}/public\n\nUSER nextjs\n\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"${appPath}/server.js\"]\n`;\n}\n\n/**\n * Where Next's prerender manifest is in the image {@link\n * generateNextjsDockerfile} builds: the standalone output is copied to the\n * runner's `/app`, and the app's `.next/` — its manifests among them — sits\n * beside its `server.js`, at `appPath` under it.\n */\nexport function nextPrerenderManifest(appPath: string): string {\n\treturn posix.join('/app', appPath, '.next', 'prerender-manifest.json');\n}\n\n/**\n * Generate a Dockerfile for a gkm backend: pruned, installed, and bundled by\n * `gkm build --provider server --production` inside the image. The runner is\n * `server.mjs` — plus the packages the bundle leaves out, which is none\n * unless it uses one with native code.\n * @internal Exported for testing\n */\nexport function generateBackendDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\thealthCheckPath?: string;\n\t\t/** The cache backend the entry registers, where not the target's. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: 'Backend Dockerfile',\n\t\tbundle: 'server.mjs',\n\t\tas: 'server.mjs',\n\t\texpose: true,\n\t});\n}\n\n/** The port a worker answers its health check on, inside its container. */\nexport const WORKER_PORT = 3000;\n\n/** The port a processor unit answers on, inside its container. */\nexport const PROCESSOR_PORT = 3000;\n\n/**\n * A Worker's image: the same build as its host app's backend — a pruned\n * slice, `gkm build --provider server --production` in the image, with the\n * encrypted credentials from the `gkm_credentials` secret — and a runner that\n * is the worker's bundle alone. It publishes nothing: its one route is the\n * health check the HEALTHCHECK asks.\n * @internal Exported for testing\n */\nexport function generateWorkerDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\t/** The worker's construct id, for the comment. */\n\t\tworker: string;\n\t\t/** Its bundle under the host app's `.gkm/server/dist`. */\n\t\tbundle: string;\n\t\thealthCheckPath?: string;\n\t\t/** The cache backend the entry registers, where not the target's. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: `Worker Dockerfile (${options.worker})`,\n\t\tbundle: options.bundle,\n\t\tas: 'worker.mjs',\n\t\texpose: false,\n\t});\n}\n\n/**\n * A file server's processor unit: its host app's build, and the unit's bundle\n * as the runner. Its native packages — `sharp` — are installed for the image's\n * platform beside the bundle, at the versions the build resolved, as for\n * every bundle.\n */\nexport function generateProcessorDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\t/** The file server's surface id, for the comment. */\n\t\tfileServer: string;\n\t\t/** Its bundle under the host app's `.gkm/server/dist`. */\n\t\tbundle: string;\n\t\thealthCheckPath?: string;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\treturn gkmBundleDockerfile(options, {\n\t\ttitle: `Processors Dockerfile (${options.fileServer})`,\n\t\tbundle: options.bundle,\n\t\tas: 'processors.mjs',\n\t\texpose: true,\n\t});\n}\n\nfunction gkmBundleDockerfile(\n\toptions: ImageTemplateOptions & {\n\t\thealthCheckPath?: string;\n\t\tcache?: CacheBackend;\n\t},\n\trunner: { title: string; bundle: string; as: string; expose: boolean },\n): string {\n\tconst { port, healthCheckPath = '/health' } = options;\n\tconst { app } = layout(options);\n\tconst externals = externalsStages(app, runner.bundle);\n\n\treturn `# syntax=docker/dockerfile:1\n# ${runner.title}: a turbo-pruned slice, bundled by gkm build in the image\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options)}\n\n# Bundle the production server, with the encrypted credentials embedded\n${credentialsStep(app, `cd ${app} && ${gkmCommand(`build --provider server --production${options.cache ? ` --cache ${options.cache}` : ''}`)}`)}\n${externals.stage}\n# Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\nRUN apk add --no-cache tini\n\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 hono\n\n# The bundled ${runner.as.replace(/\\.mjs$/, '')}\nCOPY --from=builder --chown=hono:nodejs ${app}/.gkm/server/dist/${runner.bundle} ./${runner.as === runner.bundle ? '' : runner.as}${externals.copy}\n\nENV NODE_ENV=production\nENV PORT=${port}\n\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1\n\nUSER hono\n${runner.expose ? `\\nEXPOSE ${port}\\n` : ''}\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"${runner.as}\"]\n`;\n}\n\n/**\n * Options for entry-based Dockerfile generation.\n */\nexport interface EntryDockerfileOptions extends ImageTemplateOptions {\n\t/** Entry file path relative to app path (e.g., './src/index.ts') */\n\tentry: string;\n\t/** Health check path (default: '/health') */\n\thealthCheckPath?: string;\n}\n\n/**\n * Generate a Dockerfile for apps with a custom entry point.\n * Uses esbuild to bundle the entry point into dist/index.mjs with all dependencies.\n * This is used for apps that don't use gkm routes (e.g., Better Auth servers).\n * @internal Exported for testing\n */\nexport function generateEntryDockerfile(\n\toptions: EntryDockerfileOptions,\n): string {\n\tconst { port, entry, healthCheckPath = '/health' } = options;\n\tconst { app } = layout(options);\n\n\tconst esbuild = (defines: string) =>\n\t\t`esbuild ${entry} --bundle --platform=node --target=node22 --format=esm \\\\\n --outfile=dist/index.mjs --packages=bundle \\\\\n --banner:js='import { createRequire } from \"module\"; const require = createRequire(import.meta.url);'${defines}`;\n\n\treturn `# syntax=docker/dockerfile:1\n# Entry-based Dockerfile: a turbo-pruned slice, bundled by esbuild in the image\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options)}\n\n# Bundle the entry point with every dependency (dist/index.mjs), embedding the\n# encrypted credentials when there are any.\nARG GKM_CIPHERTEXT_HASH=\"\"\nRUN --mount=type=secret,id=gkm_credentials,required=false \\\\\n echo \"credentials: \\${GKM_CIPHERTEXT_HASH:-none}\" && \\\\\n cd ${app} && export ${binPath(options)} && \\\\\n if [ -s /run/secrets/gkm_credentials ]; then \\\\\n CREDS=$(sed -n 1p /run/secrets/gkm_credentials) && \\\\\n IV=$(sed -n 2p /run/secrets/gkm_credentials) && \\\\\n ${esbuild(` \\\\\n --define:__GKM_ENCRYPTED_CREDENTIALS__=\"\\\\\"$CREDS\\\\\"\" \\\\\n --define:__GKM_CREDENTIALS_IV__=\"\\\\\"$IV\\\\\"\"`)}; \\\\\n else \\\\\n ${esbuild('')}; \\\\\n fi\n\n# Production\nFROM \\${NODE_IMAGE} AS runner\n\nWORKDIR /app\n\nRUN apk add --no-cache tini\n\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 app\n\n# Copy bundled output only (no node_modules needed - fully bundled)\nCOPY --from=builder --chown=app:nodejs ${app}/dist/index.mjs ./\n\nENV NODE_ENV=production\nENV PORT=${port}\n\nHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \\\\\n CMD wget -qO- http://localhost:${port}${healthCheckPath} > /dev/null 2>&1 || exit 1\n\nUSER app\n\nEXPOSE ${port}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\nCMD [\"node\", \"index.mjs\"]\n`;\n}\n\n/**\n * Generate a Dockerfile for Node-based SSR web frameworks (TanStack Start,\n * Remix). Builds with turbo, then runs the framework's production start\n * script.\n *\n * Public URL build args are declared so framework bundlers (Vite, Vinxi)\n * can inline them at build time. Per-framework prefix is the caller's job.\n * @internal Exported for testing\n */\nexport function generateNodeWebDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst { port, appPath } = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Node SSR web Dockerfile (TanStack Start / Remix), from a turbo-pruned slice\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: options.publicUrlArgs ?? [] })}\n\n${siteWorkspaceSteps(options)}\n\n${siteBuild(options)}\n\nFROM \\${NODE_IMAGE} AS runner\nWORKDIR /app\nRUN apk add --no-cache tini\nRUN addgroup --system --gid 1001 nodejs && \\\\\n adduser --system --uid 1001 app\n\n# Copy the whole built workspace — frameworks differ on output paths\nCOPY --from=builder --chown=app:nodejs /app/ ./\n\nENV NODE_ENV=production\nENV PORT=${port}\nENV HOSTNAME=\"0.0.0.0\"\n\nUSER app\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nENTRYPOINT [\"/sbin/tini\", \"--\"]\n# npm ships with node, and runs the start script whichever package manager\n# installed it: the runner needs no other.\nCMD [\"sh\", \"-c\", \"cd ${appPath} && npm start\"]\n`;\n}\n\n/**\n * Generate a Dockerfile for Vite SPA apps. Builds the static bundle with\n * turbo, then serves it with Caddy: Vite's hashed `/assets/*` cached for a\n * year, everything else — `index.html`, and every deep link that falls back\n * to it — revalidated on each request.\n * @internal Exported for testing\n */\nexport function generateViteStaticDockerfile(\n\toptions: FrontendDockerfileOptions,\n): string {\n\tconst { port, appPath } = options;\n\n\treturn `# syntax=docker/dockerfile:1\n# Vite SPA Dockerfile — a turbo-pruned slice built to static files, served by Caddy\n\n${prunerStage(options)}\n\n${depsStage(options)}\n\n${builderStage(options, { args: options.publicUrlArgs ?? [] })}\n\n${siteWorkspaceSteps(options)}\n\n${siteBuild(options)}\n\nFROM ${STATIC_SITE_IMAGE} AS runner\n\nCOPY <<'EOF' /etc/caddy/Caddyfile\n{\n\tadmin off\n\tauto_https off\n\tpersist_config off\n}\n\n:${port} {\n\troot * /srv\n\tencode zstd gzip\n\n\t# Vite names every built asset by its content hash: a changed file is a\n\t# new URL, so the old one can be cached for good.\n\thandle /assets/* {\n\t\theader Cache-Control \"public, max-age=31536000, immutable\"\n\t\tfile_server\n\t}\n\n\t# index.html, and every client-side route that falls back to it, is\n\t# asked for again each time so a deploy is seen at once.\n\thandle {\n\t\theader Cache-Control \"no-cache\"\n\t\ttry_files {path} /index.html\n\t\tfile_server\n\t}\n}\nEOF\n\nCOPY --from=builder /app/${appPath}/dist /srv\n\nRUN addgroup -S -g 1001 site && adduser -S -u 1001 -G site site && \\\\\n chown -R site:site /data /config\n\nUSER site\n\nEXPOSE ${port}\n\n${siteHealthcheck(port)}\n\nCMD [\"caddy\", \"run\", \"--config\", \"/etc/caddy/Caddyfile\", \"--adapter\", \"caddyfile\"]\n`;\n}\n","/**\n * Where a workspace's images are built from, and what each is built with.\n *\n * Every builder of images — `gkm docker`, `gkm compose`, a Dokploy deploy —\n * builds from the same place with the same templates: the build root (the\n * package manager's root, at or above the gkm workspace), cut by `turbo\n * prune` to one app's slice. Nothing is built on the host.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\nimport { GkmError } from '../errors';\nimport type { ClientTelemetryDefault } from '../generators/clientTelemetry.js';\nimport { allConstructGlobs } from '../workspace/index.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\ttype BuildTools,\n\tDEFAULT_BASE_IMAGE,\n\tfindBuildRoot,\n\thasTurboConfig,\n\ttype ImageTemplateOptions,\n\tresolveBuildTools,\n} from './templates.js';\n\n/** A workspace of packages with no turbo.json, which every image prunes with. */\nexport class MonorepoNeedsTurbo extends GkmError {\n\tconstructor(readonly buildRoot: string) {\n\t\tsuper(\n\t\t\t`${buildRoot} is a workspace of packages, and its images are built from a turbo-pruned slice of it — but it has no turbo.json.\\n\\n` +\n\t\t\t\t'To fix this:\\n' +\n\t\t\t\t' 1. Install turbo: pnpm add -Dw turbo\\n' +\n\t\t\t\t` 2. Create turbo.json in ${buildRoot}\\n` +\n\t\t\t\t' 3. Run this command again\\n\\n' +\n\t\t\t\t'See: https://turbo.build/repo/docs/guides/tools/docker',\n\t\t);\n\t\tthis.name = 'MonorepoNeedsTurbo';\n\t}\n}\n\nexport interface ImageLayout {\n\t/** The build context of every image, absolute. */\n\tbuildRoot: string;\n\t/** The gkm workspace's root, relative to the build root (`.` when equal). */\n\tgkmRoot: string;\n\ttools: BuildTools;\n\t/**\n\t * The gkm workspace's own package, when it is nested in a monorepo as one:\n\t * kept in every backend's slice, since it holds the config, the constructs\n\t * and the dependencies they import.\n\t */\n\tworkspacePackage?: string;\n\t/** What under the gkm root a build reads besides the app's own directory. */\n\tgkmPaths: string[];\n}\n\n/**\n * Where a workspace's images are built from.\n *\n * Refuses a workspace of packages with no turbo.json — every image prunes\n * with turbo — so only a caller about to generate or build images asks.\n */\nexport function imageLayout(workspace: NormalizedWorkspace): ImageLayout {\n\tconst buildRoot = findBuildRoot(workspace.root);\n\tconst tools = resolveBuildTools(buildRoot);\n\tif (tools.monorepo && !hasTurboConfig(buildRoot)) {\n\t\tthrow new MonorepoNeedsTurbo(buildRoot);\n\t}\n\n\tconst gkmRoot = toPosix(relative(buildRoot, workspace.root)) || '.';\n\tconst workspacePackage =\n\t\tgkmRoot !== '.' ? packageName(workspace.root) : undefined;\n\n\treturn {\n\t\tbuildRoot,\n\t\tgkmRoot,\n\t\ttools,\n\t\t...(workspacePackage ? { workspacePackage } : {}),\n\t\tgkmPaths: ['gkm.config.*', ...constructRoots(workspace)],\n\t};\n}\n\n/**\n * How a compose file builds an app: the build root as the context, relative\n * to the directory the compose file is in, and the Dockerfile — written under\n * the gkm root — relative to that context, which is what compose resolves\n * `dockerfile` against.\n */\nexport function composeBuildPaths(options: {\n\t/** The directory the compose file is in, absolute. */\n\tcomposeDir: string;\n\tbuildRoot: string;\n\tworkspaceRoot: string;\n\t/** The Dockerfile, relative to the gkm workspace's root. */\n\tdockerfile: string;\n}): { context: string; dockerfile: string } {\n\tconst { composeDir, buildRoot, workspaceRoot, dockerfile } = options;\n\treturn {\n\t\tcontext: toPosix(relative(composeDir, buildRoot)) || '.',\n\t\tdockerfile: toPosix(join(relative(buildRoot, workspaceRoot), dockerfile)),\n\t};\n}\n\n/** A path under the gkm root, as the build root sees it. */\nexport function fromBuildRoot(\n\tlayout: Pick<ImageLayout, 'gkmRoot'>,\n\tpath: string,\n): string {\n\tif (layout.gkmRoot === '.') return toPosix(path);\n\tconst joined = toPosix(join(layout.gkmRoot, path));\n\treturn joined === '' ? '.' : joined;\n}\n\n/** Everything a template needs about one app, relative to the build root. */\nexport function appImageOptions(\n\tlayout: ImageLayout,\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\tworkspaceRoot: string,\n\t/**\n\t * Every app in the workspace: a site's image generates the client of each\n\t * backend it depends on, so it has to know where they are.\n\t */\n\tapps: Readonly<Record<string, NormalizedAppConfig>> = {},\n\t/**\n\t * Whether a site's clients propagate trace context, at what rate — set\n\t * from its edge to a `Telemetry` construct and the stage's sample rate.\n\t */\n\tclientTelemetry?: ClientTelemetryDefault,\n): ImageTemplateOptions {\n\tconst turboPackage =\n\t\tpackageName(\n\t\t\tisAbsolute(app.path) ? app.path : join(workspaceRoot, app.path),\n\t\t) ?? appName;\n\treturn {\n\t\timageName: appName,\n\t\tbaseImage: DEFAULT_BASE_IMAGE,\n\t\tport: app.port,\n\t\tappPath: fromBuildRoot(layout, app.path),\n\t\tturboPackage,\n\t\tpackageManager: layout.tools.packageManager,\n\t\t...(layout.tools.packageManagerVersion\n\t\t\t? { packageManagerVersion: layout.tools.packageManagerVersion }\n\t\t\t: {}),\n\t\tturboVersion: layout.tools.turboVersion,\n\t\tmonorepo: layout.tools.monorepo,\n\t\tgkmRoot: layout.gkmRoot,\n\t\t// A backend is built by gkm, from the workspace's config and constructs.\n\t\t// So is half of a site: the typed client it imports is generated from\n\t\t// the endpoints of the backends it depends on, in its image, before its\n\t\t// bundler runs — so it carries the same workspace, and those backends'\n\t\t// packages for what their endpoints import.\n\t\t...(app.type === 'backend'\n\t\t\t? {\n\t\t\t\t\tgkmPaths: layout.gkmPaths,\n\t\t\t\t\t...(layout.workspacePackage &&\n\t\t\t\t\tlayout.workspacePackage !== turboPackage\n\t\t\t\t\t\t? { prunePackages: [layout.workspacePackage] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}\n\t\t\t: app.type === 'web'\n\t\t\t\t? siteWorkspace(\n\t\t\t\t\t\tlayout,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tapps,\n\t\t\t\t\t\tworkspaceRoot,\n\t\t\t\t\t\tturboPackage,\n\t\t\t\t\t\tclientTelemetry,\n\t\t\t\t\t)\n\t\t\t\t: {}),\n\t};\n}\n\n/**\n * What a site's image carries of the gkm workspace: its config and construct\n * directories, the workspace's own package where it is nested in a monorepo\n * (it holds the CLI), and each backend the site calls — whose endpoints its\n * client is generated from, and whose package their imports resolve in.\n */\nfunction siteWorkspace(\n\tlayout: ImageLayout,\n\tsite: NormalizedAppConfig,\n\tapps: Readonly<Record<string, NormalizedAppConfig>>,\n\tworkspaceRoot: string,\n\tturboPackage: string,\n\tclientTelemetry?: ClientTelemetryDefault,\n): Pick<ImageTemplateOptions, 'gkmPaths' | 'prunePackages' | 'clients'> {\n\tconst clients = siteClients(site, apps);\n\tconst packages = new Set<string>();\n\tif (layout.workspacePackage) packages.add(layout.workspacePackage);\n\tfor (const { app } of clients) {\n\t\tconst backend = apps[app]!;\n\t\tconst name = packageName(\n\t\t\tisAbsolute(backend.path)\n\t\t\t\t? backend.path\n\t\t\t\t: join(workspaceRoot, backend.path),\n\t\t);\n\t\tif (name) packages.add(name);\n\t}\n\tpackages.delete(turboPackage);\n\n\treturn {\n\t\tgkmPaths: layout.gkmPaths,\n\t\t...(packages.size > 0 ? { prunePackages: [...packages].sort() } : {}),\n\t\t...(clients.length > 0\n\t\t\t? {\n\t\t\t\t\tclients: clients.map(({ app }) => ({\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tpath: fromBuildRoot(layout, apps[app]!.path),\n\t\t\t\t\t\t...(clientTelemetry ? { telemetry: clientTelemetry } : {}),\n\t\t\t\t\t})),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * The backends whose clients a site imports: each it depends on that gkm\n * builds from endpoints — not one with an entry of its own, and not one that\n * turned OpenAPI off.\n */\nexport function siteClients(\n\tsite: NormalizedAppConfig,\n\tapps: Readonly<Record<string, NormalizedAppConfig>>,\n): { app: string }[] {\n\treturn site.dependencies\n\t\t.filter((name) => {\n\t\t\tconst app = apps[name];\n\t\t\tif (!app || app.type !== 'backend' || app.entry) return false;\n\t\t\tif (app.openapi === false) return false;\n\t\t\tif (typeof app.openapi === 'object' && app.openapi.enabled === false)\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t})\n\t\t.sort()\n\t\t.map((app) => ({ app }));\n}\n\n/**\n * The directories the workspace's construct globs start in, relative to its\n * root: `./constructs/**\\/*.ts` reads from `constructs`.\n */\nexport function constructRoots(workspace: NormalizedWorkspace): string[] {\n\tconst roots = new Set<string>();\n\tfor (const glob of allConstructGlobs(workspace)) {\n\t\tconst rel = toPosix(relative(workspace.root, glob));\n\t\tif (!rel || rel.startsWith('..')) continue;\n\t\tconst first = rel.split('/')[0]!;\n\t\tif (/[*?{}[\\]!]/.test(first)) continue;\n\t\troots.add(first);\n\t}\n\treturn [...roots].sort();\n}\n\nfunction packageName(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n\t\treturn typeof pkg.name === 'string' ? pkg.name : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction toPosix(path: string): string {\n\treturn path.split(sep).join('/');\n}\n","/**\n * A file server's processors as a CDN origin: the names both sides agree on.\n *\n * On a compose stage whose bucket is on S3, the CDN serves the bucket and\n * sends each processor pattern to the stack's processor unit, at a host of\n * its own. That host is public — a CDN reaches its origin over the internet —\n * so the CDN adds a secret header and the edge refuses any request without\n * it. One definition, read by the CDN that sends the header and by the stack\n * whose edge checks it, so the two cannot drift.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { environmentCase } from '@geekmidas/manifest';\nimport { fileServerLabel } from '../workspace/fileServerLabel.js';\n\n/** The header the CDN adds to every request it sends a processor. */\nexport const ORIGIN_VERIFY_HEADER = 'X-Gkm-Origin-Verify';\n\n/**\n * Where a file server's processors answer the CDN:\n * `<fileserver>-processors.<domain>`, `assets-processors.example.com` for\n * `AssetsServer`.\n */\nexport function processorOriginHost(serverId: string, domain: string): string {\n\treturn `${fileServerLabel(serverId)}-processors.${domain}`.toLowerCase();\n}\n\n/** The stage secret holding the header's value: `ASSETS_SERVER_ORIGIN_SECRET`. */\nexport function originSecretKey(serverId: string): string {\n\t// A key of the surface node itself, not one it provides.\n\treturn environmentCase(`${serverId}_originSecret`);\n}\n\n/**\n * What the processor unit reads that secret from. Set wherever the CDN fronts\n * it, so the unit refuses a request without the header itself — on Dokploy,\n * whose edge cannot match a header, the only check; behind the stack's own\n * edge, a second one.\n */\nexport const PROCESSOR_ORIGIN_SECRET_ENV = 'GKM_PROCESSOR_ORIGIN_SECRET';\n\n/** A new value for that secret: random, generated once, kept in the stage. */\nexport function newOriginSecret(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n","/**\n * The stage secrets gkm keeps for the stack itself rather than for the\n * application: the server's address, the logins of the containers it runs\n * (Redis, OpenObserve), the key backups write with, the secret a CDN sends a\n * file server's processors.\n *\n * Nothing in an app reads them, so no process is handed one as \"the stage's\n * own\" (`processEnvKeys`) — the containers that do read them are given them\n * by name.\n */\n\nimport { BACKUPS_URL_KEY } from '../backups/service.js';\nimport { isReservedStageKey } from '../compose/dnsConfig.js';\nimport { LOGS_EMAIL_KEY, LOGS_PASSWORD_KEY } from '../compose/logs.js';\nimport { REDIS_PASSWORD_KEY } from '../compose/redis.js';\nimport { PROCESSOR_ORIGIN_SECRET_ENV } from '../providers/processorOrigin.js';\n\nconst STACK_KEYS: ReadonlySet<string> = new Set([\n\tBACKUPS_URL_KEY,\n\tLOGS_EMAIL_KEY,\n\tLOGS_PASSWORD_KEY,\n\tREDIS_PASSWORD_KEY,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n]);\n\n/** A file server's origin secret: `ASSETS_SERVER_ORIGIN_SECRET`. */\nconst ORIGIN_SECRET = /_ORIGIN_SECRET$/;\n\n/** Whether a stage secret is the stack's own, which no app process reads. */\nexport function isStackKey(key: string): boolean {\n\treturn (\n\t\tisReservedStageKey(key) ||\n\t\tkey.startsWith('GKM_') ||\n\t\tSTACK_KEYS.has(key) ||\n\t\tORIGIN_SECRET.test(key)\n\t);\n}\n","/**\n * gkm's local certificate authority: one per machine, and every local edge's\n * certificate is issued from it.\n *\n * `gkm dev`'s Caddy, a local `gkm compose` stack's Caddy — and anything else\n * that serves the local stage's `*.localhost` names — serves a certificate\n * this module issued, the way a deployed stage's edge serves the files\n * `deploy.compose.tls` names. So there is one root to trust (`gkm trust`), it\n * exists before any container starts, and a container that calls the stage's\n * public hosts can be handed it (`NODE_EXTRA_CA_CERTS`) without first copying\n * it out of a proxy.\n *\n * The root lives in the CLI's home (`GKM_HOME`, else `~/.gkm`), outside every\n * project. Its key never leaves that directory: only certificates it signed —\n * and their own keys — are written to a workspace or handed to a container.\n */\n\nimport {\n\tcreatePrivateKey,\n\tcreatePublicKey,\n\tgenerateKeyPairSync,\n\trandomBytes,\n} from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { hostname, userInfo } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport forge from 'node-forge';\nimport { GkmError } from '../errors';\nimport { gkmHome } from '../home';\n\n/** Where the authority's files are. */\nexport interface LocalAuthorityPaths {\n\tdir: string;\n\t/** The root certificate, PEM — the only file anything else is handed. */\n\tcertFile: string;\n\t/** The root's private key, PEM. Owner-only, and never copied anywhere. */\n\tkeyFile: string;\n}\n\n/** The authority, loaded: its root certificate and the key it signs with. */\nexport interface LocalAuthority {\n\tcertFile: string;\n\t/** The root certificate, PEM. */\n\tcert: string;\n\t/** The root's private key, PEM. */\n\tkey: string;\n}\n\n/** A certificate the authority issued, and its key, both PEM. */\nexport interface LocalCertificate {\n\tcert: string;\n\tkey: string;\n}\n\n/** How long the root is good for: ten years, so it is trusted once. */\nconst AUTHORITY_DAYS = 3650;\n\n/**\n * How long an issued certificate is good for. Under Apple's 825-day limit\n * for a root a user added, and renewed long before it ends.\n */\nexport const CERTIFICATE_DAYS = 365;\n\n/** An issued certificate this close to its end is issued again. */\nconst RENEW_WITHIN_DAYS = 30;\n\nconst DAY = 24 * 60 * 60 * 1000;\n\n/** The authority's files, under the CLI's home. */\nexport function localAuthorityPaths(home = gkmHome()): LocalAuthorityPaths {\n\tconst dir = join(home, 'ca');\n\treturn {\n\t\tdir,\n\t\tcertFile: join(dir, 'root.pem'),\n\t\tkeyFile: join(dir, 'root-key.pem'),\n\t};\n}\n\n/** The authority's directory is there, and its root or key is not readable. */\nexport class LocalAuthorityDamaged extends GkmError {\n\tconstructor(\n\t\treadonly dir: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`gkm's local certificate authority in ${dir} cannot be used: ${reason}. ` +\n\t\t\t\t`Delete the directory and run \"gkm trust\" to make a new one — ` +\n\t\t\t\t`a browser that trusted the old root has to trust the new one.`,\n\t\t);\n\t\tthis.name = 'LocalAuthorityDamaged';\n\t}\n}\n\n/** A certificate asked for with no names to put on it. */\nexport class LocalCertificateWithoutNames extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'A local certificate needs at least one host name. Pass the hosts the ' +\n\t\t\t\t'edge serves — localCertificateNames(project, hosts) lists them.',\n\t\t);\n\t\tthis.name = 'LocalCertificateWithoutNames';\n\t}\n}\n\n/**\n * Load the authority, creating it the first time.\n *\n * Created whole or not at all: generated into a directory of its own and\n * renamed into place, so two commands starting at once — `gkm dev` for two\n * apps — end with one root between them, never one's certificate and the\n * other's key.\n *\n * @throws {LocalAuthorityDamaged} when its directory holds no usable root.\n */\nexport async function ensureLocalAuthority(\n\tpaths: LocalAuthorityPaths = localAuthorityPaths(),\n): Promise<LocalAuthority> {\n\tif (!existsSync(paths.dir)) await createAuthority(paths);\n\treturn readLocalAuthority(paths);\n}\n\n/**\n * Load an authority that exists.\n *\n * @throws {LocalAuthorityDamaged} when its root or key is missing or unreadable.\n */\nexport async function readLocalAuthority(\n\tpaths: LocalAuthorityPaths = localAuthorityPaths(),\n): Promise<LocalAuthority> {\n\tlet cert: string;\n\tlet key: string;\n\ttry {\n\t\t[cert, key] = await Promise.all([\n\t\t\treadFile(paths.certFile, 'utf-8'),\n\t\t\treadFile(paths.keyFile, 'utf-8'),\n\t\t]);\n\t} catch {\n\t\tthrow new LocalAuthorityDamaged(\n\t\t\tpaths.dir,\n\t\t\t'its root certificate or key is missing',\n\t\t);\n\t}\n\ttry {\n\t\tconst root = forge.pki.certificateFromPem(cert);\n\t\tconst signer = forge.pki.privateKeyFromPem(key) as forge.pki.rsa.PrivateKey;\n\t\tconst publicKey = root.publicKey as forge.pki.rsa.PublicKey;\n\t\tif (!publicKey.n.equals(signer.n)) {\n\t\t\tthrow new LocalAuthorityDamaged(\n\t\t\t\tpaths.dir,\n\t\t\t\t'its key is not the root certificate’s',\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof LocalAuthorityDamaged) throw error;\n\t\tthrow new LocalAuthorityDamaged(paths.dir, 'its files are not PEM');\n\t}\n\treturn { certFile: paths.certFile, cert, key };\n}\n\nasync function createAuthority(paths: LocalAuthorityPaths): Promise<void> {\n\tconst { cert, key } = selfSigned();\n\tconst staging = `${paths.dir}.${process.pid}.${randomBytes(4).toString('hex')}`;\n\tawait mkdir(staging, { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait writeFile(join(staging, 'root.pem'), cert, { mode: 0o644 });\n\t\tawait writeFile(join(staging, 'root-key.pem'), key, { mode: 0o600 });\n\t\tawait mkdir(dirname(paths.dir), { recursive: true });\n\t\tawait rename(staging, paths.dir).catch((error: NodeJS.ErrnoException) => {\n\t\t\t// Another command made it first: theirs is the machine's root.\n\t\t\tif (error.code !== 'EEXIST' && error.code !== 'ENOTEMPTY') throw error;\n\t\t});\n\t} finally {\n\t\tawait rm(staging, { recursive: true, force: true });\n\t}\n}\n\n/** A new root: who made it, on which machine, so a keychain says whose it is. */\nfunction selfSigned(): LocalCertificate {\n\tconst { privateKey, publicKey } = keyPair();\n\tconst cert = forge.pki.createCertificate();\n\tcert.publicKey = publicKey;\n\tcert.serialNumber = serialNumber();\n\tconst now = Date.now();\n\tcert.validity.notBefore = new Date(now - DAY);\n\tcert.validity.notAfter = new Date(now + AUTHORITY_DAYS * DAY);\n\tconst subject = utf8([\n\t\t{ name: 'organizationName', value: 'gkm local CA' },\n\t\t{ name: 'organizationalUnitName', value: owner() },\n\t\t{ name: 'commonName', value: `gkm local CA ${owner()}` },\n\t]);\n\tcert.setSubject(subject);\n\tcert.setIssuer(subject);\n\tcert.setExtensions([\n\t\t{\n\t\t\tname: 'basicConstraints',\n\t\t\tcA: true,\n\t\t\tpathLenConstraint: 0,\n\t\t\tcritical: true,\n\t\t},\n\t\t{ name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true },\n\t\t{ name: 'subjectKeyIdentifier' },\n\t]);\n\tcert.sign(privateKey, forge.md.sha256.create());\n\treturn {\n\t\tcert: forge.pki.certificateToPem(cert),\n\t\tkey: forge.pki.privateKeyToPem(privateKey),\n\t};\n}\n\n/**\n * The names a project's local certificate carries: its bare host and every\n * label under it — `shop.localhost`, `*.shop.localhost` — and any host the\n * edge serves that those do not cover, a stage's own wildcard among them.\n * Without a project, the hosts alone: `*.localhost` is nobody's to claim.\n */\nexport function localCertificateNames(\n\tproject: string,\n\thosts: readonly string[],\n): string[] {\n\tconst base = project\n\t\t? [`${project}.localhost`, `*.${project}.localhost`]\n\t\t: [];\n\tconst names = [...base];\n\tfor (const host of hosts) {\n\t\tconst name = host.toLowerCase();\n\t\tif (!names.some((covering) => covers(covering, name))) names.push(name);\n\t}\n\treturn names;\n}\n\n/** Whether a certificate name answers for a host, by the one-label wildcard rule. */\nfunction covers(name: string, host: string): boolean {\n\tif (name === host) return true;\n\tif (!name.startsWith('*.') || host.startsWith('*.')) return false;\n\tconst suffix = name.slice(1);\n\treturn host.endsWith(suffix) && !host.slice(0, -suffix.length).includes('.');\n}\n\n/**\n * A certificate for `names`, signed by the authority. Each call makes a new\n * key; {@link ensureLocalCertificate} is what keeps one across runs.\n *\n * @throws {LocalCertificateWithoutNames} for an empty list.\n */\nexport function issueLocalCertificate(\n\tauthority: LocalAuthority,\n\tnames: readonly string[],\n\toptions: { now?: Date; days?: number } = {},\n): LocalCertificate {\n\tif (names.length === 0) throw new LocalCertificateWithoutNames();\n\tconst root = forge.pki.certificateFromPem(authority.cert);\n\tconst signer = forge.pki.privateKeyFromPem(authority.key);\n\tconst { privateKey, publicKey } = keyPair();\n\tconst now = (options.now ?? new Date()).getTime();\n\n\tconst cert = forge.pki.createCertificate();\n\tcert.publicKey = publicKey;\n\tcert.serialNumber = serialNumber();\n\tcert.validity.notBefore = new Date(now - 60 * 60 * 1000);\n\tcert.validity.notAfter = new Date(\n\t\tnow + (options.days ?? CERTIFICATE_DAYS) * DAY,\n\t);\n\tcert.setSubject(\n\t\tutf8([\n\t\t\t{ name: 'organizationName', value: 'gkm local certificate' },\n\t\t\t{ name: 'commonName', value: names[0]! },\n\t\t]),\n\t);\n\tcert.setIssuer(root.subject.attributes);\n\tcert.setExtensions([\n\t\t{ name: 'basicConstraints', cA: false, critical: true },\n\t\t{\n\t\t\tname: 'keyUsage',\n\t\t\tdigitalSignature: true,\n\t\t\tkeyEncipherment: true,\n\t\t\tcritical: true,\n\t\t},\n\t\t{ name: 'extKeyUsage', serverAuth: true },\n\t\t{\n\t\t\tname: 'subjectAltName',\n\t\t\taltNames: names.map((value) => ({ type: 2, value })),\n\t\t},\n\t\t{ name: 'subjectKeyIdentifier' },\n\t\t{\n\t\t\tname: 'authorityKeyIdentifier',\n\t\t\tkeyIdentifier: root.generateSubjectKeyIdentifier().getBytes(),\n\t\t},\n\t]);\n\tcert.sign(signer, forge.md.sha256.create());\n\treturn {\n\t\tcert: forge.pki.certificateToPem(cert),\n\t\tkey: forge.pki.privateKeyToPem(privateKey),\n\t};\n}\n\n/**\n * The certificate for `names` kept in `file` — certificate then key, one PEM\n * file, which is what a proxy given the same path for both reads — issued\n * again only when the one there is not the authority's, does not cover every\n * name, or is near its end.\n *\n * One file written by rename, so two commands issuing at once leave a pair\n * that matches, never one's certificate beside the other's key.\n *\n * @throws {LocalCertificateWithoutNames} for an empty list.\n */\nexport async function ensureLocalCertificate(\n\tauthority: LocalAuthority,\n\tnames: readonly string[],\n\tfile: string,\n\toptions: { now?: Date } = {},\n): Promise<LocalCertificate & { issued: boolean }> {\n\tconst now = options.now ?? new Date();\n\tconst existing = await readFile(file, 'utf-8').catch(() => undefined);\n\tconst kept = existing ? splitPem(existing) : undefined;\n\tif (kept && stillGood(authority, kept, names, now)) {\n\t\treturn { ...kept, issued: false };\n\t}\n\n\tconst issued = issueLocalCertificate(authority, names, { now });\n\tawait mkdir(dirname(file), { recursive: true, mode: 0o700 });\n\tconst staging = `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;\n\tawait writeFile(staging, `${issued.cert}${issued.key}`, { mode: 0o600 });\n\tawait rename(staging, file);\n\treturn { ...issued, issued: true };\n}\n\n/** A combined PEM file's certificate and key. */\nfunction splitPem(pem: string): LocalCertificate | undefined {\n\tconst cert = pem.match(\n\t\t/-----BEGIN CERTIFICATE-----[\\s\\S]+?-----END CERTIFICATE-----\\r?\\n?/,\n\t)?.[0];\n\tconst key = pem.match(\n\t\t/-----BEGIN (?:RSA )?PRIVATE KEY-----[\\s\\S]+?-----END (?:RSA )?PRIVATE KEY-----\\r?\\n?/,\n\t)?.[0];\n\treturn cert && key ? { cert, key } : undefined;\n}\n\n/** Whether a kept certificate still serves: the authority's, every name, in date. */\nfunction stillGood(\n\tauthority: LocalAuthority,\n\tkept: LocalCertificate,\n\tnames: readonly string[],\n\tnow: Date,\n): boolean {\n\ttry {\n\t\tconst root = forge.pki.certificateFromPem(authority.cert);\n\t\tconst cert = forge.pki.certificateFromPem(kept.cert);\n\t\tif (!root.verify(cert)) return false;\n\t\tif (\n\t\t\tcert.validity.notAfter.getTime() - now.getTime() <\n\t\t\tRENEW_WITHIN_DAYS * DAY\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\t// The key is the certificate's: a half-written pair is issued again.\n\t\tconst certKey = createPublicKey(kept.cert).export({\n\t\t\ttype: 'spki',\n\t\t\tformat: 'der',\n\t\t});\n\t\tconst ownKey = createPublicKey(createPrivateKey(kept.key)).export({\n\t\t\ttype: 'spki',\n\t\t\tformat: 'der',\n\t\t});\n\t\tif (!certKey.equals(ownKey)) return false;\n\t\tconst san = cert.getExtension('subjectAltName') as\n\t\t\t| { altNames?: { type: number; value: string }[] }\n\t\t\t| undefined;\n\t\tconst dns = new Set(\n\t\t\t(san?.altNames ?? []).filter((n) => n.type === 2).map((n) => n.value),\n\t\t);\n\t\treturn names.every((name) => dns.has(name));\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** An RSA key pair, made natively — forge's own generation is slow. */\nfunction keyPair(): {\n\tprivateKey: forge.pki.rsa.PrivateKey;\n\tpublicKey: forge.pki.rsa.PublicKey;\n} {\n\tconst { privateKey: pem } = generateKeyPairSync('rsa', {\n\t\tmodulusLength: 2048,\n\t\tpublicKeyEncoding: { type: 'spki', format: 'pem' },\n\t\tprivateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n\t});\n\tconst privateKey = forge.pki.privateKeyFromPem(\n\t\tpem,\n\t) as forge.pki.rsa.PrivateKey;\n\treturn {\n\t\tprivateKey,\n\t\tpublicKey: forge.pki.setRsaPublicKey(privateKey.n, privateKey.e),\n\t};\n}\n\n/**\n * Attributes as UTF8String. forge writes PrintableString otherwise, which\n * has no `@` or `*` — and a TLS stack rejects the certificate outright.\n */\nfunction utf8(\n\tattributes: { name: string; value: string }[],\n): forge.pki.CertificateField[] {\n\treturn attributes.map((attribute) => ({\n\t\t...attribute,\n\t\tvalueTagClass: forge.asn1.Type.UTF8 as never,\n\t}));\n}\n\n/** A random, positive serial: sixteen bytes, its high bit clear. */\nfunction serialNumber(): string {\n\tconst bytes = randomBytes(16);\n\tbytes[0] = bytes[0]! & 0x7f;\n\treturn bytes.toString('hex');\n}\n\n/** `user@host`, as far as the machine will say. */\nfunction owner(): string {\n\tlet user = 'gkm';\n\ttry {\n\t\tuser = userInfo().username;\n\t} catch {\n\t\t// No passwd entry — a container's arbitrary uid.\n\t}\n\treturn `${user}@${hostname()}`;\n}\n","/**\n * The real Postgres and MinIO clients the applier runs against.\n *\n * Kept apart from `provision.ts` so the rules there — what gets created, in what\n * order, and never dropping anything — are asserted against fakes, while the\n * drivers live here where there is nothing to assert but wiring.\n *\n * Both are constructed from the same local addresses the env writer composes,\n * so the applier cannot end up talking to a different container than the app.\n */\n\nimport {\n\tCreateBucketCommand,\n\tDeleteBucketLifecycleCommand,\n\tGetBucketLifecycleConfigurationCommand,\n\tGetBucketNotificationConfigurationCommand,\n\tGetBucketPolicyCommand,\n\tHeadBucketCommand,\n\tPutBucketLifecycleConfigurationCommand,\n\tPutBucketNotificationConfigurationCommand,\n\tPutBucketPolicyCommand,\n\tS3Client,\n} from '@aws-sdk/client-s3';\nimport {\n\tCreateTopicCommand,\n\tGetTopicAttributesCommand,\n\tSNSClient,\n} from '@aws-sdk/client-sns';\nimport {\n\tCreateQueueCommand,\n\tGetQueueUrlCommand,\n\tSQSClient,\n} from '@aws-sdk/client-sqs';\nimport { Client } from 'pg';\nimport { CLUSTER_DATABASE } from './compose';\nimport {\n\tEMULATOR_REGION,\n\temulatorEndpoint,\n\temulatorTopicArn,\n} from './emulator';\nimport type { ContainerCredentials, Login } from './localCredentials';\nimport type {\n\tBucketClient,\n\tBucketNotification,\n\tCarrierClient,\n\tSqlClient,\n} from './provision';\n\n/**\n * A Postgres client that opens one connection per database it is asked about.\n *\n * `CREATE DATABASE` cannot run from a connection to the database being created,\n * and a schema must be created from inside its own database — so the database is\n * part of each query rather than fixed when the client is built.\n */\nexport function pgClient(\n\tport: number,\n\t/**\n\t * The cluster's superuser: the workspace's local login, or the one a\n\t * `gkm compose` stack serving a deployed stage derives.\n\t */\n\tlogin: Login,\n): SqlClient {\n\treturn {\n\t\tasync query(database, sql, values) {\n\t\t\tconst client = new Client({\n\t\t\t\thost: 'localhost',\n\t\t\t\tport,\n\t\t\t\tuser: login.user,\n\t\t\t\tpassword: login.password,\n\t\t\t\t// The cluster's own database, which every cluster has. Connecting\n\t\t\t\t// to it is what makes `CREATE DATABASE` possible at all.\n\t\t\t\tdatabase: database ?? CLUSTER_DATABASE,\n\t\t\t});\n\n\t\t\tawait client.connect();\n\t\t\ttry {\n\t\t\t\tconst result = await client.query(sql, values as never[]);\n\t\t\t\treturn result.rows;\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** A bucket client pointed at a MinIO on this machine. */\nexport function bucketClient(\n\tport: number,\n\t/**\n\t * Its root login: the workspace's local one, or the one a `gkm compose`\n\t * stack serving a deployed stage derives.\n\t */\n\tcredentials: Login,\n): BucketClient {\n\tconst s3 = new S3Client({\n\t\tregion: 'us-east-1',\n\t\tendpoint: `http://localhost:${port}`,\n\t\t// MinIO serves buckets as paths, not as subdomains of the endpoint.\n\t\tforcePathStyle: true,\n\t\tcredentials: {\n\t\t\taccessKeyId: credentials.user,\n\t\t\tsecretAccessKey: credentials.password,\n\t\t},\n\t});\n\n\treturn {\n\t\tasync exists(bucket) {\n\t\t\ttry {\n\t\t\t\tawait s3.send(new HeadBucketCommand({ Bucket: bucket }));\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Missing, or not reachable. Creating is idempotent enough that\n\t\t\t\t// treating both as \"missing\" is safe.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync create(bucket) {\n\t\t\tawait s3.send(new CreateBucketCommand({ Bucket: bucket }));\n\t\t},\n\n\t\tasync policy(bucket) {\n\t\t\ttry {\n\t\t\t\tconst result = await s3.send(\n\t\t\t\t\tnew GetBucketPolicyCommand({ Bucket: bucket }),\n\t\t\t\t);\n\t\t\t\treturn result.Policy;\n\t\t\t} catch {\n\t\t\t\t// No policy, or the bucket is not reachable. Both mean there is\n\t\t\t\t// nothing to compare against, and writing one is idempotent.\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\tasync setPolicy(bucket, policy) {\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketPolicyCommand({ Bucket: bucket, Policy: policy }),\n\t\t\t);\n\t\t},\n\n\t\tasync lifecycle(bucket) {\n\t\t\ttry {\n\t\t\t\tconst result = await s3.send(\n\t\t\t\t\tnew GetBucketLifecycleConfigurationCommand({ Bucket: bucket }),\n\t\t\t\t);\n\t\t\t\treturn result.Rules;\n\t\t\t} catch (error) {\n\t\t\t\t// No lifecycle is MinIO's ordinary answer for a bucket with none;\n\t\t\t\t// anything else — unreachable, refused — is not \"none\".\n\t\t\t\tif (\n\t\t\t\t\t(error as { name?: string }).name === 'NoSuchLifecycleConfiguration'\n\t\t\t\t) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\tasync setLifecycle(bucket, rules) {\n\t\t\tif (rules.length === 0) {\n\t\t\t\tawait s3.send(new DeleteBucketLifecycleCommand({ Bucket: bucket }));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketLifecycleConfigurationCommand({\n\t\t\t\t\tBucket: bucket,\n\t\t\t\t\tLifecycleConfiguration: { Rules: rules },\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\n\t\tasync notification(bucket) {\n\t\t\tconst { $metadata: _, ...notification } = await s3.send(\n\t\t\t\tnew GetBucketNotificationConfigurationCommand({ Bucket: bucket }),\n\t\t\t);\n\t\t\treturn notification as BucketNotification;\n\t\t},\n\n\t\tasync setNotification(bucket, notification) {\n\t\t\tawait s3.send(\n\t\t\t\tnew PutBucketNotificationConfigurationCommand({\n\t\t\t\t\tBucket: bucket,\n\t\t\t\t\tNotificationConfiguration: notification as never,\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** A topic and queue client pointed at the local AWS emulator. */\nexport function carrierClient(\n\tport: number,\n\tcredentials: ContainerCredentials['emulator'],\n): CarrierClient {\n\tconst config = {\n\t\tregion: EMULATOR_REGION,\n\t\tendpoint: emulatorEndpoint(port),\n\t\tcredentials,\n\t};\n\tconst sns = new SNSClient(config);\n\tconst sqs = new SQSClient(config);\n\n\treturn {\n\t\tasync topicExists(name) {\n\t\t\ttry {\n\t\t\t\tawait sns.send(\n\t\t\t\t\tnew GetTopicAttributesCommand({ TopicArn: emulatorTopicArn(name) }),\n\t\t\t\t);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Missing, or not reachable; creating is idempotent either way.\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync createTopic(name) {\n\t\t\tawait sns.send(new CreateTopicCommand({ Name: name }));\n\t\t},\n\n\t\tasync queueExists(name) {\n\t\t\ttry {\n\t\t\t\tawait sqs.send(new GetQueueUrlCommand({ QueueName: name }));\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\n\t\tasync createQueue(name) {\n\t\t\tawait sqs.send(new CreateQueueCommand({ QueueName: name }));\n\t\t},\n\t};\n}\n","/**\n * The real Docker, behind the small interface reconcile needs.\n *\n * Shells out to `docker compose` rather than talking to the daemon socket: it is\n * what a developer runs by hand when something is wrong, so the two cannot\n * disagree, and it keeps Docker out of this package's dependencies.\n *\n * Every call that acts is scoped to the generated compose file. Nothing here\n * can touch a container this project did not generate; `publisher` only reads\n * who holds a port.\n */\n\nimport { execFile, spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Docker } from './index';\n\nconst run = promisify(execFile);\n\n/**\n * The generated file, then the project's own if it has one.\n *\n * Merged in that order so the project's wins — an `image:` there pins a\n * container this file derived, and a service there is added beside them.\n */\nexport function composeFiles(composePath: string): string[] {\n\tconst project = join(dirname(composePath), 'docker-compose.yml');\n\treturn ['-f', composePath, ...(existsSync(project) ? ['-f', project] : [])];\n}\n\n/** How long to wait for containers to pass their health checks. */\nconst HEALTH_TIMEOUT_MS = 120_000;\n\n/** `docker compose up` exited unsuccessfully; its own output said why. */\nexport class ComposeUpFailed extends Error {\n\tconstructor(\n\t\treadonly services: readonly string[],\n\t\treadonly code: number | null,\n\t) {\n\t\tsuper(\n\t\t\t`docker compose could not start ${services.join(', ')} (exit ${code ?? 'signal'}). Its output above names the container; \\`docker compose logs <service>\\` shows why it stopped.`,\n\t\t);\n\t\tthis.name = 'ComposeUpFailed';\n\t}\n}\n\n/** Run compose with its output on this terminal rather than captured. */\nfunction shown(args: readonly string[], services: readonly string[]) {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn('docker', args, {\n\t\t\tstdio: ['ignore', 'inherit', 'inherit'],\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) =>\n\t\t\tcode === 0 ? resolve() : reject(new ComposeUpFailed(services, code)),\n\t\t);\n\t});\n}\n\nexport const dockerCli: Docker = {\n\tasync publishedPort(composePath, service, inside) {\n\t\ttry {\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'port',\n\t\t\t\tservice,\n\t\t\t\tString(inside),\n\t\t\t]);\n\n\t\t\t// `0.0.0.0:54321` — the part after the last colon is the host port.\n\t\t\tconst port = Number(stdout.trim().split(':').pop());\n\n\t\t\treturn Number.isFinite(port) && port > 0 ? port : undefined;\n\t\t} catch {\n\t\t\t// Not running, or no such service. Both mean \"nothing to reuse\".\n\t\t\treturn undefined;\n\t\t}\n\t},\n\n\tasync publisher(port) {\n\t\ttry {\n\t\t\t// Not scoped to the compose file: the point is to name whoever holds\n\t\t\t// the port, which is usually another project.\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'ps',\n\t\t\t\t'--filter',\n\t\t\t\t`publish=${port}`,\n\t\t\t\t'--format',\n\t\t\t\t'{{.Label \"com.docker.compose.project\"}}',\n\t\t\t]);\n\n\t\t\treturn stdout.trim().split('\\n')[0] || undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t},\n\n\tasync up(composePath, services, options = {}) {\n\t\tconst args = [\n\t\t\t'compose',\n\t\t\t...composeFiles(composePath),\n\t\t\t'up',\n\t\t\t'-d',\n\t\t\t// Recreate anything whose definition moved — a changed image pin is\n\t\t\t// exactly the case the hash detects, and leaving the old container\n\t\t\t// running would make the reconcile a lie.\n\t\t\t'--remove-orphans',\n\t\t\t'--wait',\n\t\t\t`--wait-timeout=${Math.floor(HEALTH_TIMEOUT_MS / 1000)}`,\n\t\t\t...services,\n\t\t];\n\n\t\tif (options.show) return shown(args, services);\n\t\tawait run('docker', args);\n\t},\n\n\tasync reload(composePath, service) {\n\t\t// Caddy's own reload is graceful and validates first, so a config it\n\t\t// refuses leaves the previous one serving rather than dropping the edge.\n\t\t// Forced: a certificate issued again changes no line of the config, and\n\t\t// an unforced reload of an unchanged config is skipped.\n\t\tawait run('docker', [\n\t\t\t'compose',\n\t\t\t...composeFiles(composePath),\n\t\t\t'exec',\n\t\t\t'-T',\n\t\t\tservice,\n\t\t\t'caddy',\n\t\t\t'reload',\n\t\t\t'--config',\n\t\t\t'/etc/caddy/Caddyfile',\n\t\t\t'--force',\n\t\t]);\n\t},\n\n\tasync exec(composePath, service, argv) {\n\t\ttry {\n\t\t\tconst { stdout, stderr } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'exec',\n\t\t\t\t'-T',\n\t\t\t\tservice,\n\t\t\t\t...argv,\n\t\t\t]);\n\t\t\treturn { ok: true, output: `${stdout}${stderr}` };\n\t\t} catch (error) {\n\t\t\tconst { stdout = '', stderr = '' } = error as {\n\t\t\t\tstdout?: string;\n\t\t\t\tstderr?: string;\n\t\t\t};\n\t\t\treturn { ok: false, output: `${stdout}${stderr}` };\n\t\t}\n\t},\n\n\tasync healthy(composePath, services, { mounted = [] } = {}) {\n\t\tif (services.length === 0) return true;\n\t\tconst checkout = dirname(composePath);\n\n\t\ttry {\n\t\t\tconst { stdout } = await run('docker', [\n\t\t\t\t'compose',\n\t\t\t\t...composeFiles(composePath),\n\t\t\t\t'ps',\n\t\t\t\t'--format',\n\t\t\t\t'json',\n\t\t\t\t...services,\n\t\t\t]);\n\n\t\t\tconst running = new Set<string>();\n\t\t\tfor (const line of stdout.trim().split('\\n').filter(Boolean)) {\n\t\t\t\tconst entry = JSON.parse(line) as {\n\t\t\t\t\tService?: string;\n\t\t\t\t\tState?: string;\n\t\t\t\t\tHealth?: string;\n\t\t\t\t\tLabels?: string;\n\t\t\t\t};\n\n\t\t\t\t// A container with a health check must be passing it; one without\n\t\t\t\t// only has to be running, since there is nothing better to ask.\n\t\t\t\tconst ok =\n\t\t\t\t\tentry.State === 'running' &&\n\t\t\t\t\t(entry.Health === undefined ||\n\t\t\t\t\t\tentry.Health === '' ||\n\t\t\t\t\t\tentry.Health === 'healthy');\n\n\t\t\t\t// Every checkout of a project shares its compose project name, so a\n\t\t\t\t// worktree's container answers here too. One that mounts the\n\t\t\t\t// checkout's files reads that worktree's — Caddy routing to the\n\t\t\t\t// ports another checkout's apps had — so it counts only when it was\n\t\t\t\t// created from this one.\n\t\t\t\tconst fromHere =\n\t\t\t\t\t!entry.Service ||\n\t\t\t\t\t!mounted.includes(entry.Service) ||\n\t\t\t\t\tlabel(entry.Labels, 'com.docker.compose.project.working_dir') ===\n\t\t\t\t\t\tcheckout;\n\n\t\t\t\tif (ok && fromHere && entry.Service) running.add(entry.Service);\n\t\t\t}\n\n\t\t\treturn services.every((service) => running.has(service));\n\t\t} catch {\n\t\t\t// No compose file yet, or no daemon. Either way, not healthy.\n\t\t\treturn false;\n\t\t}\n\t},\n};\n\n/** One label's value out of `docker compose ps`'s comma-joined `Labels`. */\nfunction label(labels: string | undefined, name: string): string | undefined {\n\tconst prefix = `${name}=`;\n\treturn labels\n\t\t?.split(',')\n\t\t.find((pair) => pair.startsWith(prefix))\n\t\t?.slice(prefix.length);\n}\n\nexport { HEALTH_TIMEOUT_MS };\n","/**\n * This machine's address on the local network — what a phone running the app\n * reaches it on.\n */\n\nimport { type NetworkInterfaceInfo, networkInterfaces } from 'node:os';\n\n/**\n * The first private IPv4 address of an interface that is up and not loopback.\n *\n * Private ranges only (`10/8`, `172.16/12`, `192.168/16`): a public address\n * would mean listening for a phone on the open internet, and a link-local one\n * (`169.254/16`) is what an interface has when it found no network at all.\n * Undefined when there is none — a laptop on no network still runs, its mobile\n * app reaching only a simulator.\n */\nexport function lanAddress(\n\tinterfaces: Record<\n\t\tstring,\n\t\tNetworkInterfaceInfo[] | undefined\n\t> = networkInterfaces(),\n): string | undefined {\n\tfor (const entries of Object.values(interfaces)) {\n\t\tfor (const entry of entries ?? []) {\n\t\t\tif (entry.family !== 'IPv4' || entry.internal) continue;\n\t\t\tif (isPrivate(entry.address)) return entry.address;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isPrivate(address: string): boolean {\n\treturn (\n\t\t/^10\\./.test(address) ||\n\t\t/^192\\.168\\./.test(address) ||\n\t\t/^172\\.(1[6-9]|2\\d|3[01])\\./.test(address)\n\t);\n}\n","/**\n * Bringing a container that already has data in line with the workspace's\n * generated logins.\n *\n * Postgres and RabbitMQ read their login from the environment once, when the\n * volume is first initialised; a volume an older gkm made was initialised\n * with the old fixed one, and a changed environment alone would lock the\n * developer out of their own data. So after the containers are up, each one\n * is asked whether the generated login opens it, and if not:\n *\n * - **Postgres**: signed in to with the old login, the generated superuser is\n * created (or given its password), and the old one stops logging in. Where\n * no login is accepted — another checkout of the same project rotated it —\n * the password is set from inside the container, which trusts its own\n * socket.\n * - **MinIO** reads its root login on every start, so recreating the\n * container rotated it already. If the old login is still the one it takes —\n * a project's own `docker-compose.yml` pins it — that is kept, with a note.\n * - **RabbitMQ**: the user is added, or given its password, with `rabbitmqctl`\n * inside the container.\n *\n * Nothing is deleted: no volume, no database, no bucket.\n */\n\nimport { ListBucketsCommand, S3Client } from '@aws-sdk/client-s3';\nimport { Client } from 'pg';\nimport { GkmError } from '../errors';\nimport { CLUSTER_DATABASE } from './compose';\nimport type { LocalCredentials, Login } from './localCredentials';\n\n/**\n * The login every local container was brought up with before logins were\n * generated. Kept only to recognise — and rotate away from — a volume made\n * then.\n */\nexport const LEGACY_LOCAL_LOGIN: Login = Object.freeze({\n\tuser: 'geekmidas',\n\tpassword: 'geekmidas',\n});\n\n/** Runs a command inside a running compose service. */\nexport type ServiceExec = (\n\tservice: string,\n\targv: readonly string[],\n) => Promise<{ ok: boolean; output: string }>;\n\n/** What checking one service's login found and did. */\nexport interface LoginOutcome {\n\tservice: 'postgres' | 'minio' | 'rabbitmq';\n\t/**\n\t * `current` — the generated login opened it; `rotated` — an older login\n\t * did, and the service now takes the generated one; `kept` — an older\n\t * login did and could not be rotated, so it is what is used.\n\t */\n\tstatus: 'current' | 'rotated' | 'kept';\n\t/** The login the service takes now. */\n\tlogin: Login;\n\t/** A line for the developer, where anything changed. */\n\tnotice?: string;\n}\n\n/** No login this workspace knows opens its Postgres. */\nexport class PostgresLoginRefused extends GkmError {\n\tconstructor(\n\t\treadonly port: number,\n\t\treadonly user: string,\n\t) {\n\t\tsuper(\n\t\t\t`The Postgres on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used, and could not be reset from inside its container. ` +\n\t\t\t\t\"If it is not this project's container, stop whatever holds the port. If it is, removing its volume starts it over with the generated login — and deletes its data: docker compose -f docker-compose.constructs.yml down -v\",\n\t\t);\n\t\tthis.name = 'PostgresLoginRefused';\n\t}\n}\n\n/** No login this workspace knows opens its MinIO. */\nexport class MinioLoginRefused extends GkmError {\n\tconstructor(\n\t\treadonly port: number,\n\t\treadonly user: string,\n\t) {\n\t\tsuper(\n\t\t\t`The MinIO on port ${port} accepts neither '${user}' with this workspace's generated password nor the login older gkm versions used. ` +\n\t\t\t\t'If your docker-compose.yml sets MINIO_ROOT_USER or MINIO_ROOT_PASSWORD, remove them so the generated login applies.',\n\t\t);\n\t\tthis.name = 'MinioLoginRefused';\n\t}\n}\n\n/** Whether `login` opens the Postgres on `port`, as a connected client. */\nasync function connect(port: number, login: Login): Promise<Client | null> {\n\tconst client = new Client({\n\t\thost: 'localhost',\n\t\tport,\n\t\tuser: login.user,\n\t\tpassword: login.password,\n\t\tdatabase: CLUSTER_DATABASE,\n\t});\n\ttry {\n\t\tawait client.connect();\n\t\treturn client;\n\t} catch (error) {\n\t\tawait client.end().catch(() => {});\n\t\t// 28P01: wrong password. 28000: no such role, or no pg_hba entry.\n\t\t// 3D000: no such database — a cluster whose default database was\n\t\t// named after an older superuser still answers for `postgres`, so\n\t\t// this is only a login that is not ours.\n\t\tconst code = (error as { code?: string }).code;\n\t\tif (code === '28P01' || code === '28000' || code === '3D000') return null;\n\t\tthrow error;\n\t}\n}\n\n/** Quote a string literal for DDL that cannot take parameters. */\nfunction literal(value: string): string {\n\treturn `'${value.replace(/'/g, \"''\")}'`;\n}\n\nfunction ident(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** The SQL that makes `login` a superuser with its password, new or not. */\nfunction superuserSql(login: Login): string {\n\treturn (\n\t\t`DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(login.user)}) ` +\n\t\t`THEN ALTER ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; ` +\n\t\t`ELSE CREATE ROLE ${ident(login.user)} WITH SUPERUSER LOGIN PASSWORD ${literal(login.password)}; ` +\n\t\t'END IF; END $$'\n\t);\n}\n\n/**\n * Make the Postgres on `port` take `login`, rotating it from an older one\n * where that is what it takes.\n */\nexport async function ensurePostgresLogin(options: {\n\tport: number;\n\tlogin: Login;\n\t/** Older logins it may still take, most likely first. */\n\tlegacy: readonly Login[];\n\t/** Inside the container, where its socket trusts any role. */\n\texec?: ServiceExec;\n}): Promise<LoginOutcome> {\n\tconst { port, login, legacy } = options;\n\n\tconst current = await connect(port, login);\n\tif (current) {\n\t\tawait current.end();\n\t\treturn { service: 'postgres', status: 'current', login };\n\t}\n\n\tfor (const old of legacy) {\n\t\tconst client = await connect(port, old);\n\t\tif (!client) continue;\n\t\ttry {\n\t\t\tawait client.query(superuserSql(login));\n\t\t} catch {\n\t\t\t// The old login is not allowed to make a superuser: keep using it.\n\t\t\tawait client.end();\n\t\t\treturn {\n\t\t\t\tservice: 'postgres',\n\t\t\t\tstatus: 'kept',\n\t\t\t\tlogin: old,\n\t\t\t\tnotice: `⚠️ Postgres still signs in as '${old.user}' with the old fixed password: it could not be rotated. To start over with a generated one, remove its volume (this deletes its data): docker compose -f docker-compose.constructs.yml down -v`,\n\t\t\t};\n\t\t}\n\t\tawait client.end();\n\t\tawait retire(port, login, old);\n\t\treturn {\n\t\t\tservice: 'postgres',\n\t\t\tstatus: 'rotated',\n\t\t\tlogin,\n\t\t\tnotice: `🔑 Postgres moved from the old fixed login to a generated one ('${login.user}'); its data is unchanged. See it with: gkm dev:credentials`,\n\t\t};\n\t}\n\n\t// Nothing we know opens it over TCP. Its socket inside the container\n\t// trusts any role that exists, which one of these is.\n\tif (options.exec) {\n\t\tfor (const user of [login.user, ...legacy.map((l) => l.user)]) {\n\t\t\tconst result = await options.exec('postgres', [\n\t\t\t\t'psql',\n\t\t\t\t'-v',\n\t\t\t\t'ON_ERROR_STOP=1',\n\t\t\t\t'-U',\n\t\t\t\tuser,\n\t\t\t\t'-d',\n\t\t\t\tCLUSTER_DATABASE,\n\t\t\t\t'-c',\n\t\t\t\tsuperuserSql(login),\n\t\t\t]);\n\t\t\tif (!result.ok) continue;\n\t\t\tconst client = await connect(port, login);\n\t\t\tif (!client) continue;\n\t\t\tawait client.end();\n\t\t\tfor (const old of legacy) await retire(port, login, old);\n\t\t\treturn {\n\t\t\t\tservice: 'postgres',\n\t\t\t\tstatus: 'rotated',\n\t\t\t\tlogin,\n\t\t\t\tnotice: `🔑 Postgres's login was reset to this workspace's generated one ('${login.user}'); its data is unchanged.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tthrow new PostgresLoginRefused(port, login.user);\n}\n\n/** Stop an older login from opening the cluster, now another does. */\nasync function retire(port: number, login: Login, old: Login): Promise<void> {\n\tif (old.user === login.user) return;\n\tconst client = await connect(port, login);\n\tif (!client) return;\n\ttry {\n\t\tconst exists = await client.query(\n\t\t\t'SELECT 1 FROM pg_roles WHERE rolname = $1',\n\t\t\t[old.user],\n\t\t);\n\t\tif (exists.rowCount) {\n\t\t\tawait client.query(\n\t\t\t\t`ALTER ROLE ${ident(old.user)} WITH NOLOGIN PASSWORD NULL`,\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tawait client.end();\n\t}\n}\n\n/** Whether `login` signs in to the MinIO on `port`. */\nexport async function minioAccepts(\n\tport: number,\n\tlogin: Login,\n): Promise<boolean> {\n\tconst s3 = new S3Client({\n\t\tregion: 'us-east-1',\n\t\tendpoint: `http://localhost:${port}`,\n\t\tforcePathStyle: true,\n\t\tcredentials: { accessKeyId: login.user, secretAccessKey: login.password },\n\t\tmaxAttempts: 1,\n\t});\n\ttry {\n\t\tawait s3.send(new ListBucketsCommand({}));\n\t\treturn true;\n\t} catch (error) {\n\t\tconst name = (error as { name?: string }).name ?? '';\n\t\tif (\n\t\t\tname === 'InvalidAccessKeyId' ||\n\t\t\tname === 'SignatureDoesNotMatch' ||\n\t\t\tname === 'AccessDenied'\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\ts3.destroy();\n\t}\n}\n\n/**\n * Check the MinIO on `port` takes `login`. It reads its root login on every\n * start, so a recreated container already does — unless something pins an\n * older one, which is then kept.\n */\nexport async function ensureMinioLogin(options: {\n\tport: number;\n\tlogin: Login;\n\tlegacy: readonly Login[];\n}): Promise<LoginOutcome> {\n\tconst { port, login, legacy } = options;\n\tif (await minioAccepts(port, login)) {\n\t\treturn { service: 'minio', status: 'current', login };\n\t}\n\tfor (const old of legacy) {\n\t\tif (await minioAccepts(port, old)) {\n\t\t\treturn {\n\t\t\t\tservice: 'minio',\n\t\t\t\tstatus: 'kept',\n\t\t\t\tlogin: old,\n\t\t\t\tnotice: `⚠️ MinIO still signs in as '${old.user}' with the old fixed password: something — usually your docker-compose.yml's MINIO_ROOT_USER/MINIO_ROOT_PASSWORD — pins it. Remove that to use the generated login.`,\n\t\t\t};\n\t\t}\n\t}\n\tthrow new MinioLoginRefused(port, login.user);\n}\n\n/**\n * Make the RabbitMQ in the project's container take `login`, with\n * `rabbitmqctl` inside it — which needs no password.\n */\nexport async function ensureRabbitmqLogin(options: {\n\tlogin: Login;\n\tlegacy: readonly Login[];\n\texec: ServiceExec;\n}): Promise<LoginOutcome> {\n\tconst { login, legacy, exec } = options;\n\tconst ctl = (...args: string[]) => exec('rabbitmq', ['rabbitmqctl', ...args]);\n\n\tif ((await ctl('authenticate_user', login.user, login.password)).ok) {\n\t\treturn { service: 'rabbitmq', status: 'current', login };\n\t}\n\n\tif (!(await ctl('add_user', login.user, login.password)).ok) {\n\t\tawait ctl('change_password', login.user, login.password);\n\t}\n\tawait ctl('set_user_tags', login.user, 'administrator');\n\tawait ctl('set_permissions', '-p', '/', login.user, '.*', '.*', '.*');\n\tfor (const old of legacy) {\n\t\tif (old.user !== login.user) await ctl('delete_user', old.user);\n\t}\n\treturn {\n\t\tservice: 'rabbitmq',\n\t\tstatus: 'rotated',\n\t\tlogin,\n\t\tnotice: `🔑 RabbitMQ moved from the old fixed login to a generated one ('${login.user}'); its queues are unchanged.`,\n\t};\n}\n\n/** Every container's login, checked — and what is used from now on. */\nexport interface LoginsResult {\n\tcredentials: LocalCredentials;\n\toutcomes: LoginOutcome[];\n}\n\n/**\n * Check the login of each running container that keeps one, and the\n * credentials to use from here: the generated ones, or an older login a\n * service could not be moved off.\n */\nexport async function ensureLogins(options: {\n\tcredentials: LocalCredentials;\n\tcontainers: readonly string[];\n\tports: { postgres?: number; minio?: number };\n\texec?: ServiceExec;\n}): Promise<LoginsResult> {\n\tconst { containers, ports, exec } = options;\n\tlet credentials = options.credentials;\n\tconst outcomes: LoginOutcome[] = [];\n\tconst legacy = [LEGACY_LOCAL_LOGIN];\n\n\tif (containers.includes('postgres') && ports.postgres !== undefined) {\n\t\tconst outcome = await ensurePostgresLogin({\n\t\t\tport: ports.postgres,\n\t\t\tlogin: credentials.postgres,\n\t\t\tlegacy,\n\t\t\t...(exec ? { exec } : {}),\n\t\t});\n\t\toutcomes.push(outcome);\n\t\tcredentials = { ...credentials, postgres: outcome.login };\n\t}\n\n\tif (containers.includes('minio') && ports.minio !== undefined) {\n\t\tconst outcome = await ensureMinioLogin({\n\t\t\tport: ports.minio,\n\t\t\tlogin: credentials.minio,\n\t\t\tlegacy,\n\t\t});\n\t\toutcomes.push(outcome);\n\t\tcredentials = { ...credentials, minio: outcome.login };\n\t}\n\n\tif (containers.includes('rabbitmq') && exec) {\n\t\toutcomes.push(\n\t\t\tawait ensureRabbitmqLogin({\n\t\t\t\tlogin: credentials.rabbitmq,\n\t\t\t\tlegacy,\n\t\t\t\texec,\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn { credentials, outcomes };\n}\n","/**\n * Port allocation — why two projects can run at once.\n *\n * Publishing `5432:5432` means the second project on your machine cannot start.\n * Nothing solves that except giving each project its own ports, and what makes\n * it *possible* is the single-`<NAME>_URL` rule: an app reads `ORDERS_URL` and\n * never sees a host or a port, so reconcile is free to bind whatever is\n * available and compose the URL from what it bound. An app reading `DB_HOST` and\n * `DB_PORT` separately could not be moved this way.\n *\n * Assignments are **persisted, not recomputed**. Recomputing means adding a\n * construct renumbers its neighbours, and every running container, saved\n * connection string, and `psql` history goes stale at once.\n *\n * Pure, with the liveness probe injected — a collision with another project's\n * stack is a fact about the machine, and keeping it a parameter is what lets the\n * rules be asserted without binding a socket.\n */\n\nimport { createHash } from 'node:crypto';\nimport { createServer } from 'node:net';\nimport { GkmError } from '../errors';\n\n/** What was assigned, by container name. Persisted between runs. */\nexport type PortAssignments = Readonly<Record<string, number>>;\n\n/**\n * The window ports are drawn from.\n *\n * Above the registered range so nothing here needs privileges, and below the\n * ephemeral range both Linux (32768+) and macOS (49152+) allocate from — a port\n * the kernel might hand to an outgoing connection is one that is free when\n * checked and taken by the time it is bound.\n */\nconst WINDOW = { min: 20000, max: 32000 } as const;\n\n/**\n * How far apart two projects start.\n *\n * Wide enough that a project can add containers without walking into its\n * neighbour's block, narrow enough that the window holds many projects.\n */\nconst BLOCK = 50;\n\n/**\n * Where a project's ports start.\n *\n * Derived from the name rather than assigned sequentially so that a fresh clone\n * of the same project on the same machine lands on the same block — the first\n * run has nothing persisted to read, and hashing is what keeps that first run\n * from colliding with whatever else is already allocated.\n *\n * @example startingPort('toolbox') // stable for a given name\n */\nexport function startingPort(project: string): number {\n\tconst digest = createHash('sha256').update(project).digest();\n\tconst blocks = Math.floor((WINDOW.max - WINDOW.min) / BLOCK);\n\n\treturn WINDOW.min + (digest.readUInt32BE(0) % blocks) * BLOCK;\n}\n\n/**\n * Whether a port can be bound right now.\n *\n * Async because the only way to answer it is to try binding, and\n * `server.listen` is asynchronous — there is no synchronous form to wrap. A\n * probe that pretended otherwise would have to lie.\n */\nexport type PortProbe = (port: number) => Promise<boolean>;\n\n/**\n * Assign a port to every container that has none, keeping the ones that do.\n *\n * Existing assignments are returned untouched even when the container is no\n * longer in the plan: removing a construct must not renumber what is left, and\n * keeping the entry means re-adding it later restores the same port rather than\n * inventing a new one.\n *\n * @param probe - reports what is actually listening. A port assigned to this\n * project is skipped without probing, because on a converged reconcile our own\n * container is the thing listening on it.\n * @throws {NoPortAvailable} when the window is exhausted.\n */\nexport async function allocate(\n\tproject: string,\n\tcontainers: readonly string[],\n\texisting: PortAssignments = {},\n\tprobe: PortProbe = isPortFree,\n): Promise<PortAssignments> {\n\tconst assignments: Record<string, number> = { ...existing };\n\tconst taken = new Set(Object.values(assignments));\n\n\t// Sorted so the order containers happen to appear in the plan cannot change\n\t// which port each one gets.\n\tfor (const container of [...containers].sort()) {\n\t\tif (assignments[container] !== undefined) continue;\n\n\t\tconst port = await nextFree(startingPort(project), taken, probe);\n\t\tassignments[container] = port;\n\t\ttaken.add(port);\n\t}\n\n\treturn assignments;\n}\n\n/**\n * The ports to keep: what running containers are observed on, then what was\n * saved — minus any saved entry whose port something else already holds.\n *\n * Spreading one over the other let an observed port override its own key and\n * leave a *different* key still saved on the same number: two services on one\n * port, and whichever answered first won. Saved keys for containers the plan no\n * longer has — a backend switched and back — were the usual source. Observed\n * wins because it is what is actually bound; a dropped entry is simply\n * allocated again.\n */\nexport function keptPorts(\n\tsaved: PortAssignments = {},\n\tobserved: PortAssignments = {},\n): PortAssignments {\n\tconst kept: Record<string, number> = { ...observed };\n\tconst taken = new Set(Object.values(observed));\n\n\t// Sorted, so which of two colliding saved entries survives is stable.\n\tfor (const [key, port] of Object.entries(saved).sort(([a], [b]) =>\n\t\ta < b ? -1 : 1,\n\t)) {\n\t\tif (key in kept || taken.has(port)) continue;\n\t\tkept[key] = port;\n\t\ttaken.add(port);\n\t}\n\n\treturn kept;\n}\n\n/**\n * Whether a port is published by one of this project's own containers.\n *\n * Asked only of a port the probe found taken: our own container on it is the\n * normal re-run, anything else is a stack that took the port since it was\n * saved.\n */\nexport type PortOwner = (port: number) => Promise<boolean>;\n\n/** A kept port something else now holds, and where its container moved. */\nexport interface PortMove {\n\tkey: string;\n\tfrom: number;\n\tto: number;\n}\n\n/**\n * The kept ports, among those the plan publishes, that something other than\n * this project now holds.\n *\n * A saved port is only a memory of a free one. Another checkout's stack — the\n * same project name hashes to the same block — can bind it in the meantime,\n * and keeping it unchecked fails `docker compose up` with \"port is already\n * allocated\". An observed port is ours by definition and is never asked\n * about; neither is a saved one the plan no longer publishes, which is only\n * kept for when it returns.\n */\nexport async function heldElsewhere(\n\tkept: PortAssignments,\n\tkeys: readonly string[],\n\tobserved: PortAssignments,\n\tprobe: PortProbe,\n\tours: PortOwner,\n): Promise<string[]> {\n\tconst held: string[] = [];\n\n\tfor (const key of [...keys].sort()) {\n\t\tconst port = kept[key];\n\t\tif (port === undefined || key in observed) continue;\n\t\tif (await probe(port)) continue;\n\t\tif (await ours(port)) continue;\n\t\theld.push(key);\n\t}\n\n\treturn held;\n}\n\n/** The window was exhausted. */\nexport class NoPortAvailable extends GkmError {\n\t/** Where the search started. */\n\treadonly from: number;\n\t/** The window searched, so the caller can report what was full. */\n\treadonly window: { min: number; max: number } = WINDOW;\n\n\tconstructor(from: number) {\n\t\tsuper('No free port is available in the local port range');\n\t\tthis.name = 'NoPortAvailable';\n\t\tthis.from = from;\n\t}\n}\n\n/**\n * The first port at or after `from` that is neither ours nor in use.\n *\n * Wraps at the top of the window rather than stopping, so a project whose block\n * sits near the end is not the one that fails.\n */\nasync function nextFree(\n\tfrom: number,\n\ttaken: ReadonlySet<number>,\n\tprobe: PortProbe,\n): Promise<number> {\n\tconst span = WINDOW.max - WINDOW.min;\n\n\tfor (let offset = 0; offset < span; offset++) {\n\t\tconst port = WINDOW.min + ((from - WINDOW.min + offset) % span);\n\t\tif (taken.has(port)) continue;\n\t\tif (await probe(port)) return port;\n\t}\n\n\tthrow new NoPortAvailable(from);\n}\n\n/**\n * Whether nothing is listening on a port.\n *\n * Binds rather than connects: a refused connection says nothing about whether\n * the port can be *published*, which is the question Docker will ask. Binds on\n * `0.0.0.0` for the same reason — a port free on loopback can still be taken on\n * the address Docker publishes to — and then on `127.0.0.1`, because on macOS\n * a wildcard bind succeeds beside a listener on loopback alone.\n *\n * Inherently racy, and that is acceptable: Docker failing to bind stays the real\n * check. This exists so the common case surfaces as a message at reconcile\n * rather than as a connection failure ten minutes later.\n */\nexport async function isPortFree(port: number): Promise<boolean> {\n\treturn (await canBind(port, '0.0.0.0')) && (await canBind(port, '127.0.0.1'));\n}\n\nfunction canBind(port: number, host: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst server = createServer();\n\n\t\tserver.once('error', () => resolve(false));\n\t\tserver.once('listening', () => server.close(() => resolve(true)));\n\t\tserver.listen(port, host);\n\t});\n}\n","/**\n * What reconcile records, and the hash that lets it do nothing.\n *\n * Reconciling on every `gkm dev` is only acceptable if the converged case is\n * free, so the desired plan is hashed: matching hash plus healthy containers\n * means there is nothing to do. Without that, the automatic reconcile the design\n * asks for would tax every start.\n *\n * Almost nothing needs recording — roles are queried, migrations have their own\n * table, containers are remembered by Docker. Only ports and this hash have no\n * other owner.\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { ComposeFile } from './compose';\nimport type { Plan } from './plan';\n\n/** What was true at the end of the last successful reconcile. */\nexport interface ReconcileState {\n\t/** The hash of the plan that was applied. */\n\thash: string;\n\t/** The stage it was applied for, so a mismatched file is ignored. */\n\tstage: string;\n}\n\nconst STATE_DIR = '.gkm/reconcile';\n\n/**\n * The hash of everything a reconcile would act on.\n *\n * Covers the compose document rather than the plan alone, because the plan is\n * unchanged when only an image pin moves — and a changed image is exactly a\n * container that must be recreated. `stringify` is stable here because\n * `composeFor` sorts its containers, which is what makes the hash meaningful.\n *\n * Deliberately a plain function over serialisable input: the deployed target\n * keys its provisioner invocation on the same idea, and the two must not be able\n * to disagree about what counts as a change.\n */\nexport function planHash(\n\tplan: Plan,\n\tcompose: ComposeFile,\n\t/**\n\t * Anything else generated from the plan that a container reads.\n\t *\n\t * The edge's Caddyfile is the case: a file server added or a bucket renamed\n\t * changes the routing without changing a single container, so a hash over\n\t * the compose document alone would report convergence and leave the old\n\t * routes serving.\n\t */\n\tgenerated: Readonly<Record<string, string>> = {},\n): string {\n\treturn createHash('sha256')\n\t\t.update(JSON.stringify({ stage: plan.stage, plan, compose, generated }))\n\t\t.digest('hex');\n}\n\n/** Read the recorded state, or nothing if this stage has never reconciled. */\nexport async function loadState(\n\troot: string,\n\tstage: string,\n): Promise<ReconcileState | undefined> {\n\ttry {\n\t\tconst raw = await readFile(statePath(root, stage), 'utf-8');\n\t\tconst state = JSON.parse(raw) as ReconcileState;\n\n\t\t// A file written for another stage is not this stage's state. Treating it\n\t\t// as one is how `gkm test` would skip work `gkm dev` did.\n\t\treturn state.stage === stage ? state : undefined;\n\t} catch {\n\t\t// Unreadable, absent, or corrupt all mean the same thing: reconcile. The\n\t\t// loop is convergent, so the cost of being wrong here is one slow start.\n\t\treturn undefined;\n\t}\n}\n\n/** Record what was applied, so the next run can skip it. */\nexport async function saveState(\n\troot: string,\n\tstate: ReconcileState,\n): Promise<void> {\n\tconst path = statePath(root, state.stage);\n\n\tawait mkdir(dirname(path), { recursive: true });\n\tawait writeFile(path, `${JSON.stringify(state, null, 2)}\\n`);\n}\n\n/**\n * Forget what was applied, so the next reconcile of this stage converges from\n * nothing — creating again whatever was dropped underneath the record.\n */\nexport async function forgetState(root: string, stage: string): Promise<void> {\n\tawait rm(statePath(root, stage), { force: true });\n}\n\nfunction statePath(root: string, stage: string): string {\n\treturn join(root, STATE_DIR, `${stage}.json`);\n}\n","/**\n * Reconcile — the one convergent function `gkm dev`, `gkm test`, and `gkm setup`\n * all call.\n *\n * Three phases, and only this one has side effects: declaring is pure (`gkm\n * build` and the dev watcher), running reads `<NAME>_URL` and provisions\n * nothing. Reconcile computes the desired state, compares, and applies the\n * difference — which is what makes \"when does it run\" answerable with\n * *whenever, repeatedly*.\n *\n * It is safe to run automatically because its blast radius is entirely local:\n * this project's containers, this project's `.gkm/`. Nothing it does can reach a\n * cloud. The line is drawn at data, not at side effects — it allocates ports,\n * writes compose, starts containers, and creates roles; it never seeds, resets,\n * or drops.\n *\n * Docker is injected rather than imported so the rules above can be asserted\n * without a daemon. The default implementation is the real one.\n */\n\nimport { existsSync } from 'node:fs';\nimport {\n\tchmod,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trm,\n\twriteFile,\n} from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { type ConstructManifest, provisionOrder } from '@geekmidas/manifest';\nimport { scopeTelemetryEnv } from '../telemetry/edges';\nimport {\n\tensureLocalAuthority,\n\tensureLocalCertificate,\n\ttype LocalAuthorityPaths,\n\tlocalAuthorityPaths,\n\tlocalCertificateNames,\n} from '../trust/authority';\nimport type { CacheBackend, EventsBackend } from '../types';\nimport { TEST_STAGE } from '../workspace/stages';\nimport {\n\tCADDY_SITES_IN_CONTAINER,\n\tcaddyfileRoot,\n\tsitesFor,\n\ttoCaddyfile,\n} from './caddyfile';\nimport { bucketClient, carrierClient, pgClient } from './clients';\nimport {\n\ttype ComposeFile,\n\ttype ComposeService,\n\tcomposeFor,\n\ttoYaml,\n} from './compose';\nimport {\n\tportKeys,\n\tportsOf,\n\tprimaryPortKey,\n\ttype ServiceAddress,\n\tserviceAddresses,\n} from './containers';\nimport { dockerCli } from './docker';\nimport { edgeToken, envFor } from './env';\nimport type { LocalFake } from './fakes';\nimport { lanAddress } from './lan';\nimport type { LocalCredentials, Login } from './localCredentials';\nimport { ensureLogins, type LoginOutcome } from './logins';\nimport type { ObjectWebhook } from './objectEvents';\nimport {\n\ttype Plan,\n\ttype PlanOptions,\n\tplanFor,\n\tTELEMETRY_CONTAINER,\n} from './plan';\nimport {\n\tallocate,\n\theldElsewhere,\n\tisPortFree,\n\tkeptPorts,\n\ttype PortAssignments,\n\ttype PortMove,\n\ttype PortProbe,\n} from './ports';\nimport {\n\ttype Applied,\n\tapplyBuckets,\n\tapplyCarriers,\n\tapplyLifecycles,\n\tapplyNotifications,\n\tapplyPolicies,\n\tapplyPostgres,\n\ttype BucketClient,\n\tbucketLifecycles,\n\tbucketNames,\n\tbucketPolicies,\n\ttype CarrierClient,\n\tcarrierNames,\n\tdatabasesExist,\n\tpostgresDatabaseNames,\n\tpostgresStatements,\n\ttype SqlClient,\n} from './provision';\nimport { loadState, planHash, saveState } from './state';\n\nexport type { ComposeFile } from './compose';\nexport type { Plan, PlannedResource } from './plan';\nexport type { PortAssignments, PortMove } from './ports';\n\n/**\n * Where the generated compose file is written, relative to the project root.\n *\n * At the root, beside the project's own `docker-compose.yml`, because the two\n * are one stack: this file is everything the constructs imply and is never\n * edited, that one is anything they cannot express — an image pin, an extra\n * service — and is merged over it, so it wins.\n */\nexport const COMPOSE_PATH = 'docker-compose.constructs.yml';\n\n/** The project's own compose file, merged over the generated one if present. */\nexport const PROJECT_COMPOSE_PATH = 'docker-compose.yml';\n\n/**\n * The local edge's config, beside the compose file that mounts it.\n *\n * Relative in the compose volume, so it resolves against `.gkm/` wherever the\n * project lives.\n */\nexport const CADDYFILE_PATH = '.gkm/Caddyfile';\n\n/**\n * The containers that mount this checkout's files: Caddy reads its routes out\n * of `.gkm/`, so one started from a worktree serves that worktree's ports.\n */\nconst CHECKOUT_MOUNTS = ['caddy'];\n\n/**\n * Where one stage's routes live, imported by the file above.\n *\n * Per stage because one edge serves every stage, the same way one Postgres\n * holds `orders` and `orders_test`. A single file would mean `gkm test`\n * deleting the routes `gkm dev` is serving.\n */\nexport const caddySitesPath = (stage: string) =>\n\t`.gkm/caddy-sites/${stage}.caddy`;\n\n/**\n * Where one stage's certificate is kept: certificate and key in one PEM,\n * issued from gkm's local authority (`trust/authority.ts`), beside the\n * stage's routes — so the edge reads it through the mount it already has, and\n * a stage removed takes its certificate with it.\n */\nexport const caddyCertificatePath = (stage: string) =>\n\t`.gkm/caddy-sites/${stage}.pem`;\n\n/**\n * The Docker operations reconcile needs.\n *\n * Small on purpose: everything else about containers Docker already remembers,\n * so there is no state here to keep in step with it.\n */\nexport interface Docker {\n\t/**\n\t * The host port a running container publishes for one of its internal ports,\n\t * or `undefined` if it is not running.\n\t *\n\t * Consulted before the saved assignments so that reconcile converges against\n\t * what is actually running rather than only against its own file — a\n\t * container someone started by hand is still the container serving the app.\n\t */\n\tpublishedPort(\n\t\tcomposePath: string,\n\t\tservice: string,\n\t\tinside: number,\n\t): Promise<number | undefined>;\n\t/**\n\t * The compose project of the running container publishing a host port, or\n\t * `undefined` when no container does — the port is held by something\n\t * outside Docker, or by nothing. Absent, nothing is known to be ours.\n\t */\n\tpublisher?(port: number): Promise<string | undefined>;\n\t/**\n\t * Bring the named services up, detached, and wait for their health checks.\n\t *\n\t * `show` lets Compose draw its own progress — the pulls, the containers it\n\t * creates, each one turning healthy — rather than capturing it. A first\n\t * start pulls every image and can take minutes, and minutes of nothing\n\t * read as a hang.\n\t */\n\tup(\n\t\tcomposePath: string,\n\t\tservices: readonly string[],\n\t\toptions?: { show?: boolean },\n\t): Promise<void>;\n\t/**\n\t * Whether every named service is running and passing its health check.\n\t *\n\t * `mounted` names the services that mount this checkout's files; one of\n\t * those counts only when it was created from the compose file's directory,\n\t * not from another checkout of the same project.\n\t */\n\thealthy(\n\t\tcomposePath: string,\n\t\tservices: readonly string[],\n\t\toptions?: { mounted?: readonly string[] },\n\t): Promise<boolean>;\n\t/**\n\t * Ask a running service to re-read its configuration.\n\t *\n\t * The local edge is the case: its routes are a mounted file, and a container\n\t * that is already up will not notice one changing.\n\t */\n\treload(composePath: string, service: string): Promise<void>;\n\t/**\n\t * Run a command inside a running service, reporting whether it exited\n\t * cleanly. Bringing an older volume's login in line uses it: Postgres's\n\t * socket and `rabbitmqctl` need no password from inside. Absent, that\n\t * fallback is skipped.\n\t */\n\texec?(\n\t\tcomposePath: string,\n\t\tservice: string,\n\t\targv: readonly string[],\n\t): Promise<{ ok: boolean; output: string }>;\n}\n\nexport interface ReconcileOptions {\n\t/** The project root — where `.gkm/` lives. */\n\troot: string;\n\t/**\n\t * gkm's local certificate authority, which the edge's certificate is\n\t * issued from and every process is pointed at. The CLI's home's when not\n\t * given.\n\t */\n\tauthority?: LocalAuthorityPaths;\n\t/**\n\t * Told each slow step as it starts — starting the containers, creating what\n\t * the constructs declare — and, given one, Docker shows its own progress.\n\t * Absent, reconcile is silent: `gkm test` and the converged case say\n\t * nothing.\n\t */\n\tprogress?: (message: string) => void;\n\t/**\n\t * The project name, which seeds port allocation and names the compose\n\t * project. Two checkouts of the same repo share it deliberately.\n\t */\n\tproject: string;\n\t/** The construct manifest — what the app declared. */\n\tmanifest: ConstructManifest;\n\t/** The stage being reconciled: the project's local stage, or `test`. */\n\tstage: string;\n\t/**\n\t * This machine's LAN address, for a mobile app's `exp://` origins and the\n\t * address its sign-in links are built on. Read from the network interfaces\n\t * when absent; `null` for none.\n\t */\n\tlanAddress?: string | null;\n\t/** Each mobile app's Metro port, by construct id. */\n\tmetroPorts?: Readonly<Record<string, number>>;\n\t/** The project's local stage, whose resources carry no suffix. */\n\tlocalStage?: string;\n\t/** The events backend, until `topic` and `queue` are kinds. */\n\tevents?: EventsBackend;\n\t/** Where a declared cache lives — see {@link CacheBackend}. */\n\tcache?: CacheBackend;\n\t/** Containers no construct implies — the config exceptions. */\n\textraContainers?: readonly string[];\n\t/** Each external API's fake, by id — see `readFakes`. */\n\tfakes?: PlanOptions['fakes'];\n\t/** Each credential's fake value, by id — see `readCredentialFakes`. */\n\tcredentialFakes?: PlanOptions['credentialFakes'];\n\t/**\n\t * The workspace's generated local logins — what every container is\n\t * brought up with and every URL carries. See `localCredentials.ts`.\n\t */\n\tcredentials: LocalCredentials;\n\t/** Whether the local edge fronts surfaces, sites and file servers. */\n\tedge?: boolean;\n\t/** The workspace's `protectedSubdomains` — see `PlanOptions`. */\n\tprotectedSubdomains?: readonly string[];\n\t/**\n\t * Where MinIO posts each watched bucket's events — see `objectEvents.ts`.\n\t * The same for every stage, because one MinIO serves them all; only the\n\t * local stage's buckets are pointed at them, so `gkm test`'s uploads never\n\t * reach the process `gkm dev` runs.\n\t */\n\tobjectWebhooks?: readonly ObjectWebhook[];\n\t/** Mailpit's webhook, where an inbox has a subscriber — see `inboxRelay.ts`. */\n\tinboxRelay?: string;\n\t/**\n\t * The apps, as services beside the containers — see `reconcile/apps.ts`.\n\t * Handed the derived containers so an app can depend on them.\n\t */\n\tapps?: (containers: readonly string[]) => Record<string, ComposeService>;\n\t/** Ports assigned by previous runs, from `.gkm/ports.json`. */\n\tsaved?: PortAssignments;\n\t/** Start containers and wait for health. Off answers \"what would change\". */\n\tstart?: boolean;\n\t/**\n\t * Create the databases, schemas, and buckets the plan names.\n\t *\n\t * Requires the containers to be running, so it is skipped when `start` is\n\t * off. Never seeds, resets, or drops — the line is at data, not side effects.\n\t */\n\tprovision?: boolean;\n\t/** The domain mail is sent from locally — see `EnvOptions.mailDomain`. */\n\tmailDomain?: string;\n\t/**\n\t * Where each address-owning construct answers, keyed by id.\n\t *\n\t * Surfaces and sites. Assigned by whatever starts them, which is why it\n\t * arrives here rather than being read off a published container port.\n\t */\n\taddresses?: Readonly<Record<string, string>>;\n\t/**\n\t * Where each file server's processors answer, keyed by the file server's\n\t * id: the dev server of the app holding them. Only the edge reads it — a\n\t * file server's own address is still the bucket's.\n\t */\n\tprocessorAddresses?: Readonly<Record<string, string>>;\n\tdocker?: Docker;\n\tprobe?: PortProbe;\n\t/** Injected for tests; the defaults talk to the containers just started. */\n\tsql?: (port: number, login: Login) => SqlClient;\n\tbuckets?: (port: number, login: Login) => BucketClient;\n\tcarriers?: (\n\t\tport: number,\n\t\tcredentials: LocalCredentials['emulator'],\n\t) => CarrierClient;\n\t/**\n\t * Bring each running container's login in line with `credentials` — see\n\t * `logins.ts`. Injected for tests that run no containers.\n\t */\n\tlogins?: typeof ensureLogins;\n}\n\nexport interface ReconcileResult {\n\tstage: string;\n\tplan: Plan;\n\tcompose: ComposeFile;\n\t/** Every assigned port, keyed by port key. Persist this. */\n\tports: PortAssignments;\n\t/**\n\t * Saved ports something outside this project had bound, each moved to a\n\t * free one. Say so: a connection string copied before now is stale.\n\t */\n\tmoved: readonly PortMove[];\n\t/** Every port the containers publish, labelled — consoles and inbox too. */\n\tservices: readonly ServiceAddress[];\n\t/** The `<NAME>_URL` values this stage resolves. */\n\tenv: Readonly<Record<string, string>>;\n\t/**\n\t * The logins in use: the ones passed in, or — where a container that\n\t * already had data could not be moved to one — the login it still takes.\n\t * Keep them when they differ.\n\t */\n\tcredentials: LocalCredentials;\n\t/** What checking each container's login did, when it was checked. */\n\tlogins: readonly LoginOutcome[];\n\t/** What the applier created, or found already there. */\n\tprovisioned: Applied[];\n\t/**\n\t * Each external API's fake, by id. An image fake is already running with\n\t * the containers; an app fake is the caller's to serve — `gkm dev` does —\n\t * on `ports[fakeKey(id)]`.\n\t */\n\tfakes: Readonly<Record<string, LocalFake>>;\n\t/** The hash recorded for this state. */\n\thash: string;\n\t/**\n\t * Whether anything was applied. False is the fast path — the recorded hash\n\t * matched and the containers were healthy, so nothing was written or started.\n\t */\n\tchanged: boolean;\n}\n\n/**\n * Converge the local target on what the manifest declares.\n *\n * Cheap when there is nothing to do: the hash is compared before the compose\n * file is written or a container is touched, and a converged project pays one\n * hash and one health check.\n */\nexport async function reconcile(\n\toptions: ReconcileOptions,\n): Promise<ReconcileResult> {\n\tconst {\n\t\troot,\n\t\tproject,\n\t\tmanifest,\n\t\tstage,\n\t\tstart = true,\n\t\tprovision = true,\n\t\tdocker = dockerCli,\n\t\tprobe = isPortFree,\n\t\tsql = pgClient,\n\t\tbuckets = bucketClient,\n\t\tcarriers = carrierClient,\n\t\tlogins = ensureLogins,\n\t} = options;\n\tconst { seed } = options.credentials;\n\n\tconst plan = planFor(manifest, stage, provisionOrder(manifest), {\n\t\tlocalStage: options.localStage,\n\t\tevents: options.events,\n\t\tcache: options.cache,\n\t\textraContainers: options.extraContainers,\n\t\t...(options.fakes ? { fakes: options.fakes } : {}),\n\t\t...(options.credentialFakes\n\t\t\t? { credentialFakes: options.credentialFakes }\n\t\t\t: {}),\n\t\t...(options.edge === undefined ? {} : { edge: options.edge }),\n\t\t...(options.protectedSubdomains\n\t\t\t? { protectedSubdomains: options.protectedSubdomains }\n\t\t\t: {}),\n\t});\n\n\t// `gkm test` exports nothing: its stage starts no collector and hands no\n\t// process a telemetry key. The container stays in the file — it is the\n\t// same file `gkm dev` runs from, and dropping it would have `up\n\t// --remove-orphans` stop the one a running `gkm dev` is exporting to.\n\tconst exports = stage !== TEST_STAGE;\n\tconst running = exports\n\t\t? plan.containers\n\t\t: plan.containers.filter((c) => c !== TELEMETRY_CONTAINER);\n\n\tconst composePath = join(root, COMPOSE_PATH);\n\n\t// What is already running wins over what was recorded: a container on a port\n\t// is the fact, and the file is only a memory of one.\n\tconst observed = await observedPorts(\n\t\tdocker,\n\t\tcomposePath,\n\t\tplan.containers,\n\t\tplan.fakes,\n\t);\n\tconst keys = portKeys(plan.containers, plan.fakes);\n\tconst kept = keptPorts(options.saved, observed);\n\t// A saved port another stack has bound since is given up rather than handed\n\t// to `docker compose up` to fail on. Compose's own project name decides\n\t// what is ours, and `COMPOSE_PROJECT_NAME` overrides the file's.\n\tconst composeProject = process.env.COMPOSE_PROJECT_NAME || project;\n\tconst held = await heldElsewhere(\n\t\tkept,\n\t\tkeys,\n\t\tobserved,\n\t\tprobe,\n\t\tasync (port) => (await docker.publisher?.(port)) === composeProject,\n\t);\n\tconst ports = await allocate(\n\t\tproject,\n\t\tkeys,\n\t\tObject.fromEntries(\n\t\t\tObject.entries(kept).filter(([key]) => !held.includes(key)),\n\t\t),\n\t\tprobe,\n\t);\n\tconst moved = held.map((key) => ({\n\t\tkey,\n\t\tfrom: kept[key] as number,\n\t\tto: ports[key] as number,\n\t}));\n\n\tconst compose = composeFor(plan, {\n\t\tproject,\n\t\tports,\n\t\tcredentials: options.credentials,\n\t\t...(options.apps ? { apps: options.apps(plan.containers) } : {}),\n\t\t...(options.objectWebhooks?.length\n\t\t\t? { objectWebhooks: options.objectWebhooks }\n\t\t\t: {}),\n\t\t...(options.inboxRelay ? { inboxRelay: options.inboxRelay } : {}),\n\t});\n\n\t// The edge's config is part of what \"converged\" means: a file server added or\n\t// a bucket renamed changes the routing without changing a container, and a\n\t// hash that ignored it would leave the old routes in place.\n\tconst sites = sitesFor(\n\t\tplan,\n\t\tproject,\n\t\toptions.addresses,\n\t\toptions.processorAddresses,\n\t);\n\tconst edged = plan.containers.includes('caddy');\n\tconst authorityPaths = options.authority ?? localAuthorityPaths();\n\tconst edgePort = ports[primaryPortKey('caddy')];\n\tconst caddyfile = toCaddyfile(sites, {\n\t\tcertificate: `${CADDY_SITES_IN_CONTAINER}/${stage}.pem`,\n\t\t// What the apps are handed (`envFor`), so a service calling a sibling\n\t\t// through this edge keeps the client's address.\n\t\tedgeToken: edgeToken(project, seed),\n\t\t...(edgePort !== undefined ? { port: edgePort } : {}),\n\t});\n\t// And so is what provisioning runs. A toolbox upgrade that changes the role\n\t// DDL — a new grant — changes no container and no route, so a hash without\n\t// it reported convergence and the existing database never got the grant.\n\tconst postgres = postgresStatements(plan, project, seed)\n\t\t.map((statement) => statement.create)\n\t\t.join(';\\n');\n\tconst hash = planHash(plan, compose, { caddyfile, postgres });\n\tconst services = serviceAddresses(running, ports, plan.fakes);\n\t// Only a project with a mobile app reads it, so only one looks for it.\n\tconst lan = plan.resources.some((r) => r.kind === 'mobile-app')\n\t\t? options.lanAddress === undefined\n\t\t\t? lanAddress()\n\t\t\t: (options.lanAddress ?? undefined)\n\t\t: undefined;\n\tconst envWith = (credentials: LocalCredentials) => {\n\t\tconst resolved = envFor(plan, {\n\t\t\tports,\n\t\t\tproject,\n\t\t\tcredentials,\n\t\t\tseed,\n\t\t\t...(options.mailDomain ? { mailDomain: options.mailDomain } : {}),\n\t\t\t...(options.addresses ? { addresses: options.addresses } : {}),\n\t\t\t...(lan ? { lanAddress: lan } : {}),\n\t\t\t...(options.metroPorts ? { metroPorts: options.metroPorts } : {}),\n\t\t\t...(options.objectWebhooks?.length\n\t\t\t\t? {\n\t\t\t\t\t\trelayedBuckets: options.objectWebhooks.map((hook) => hook.bucket),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t\t// `gkm test` hands no process a telemetry key.\n\t\tconst env = exports\n\t\t\t? resolved\n\t\t\t: scopeTelemetryEnv(resolved, { uses: false, serviceName: project });\n\t\t// gkm's root, which the edge's certificate is issued from — made below,\n\t\t// before anything that reads the environment starts.\n\t\tif (edged) env.NODE_EXTRA_CA_CERTS = authorityPaths.certFile;\n\t\treturn env;\n\t};\n\tconst env = envWith(options.credentials);\n\n\tconst result: ReconcileResult = {\n\t\tstage,\n\t\tplan,\n\t\tcompose,\n\t\tports,\n\t\tmoved,\n\t\tservices,\n\t\tenv,\n\t\tcredentials: options.credentials,\n\t\tlogins: [],\n\t\tprovisioned: [],\n\t\tfakes: options.fakes ?? {},\n\t\thash,\n\t\tchanged: false,\n\t};\n\n\t// The edge's certificate, issued before anything starts: the root exists\n\t// from the first run, and one issued again — expiring, or a host it did\n\t// not name — is a change the running edge has to be told about.\n\tconst certificate = edged\n\t\t? await ensureLocalCertificate(\n\t\t\t\tawait ensureLocalAuthority(authorityPaths),\n\t\t\t\tlocalCertificateNames(\n\t\t\t\t\tproject,\n\t\t\t\t\tsites.flatMap((site) => [\n\t\t\t\t\t\tsite.host,\n\t\t\t\t\t\t...(site.aliases ?? []),\n\t\t\t\t\t\t...(site.redirects ?? []),\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\tjoin(root, caddyCertificatePath(stage)),\n\t\t\t)\n\t\t: undefined;\n\n\tconst recorded = await loadState(root, stage);\n\tconst postgresPort = ports[primaryPortKey('postgres')];\n\tconst converged =\n\t\t!certificate?.issued &&\n\t\trecorded?.hash === hash &&\n\t\t// The file is gitignored and derived; a fresh checkout with the state\n\t\t// still around must write it rather than trust a hash of nothing.\n\t\texistsSync(composePath) &&\n\t\t(!start ||\n\t\t\t(await docker.healthy(composePath, running, {\n\t\t\t\tmounted: CHECKOUT_MOUNTS,\n\t\t\t}))) &&\n\t\t// Every checkout shares one Postgres, so another one's test teardown can\n\t\t// drop a database this checkout's state still records as created.\n\t\t(!start ||\n\t\t\t!provision ||\n\t\t\tpostgresPort === undefined ||\n\t\t\t(await databasesExist(\n\t\t\t\tsql(postgresPort, options.credentials.postgres),\n\t\t\t\tpostgresDatabaseNames(plan),\n\t\t\t)));\n\n\t// The fast path, and the reason reconciling on every start is acceptable.\n\tif (converged) return result;\n\n\t// Owner-only: it carries the containers' generated logins.\n\tawait write(composePath, toYaml(compose), 0o600);\n\n\t// Before the containers: Caddy reads these at startup, and mounting a file\n\t// that does not exist yet gets a directory instead.\n\tif (edged) {\n\t\tawait write(join(root, CADDYFILE_PATH), caddyfileRoot());\n\t\tawait write(join(root, caddySitesPath(stage)), caddyfile);\n\t\tawait pruneCaddySites(root, [stage, options.localStage, TEST_STAGE]);\n\t}\n\n\tif (start && running.length > 0) {\n\t\toptions.progress?.(\n\t\t\t`🐳 Starting ${running.join(', ')} — the first start pulls each image, which can take a few minutes`,\n\t\t);\n\t\tawait docker.up(\n\t\t\tcomposePath,\n\t\t\trunning,\n\t\t\toptions.progress ? { show: true } : {},\n\t\t);\n\t}\n\n\t// A running Caddy does not notice a changed import or a certificate issued\n\t// again, so what this reconcile just wrote is inert until it is told.\n\t// Failing is not fatal: the container may have only this second come up, in\n\t// which case it already read them.\n\tif (start && edged) {\n\t\tawait docker.reload(composePath, 'caddy').catch(() => {});\n\t}\n\n\t// A container that already had data may have been made with another\n\t// login — an older gkm's fixed one. Brought in line before anything signs\n\t// in, and where one cannot be, its login is what is used.\n\tconst checked =\n\t\tstart && plan.containers.length > 0\n\t\t\t? await logins({\n\t\t\t\t\tcredentials: options.credentials,\n\t\t\t\t\tcontainers: plan.containers,\n\t\t\t\t\tports: {\n\t\t\t\t\t\t...(postgresPort !== undefined ? { postgres: postgresPort } : {}),\n\t\t\t\t\t\t...(ports[primaryPortKey('minio')] !== undefined\n\t\t\t\t\t\t\t? { minio: ports[primaryPortKey('minio')] }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t\t...(docker.exec\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\texec: (service: string, argv: readonly string[]) =>\n\t\t\t\t\t\t\t\t\tdocker.exec!(composePath, service, argv),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t})\n\t\t\t: { credentials: options.credentials, outcomes: [] };\n\tconst credentials = checked.credentials;\n\n\t// Only once the containers are up: there is nothing to create inside a\n\t// container that is not running.\n\tif (start && provision) {\n\t\toptions.progress?.(\n\t\t\t'🗄️ Creating what the constructs declare — databases, roles, buckets, topics',\n\t\t);\n\t}\n\tconst provisioned =\n\t\tstart && provision\n\t\t\t? await create(\n\t\t\t\t\tplan,\n\t\t\t\t\tports,\n\t\t\t\t\tcredentials,\n\t\t\t\t\tsql,\n\t\t\t\t\tbuckets,\n\t\t\t\t\tcarriers,\n\t\t\t\t\tproject,\n\t\t\t\t\t// Only the local stage's buckets post their events: `gkm test`\n\t\t\t\t\t// shares the MinIO, and its uploads are not `gkm dev`'s business.\n\t\t\t\t\tnew Set(\n\t\t\t\t\t\tstage === (options.localStage ?? stage)\n\t\t\t\t\t\t\t? (options.objectWebhooks ?? []).map((hook) => hook.bucket)\n\t\t\t\t\t\t\t: [],\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [];\n\n\tawait saveState(root, { hash, stage });\n\n\treturn {\n\t\t...result,\n\t\t...(credentials === options.credentials\n\t\t\t? {}\n\t\t\t: { env: envWith(credentials) }),\n\t\tcredentials,\n\t\tlogins: checked.outcomes,\n\t\tprovisioned,\n\t\tchanged: true,\n\t};\n}\n\n/**\n * Create the databases, schemas, buckets, topics and queues the plan names.\n *\n * Idempotent throughout, so this runs on every non-converged reconcile rather\n * than being something to remember.\n */\nasync function create(\n\tplan: Plan,\n\tports: PortAssignments,\n\tcredentials: LocalCredentials,\n\tsql: NonNullable<ReconcileOptions['sql']>,\n\tbuckets: NonNullable<ReconcileOptions['buckets']>,\n\temulatorCarriers: NonNullable<ReconcileOptions['carriers']>,\n\t/** Seeds the derived role passwords — see `localRolePassword`. */\n\tproject: string,\n\t/** The buckets, by construct id, whose events MinIO posts on. */\n\twatched: ReadonlySet<string>,\n): Promise<Applied[]> {\n\tconst applied: Applied[] = [];\n\n\tconst postgresPort = ports[primaryPortKey('postgres')];\n\tconst statements = postgresStatements(plan, project, credentials.seed);\n\tif (postgresPort !== undefined && statements.length > 0) {\n\t\tapplied.push(\n\t\t\t...(await applyPostgres(\n\t\t\t\tsql(postgresPort, credentials.postgres),\n\t\t\t\tstatements,\n\t\t\t)),\n\t\t);\n\t}\n\n\tconst minioPort = ports[primaryPortKey('minio')];\n\tconst names = bucketNames(plan);\n\tconst policies = bucketPolicies(plan);\n\tconst lifecycles = bucketLifecycles(plan);\n\tif (minioPort !== undefined && (names.length > 0 || policies.length > 0)) {\n\t\tconst client = buckets(minioPort, credentials.minio);\n\n\t\t// Buckets first: a policy or a lifecycle names a bucket, and applying\n\t\t// one to a bucket that does not exist yet fails on the first reconcile\n\t\t// of a new project.\n\t\tif (names.length > 0) applied.push(...(await applyBuckets(client, names)));\n\t\tif (policies.length > 0)\n\t\t\tapplied.push(...(await applyPolicies(client, policies)));\n\t\tif (lifecycles.length > 0)\n\t\t\tapplied.push(...(await applyLifecycles(client, lifecycles)));\n\t\t// After the buckets, and only once MinIO runs with the targets: a rule\n\t\t// naming a target MinIO was not started with is refused.\n\t\tif (names.length > 0) {\n\t\t\tapplied.push(\n\t\t\t\t...(await applyNotifications(\n\t\t\t\t\tclient,\n\t\t\t\t\tplan.resources\n\t\t\t\t\t\t.filter((r) => r.provisions && r.kind === 'objects')\n\t\t\t\t\t\t.map((r) => ({ id: r.id, name: r.name })),\n\t\t\t\t\twatched,\n\t\t\t\t)),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst emulatorPort = ports[primaryPortKey('localstack')];\n\tconst carriers = carrierNames(plan);\n\tif (\n\t\temulatorPort !== undefined &&\n\t\tcarriers.topics.length + carriers.queues.length > 0\n\t) {\n\t\tapplied.push(\n\t\t\t...(await applyCarriers(\n\t\t\t\temulatorCarriers(emulatorPort, credentials.emulator),\n\t\t\t\tcarriers,\n\t\t\t)),\n\t\t);\n\t}\n\n\treturn applied;\n}\n\n/**\n * The host ports of containers already running.\n *\n * Keyed the same way allocation keys them, so the two merge without either\n * knowing about the other.\n */\nasync function observedPorts(\n\tdocker: Docker,\n\tcomposePath: string,\n\tcontainers: readonly string[],\n\tfakes?: Plan['fakes'],\n): Promise<PortAssignments> {\n\tconst observed: Record<string, number> = {};\n\n\tfor (const container of containers) {\n\t\tfor (const port of portsOf(container, fakes)) {\n\t\t\tconst running = await docker.publishedPort(\n\t\t\t\tcomposePath,\n\t\t\t\tcontainer,\n\t\t\t\tport.inside,\n\t\t\t);\n\t\t\tif (running !== undefined) observed[port.key] = running;\n\t\t}\n\t}\n\n\treturn observed;\n}\n\n/** Write a file only when its content would change, so mtimes stay meaningful. */\n/**\n * Remove the routes of stages this project no longer reconciles.\n *\n * Only the local stage and `test` are ever written, so any other file is left\n * over from a stage that was renamed — `development` becoming `dev`. Caddy\n * imports every file, and the leftover declares the same hosts as its\n * replacement: it refuses the whole config as ambiguous, and every URL behind\n * the edge goes with it.\n */\nasync function pruneCaddySites(\n\troot: string,\n\tstages: ReadonlyArray<string | undefined>,\n): Promise<void> {\n\tconst dir = dirname(join(root, caddySitesPath(TEST_STAGE)));\n\tconst keep = new Set(\n\t\tstages.flatMap((stage) =>\n\t\t\tstage ? [`${stage}.caddy`, `${stage}.pem`] : [],\n\t\t),\n\t);\n\n\tfor (const file of await readdir(dir)) {\n\t\t// A stage's certificate goes with its routes.\n\t\tif (/\\.(caddy|pem)$/.test(file) && !keep.has(file)) {\n\t\t\tawait rm(join(dir, file));\n\t\t}\n\t}\n}\n\nasync function write(\n\tpath: string,\n\tcontent: string,\n\tmode?: number,\n): Promise<void> {\n\ttry {\n\t\tif ((await readFile(path, 'utf-8')) === content) {\n\t\t\tif (mode !== undefined) await chmod(path, mode);\n\t\t\treturn;\n\t\t}\n\t} catch {\n\t\t// Absent or unreadable — write it.\n\t}\n\n\tawait mkdir(dirname(path), { recursive: true });\n\tawait writeFile(path, content, mode === undefined ? {} : { mode });\n\tif (mode !== undefined) await chmod(path, mode);\n}\n","/**\n * Workspace config → reconcile.\n *\n * Nothing here is read from a `services:` block — there is none. Which\n * containers exist comes from the manifest; which backend a cache or a broker\n * resolves to comes from the deploy target; and an image pin is the project's\n * own `docker-compose.yml`, merged over the generated file.\n *\n * Shared by `gkm setup`, `gkm dev`, and `gkm test` so all three converge on the\n * same state, differing only in the stage they pass.\n */\n\nimport { type ConstructManifest, provisionOrder } from '@geekmidas/manifest';\nimport {\n\tprocessorUnits,\n\tWorkerHasNoApp,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadPortState, savePortState } from '../credentials/index.js';\nimport { objectsRoute } from '../generators/subscriberRoute.js';\nimport {\n\tcacheBackendFor,\n\teventsBackendFor,\n\tproviderOf,\n} from '../workspace/backends.js';\nimport { appKey } from '../workspace/derive.js';\nimport { allConstructGlobs } from '../workspace/index.js';\nimport { TEST_STAGE } from '../workspace/stages.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { appServices } from './apps.js';\nimport { type BoundSubscriber, discover } from './discover.js';\nimport { readCredentialFakes, readFakes } from './fakes.js';\nimport {\n\tinboxRelayToken,\n\tinboxRelayWorker,\n\tinboxWebhookUrl,\n} from './inboxRelay';\nimport { type ReconcileResult, reconcile } from './index.js';\nimport {\n\tloadLocalCredentials,\n\tsaveLocalCredentials,\n} from './localCredentials.js';\nimport {\n\tHOST_GATEWAY,\n\ttype ObjectWebhook,\n\tobjectsWebhookToken,\n\twatchedBuckets,\n} from './objectEvents.js';\nimport { planFor } from './plan.js';\n\n/**\n * Every constructs glob in the workspace, resolved against its app.\n *\n * Absolute because discovery globs from a single cwd while apps live in\n * different directories.\n */\nexport function constructGlobs(workspace: NormalizedWorkspace): string[] {\n\treturn allConstructGlobs(workspace);\n}\n\n/** The backends a workspace's target implies, as the plan takes them. */\nexport function backendsOf(workspace: NormalizedWorkspace) {\n\tconst on = providerOf(workspace);\n\treturn { events: eventsBackendFor(on), cache: cacheBackendFor(on) };\n}\n\n/**\n * The containers a workspace's declarations imply, without reconciling.\n *\n * The same derivation `reconcileWorkspace` makes, available to callers that\n * need to know *what would run* without starting anything or writing ports —\n * `gkm setup` deciding which credentials to generate, `gkm docker` writing a\n * compose file. Those used to each read a boolean per service out of config,\n * which is how a container could exist because config asked for one rather than\n * because something declared it.\n */\nexport async function derivedContainers(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\tmanifest?: ConstructManifest,\n): Promise<readonly string[]> {\n\tconst found =\n\t\tmanifest ??\n\t\t(await discover({\n\t\t\tpatterns: constructGlobs(workspace),\n\t\t\tcwd: workspace.root,\n\t\t}));\n\n\t// No fakes: they run only for `gkm test` and `gkm dev --fake`, and the\n\t// commands asking this — `setup`, `secrets:*`, `docker` — are neither.\n\treturn planFor(found, stage, provisionOrder(found), {\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t}).containers;\n}\n\nexport interface WorkspaceReconcileOptions {\n\tstage: string;\n\t/** Start containers and wait for health. */\n\tstart?: boolean;\n\t/** A manifest already in hand — the dev watcher has one; setup does not. */\n\tmanifest?: ConstructManifest;\n\t/**\n\t * Point every external API at its fake (`test/fakes/<id>.ts`) instead of\n\t * the provider, and hand every credential with a fake its fake's value —\n\t * `gkm dev --fake`. Always so for the test stage; otherwise an external\n\t * API is the real one, at its URL for this stage, and a credential the\n\t * stage's own.\n\t */\n\tfake?: boolean;\n\t/** Told each slow step as it starts — see `ReconcileOptions.progress`. */\n\tprogress?: (message: string) => void;\n}\n\n/**\n * Set by `gkm dev --fake` for the apps it starts. Each app's own `gkm dev`\n * reconciles too, and must answer the way the workspace did.\n */\nexport const FAKE_ENV = 'GKM_FAKE';\n\n/**\n * Whether third parties are faked — external APIs, and credentials with a\n * fake: always for `gkm test`, and for `gkm dev`\n * only when asked — by `--fake`, or by the workspace that started this app\n * with it. Never for anything acting on a deployed stage.\n */\nexport function fakesApply(\n\tstage: string,\n\tfake?: boolean,\n\tenv: NodeJS.ProcessEnv = process.env,\n): boolean {\n\treturn fake === true || stage === TEST_STAGE || env[FAKE_ENV] === '1';\n}\n\n/**\n * Reconcile a workspace for one stage.\n *\n * Ports are loaded and saved around the call rather than inside it, so the loop\n * stays a pure-ish function of its inputs and the store keeps its single owner.\n */\nexport async function reconcileWorkspace(\n\tworkspace: NormalizedWorkspace,\n\toptions: WorkspaceReconcileOptions,\n): Promise<\n\tReconcileResult & {\n\t\tmanifest: ConstructManifest;\n\t\t/** Each worker's background files, which say which app runs its work. */\n\t\tbackground: Record<string, string[]>;\n\t}\n> {\n\t// Discovered here even when a manifest was handed in: where each worker's\n\t// background work and each bucket's subscribers are is only discovery's.\n\tconst background: Record<string, string[]> = {};\n\tconst subscribers: Record<string, BoundSubscriber[]> = {};\n\tconst discovered = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tbackground,\n\t\tsubscribers,\n\t});\n\tconst manifest = options.manifest ?? discovered;\n\tconst faked = fakesApply(options.stage, options.fake);\n\tconst fakes = faked ? await readFakes(workspace.root, manifest) : {};\n\tconst credentialFakes = faked\n\t\t? await readCredentialFakes(workspace.root, manifest)\n\t\t: {};\n\n\t// Generated the first time anything needs them, and read back after: one\n\t// set per machine and workspace, shared by the local stage and `test`,\n\t// which run on the same containers.\n\tconst { credentials } = await loadLocalCredentials(workspace);\n\n\tconst objectWebhooks = localObjectWebhooks(workspace, manifest, {\n\t\tbackground,\n\t\tsubscribers,\n\t\tseed: credentials.seed,\n\t});\n\n\tconst inboxRelay = localInboxWebhook(workspace, manifest, {\n\t\tbackground,\n\t\tsubscribers,\n\t\tseed: credentials.seed,\n\t});\n\n\tconst result = await reconcile({\n\t\tcredentials,\n\t\troot: workspace.root,\n\t\tproject: workspace.name,\n\t\tmanifest,\n\t\tstage: options.stage,\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t\t...(workspace.protectedSubdomains\n\t\t\t? { protectedSubdomains: workspace.protectedSubdomains }\n\t\t\t: {}),\n\t\tsaved: await loadPortState(workspace.root),\n\t\taddresses: surfaceAddresses(workspace, manifest),\n\t\tprocessorAddresses: processorAddresses(workspace, manifest),\n\t\tmetroPorts: metroPorts(workspace, manifest),\n\t\tfakes,\n\t\tcredentialFakes,\n\t\t...(objectWebhooks.length > 0 ? { objectWebhooks } : {}),\n\t\t...(inboxRelay ? { inboxRelay } : {}),\n\t\tapps: (containers) =>\n\t\t\tappServices(\n\t\t\t\tworkspace,\n\t\t\t\tmanifest,\n\t\t\t\tcontainers,\n\t\t\t\tcredentials,\n\t\t\t\tfakes,\n\t\t\t\tcredentialFakes,\n\t\t\t),\n\t\t...(options.start === undefined ? {} : { start: options.start }),\n\t\t...(options.progress ? { progress: options.progress } : {}),\n\t});\n\n\tawait savePortState(workspace.root, { ...result.ports });\n\tfor (const { key, from, to } of result.moved) {\n\t\tconsole.log(\n\t\t\t`⚠️ Port ${from} (${key}) is held by another process; moved to ${to}.`,\n\t\t);\n\t}\n\n\t// A container that could not be moved to its generated login keeps the\n\t// one it takes, and that is what later runs use.\n\tif (result.credentials !== credentials) {\n\t\tawait saveLocalCredentials(workspace, result.credentials);\n\t}\n\tfor (const outcome of result.logins) {\n\t\tif (outcome.notice) console.log(outcome.notice);\n\t}\n\n\t// With the manifest, so `gkm dev` can say what the workspace declares\n\t// without discovering it a second time.\n\treturn { ...result, manifest, background };\n}\n\n/**\n * Where MinIO posts each watched bucket's events under `gkm dev`: the dev\n * server of the app that builds the worker running the bucket's subscribers,\n * on the host, on that app's port — the process that relays them onto the\n * broker.\n *\n * None where the broker is SNS: there a bucket's events come from a topic, and\n * nothing relays them. None for a worker no app can build — `gkm build` says\n * so; a dev loop has nothing to post to.\n */\nexport function localObjectWebhooks(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\toptions: {\n\t\tbackground: Readonly<Record<string, readonly string[]>>;\n\t\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\t\t/** The local logins' seed, which derives each bucket's token. */\n\t\tseed?: string;\n\t},\n): ObjectWebhook[] {\n\tif (backendsOf(workspace).events === 'sns') return [];\n\n\tconst watched = watchedBuckets(manifest, options.subscribers);\n\tif (watched.size === 0) return [];\n\n\tlet units: WorkerUnit[];\n\ttry {\n\t\tunits = workerUnits(workspace, manifest, options.background);\n\t} catch (error) {\n\t\tif (error instanceof WorkerHasNoApp) return [];\n\t\tthrow error;\n\t}\n\n\tconst hooks: ObjectWebhook[] = [];\n\tfor (const [bucket, worker] of watched) {\n\t\tconst app = units.find((unit) => unit.id === worker)?.app;\n\t\tconst port = app ? workspace.apps[app]?.port : undefined;\n\t\tif (!port) continue;\n\t\thooks.push({\n\t\t\tbucket,\n\t\t\tendpoint: `http://${HOST_GATEWAY}:${port}${objectsRoute(bucket)}`,\n\t\t\ttoken: objectsWebhookToken(workspace.name, bucket, options.seed),\n\t\t});\n\t}\n\treturn hooks;\n}\n\n/**\n * Where Mailpit posts each message it receives, locally: the relay route on\n * the dev server of the app that builds the worker running the inbox\n * subscribers, through the host's gateway — as MinIO reaches a bucket's\n * subscribers. `undefined` with no inbox subscriber, or none an app builds.\n */\nexport function localInboxWebhook(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\toptions: {\n\t\tbackground: Readonly<Record<string, readonly string[]>>;\n\t\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>;\n\t\tseed?: string;\n\t},\n): string | undefined {\n\tconst worker = inboxRelayWorker(manifest, options.subscribers);\n\tif (!worker) return undefined;\n\n\tlet units: WorkerUnit[];\n\ttry {\n\t\tunits = workerUnits(workspace, manifest, options.background);\n\t} catch (error) {\n\t\tif (error instanceof WorkerHasNoApp) return undefined;\n\t\tthrow error;\n\t}\n\tconst app = units.find((unit) => unit.id === worker)?.app;\n\tconst port = app ? workspace.apps[app]?.port : undefined;\n\tif (!port) return undefined;\n\treturn inboxWebhookUrl(\n\t\t`http://${HOST_GATEWAY}:${port}`,\n\t\tinboxRelayToken(workspace.name, options.seed),\n\t);\n}\n\n/**\n * Where each mobile app's Metro runs: its app's port, which `gkm exec` hands\n * Expo as `RCT_METRO_PORT`. Kept apart from the surfaces' addresses — a phone\n * reaches Metro by `exp://`, not through the edge.\n */\nexport function metroPorts(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): Record<string, number> {\n\tconst ports: Record<string, number> = {};\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration.kind !== 'mobile-app') continue;\n\t\tconst port = workspace.apps[appKey(id)]?.port;\n\t\tif (port) ports[id] = port;\n\t}\n\treturn ports;\n}\n\n/**\n * Where each file server's processors answer locally: the dev server of the\n * app holding them, which `gkm dev` mounts them on — the same app whose build\n * writes their unit deployed.\n */\nexport function processorAddresses(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n): Record<string, string> {\n\tconst addresses: Record<string, string> = {};\n\tfor (const unit of processorUnits(workspace, manifest)) {\n\t\tconst port = workspace.apps[unit.app]?.port;\n\t\tif (port) addresses[unit.id] = localAddress(port);\n\t}\n\treturn addresses;\n}\n\n/**\n * Where each declared surface and site answers locally.\n *\n * The addresses come from the ports the workspace already assigns; which\n * construct sits at which one comes from the manifest. That split is the point:\n * this used to answer \"who may call whom\" by listing every app the workspace\n * runs, which is a different question that happened to give the same answer in\n * a single-repo workspace and no answer at all deployed. Now it answers only\n * \"where does this construct answer\", and the graph answers the rest.\n *\n * A site is matched to its app by `path`, because that is the one thing a site\n * declaration and a workspace app both name. Surfaces are matched to the\n * backend app: every `rest-api` in a process answers on that process's port, so\n * an app serving both its own API and an auth server publishes one address\n * twice — which is exactly what it does at runtime.\n */\nexport function surfaceAddresses(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\t/**\n\t * How an app is addressed: on the host by default, or — for the compose\n\t * apps — by service name on the compose network.\n\t */\n\tat: (app: string, port: number) => string = (_app, port) =>\n\t\tlocalAddress(port),\n): Record<string, string> {\n\tconst addresses: Record<string, string> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (\n\t\t\tdeclaration.kind !== 'rest-api' &&\n\t\t\tdeclaration.kind !== 'websocket-api' &&\n\t\t\tdeclaration.kind !== 'site'\n\t\t)\n\t\t\tcontinue;\n\n\t\t// Every site and every surface is its own app, keyed by its id the way\n\t\t// the derivation keyed it.\n\t\tconst host = appKey(id);\n\t\tconst port = workspace.apps[host]?.port;\n\n\t\tif (port) addresses[id] = at(host, port);\n\t}\n\n\treturn addresses;\n}\n\n/** Where a local process answers, given the port the workspace gave it. */\nfunction localAddress(port: number): string {\n\treturn `http://localhost:${port}`;\n}\n","/**\n * The apps, as services beside the containers their constructs derive.\n *\n * `gkm docker` used to write these by hand: every backend got\n * `DATABASE_URL=postgresql://…@postgres:5432/app` and `REDIS_URL=redis://redis`,\n * which was right only for a project whose single database happened to be\n * called `Database` — an `Orders` database publishes `ORDERS_URL`, a schema\n * tenant has a URL of its own, and buckets and mail were not wired at all.\n *\n * Now an app's environment is exactly what reconcile hands `gkm dev`: every key\n * the declared constructs provide, from the same derivation. The only\n * difference is where the addresses point — at the containers by service name\n * on the compose network, rather than at `localhost` on the ports published for\n * the host.\n *\n * Always from the *local* stage's plan, whichever stage is being reconciled:\n * `gkm test` rewrites the same file, and running the tests must not quietly\n * point these apps at the test databases.\n */\n\nimport {\n\ttype ConstructManifest,\n\tdependenciesOf,\n\tdependentsOf,\n\tEDGE_TOKEN_KEY,\n\tisPublicDeclaration,\n\tprovidedKeyFor,\n\tprovisionOrder,\n\tpublicEnvFor,\n\tpublicValues,\n\treachesServerHalf,\n\tTELEMETRY_KEYS,\n} from '@geekmidas/manifest';\nimport {\n\tProcessorsHaveNoApp,\n\tprocessorUnits,\n\tWorkerHasNoApp,\n\tWorkerNameTaken,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { publicBuildValues } from '../compose/siteBuild.js';\nimport { composeBuildPaths } from '../docker/layout.js';\nimport { findBuildRoot } from '../docker/templates.js';\nimport { isStackKey } from '../secrets/stackKeys.js';\nimport { appTelemetry, scopeTelemetryEnv } from '../telemetry/edges.js';\nimport { appKey } from '../workspace/derive.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport type { ComposeService } from './compose.js';\nimport { portKeys, portsOf } from './containers.js';\nimport { eventsEdgeBucket, workerEdges } from './edges.js';\nimport { type EnvOptions, envFor, stageEnv } from './env.js';\nimport { INBOX_RELAY_TOKEN_KEY } from './inboxRelay.js';\nimport type { LocalCredentials } from './localCredentials.js';\nimport { type Plan, type PlanOptions, planFor } from './plan.js';\nimport { backendsOf, surfaceAddresses } from './workspace.js';\n\n/** The profile app services carry, so `gkm dev` starts only the containers. */\nexport const APPS_PROFILE = 'apps';\n\n/**\n * Where an app's image is built from.\n *\n * An app at the project root is a single-app project, whose `gkm docker`\n * writes `.gkm/docker/Dockerfile`; a workspace writes one per app.\n */\nexport function dockerfileOf(appName: string, path: string): string {\n\treturn path === '.'\n\t\t? '.gkm/docker/Dockerfile'\n\t\t: `.gkm/docker/Dockerfile.${appName}`;\n}\n\n/**\n * Every construct key, addressed across the compose network.\n *\n * `envFor` is asked with a placeholder port for every port key, so each\n * `localhost:<placeholder>` in its answer names exactly one container port —\n * two containers listening on the same port inside cannot be confused — and is\n * rewritten to `<container>:<inside>`.\n */\nexport function inNetworkEnv(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\t/** The workspace's local logins — see `localCredentials.ts`. */\n\tcredentials: LocalCredentials,\n\t/**\n\t * External APIs' fakes. An image fake is a container on the network like\n\t * any other; a module fake is served by `gkm dev` on the host, which an app\n\t * container does not reach, so its URL is left as the host sees it.\n\t */\n\tfakes: PlanOptions['fakes'] = {},\n): Record<string, string> {\n\treturn networkEnv(localPlan(workspace, manifest, fakes), {\n\t\tproject: workspace.name,\n\t\tcredentials,\n\t\tseed: credentials.seed,\n\t\taddresses: surfaceAddresses(\n\t\t\tworkspace,\n\t\t\tmanifest,\n\t\t\t(app, port) => `http://${app}:${port}`,\n\t\t),\n\t});\n}\n\n/**\n * The local stage's plan, which the app services are always written from.\n *\n * Without the edge: these apps reach each other by service name and a browser\n * reaches them on the ports this file publishes. Behind the edge every\n * surface resolved to its `*.localhost` host on the edge's port, which the\n * rewrite to the compose network then turned into an address nothing answers.\n */\nfunction localPlan(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tfakes: PlanOptions['fakes'] = {},\n\tcredentialFakes: PlanOptions['credentialFakes'] = {},\n): Plan {\n\treturn planFor(manifest, workspace.stages.local, provisionOrder(manifest), {\n\t\tlocalStage: workspace.stages.local,\n\t\t...backendsOf(workspace),\n\t\t...(workspace.protectedSubdomains\n\t\t\t? { protectedSubdomains: workspace.protectedSubdomains }\n\t\t\t: {}),\n\t\tfakes,\n\t\tcredentialFakes,\n\t\tedge: false,\n\t});\n}\n\n/**\n * The values a site's bundler inlines, by the name it inlines them under —\n * `{ VITE_API_URL: 'http://localhost:3000' }`.\n *\n * Build arguments, not environment: a static bundle is finished when it is\n * built, so a value handed to its container at runtime reaches nothing. And\n * addresses a *browser* can open, since that is where the bundle runs — the\n * host's port for each app, never a name on the compose network.\n */\nexport function sitePublicArgs(\n\tmanifest: ConstructManifest,\n\tappName: string,\n\t/** Every key the stage resolves, with surfaces at their public addresses. */\n\tenv: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst declaration = Object.entries(manifest).find(\n\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t)?.[1];\n\tif (declaration?.kind !== 'site') return {};\n\n\t// The image build's own rule, so a site built here gets what a stage's\n\t// image does. No stage secrets: the local stage's reach a site through\n\t// `gkm exec`, which hands it every one.\n\treturn publicBuildValues(declaration, manifest, (key) => env[key], {});\n}\n\n/**\n * Every key a plan resolves, with each container addressed by its service\n * name on the compose network — `postgres:5432` rather than the port\n * published for the host.\n *\n * The addresses of surfaces and sites are the caller's: `gkm compose` hands\n * every process the public ones, which one app calls another on through the\n * edge; `gkm docker`'s apps profile, which runs no edge, the compose\n * network's.\n */\nexport function networkEnv(\n\tplan: Plan,\n\toptions: Omit<EnvOptions, 'ports'>,\n\t/**\n\t * The name a container is reached by, where it is not its service name —\n\t * a stack behind a shared edge reaches its public services by an alias\n\t * unique on the network the edge shares.\n\t */\n\thostOf: (container: string) => string = (container) => container,\n): Record<string, string> {\n\tconst placeholders: Record<string, number> = {};\n\tconst targets = new Map<number, string>();\n\tlet next = 49_152;\n\tfor (const container of [...plan.containers].sort()) {\n\t\tfor (const port of portsOf(container, plan.fakes)) {\n\t\t\tplaceholders[port.key] = next;\n\t\t\ttargets.set(next, `${hostOf(container)}:${port.inside}`);\n\t\t\tnext += 1;\n\t\t}\n\t}\n\t// Every key allocation would have assigned, so envFor finds each one.\n\tfor (const key of portKeys(plan.containers, plan.fakes)) {\n\t\tplaceholders[key] ??= next++;\n\t}\n\n\tconst env = envFor(plan, { ...options, ports: placeholders });\n\n\tconst rewrite = (value: string) =>\n\t\tvalue.replace(/(?:localhost|127\\.0\\.0\\.1):(\\d+)/g, (match, port) => {\n\t\t\treturn targets.get(Number(port)) ?? match;\n\t\t});\n\n\treturn Object.fromEntries(\n\t\tObject.entries(env).map(([key, value]) => [key, rewrite(value)]),\n\t);\n}\n\n/**\n * The keys one app's environment may hold: what its own declaration provides\n * and requires, what each construct it has an edge to provides, and — for a\n * surface — the identity of each client with an edge to it.\n *\n * The one rule for every command and stage: `gkm dev`, `gkm exec` and `gkm\n * test` hand an app these keys (through `processEnvKeys`), `gkm compose`\n * writes them to its env file, and `gkm docker`'s apps profile to its\n * service. A key missing here is missing everywhere, so an app that reads it\n * fails on its first local request rather than in production.\n *\n * What an edge `caller.dependsOn([target])` hands each side, `<C>` and `<T>`\n * being the caller's and the target's ids (`providedKeyFor`) — keep this list and\n * `apps/docs/guide/edges.md` in step with the code below:\n *\n * - `rest-api`: the caller gets `<T>_URL`. The target gets `<C>_URL` from a\n * site caller and `<C>_SCHEME` from a mobile app caller (`callerKeys`).\n * - `websocket-api`: the caller gets `<T>_URL`, and a server process also\n * `<T>_PUBLISHER_CONNECTION_STRING`. The target gets what a `rest-api`\n * does.\n * - `queue`, `topic`: the caller gets the target's `provides` and\n * `EVENT_PUBLISHER_CONNECTION_STRING`. The target gets nothing.\n * - `objects`: the target's `provides`, its file server's, and the S3 key\n * pair (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`). A site\n * or mobile app gets `<T>_SIGNED_ORIGIN` and nothing else on its plain\n * edge, and all of it, signed origin included, on `.server`\n * (`reachesServerHalf`).\n * - `inbox`: the target's `provides`, and the local relay token.\n * - anything else (a database, cache, secret, credential, external API…):\n * the target's `provides`. The target gets nothing.\n *\n * Beside the keys, a surface's `<T>_TRUSTED_ORIGINS` lists every caller's\n * origin (a mobile app's as its scheme) and `<T>_COOKIE_DOMAIN` the parent\n * they share — values of the surface's own keys, derived from the same\n * inbound edges (`surfaceEnv`).\n *\n * A site or mobile app is a bundle: it also gets the public-prefixed name of\n * each of those its bundler inlines (`publicEnvFor`: `VITE_API_URL`,\n * `EXPO_PUBLIC_API_URL`), and never a `Telemetry` node's keys.\n *\n * The edges, not the manifest. Every app used to be handed every key the\n * workspace resolved — a web app got the database's owner URL and the auth\n * server's signing secret, and the API got the auth server's database — which\n * is exactly what a declared edge exists to rule out. A deploy composes an\n * app's environment from its edges; so does this.\n *\n * One hop: a surface an app calls is reached over HTTP, so its URL is the\n * app's business and its database is not.\n *\n * A surface's process runs its own endpoints and nothing else. A Worker's\n * crons, queue consumers and subscribers run in the worker's own process\n * (`workerEnvKeys`), so no surface is handed a worker's edges — however its\n * endpoints were found.\n *\n * `undefined` for an app no declaration describes, which gets nothing but its\n * port.\n */\nexport function appEnvKeys(\n\tmanifest: ConstructManifest,\n\tappName: string,\n): Set<string> | undefined {\n\tconst entry = Object.entries(manifest).find(\n\t\t([id, d]) =>\n\t\t\t(d.kind === 'rest-api' ||\n\t\t\t\td.kind === 'websocket-api' ||\n\t\t\t\td.kind === 'site' ||\n\t\t\t\td.kind === 'mobile-app') &&\n\t\t\tappKey(id) === appName,\n\t);\n\tif (!entry) return undefined;\n\tconst [id, declaration] = entry;\n\n\tconst keys = new Set<string>([\n\t\t...(declaration.provides ?? []),\n\t\t...(declaration.requires ?? []),\n\t\t// A handler the surface declares itself — an auth server's wildcard —\n\t\t// states what it needs on the handler.\n\t\t...(declaration.kind === 'rest-api'\n\t\t\t? declaration.endpoints.flatMap((endpoint) => endpoint.requires ?? [])\n\t\t\t: []),\n\t]);\n\n\t// A surface's own edges and its endpoints' — every route it serves.\n\tconst client = isPublicDeclaration(declaration);\n\t// A frontend's plain edge to a bucket is to where the bucket's links are\n\t// signed — one of its public values, below — and to nothing that writes\n\t// to it. `.server` asks for the rest.\n\tconst edges = dependenciesOf(declaration)\n\t\t.filter(\n\t\t\t(edge) =>\n\t\t\t\tmanifest[edge.target]?.kind !== 'objects' ||\n\t\t\t\treachesServerHalf(declaration, edge),\n\t\t)\n\t\t.map((edge) => edge.target);\n\taddEdgeKeys(manifest, edges, keys, client);\n\n\t// The other direction: who calls this surface, by the identity it links\n\t// and redirects back to (`APP_SCHEME`, `WEB_URL`).\n\tif (declaration.kind === 'rest-api' || declaration.kind === 'websocket-api') {\n\t\tfor (const key of callerKeys(manifest, id)) keys.add(key);\n\t}\n\n\tif (client) {\n\t\t// A site's edge to a `Telemetry` node hands it none of the node's keys:\n\t\t// an exporter's endpoint and headers are a server's, and a site's\n\t\t// environment is a bundle's.\n\t\tfor (const key of TELEMETRY_KEYS) keys.delete(key);\n\t\tfor (const key of Object.keys(publicEnvFor(declaration, manifest))) {\n\t\t\tkeys.add(key);\n\t\t}\n\t\t// And each unprefixed, for its server half: `<T>_SIGNED_ORIGIN` on\n\t\t// either edge to a bucket, a file server's address.\n\t\tfor (const { key } of publicValues(declaration, manifest)) keys.add(key);\n\t}\n\n\treturn keys;\n}\n\n/**\n * The keys a Worker's own process reads: what the worker and everything built\n * from it declared an edge to — the queues its consumers drain and the topics\n * its subscribers are bound to among them (see `workerEdges`) — and the\n * broker its crons schedule through.\n *\n * `undefined` when no worker has that id.\n */\nexport function workerEnvKeys(\n\tmanifest: ConstructManifest,\n\tworkerId: string,\n): Set<string> | undefined {\n\tconst declaration = manifest[workerId];\n\tif (declaration?.kind !== 'worker') return undefined;\n\n\tconst keys = new Set<string>([\n\t\t...(declaration.provides ?? []),\n\t\t...(declaration.requires ?? []),\n\t\t// A server schedules its crons through the broker.\n\t\t'EVENT_PUBLISHER_CONNECTION_STRING',\n\t]);\n\taddEdgeKeys(manifest, workerEdges(manifest, workerId), keys);\n\treturn keys;\n}\n\n/**\n * The keys a file server's processor unit reads: its bucket's, and what each\n * of its processors depends on. `undefined` for a file server with none.\n */\nexport function processorEnvKeys(\n\tmanifest: ConstructManifest,\n\tfileServerId: string,\n): Set<string> | undefined {\n\tconst server = manifest[fileServerId];\n\tif (server?.kind !== 'file-server' || !server.processors?.length) {\n\t\treturn undefined;\n\t}\n\n\tconst keys = new Set<string>();\n\taddEdgeKeys(\n\t\tmanifest,\n\t\t[\n\t\t\tserver.of,\n\t\t\t...server.processors.flatMap((p) => p.dependencies.map((d) => d.target)),\n\t\t],\n\t\tkeys,\n\t);\n\treturn keys;\n}\n\n/**\n * What one process runs: an app's surface or site, and the workers and file\n * servers' processors whose work it carries.\n *\n * The same app is a different process on different commands — under `gkm\n * dev` an API's own process runs the crons of the workers it hosts, while a\n * stack runs each worker in a container of its own — so a command names what\n * its process runs, and the keys follow from that alone.\n */\nexport interface ProcessUnits {\n\t/** The app's name, `api` or `web`. */\n\tapp?: string;\n\t/** Worker ids, `Jobs`. */\n\tworkers?: readonly string[];\n\t/** File servers' ids whose processors it runs, `AssetsServer`. */\n\tprocessors?: readonly string[];\n}\n\n/**\n * The keys the declared constructs hand to some process — each scoped to the\n * processes with an edge to it. A stage key outside this set is the stage's\n * own: one set by hand, which nothing declares a reader of.\n */\nexport function constructKeys(manifest: ConstructManifest): Set<string> {\n\tconst keys = new Set<string>();\n\tconst add = (more: Iterable<string> | undefined) => {\n\t\tfor (const key of more ?? []) keys.add(key);\n\t};\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tadd(declaration.provides);\n\t\tadd(declaration.requires);\n\t\tif (declaration.kind === 'worker') add(workerEnvKeys(manifest, id));\n\t\tif (declaration.kind === 'file-server') {\n\t\t\tadd(processorEnvKeys(manifest, id));\n\t\t}\n\t\tif (\n\t\t\tdeclaration.kind === 'rest-api' ||\n\t\t\tdeclaration.kind === 'websocket-api' ||\n\t\t\tdeclaration.kind === 'site' ||\n\t\t\tdeclaration.kind === 'mobile-app'\n\t\t) {\n\t\t\tadd(appEnvKeys(manifest, appKey(id)));\n\t\t}\n\t}\n\treturn keys;\n}\n\n/**\n * The keys one process is handed — the one rule `gkm dev`, `gkm exec` and\n * `gkm compose` all apply, so an app gets the same keys whichever runs it:\n *\n * - **What its constructs reach**, by their edges: `appEnvKeys` for its app,\n * `workerEnvKeys` for each worker it runs, `processorEnvKeys` for each\n * file server's processors. A key a construct provides reaches only a\n * process with an edge to it, a stored one included — an auth server's\n * signing secret stays with the auth server.\n * - **The stack's edge token** (`EDGE_TOKEN_KEY`), which a call to a\n * sibling through the edge carries beside the client's address.\n * - **Every one of the stage's own keys** (`stageKeys` no construct\n * provides): a value set with `gkm secrets:set` that the code reads with\n * `get('X')`. Nothing declares which process reads it, so every process is\n * handed it — but for what gkm keeps for the stack itself (`isStackKey`):\n * a container's login, the backups key, the server's address.\n *\n * `undefined` for an app no declaration describes, which nothing narrows.\n */\nexport function processEnvKeys(\n\tmanifest: ConstructManifest,\n\tunits: ProcessUnits,\n\tstageKeys: Iterable<string>,\n): Set<string> | undefined {\n\tconst keys = new Set<string>();\n\tif (units.app !== undefined) {\n\t\tconst own = appEnvKeys(manifest, units.app);\n\t\tif (!own && !units.workers?.length && !units.processors?.length) {\n\t\t\treturn undefined;\n\t\t}\n\t\tfor (const key of own ?? []) keys.add(key);\n\t}\n\tfor (const id of units.workers ?? []) {\n\t\tfor (const key of workerEnvKeys(manifest, id) ?? []) keys.add(key);\n\t}\n\tfor (const id of units.processors ?? []) {\n\t\tfor (const key of processorEnvKeys(manifest, id) ?? []) keys.add(key);\n\t}\n\n\t// Every process may call a sibling through the edge, with the stack's\n\t// token beside the client's address.\n\tkeys.add(EDGE_TOKEN_KEY);\n\n\tconst owned = constructKeys(manifest);\n\tfor (const key of stageKeys) {\n\t\tif (!owned.has(key) && !isStackKey(key)) keys.add(key);\n\t}\n\treturn keys;\n}\n\n/**\n * One process's environment, from the stage's stored keys and every value\n * it resolved (`stageEnv`'s merge): exactly {@link processEnvKeys}.\n */\nexport function processEnv(\n\tmanifest: ConstructManifest,\n\tunits: ProcessUnits,\n\tstored: Readonly<Record<string, string>>,\n\tresolved: Readonly<Record<string, string>>,\n): Record<string, string> {\n\tconst env = stageEnv(stored, resolved);\n\tconst keys = processEnvKeys(manifest, units, Object.keys(stored));\n\tif (!keys) return env;\n\treturn Object.fromEntries(\n\t\tObject.entries(env).filter(([key]) => keys.has(key)),\n\t);\n}\n\n/**\n * What an app's own process runs locally: its surface or site, and the\n * workers and processors whose code it holds — the same choice `gkm build`\n * makes (`workerUnits`, `processorUnits`).\n *\n * A worker no app can build is left out here: `gkm build` says so, and a\n * dev loop has nothing to run it in.\n */\nexport function appProcess(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tbackground: Readonly<Record<string, readonly string[]>>,\n\tappName: string,\n): ProcessUnits {\n\tconst hosted = <T extends { id: string; app: string }>(units: () => T[]) => {\n\t\ttry {\n\t\t\treturn units()\n\t\t\t\t.filter((unit) => unit.app === appName)\n\t\t\t\t.map((unit) => unit.id);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof WorkerHasNoApp ||\n\t\t\t\terror instanceof WorkerNameTaken ||\n\t\t\t\terror instanceof ProcessorsHaveNoApp\n\t\t\t) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\treturn {\n\t\tapp: appName,\n\t\tworkers: hosted(() => workerUnits(workspace, manifest, background)),\n\t\tprocessors: hosted(() => processorUnits(workspace, manifest)),\n\t};\n}\n\n/**\n * What a surface is told about the clients that call it: the identity it\n * links and redirects back to.\n *\n * An API that finishes an OAuth callback by sending a phone back into the app\n * builds `<scheme>://…`; one that mails a link to the site builds it on the\n * site's address. Both are the caller's own key, named by the caller's id —\n * `APP_SCHEME` for `MobileApp('App')`, `WEB_URL` for `StaticSite('Web')` — so\n * two apps calling one API arrive as `APP_SCHEME` and `ADMIN_APP_SCHEME`.\n *\n * Clients only. A surface or a worker that calls this one is something it\n * answers, never somewhere it sends a user, so nothing of theirs comes back\n * along the edge. Their origins still reach the surface, folded into its\n * `<ID>_TRUSTED_ORIGINS`.\n */\nexport function callerKeys(\n\tmanifest: ConstructManifest,\n\tsurfaceId: string,\n): string[] {\n\tconst keys: string[] = [];\n\tfor (const caller of dependentsOf(manifest, surfaceId)) {\n\t\tconst declaration = manifest[caller];\n\t\tif (declaration?.kind === 'mobile-app') {\n\t\t\tkeys.push(providedKeyFor(caller, declaration.kind, 'scheme'));\n\t\t} else if (declaration?.kind === 'site') {\n\t\t\tkeys.push(providedKeyFor(caller, declaration.kind, 'url'));\n\t\t}\n\t}\n\treturn keys;\n}\n\n/**\n * What a caller gets for each construct it has an edge to — the left half of\n * the table on {@link appEnvKeys}.\n */\nfunction addEdgeKeys(\n\tmanifest: ConstructManifest,\n\tedges: readonly string[],\n\tkeys: Set<string>,\n\t/** The process is a bundle a browser or a phone runs. */\n\tclient = false,\n): void {\n\tfor (const id of edges) {\n\t\t// A bucket's events: its subscribers' process reads where they are\n\t\t// delivered from, and nothing else of the bucket.\n\t\tconst bucket = eventsEdgeBucket(id);\n\t\tif (bucket) {\n\t\t\tif (manifest[bucket]?.kind === 'objects') {\n\t\t\t\tkeys.add(providedKeyFor(bucket, 'objects', 'eventsConnectionString'));\n\t\t\t\tkeys.add(providedKeyFor(bucket, 'objects', 'eventsToken'));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst target = manifest[id];\n\t\tif (!target) continue;\n\t\t// A surface is reached over HTTP, so its caller is given its address\n\t\t// and nothing else it provides: who it trusts and the domain its\n\t\t// cookies are scoped to are the surface's own settings, read by its own\n\t\t// process. For an auth server that is the whole point — the API gets\n\t\t// AUTH_URL, and the auth app alone holds its secret, tenant and mailer.\n\t\tif (target.kind === 'rest-api') {\n\t\t\tkeys.add(providedKeyFor(id, target.kind, 'url'));\n\t\t\tcontinue;\n\t\t}\n\t\t// A WebSocket surface is opened at its address, and sent to through its\n\t\t// publisher — which writes to every socket, so a client is handed the\n\t\t// address alone.\n\t\tif (target.kind === 'websocket-api') {\n\t\t\tkeys.add(providedKeyFor(id, target.kind, 'url'));\n\t\t\tif (!client)\n\t\t\t\tkeys.add(providedKeyFor(id, target.kind, 'publisherConnectionString'));\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const key of target.provides ?? []) keys.add(key);\n\n\t\t// Locally Mailpit posts what an inbox receives to the worker that\n\t\t// runs its subscriber, with this token.\n\t\tif (target.kind === 'inbox') keys.add(INBOX_RELAY_TOKEN_KEY);\n\n\t\tif (target.kind === 'queue' || target.kind === 'topic') {\n\t\t\tkeys.add('EVENT_PUBLISHER_CONNECTION_STRING');\n\t\t}\n\t\t// The S3 client's shared key pair, for a bucket whose URL carries no key\n\t\t// of its own — handed over only where the stage has one. A file server\n\t\t// is reached by its URL alone.\n\t\tif (target.kind === 'objects') {\n\t\t\t// A FileServer is one construct declaring two nodes — the bucket,\n\t\t\t// which the edge points at, and the domain that serves it — and its\n\t\t\t// client reads both: a handler signs uploads to the bucket and hands\n\t\t\t// out URLs on the domain. The domain's address comes with the edge.\n\t\t\tfor (const other of Object.values(manifest)) {\n\t\t\t\tif (other.kind === 'file-server' && other.of === id) {\n\t\t\t\t\tfor (const key of other.provides ?? []) keys.add(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tkeys.add('AWS_ACCESS_KEY_ID');\n\t\t\tkeys.add('AWS_SECRET_ACCESS_KEY');\n\t\t\tkeys.add('AWS_REGION');\n\t\t}\n\t}\n}\n\n/** One compose service per app the workspace runs, behind the apps profile. */\nexport function appServices(\n\tworkspace: NormalizedWorkspace,\n\tmanifest: ConstructManifest,\n\tcontainers: readonly string[],\n\t/** The workspace's local logins — see `localCredentials.ts`. */\n\tcredentials: LocalCredentials,\n\tfakes: PlanOptions['fakes'] = {},\n\t/**\n\t * Each credential's fake value, under `gkm dev --fake` — handed to the\n\t * apps that read the credential, as an external API's fake is.\n\t */\n\tcredentialFakes: PlanOptions['credentialFakes'] = {},\n): Record<string, ComposeService> {\n\tconst plan = localPlan(workspace, manifest, fakes, credentialFakes);\n\tconst derivation = {\n\t\tproject: workspace.name,\n\t\tcredentials,\n\t\tseed: credentials.seed,\n\t};\n\tconst env = networkEnv(plan, {\n\t\t...derivation,\n\t\taddresses: surfaceAddresses(\n\t\t\tworkspace,\n\t\t\tmanifest,\n\t\t\t(app, port) => `http://${app}:${port}`,\n\t\t),\n\t});\n\t// What a browser is handed: each app on the port this file publishes it on.\n\tconst browser = networkEnv(plan, {\n\t\t...derivation,\n\t\taddresses: surfaceAddresses(workspace, manifest),\n\t});\n\tconst services: Record<string, ComposeService> = {};\n\tconst buildRoot = findBuildRoot(workspace.root);\n\n\tfor (const [name, app] of Object.entries(workspace.apps)) {\n\t\t// A mobile app ships through its own toolchain; nothing here runs it.\n\t\tif (app.type === 'mobile' || !app.port) continue;\n\n\t\tconst key = appKey(name);\n\t\tconst health = app.type === 'web' ? '/' : '/health';\n\t\t// Built from the build root — the package manager's, which is above the\n\t\t// workspace when it is nested in a monorepo — by the Dockerfile `gkm\n\t\t// docker` writes under the workspace.\n\t\tconst build = composeBuildPaths({\n\t\t\tcomposeDir: workspace.root,\n\t\t\tbuildRoot,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tdockerfile: dockerfileOf(name, app.path),\n\t\t});\n\t\tconst ports = [`${app.port}:${app.port}`];\n\n\t\t// A site is a bundle: its public URLs are inlined when it is built, so\n\t\t// they are build arguments, and it reads nothing at runtime — no server\n\t\t// env, and nothing to wait for but its own server.\n\t\tif (app.type === 'web') {\n\t\t\tconst args = sitePublicArgs(manifest, name, browser);\n\t\t\tservices[key] = {\n\t\t\t\timage: `${key}:\\${TAG:-latest}`,\n\t\t\t\tbuild: {\n\t\t\t\t\t...build,\n\t\t\t\t\t...(Object.keys(args).length ? { args } : {}),\n\t\t\t\t},\n\t\t\t\tprofiles: [APPS_PROFILE],\n\t\t\t\tports,\n\t\t\t\thealthcheck: healthcheck(app.port, health),\n\t\t\t};\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst allowed = appEnvKeys(manifest, name);\n\t\t// The local stage's telemetry, named for this app, where it has the\n\t\t// edge — and none of it where it has not.\n\t\tconst own = scopeTelemetryEnv(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(env).filter(([envKey]) => allowed?.has(envKey)),\n\t\t\t),\n\t\t\t{\n\t\t\t\tuses: appTelemetry(manifest, name) !== undefined,\n\t\t\t\tserviceName: name,\n\t\t\t\ttelemetry: env,\n\t\t\t},\n\t\t);\n\n\t\tservices[key] = {\n\t\t\timage: `${key}:\\${TAG:-latest}`,\n\t\t\tbuild,\n\t\t\tprofiles: [APPS_PROFILE],\n\t\t\tports,\n\t\t\tenvironment: {\n\t\t\t\tNODE_ENV: 'production',\n\t\t\t\tPORT: String(app.port),\n\t\t\t\t...own,\n\t\t\t},\n\t\t\t// The edge fronts the host's browser; apps talk to each other directly.\n\t\t\t...(containers.some((c) => c !== 'caddy')\n\t\t\t\t? { depends_on: containers.filter((c) => c !== 'caddy') }\n\t\t\t\t: {}),\n\t\t\thealthcheck: healthcheck(app.port, health),\n\t\t};\n\t}\n\n\treturn services;\n}\n\n/** An app's health check: its own server answering on `path`. */\nexport function healthcheck(\n\tport: number,\n\tpath: string,\n): NonNullable<ComposeService['healthcheck']> {\n\treturn {\n\t\ttest: ['CMD', 'wget', '-q', '--spider', `http://localhost:${port}${path}`],\n\t\tinterval: '10s',\n\t\ttimeout: '5s',\n\t\tretries: 5,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,WAAyC;CAC3E,OACC,UAAU,QAAQ,YAAY,aAC9B,OAAO,OAAO,UAAU,IAAI,CAAC,CAAC,MAC5B,QAAQ,IAAI,yBAAyB,SACvC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;AC6BA,SAAgB,aAAa,UAAsC;CAClE,OAAO,OAAO,OAAO,QAAQ,CAAC,CAAC,MAAM,MAAM,EAAE,SAAS,UAAU;AACjE;;;;;;AAOA,SAAgB,aACf,WACA,UACA,OACqB;CACrB,IAAI,UAAU,UAAU,QAAQ,OAC/B,OAAO;EAAE,MAAM;EAAQ,QAAQ;CAAQ;CAExC,IAAI,CAAC,mBAAmB,SAAgC,GACvD,OAAO;EAAE,MAAM;EAAQ,QAAQ;CAAc;CAE9C,IAAI,CAAC,aAAa,QAAQ,GAAG,OAAO;EAAE,MAAM;EAAQ,QAAQ;CAAc;CAC1E,MAAM,SACL,UAAU,QAAQ,QAAA,GACf;CACJ,MAAM,UAAU,kBAAkB,OAAO,SAAS,CAAC,CAAC;CACpD,IAAI,YAAY,OAAO,OAAO,EAAE,MAAM,WAAW;CACjD,OAAO;EACN,MAAM;EACN,SAAS;EACT,QAAQ,UAAU,KAAA,IAAY,YAAY;CAC3C;AACD;;;;;AAMA,SAAgB,cACf,WACA,OACS;CACT,MAAM,QAAQ,UAAU;CACxB,MAAM,SACL,OAAO,aAAa,QAAQ,MAAM,WAAW,KAAA,IAC1C,MAAM,OAAO,QAAQ,QAAQ,EAAE,IAC/B;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