@geekmidas/cli 10.0.0-alpha.154 → 10.0.0-alpha.156
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 +10 -0
- package/dist/{GoDaddyProvider-CQ4YrB5P.mjs → GoDaddyProvider-C6kihaSF.mjs} +2 -2
- package/dist/{GoDaddyProvider-CQ4YrB5P.mjs.map → GoDaddyProvider-C6kihaSF.mjs.map} +1 -1
- package/dist/{GoDaddyProvider-H59_cXa0.cjs → GoDaddyProvider-bCGjHmq_.cjs} +2 -2
- package/dist/{GoDaddyProvider-H59_cXa0.cjs.map → GoDaddyProvider-bCGjHmq_.cjs.map} +1 -1
- package/dist/{HostingerProvider-DBfHH0qT.mjs → HostingerProvider-CH3qcNOp.mjs} +2 -2
- package/dist/{HostingerProvider-DBfHH0qT.mjs.map → HostingerProvider-CH3qcNOp.mjs.map} +1 -1
- package/dist/{HostingerProvider-DecF9ELH.cjs → HostingerProvider-l-pKR3UU.cjs} +2 -2
- package/dist/{HostingerProvider-DecF9ELH.cjs.map → HostingerProvider-l-pKR3UU.cjs.map} +1 -1
- package/dist/{LegacyStateStore-DwsnVS-2.cjs → LegacyStateStore-BLTALNNX.cjs} +2 -2
- package/dist/{LegacyStateStore-DwsnVS-2.cjs.map → LegacyStateStore-BLTALNNX.cjs.map} +1 -1
- package/dist/{LegacyStateStore-Cz1ORtCx.mjs → LegacyStateStore-kxFSoD1P.mjs} +2 -2
- package/dist/{LegacyStateStore-Cz1ORtCx.mjs.map → LegacyStateStore-kxFSoD1P.mjs.map} +1 -1
- package/dist/{LocalStateStore-BZ5b3sw4.cjs → LocalStateStore-CCYbRnLH.cjs} +2 -2
- package/dist/{LocalStateStore-BZ5b3sw4.cjs.map → LocalStateStore-CCYbRnLH.cjs.map} +1 -1
- package/dist/{LocalStateStore-dz7OkMGm.mjs → LocalStateStore-CjA4PPQ8.mjs} +2 -2
- package/dist/{LocalStateStore-dz7OkMGm.mjs.map → LocalStateStore-CjA4PPQ8.mjs.map} +1 -1
- package/dist/{S3StateStore-Dw9Dx_vy.cjs → S3StateStore-B4Qu-euw.cjs} +4 -4
- package/dist/{S3StateStore-Dw9Dx_vy.cjs.map → S3StateStore-B4Qu-euw.cjs.map} +1 -1
- package/dist/{S3StateStore-Bda3aGqz.mjs → S3StateStore-nCDpz4Gi.mjs} +4 -4
- package/dist/{S3StateStore-Bda3aGqz.mjs.map → S3StateStore-nCDpz4Gi.mjs.map} +1 -1
- package/dist/{SSMStateStore-DPZpYnda.cjs → SSMStateStore-BI5sYXl-.cjs} +2 -2
- package/dist/{SSMStateStore-DPZpYnda.cjs.map → SSMStateStore-BI5sYXl-.cjs.map} +1 -1
- package/dist/{SSMStateStore-CcT6YJFd.mjs → SSMStateStore-VOk8OdaW.mjs} +2 -2
- package/dist/{SSMStateStore-CcT6YJFd.mjs.map → SSMStateStore-VOk8OdaW.mjs.map} +1 -1
- package/dist/{add-Bwek61Bv.cjs → add-B0VtHNY5.cjs} +4 -4
- package/dist/{add-Bwek61Bv.cjs.map → add-B0VtHNY5.cjs.map} +1 -1
- package/dist/{add-Feiof1dz.mjs → add-CtkmKzg0.mjs} +4 -4
- package/dist/{add-Feiof1dz.mjs.map → add-CtkmKzg0.mjs.map} +1 -1
- package/dist/{apps-CrQhJueV.cjs → apps-Bj3U4v3a.cjs} +3 -3
- package/dist/{apps-CrQhJueV.cjs.map → apps-Bj3U4v3a.cjs.map} +1 -1
- package/dist/{apps-C0kZVQpf.mjs → apps-CggMxcW9.mjs} +3 -3
- package/dist/{apps-C0kZVQpf.mjs.map → apps-CggMxcW9.mjs.map} +1 -1
- package/dist/{bundler-CV-UpPpb.cjs → bundler-CcK6uiP5.cjs} +6 -6
- package/dist/{bundler-CV-UpPpb.cjs.map → bundler-CcK6uiP5.cjs.map} +1 -1
- package/dist/{bundler-o10_P4d9.mjs → bundler-isYJiy1x.mjs} +6 -6
- package/dist/{bundler-o10_P4d9.mjs.map → bundler-isYJiy1x.mjs.map} +1 -1
- package/dist/{cli-BO4qIuTd.cjs → cli-B5k3qrO4.cjs} +4 -4
- package/dist/{cli-BO4qIuTd.cjs.map → cli-B5k3qrO4.cjs.map} +1 -1
- package/dist/{cli-KFbKAyaH.mjs → cli-BVHsKFMj.mjs} +4 -4
- package/dist/{cli-KFbKAyaH.mjs.map → cli-BVHsKFMj.mjs.map} +1 -1
- package/dist/{compose-djwQcfQD.cjs → compose-8_6I_Vhv.cjs} +4 -4
- package/dist/{compose-djwQcfQD.cjs.map → compose-8_6I_Vhv.cjs.map} +1 -1
- package/dist/{compose-C-k9AoH0.mjs → compose-DA4mTDZr.mjs} +7 -7
- package/dist/{compose-C-k9AoH0.mjs.map → compose-DA4mTDZr.mjs.map} +1 -1
- package/dist/{compose-D8fn0ebx.mjs → compose-DS0L5WGA.mjs} +4 -4
- package/dist/{compose-D8fn0ebx.mjs.map → compose-DS0L5WGA.mjs.map} +1 -1
- package/dist/{compose-CyGZOLcK.cjs → compose-Dxaaqmzz.cjs} +7 -7
- package/dist/{compose-CyGZOLcK.cjs.map → compose-Dxaaqmzz.cjs.map} +1 -1
- package/dist/{credentials-DY_Cu5Ht.mjs → credentials-DidjPIcM.mjs} +5 -5
- package/dist/{credentials-DY_Cu5Ht.mjs.map → credentials-DidjPIcM.mjs.map} +1 -1
- package/dist/{credentials-DixsjQcu.cjs → credentials-LLoLkwjB.cjs} +5 -5
- package/dist/{credentials-DixsjQcu.cjs.map → credentials-LLoLkwjB.cjs.map} +1 -1
- package/dist/deploy/public.cjs +10 -10
- package/dist/deploy/public.mjs +10 -10
- package/dist/{deploy-DsWQ8kTC.mjs → deploy-BEwiKZBG.mjs} +11 -11
- package/dist/{deploy-DsWQ8kTC.mjs.map → deploy-BEwiKZBG.mjs.map} +1 -1
- package/dist/{deploy-DzYn1rNl.cjs → deploy-DpQPFrhf.cjs} +11 -11
- package/dist/{deploy-DzYn1rNl.cjs.map → deploy-DpQPFrhf.cjs.map} +1 -1
- package/dist/{docker-CobK4rVH.mjs → docker-BeO31G2F.mjs} +4 -4
- package/dist/{docker-CobK4rVH.mjs.map → docker-BeO31G2F.mjs.map} +1 -1
- package/dist/{docker-DDHfNbM8.cjs → docker-BficHJMS.cjs} +4 -4
- package/dist/{docker-DDHfNbM8.cjs.map → docker-BficHJMS.cjs.map} +1 -1
- package/dist/{dokploy-2bH8IDTX.mjs → dokploy-BLZlrTf7.mjs} +2 -2
- package/dist/{dokploy-2bH8IDTX.mjs.map → dokploy-BLZlrTf7.mjs.map} +1 -1
- package/dist/{dokploy-CCgBM22f.cjs → dokploy-D6ktFzjP.cjs} +2 -2
- package/dist/{dokploy-CCgBM22f.cjs.map → dokploy-D6ktFzjP.cjs.map} +1 -1
- package/dist/{eas-CYs_Grue.mjs → eas-DdE1PH-Z.mjs} +2 -2
- package/dist/{eas-CYs_Grue.mjs.map → eas-DdE1PH-Z.mjs.map} +1 -1
- package/dist/{eas-8X90Y3ks.cjs → eas-Dh9LBIJi.cjs} +2 -2
- package/dist/{eas-8X90Y3ks.cjs.map → eas-Dh9LBIJi.cjs.map} +1 -1
- package/dist/{emit-Bj6XSivk.mjs → emit-C4KSXOeS.mjs} +18 -1
- package/dist/emit-C4KSXOeS.mjs.map +1 -0
- package/dist/{emit-CDC__ubE.cjs → emit-DiW0kbue.cjs} +18 -1
- package/dist/emit-DiW0kbue.cjs.map +1 -0
- package/dist/{encryption-Bm9pJAlv.mjs → encryption-1TTbMp4E.mjs} +2 -2
- package/dist/{encryption-Bm9pJAlv.mjs.map → encryption-1TTbMp4E.mjs.map} +1 -1
- package/dist/{encryption-BlvEsxDL.cjs → encryption-BDCTITiO.cjs} +2 -2
- package/dist/{encryption-BlvEsxDL.cjs.map → encryption-BDCTITiO.cjs.map} +1 -1
- package/dist/{engine-CVgtgVgf.mjs → engine-DBimzOpv.mjs} +8 -8
- package/dist/{engine-CVgtgVgf.mjs.map → engine-DBimzOpv.mjs.map} +1 -1
- package/dist/{engine-BL_34-M8.cjs → engine-DPVbMn1R.cjs} +8 -8
- package/dist/{engine-BL_34-M8.cjs.map → engine-DPVbMn1R.cjs.map} +1 -1
- package/dist/{github-Ci0PUjjW.cjs → github-Bur2rvbL.cjs} +6 -6
- package/dist/{github-Ci0PUjjW.cjs.map → github-Bur2rvbL.cjs.map} +1 -1
- package/dist/{github-j9ytVxlm.mjs → github-e4EXHIAd.mjs} +6 -6
- package/dist/{github-j9ytVxlm.mjs.map → github-e4EXHIAd.mjs.map} +1 -1
- package/dist/{googlePlay-CvYKw65D.mjs → googlePlay-CH5BrkCd.mjs} +4 -4
- package/dist/{googlePlay-CvYKw65D.mjs.map → googlePlay-CH5BrkCd.mjs.map} +1 -1
- package/dist/{googlePlay-jR8oRAzy.cjs → googlePlay-gCxefG71.cjs} +4 -4
- package/dist/{googlePlay-jR8oRAzy.cjs.map → googlePlay-gCxefG71.cjs.map} +1 -1
- package/dist/index.cjs +222 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +222 -68
- package/dist/index.mjs.map +1 -1
- package/dist/{local-5DkpRnl2.cjs → local-B9psHtjC.cjs} +2 -2
- package/dist/{local-5DkpRnl2.cjs.map → local-B9psHtjC.cjs.map} +1 -1
- package/dist/{local-pFyO21et.mjs → local-qbOxBD9I.mjs} +2 -2
- package/dist/{local-pFyO21et.mjs.map → local-qbOxBD9I.mjs.map} +1 -1
- package/dist/{migrate-DKep6Tol.cjs → migrate-B3T5iHyR.cjs} +2 -2
- package/dist/{migrate-DKep6Tol.cjs.map → migrate-B3T5iHyR.cjs.map} +1 -1
- package/dist/{migrate-CPoStsvd.cjs → migrate-BqjeJXXX.cjs} +4 -4
- package/dist/{migrate-CPoStsvd.cjs.map → migrate-BqjeJXXX.cjs.map} +1 -1
- package/dist/{migrate-C1SSvzNZ.mjs → migrate-Cg6ogGbR.mjs} +2 -2
- package/dist/{migrate-C1SSvzNZ.mjs.map → migrate-Cg6ogGbR.mjs.map} +1 -1
- package/dist/{migrate-Dv8Qk0jw.mjs → migrate-DJ6o58e4.mjs} +4 -4
- package/dist/{migrate-Dv8Qk0jw.mjs.map → migrate-DJ6o58e4.mjs.map} +1 -1
- package/dist/{notes-Dwz8jmoh.mjs → notes-CV9tczQF.mjs} +2 -2
- package/dist/{notes-Dwz8jmoh.mjs.map → notes-CV9tczQF.mjs.map} +1 -1
- package/dist/{notes-CFCdqMQ4.cjs → notes-WW3tkekq.cjs} +2 -2
- package/dist/{notes-CFCdqMQ4.cjs.map → notes-WW3tkekq.cjs.map} +1 -1
- package/dist/{projectBucket-UCuebUhW.cjs → projectBucket-BCutOEvv.cjs} +2 -2
- package/dist/{projectBucket-UCuebUhW.cjs.map → projectBucket-BCutOEvv.cjs.map} +1 -1
- package/dist/{projectBucket-Daak2eUn.mjs → projectBucket-CRAuyO-t.mjs} +2 -2
- package/dist/{projectBucket-Daak2eUn.mjs.map → projectBucket-CRAuyO-t.mjs.map} +1 -1
- package/dist/{publish-DibqEZ2a.mjs → publish-BJyVR2lE.mjs} +2 -2
- package/dist/{publish-DibqEZ2a.mjs.map → publish-BJyVR2lE.mjs.map} +1 -1
- package/dist/{publish-CBuMAY04.cjs → publish-BcPp-_qQ.cjs} +2 -2
- package/dist/{publish-CBuMAY04.cjs.map → publish-BcPp-_qQ.cjs.map} +1 -1
- package/dist/reconcile/public.cjs +1 -1
- package/dist/reconcile/public.d.cts +3 -1
- package/dist/reconcile/public.d.cts.map +1 -1
- package/dist/reconcile/public.d.mts +3 -1
- package/dist/reconcile/public.d.mts.map +1 -1
- package/dist/reconcile/public.mjs +1 -1
- package/dist/{resolve-BF4-f30m.mjs → resolve-CH_DwRLq.mjs} +4 -4
- package/dist/{resolve-BF4-f30m.mjs.map → resolve-CH_DwRLq.mjs.map} +1 -1
- package/dist/{resolve-BjgqLxcZ.cjs → resolve-CwJ_ScjX.cjs} +4 -4
- package/dist/{resolve-BjgqLxcZ.cjs.map → resolve-CwJ_ScjX.cjs.map} +1 -1
- package/dist/{rollback-BXkzAkAh.cjs → rollback-BBdR1h3T.cjs} +5 -5
- package/dist/{rollback-BXkzAkAh.cjs.map → rollback-BBdR1h3T.cjs.map} +1 -1
- package/dist/{rollback-DBewZGz9.mjs → rollback-Bpuaon23.mjs} +5 -5
- package/dist/{rollback-DBewZGz9.mjs.map → rollback-Bpuaon23.mjs.map} +1 -1
- package/dist/{s3-CR8gEP-7.mjs → s3-C5pbgCxY.mjs} +2 -2
- package/dist/{s3-CR8gEP-7.mjs.map → s3-C5pbgCxY.mjs.map} +1 -1
- package/dist/{s3-Cp2eA2v_.cjs → s3-Cx5XUsK2.cjs} +2 -2
- package/dist/{s3-Cp2eA2v_.cjs.map → s3-Cx5XUsK2.cjs.map} +1 -1
- package/dist/{serverSetup-B9BPzpUQ.mjs → serverSetup-B9sp6uWM.mjs} +5 -5
- package/dist/{serverSetup-B9BPzpUQ.mjs.map → serverSetup-B9sp6uWM.mjs.map} +1 -1
- package/dist/{serverSetup-0eV8bl75.cjs → serverSetup-CQ96N5tn.cjs} +5 -5
- package/dist/{serverSetup-0eV8bl75.cjs.map → serverSetup-CQ96N5tn.cjs.map} +1 -1
- package/dist/{sniffer-0wN20Fuy.cjs → sniffer-CSgeus1c.cjs} +6 -6
- package/dist/{sniffer-0wN20Fuy.cjs.map → sniffer-CSgeus1c.cjs.map} +1 -1
- package/dist/{sniffer-C2yPOlOW.mjs → sniffer-DmigJFSC.mjs} +6 -6
- package/dist/{sniffer-C2yPOlOW.mjs.map → sniffer-DmigJFSC.mjs.map} +1 -1
- package/dist/{snsSubscriptions-DR3drFJK.cjs → snsSubscriptions-PcvjBC8J.cjs} +2 -2
- package/dist/{snsSubscriptions-DR3drFJK.cjs.map → snsSubscriptions-PcvjBC8J.cjs.map} +1 -1
- package/dist/{snsSubscriptions-CtOrP15M.mjs → snsSubscriptions-UJrUbrPC.mjs} +2 -2
- package/dist/{snsSubscriptions-CtOrP15M.mjs.map → snsSubscriptions-UJrUbrPC.mjs.map} +1 -1
- package/dist/{sst-fbVtyw_h.cjs → sst-BX_dHQYC.cjs} +21 -5
- package/dist/{sst-fbVtyw_h.cjs.map → sst-BX_dHQYC.cjs.map} +1 -1
- package/dist/{sst-BF85FnBg.mjs → sst-CVBDMb9x.mjs} +21 -5
- package/dist/{sst-BF85FnBg.mjs.map → sst-CVBDMb9x.mjs.map} +1 -1
- package/dist/{stack-CB0U6NiV.cjs → stack-B8JVuA2N.cjs} +35 -14
- package/dist/stack-B8JVuA2N.cjs.map +1 -0
- package/dist/{stack-ZV2le8OB.mjs → stack-BrqdoNWg.mjs} +35 -14
- package/dist/stack-BrqdoNWg.mjs.map +1 -0
- package/dist/{stage-B6bQKczF.cjs → stage-BtX7qbNh.cjs} +5 -5
- package/dist/{stage-B6bQKczF.cjs.map → stage-BtX7qbNh.cjs.map} +1 -1
- package/dist/{stage-CPtCIwru.mjs → stage-DfDPXyKq.mjs} +5 -5
- package/dist/{stage-CPtCIwru.mjs.map → stage-DfDPXyKq.mjs.map} +1 -1
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.mjs +1 -1
- package/dist/{terminal-b_4H0MHd.mjs → terminal-BG75hJ72.mjs} +2 -2
- package/dist/{terminal-b_4H0MHd.mjs.map → terminal-BG75hJ72.mjs.map} +1 -1
- package/dist/{terminal-CyB5bRPt.cjs → terminal-Cz-uD2VK.cjs} +2 -2
- package/dist/{terminal-CyB5bRPt.cjs.map → terminal-Cz-uD2VK.cjs.map} +1 -1
- package/package.json +15 -15
- package/dist/emit-Bj6XSivk.mjs.map +0 -1
- package/dist/emit-CDC__ubE.cjs.map +0 -1
- package/dist/stack-CB0U6NiV.cjs.map +0 -1
- package/dist/stack-ZV2le8OB.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docker-DDHfNbM8.cjs","names":["GkmError","join","processorUnitName","ConstructGenerator","Processor","mkdir","relative","dirname","writeFile","PROCESSORS_DEV_PREFIX","writeTelemetryModule","startTelemetryCode","PROCESSOR_ORIGIN_SECRET_ENV","ORIGIN_VERIFY_HEADER","ConstructGenerator","join","mkdir","relative","Cron","writeFile","dirname","runtimeFor","ConstructGenerator","Queue","join","mkdir","relative","dirname","runtimeFor","writeFile","provideKey","GkmError","join","appKey","SubscriberGenerator","mkdir","writeFile","writeTelemetryModule","runtimeFor","startTelemetryCode","output","GkmError","loadWorkspaceConfig","resolveDockerConfig","run","relative","imageLayout","dockerfileOf","join","mkdir","dirname","writeFile","workerUnits","processorUnits","COMPOSE_PATH","appImageOptions","siteClientTelemetry","generateEntryDockerfile","generateBackendDockerfile","generateWorkerDockerfile","WORKER_PORT","generateProcessorDockerfile","PROCESSOR_PORT","appKey","provideKey","publicEnvFor","getPublicUrlArgNames","generateViteStaticDockerfile","generateNodeWebDockerfile","generateNextjsDockerfile","existsSync","generateDockerignore","readFile","appendFile","reconcileWorkspace"],"sources":["../src/docker/imageRef.ts","../src/generators/ProcessorGenerator.ts","../src/generators/CronGenerator.ts","../src/generators/QueueGenerator.ts","../src/generators/WorkerGenerator.ts","../src/docker/index.ts"],"sourcesContent":["/**\n * An image reference, checked before it reaches `docker`.\n *\n * The parts come from the workspace — a registry in `gkm.config.ts`, an image\n * name from the project, a tag from `--tag` — and an argument array already\n * keeps them out of a shell. What it cannot do is stop `docker` reading a value\n * that starts with `-` as one of its own flags, so a ref is held to Docker's\n * own grammar (distribution/reference) and anything else is refused by name\n * before a build starts.\n */\n\nimport { GkmError } from '../errors';\n\nconst DOMAIN_COMPONENT = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])';\nconst DOMAIN = `${DOMAIN_COMPONENT}(?:\\\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;\nconst PATH_COMPONENT = '[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*';\nconst TAG = '[\\\\w][\\\\w.-]{0,127}';\nconst DIGEST =\n\t'[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}';\n\nconst REFERENCE = new RegExp(\n\t`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`,\n);\n\n/** Docker refuses a repository name longer than this. */\nconst MAX_NAME_LENGTH = 255;\n\n/** A value that is not an image reference was about to be built or pushed. */\nexport class ImageRefInvalid extends GkmError {\n\tconstructor(readonly ref: string) {\n\t\tsuper(\n\t\t\t`'${ref}' is not a valid image reference. An image is \\`[registry/]name[:tag]\\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`,\n\t\t);\n\t\tthis.name = 'ImageRefInvalid';\n\t}\n}\n\n/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */\nexport function validateImageRef(ref: string): string {\n\tconst name = ref.split('@')[0]!.replace(/:[\\w][\\w.-]*$/, '');\n\tif (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) {\n\t\tthrow new ImageRefInvalid(ref);\n\t}\n\treturn ref;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Processor } from '@geekmidas/constructs/processors';\nimport type { ProcessorInfo } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport { processorUnitName } from '../build/workers';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n} from '../providers/processorOrigin';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport { PROCESSORS_DEV_PREFIX } from './processorRoute';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\ntype AnyProcessor = Processor<string, any, any, any>;\n\n/** Where a file server's processor entry lives, under an app's `.gkm/server`. */\nexport function processorEntryDir(\n\tserverDir: string,\n\tfileServerId: string,\n): string {\n\treturn join(serverDir, 'processors', processorUnitName(fileServerId));\n}\n\n/** The file its bundle is written to, beside the server's. */\nexport function processorBundleName(fileServerId: string): string {\n\treturn `${processorUnitName(fileServerId)}.mjs`;\n}\n\n/**\n * A file server's processors, as the build generates them.\n *\n * On AWS each is a Lambda behind a function URL — the CDN's origin for its\n * pattern. On a server they are one process per file server, the processor\n * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target\n * generates nothing per processor here.\n */\nexport class ProcessorGenerator extends ConstructGenerator<\n\tAnyProcessor,\n\tProcessorInfo[]\n> {\n\tisConstruct(value: unknown): value is AnyProcessor {\n\t\treturn Processor.isProcessor(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<AnyProcessor>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<ProcessorInfo[]> {\n\t\tif ((options?.target ?? 'aws') !== 'aws' || constructs.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst dir = join(outputDir, 'processors');\n\t\tawait mkdir(dir, { recursive: true });\n\n\t\tconst infos: ProcessorInfo[] = [];\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst file = join(dir, `${key}.ts`);\n\t\t\tconst importPath = relative(dirname(file), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tawait writeFile(\n\t\t\t\tfile,\n\t\t\t\t`import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';\nimport { ${key} } from '${importPath}';\n${context.storageDrivers?.imports ?? ''}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaProcessor(${key});\n\nexport const handler = adapter.handler;\n`,\n\t\t\t);\n\t\t\tinfos.push(\n\t\t\t\tawait processorInfo(\n\t\t\t\t\tkey,\n\t\t\t\t\tconstruct,\n\t\t\t\t\trelative(options?.root ?? process.cwd(), file).replace(\n\t\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t\t'.handler',\n\t\t\t\t\t),\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn infos;\n\t}\n\n\t/**\n\t * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting\n\t * each file server's processors under `/__gkm/processors/<FileServer>`.\n\t * The local edge sends each pattern on the file server's host there, so\n\t * `processedUrl()` answers locally as it does deployed.\n\t *\n\t * In the dev server's own process rather than a unit of its own: locally\n\t * there is no CPU to protect, and the dev server already reloads on change.\n\t */\n\tasync buildDev(\n\t\toutputDir: string,\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst file = join(outputDir, 'processors.ts');\n\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\t\tconst byServer = new Map<string, string[]>();\n\t\tfor (const { key, construct } of processors) {\n\t\t\tbyServer.set(construct.surfaceId, [\n\t\t\t\t...(byServer.get(construct.surfaceId) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst units = [...byServer.entries()]\n\t\t\t.map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(', ')}],`)\n\t\t\t.join('\\n');\n\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\t`/**\n * Generated processors setup for \\`gkm dev\\`.\n *\n * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the\n * local edge rewrites each processor pattern on the file server's host here.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${imports}\n\nexport function setupProcessors(\n app: { all: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n): void {\n const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(\n Object.entries({\n${units}\n }).map(([id, processors]) => [id, processorServer(processors, envParser)]),\n );\n\n app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {\n const server = c.req.param('server') as string;\n const serve = units[server];\n if (!serve) return c.notFound();\n const path = c.req.path.slice(\\`${PROCESSORS_DEV_PREFIX}\\${server}\\`.length) || '/';\n const response = await serve({ method: c.req.method, path });\n if (!response) {\n return new Response(null, {\n status: 404,\n headers: { 'cache-control': 'public, max-age=60' },\n });\n }\n return new Response(c.req.method === 'HEAD' ? null : response.body, {\n status: response.status,\n headers: response.headers,\n });\n });\n}\n`,\n\t\t);\n\t\treturn file;\n\t}\n\n\t/**\n\t * A file server's processor unit: one process answering each of its\n\t * processors' patterns, and `/health`. Returns its entry, `processors.ts`.\n\t *\n\t * Its own process because making a derivative is CPU-bound — a resize\n\t * spike in the API's process would be every request's latency.\n\t */\n\tasync buildEntry(input: {\n\t\tcontext: BuildContext;\n\t\tfileServerId: string;\n\t\toutputDir: string;\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[];\n\t\t/** From the file server's edge to a `Telemetry` node, when it has one. */\n\t\ttelemetry?: TelemetryContext;\n\t}): Promise<string> {\n\t\tconst { context, outputDir, processors } = input;\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\t// The file server's own edge decides; without one the module loads\n\t\t// nothing, and the entry's start-up is the same shape either way.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst healthCheck = context.production?.healthCheck ?? '/health';\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\tconst entry = join(outputDir, 'processors.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\t`#!/usr/bin/env node\n/**\n * Production entry for ${input.fileServerId}'s processors.\n * Generated by 'gkm build --production'.\n *\n * Answers each processor's pattern, and ${healthCheck} on PORT. The edge\n * routes only those patterns here; everything else on the file server's\n * domain is the bucket.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${context.storageDrivers?.imports ?? ''}\n${imports}\n\n${startTelemetryCode([healthCheck])}\n${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};\n\nconst processors = [${processors.map(({ key }) => key).join(', ')}];\nconst serve = processorServer(processors);\nconst port = Number(process.env.PORT) || 3000;\nlet stopping = false;\n\n${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}\n// Where the CDN fronts this unit, the secret it adds to every request: one\n// without it is refused here, whatever the edge in front did or could not.\nconst originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}\n ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})\n : undefined;\nconst fromOrigin = (header: string | string[] | undefined) => {\n if (!originSecret) return true;\n const given = Buffer.from(typeof header === 'string' ? header : '');\n return given.length === originSecret.length && timingSafeEqual(given, originSecret);\n};\n\nconst server = createServer(async (req, res) => {\n const method = req.method ?? 'GET';\n const path = (req.url ?? '/').split('?')[0] ?? '/';\n if (path === ${JSON.stringify(healthCheck)}) {\n res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));\n return;\n }\n if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {\n res.writeHead(403, { 'cache-control': 'no-store' }).end();\n return;\n }\n await traced(method, path, async () => {\n try {\n const response = await serve({ method, path });\n if (!response) {\n res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();\n return 404;\n }\n res.writeHead(response.status, response.headers);\n res.end(method === 'HEAD' ? undefined : response.body);\n return response.status;\n } catch (error) {\n console.error(error);\n res.writeHead(500, { 'cache-control': 'no-store' }).end();\n return 500;\n }\n });\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();\n server.close();\n await runShutdownHooks((error) => console.error(error));\n process.exit(0);\n};\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n`,\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * A SERVER span per request, once telemetry has started — opened by the unit\n * rather than by hooking node:http, which sees nothing inside a bundle. Named\n * after the processor's pattern, never the key, which has no bound.\n *\n * Only in an entry whose file server has a `Telemetry` node: the bundle\n * follows the import, and an app without one need not install the API.\n */\nconst REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;\nconst routeOf = (path: string) =>\n processors.find((processor) => path.startsWith(processor.prefix))?.pattern;\n\nasync function traced(\n method: string,\n path: string,\n run: () => Promise<number>,\n): Promise<void> {\n if (!tracing) {\n await run();\n return;\n }\n const route = routeOf(path);\n await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(\n route ? \\`\\${method} \\${route}\\` : method,\n {\n kind: tracing.SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': path,\n ...(route ? { 'http.route': route } : {}),\n },\n },\n async (span) => {\n try {\n const status = await run();\n span.setAttribute('http.response.status_code', status);\n if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });\n } finally {\n span.end();\n }\n },\n );\n}\n`;\n\n/** The same shape without telemetry: each request just runs. */\nconst NO_REQUEST_SPANS = `async function traced(\n _method: string,\n _path: string,\n run: () => Promise<number>,\n): Promise<void> {\n await run();\n}\n`;\n\n/** What the manifest records of one processor. */\nexport async function processorInfo(\n\tname: string,\n\tprocessor: AnyProcessor,\n\thandler: string,\n\tcontext: Pick<BuildContext, 'markOptional'>,\n): Promise<ProcessorInfo> {\n\treturn {\n\t\tname,\n\t\thandler,\n\t\tfileServer: processor.surfaceId,\n\t\tpath: processor.pattern,\n\t\tprefix: processor.prefix,\n\t\t...(processor.native.length ? { native: [...processor.native] } : {}),\n\t\t...(processor.timeout !== undefined ? { timeout: processor.timeout } : {}),\n\t\t...(processor.memorySize !== undefined\n\t\t\t? { memorySize: processor.memorySize }\n\t\t\t: {}),\n\t\tenvironment: await processor.getEnvironment({\n\t\t\tmarkOptional: context.markOptional,\n\t\t}),\n\t\tdependencies: processor.constructs,\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Cron } from '@geekmidas/constructs/crons';\nimport type { BuildContext } from '../build/types';\nimport type { CronInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\nexport class CronGenerator extends ConstructGenerator<\n\tCron<any, any, any, any, any, any>,\n\tCronInfo[]\n> {\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<CronInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst cronInfos: CronInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// A server runs its crons itself, the way it already runs its\n\t\t\t// subscribers: one file, wired into the generated entry. Written even\n\t\t\t// when there are none, so the entry can import it unconditionally.\n\t\t\tawait this.generateServerCronsFile(outputDir, constructs);\n\n\t\t\tlogger.log(`Generated server crons file with ${constructs.length} crons`);\n\n\t\t\t// A server cron has no individual handler to point infra at — the\n\t\t\t// process schedules it.\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\t// Create crons subdirectory\n\t\tconst cronsDir = join(outputDir, 'crons');\n\t\tawait mkdir(cronsDir, { recursive: true });\n\n\t\t// Generate cron handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateCronHandler(\n\t\t\t\tcronsDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tcronInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tschedule: construct.schedule || 'rate(1 hour)',\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated cron handler: ${key}`);\n\t\t}\n\n\t\treturn cronInfos;\n\t}\n\n\tisConstruct(value: any): value is Cron<any, any, any, any, any, any> {\n\t\treturn Cron.isCron(value);\n\t}\n\n\t/**\n\t * The crons file a server entry imports.\n\t *\n\t * Shaped after `generateServerSubscribersFile`: one module, every cron, a\n\t * `setupCrons` the generated entry calls beside `setupSubscribers`.\n\t *\n\t * It picks its scheduler from what the process can reach. With a Postgres it\n\t * uses pg-boss, whose schedules live in the database — so a deployment\n\t * running four replicas fires each job once, which is the thing a timer in\n\t * every process gets wrong and does not report. With no database it falls\n\t * back to timers and says plainly that it is doing so.\n\t */\n\tprivate async generateServerCronsFile(\n\t\toutputDir: string,\n\t\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst cronsPath = join(outputDir, 'crons.ts');\n\n\t\t// Nothing to schedule, so nothing to import — the entry imports this file\n\t\t// whatever the app declares, and a project with no events must not have\n\t\t// to resolve `@geekmidas/events`.\n\t\tif (crons.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tcronsPath,\n\t\t\t\t`/**\n * Generated cron setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupCrons(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function cronsStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopCrons(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn cronsPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of crons) {\n\t\t\tconst relativePath = relative(dirname(cronsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) importsByFile.set(importPath, []);\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst entries = crons\n\t\t\t.map(({ key }) => ` { name: '${key}', cron: ${key} }`)\n\t\t\t.join(',\\n');\n\n\t\tconst content = `/**\n * Generated cron setup.\n *\n * Schedules every cron this app declares, in the process that serves it.\n *\n * The schedule lives in Postgres, through pg-boss, in the database the worker\n * named with \\`.database(db)\\`. That is what makes running several replicas\n * safe: each job fires once, where a timer in every process fires it once per\n * replica and reports nothing.\n *\n * No connection string appears here. The construct that owns the database is\n * the only thing that knows its key, and it is resolved through service\n * discovery like any other dependency.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst crons = [\n${entries}\n];\n\ntype Stoppable = { stop: () => Promise<void> | void };\nconst running: Stoppable[] = [];\n// What a worker's health check reads: the crons that cannot be scheduled, and\n// the broker connection the schedule is kept through.\nconst failed: string[] = [];\nconst connections: import('@geekmidas/events').EventConnection[] = [];\n\nexport async function setupCrons(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n if (crons.length === 0) {\n return;\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Resolved once per cron rather than per firing: registering services on\n // every tick would reconnect a database every minute.\n const prepared = [];\n for (const { name, cron } of crons) {\n try {\n const schedule = toCronExpression(cron.schedule);\n const services = cron.services.length > 0\n ? await serviceDiscovery.register(cron.services)\n : {};\n\n prepared.push({ name, cron, schedule, services });\n } catch (error) {\n // An unrepresentable schedule is a build-time mistake, and failing the\n // process for it would take the HTTP server down with it.\n logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');\n failed.push(name);\n }\n }\n\n const run = async (entry: (typeof prepared)[number]) => {\n try {\n // The cron's own function, the way its Lambda would run it — services,\n // the worker's database as \\`db\\`, its events. It used to call a\n // \\`handler\\` a Cron does not have, so every firing logged a failure.\n await runCron(entry.cron, serviceDiscovery, entry.name);\n } catch (error) {\n logger.error({ err: error, cron: entry.name }, 'Cron failed');\n }\n };\n\n // The app's one pg-boss: the events broker's, as the broker's role, in the\n // broker's schema. A server fires its own crons, and a process scheduling in\n // memory fires each job once per replica — so the schedule lives in\n // Postgres. It used to be a second pg-boss on the worker's database, as the\n // runtime role, which can neither create a schema nor use the broker's.\n const { url, devPid } = envParser\n .create((get) => ({\n url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),\n // Set by \\`gkm dev\\` on the server it starts, and by nothing deployed.\n devPid: get('GKM_DEV_PID').string().optional(),\n }))\n .parse();\n\n if (!url?.startsWith('pgboss://')) {\n // \\`gkm dev\\` on a target whose crons are infrastructure once deployed —\n // EventBridge rules on AWS — has no broker to keep a schedule in. It is one\n // process, so a timer fires each job once, which is all pg-boss is for\n // here. Only there: a deployed server firing by timer fires once per\n // replica, so outside dev this stays the error below.\n if (devPid) {\n for (const entry of prepared) {\n running.push(scheduleInProcess(entry.schedule, () => run(entry)));\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');\n }\n return;\n }\n\n logger.error(\n { crons: prepared.map(({ name }) => name) },\n 'These crons have nowhere to keep their schedule. On a server they are ' +\n 'scheduled through the pg-boss events broker ' +\n '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +\n (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),\n );\n failed.push(...prepared.map(({ name }) => name));\n return;\n }\n\n // Through the registered pg-boss driver, which the entry registers for a\n // server whose broker is pg-boss. Naming \\`@geekmidas/events/pgboss\\` here\n // made every bundle with a cron resolve pg-boss, whatever its broker.\n const { EventConnectionFactory } = await import('@geekmidas/events');\n const connection = (await EventConnectionFactory.fromConnectionString(\n url,\n )) as import('@geekmidas/events').EventConnection & { instance?: any };\n const boss = connection.instance!;\n\n // What this app declares now. Anything else under the prefix belonged to a\n // cron since renamed or deleted, and would keep firing at a handler that has\n // gone.\n //\n // The prefix is \\`cron.\\` rather than \\`cron:\\`: pg-boss accepts\n // alphanumerics, underscores, hyphens, periods and slashes in a queue name,\n // and rejects a colon outright.\n const declared = new Set(prepared.map(({ name }) => \\`cron.\\${name}\\`));\n for (const existing of await boss.getSchedules()) {\n if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {\n await boss.unschedule(existing.name);\n logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');\n }\n }\n\n for (const entry of prepared) {\n const queue = \\`cron.\\${entry.name}\\`;\n await boss.createQueue(queue);\n // UTC, so this agrees with the schedule a deploy target would have made.\n await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });\n await boss.work(queue, () => run(entry));\n\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');\n }\n\n running.push({ stop: () => connection.close() });\n connections.push(connection);\n logger.info({ count: prepared.length }, 'Crons scheduled');\n}\n\n/** The crons that cannot be scheduled, and the connection that schedules the rest. */\nexport function cronsStatus(): {\n failed: string[];\n connections: import('@geekmidas/events').EventConnection[];\n} {\n return { failed: [...failed], connections: [...connections] };\n}\n\n/**\n * Stop scheduling, let a firing in flight finish, and close the broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopCrons(): Promise<void> {\n const open = [...running];\n running.length = 0;\n connections.length = 0;\n await Promise.all(open.map((r) => r.stop()));\n}\n`;\n\n\t\tawait writeFile(cronsPath, content);\n\n\t\treturn cronsPath;\n\t}\n\n\tprivate async generateCronHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSScheduledFunction(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Queue } from '@geekmidas/constructs/queue';\nimport { provideKey } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport type { QueueInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\n/**\n * Generates the runtime for queue consumers (`worker.queue(…)`).\n *\n * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that\n * polls each queue in-process, alongside the Hono server, through the queue's\n * own connection string — pg-boss by default, SQS on the AWS emulator.\n * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed\n * by an SQS event-source mapping.\n */\nexport class QueueGenerator extends ConstructGenerator<\n\tQueue<any, any, any, any, any, any>,\n\tQueueInfo[]\n> {\n\tisConstruct(value: any): value is Queue<any, any, any, any, any, any> {\n\t\treturn Queue.isQueue(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<QueueInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst queueInfos: QueueInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// Generate queues.ts for in-process polling (even if empty, so the\n\t\t\t// server entry can always import setupQueues).\n\t\t\tawait this.generateServerQueuesFile(outputDir, constructs);\n\t\t\tlogger.log(\n\t\t\t\t`Generated server queues file with ${constructs.length} queues (polling mode)`,\n\t\t\t);\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tconst queuesDir = join(outputDir, 'queues');\n\t\tawait mkdir(queuesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateQueueHandler(\n\t\t\t\tqueuesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tqueueInfos.push({\n\t\t\t\tname: construct.name,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tbatchSize: construct.batchSize,\n\t\t\t\tfifo: construct.fifo,\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated queue handler: ${key}`);\n\t\t}\n\n\t\treturn queueInfos;\n\t}\n\n\tprivate async generateQueueHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\t\tconst importPath = relative(dirname(handlerPath), sourceFile).replace(\n\t\t\t/\\.ts$/,\n\t\t\t'.js',\n\t\t);\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaQueue(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerQueuesFile(\n\t\toutputDir: string,\n\t\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst queuesPath = join(outputDir, 'queues.ts');\n\n\t\t// Nothing to poll, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (queues.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tqueuesPath,\n\t\t\t\t`/**\n * Generated queues setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupQueues(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function queuesStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopQueues(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn queuesPath;\n\t\t}\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of queues) {\n\t\t\tconst importPath = relative(dirname(queuesPath), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each queue's consumer reaches its own queue, by the queue's own key.\n\t\tconst entries = queues\n\t\t\t.map(\n\t\t\t\t({ key, construct }) =>\n\t\t\t\t\t` { queue: ${key}, connectionKey: '${provideKey(\n\t\t\t\t\t\tconstruct.id,\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)}' },`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst content = `/**\n * Generated queue consumers setup.\n *\n * Each queue's one consumer polls its own queue, through the queue's own\n * connection string — the one its producers publish on. SQS cannot push, so\n * this is a poller on every transport: pg-boss locally by default, the SQS\n * queue on the AWS emulator.\n *\n * Deployed on Lambda, a queue's consumer is an SQS event source instead.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst queues = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\nexport async function setupQueues(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n for (const { queue, connectionKey } of queues) {\n const connectionString = process.env[connectionKey];\n if (!connectionString) {\n logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');\n failed.push(queue.name);\n continue;\n }\n\n try {\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n const eventSubscriber = await Subscriber.fromConnection(connection);\n const services = queue.services.length > 0\n ? await serviceDiscovery.register(queue.services)\n : {};\n // The queue's database — the worker's, or its own — handed over as \\`db\\`.\n const db = queue.databaseService\n ? (await serviceDiscovery.register([queue.databaseService]))[\n queue.databaseService.serviceName\n ]\n : undefined;\n\n // A queue's messages carry one type — its own name.\n await eventSubscriber.subscribe([queue.name], async (message) => {\n try {\n const validation = await queue.messageSchema['~standard'].validate(message.payload);\n if (validation.issues) {\n logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');\n return;\n }\n\n await queue.handler({\n messages: [validation.value],\n services: services,\n logger: queue.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');\n // Rethrown so the transport keeps the message for a retry.\n throw error;\n }\n });\n logger.info({ queue: queue.name }, 'Queue consumer started polling');\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');\n failed.push(queue.name);\n }\n }\n}\n\n/** The consumers that could not start, and the connections that did. */\nexport function queuesStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the messages in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopQueues(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(queuesPath, content);\n\t\treturn queuesPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Cron } from '@geekmidas/constructs/crons';\nimport type { Queue } from '@geekmidas/constructs/queue';\nimport type { Subscriber } from '@geekmidas/constructs/subscribers';\nimport type { BuildContext } from '../build/types';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport { CronGenerator } from './CronGenerator';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport type { GeneratedConstruct } from './Generator';\nimport { QueueGenerator } from './QueueGenerator';\nimport { SubscriberGenerator } from './SubscriberGenerator';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * A worker whose topic subscribers would have to be pushed to over HTTP.\n *\n * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's\n * process serves nothing but its health check. A server target's broker is\n * pg-boss, where each subscriber polls a queue of its own, so this is only\n * reached by building server images for a project that deploys to AWS — where\n * a subscriber is a Lambda instead.\n */\nexport class WorkerSubscribersNeedPush extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly subscribers: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs topic subscribers (${subscribers.join(', ')}), ` +\n\t\t\t\t`and this build's broker is SNS, which pushes each event to its ` +\n\t\t\t\t`subscriber over HTTP. A worker image serves only its health check. ` +\n\t\t\t\t`Deploy to a server target, whose broker is pg-boss and whose ` +\n\t\t\t\t`subscribers poll, or to AWS, where each subscriber is a Lambda.`,\n\t\t);\n\t\tthis.name = 'WorkerSubscribersNeedPush';\n\t}\n}\n\n/** Where a worker's generated entry lives, under an app's `.gkm/server`. */\nexport function workerEntryDir(serverDir: string, workerId: string): string {\n\treturn join(serverDir, 'workers', appKey(workerId));\n}\n\n/** The file a worker's bundle is written to, beside the server's. */\nexport function workerBundleName(workerId: string): string {\n\treturn `worker-${appKey(workerId)}.mjs`;\n}\n\nexport interface WorkerEntryInput {\n\tcontext: BuildContext;\n\t/** The worker's construct id, `Jobs`. */\n\tworkerId: string;\n\t/** The worker's own directory — see `workerEntryDir`. */\n\toutputDir: string;\n\t/** Everything built from this worker, and nothing built from another. */\n\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[];\n\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[];\n\tsubscribers: GeneratedConstruct<\n\t\tSubscriber<any, any, any, any, any, any, any>\n\t>[];\n\t/** What its process starts OpenTelemetry with — none without an edge. */\n\ttelemetry?: TelemetryContext;\n}\n\n/**\n * A Worker's production entry: the process that runs its crons, its queue\n * consumers and its topic subscribers, and answers nothing but a health check.\n *\n * It is the server's runtime without the server. The `crons.ts`, `queues.ts`\n * and `subscribers.ts` it starts are the files `gkm dev` starts — written by\n * the same generators, given only this worker's constructs — so a consumer\n * runs the same code in development and in the image. What it adds is the\n * process around them: drivers, a health check that says when a consumer or\n * the broker is down, and a shutdown that drains.\n */\nexport class WorkerGenerator {\n\tconstructor(\n\t\tprivate readonly generators = {\n\t\t\tcron: new CronGenerator(),\n\t\t\tqueue: new QueueGenerator(),\n\t\t\tsubscriber: new SubscriberGenerator(),\n\t\t},\n\t) {}\n\n\t/** Write the worker's files; returns its entry, `worker.ts`. */\n\tasync build(input: WorkerEntryInput): Promise<string> {\n\t\tconst { context, workerId, outputDir } = input;\n\n\t\tif (\n\t\t\tinput.subscribers.length > 0 &&\n\t\t\tcontext.eventsBackends?.includes('sns')\n\t\t) {\n\t\t\tthrow new WorkerSubscribersNeedPush(\n\t\t\t\tworkerId,\n\t\t\t\tinput.subscribers.map(({ key }) => key),\n\t\t\t);\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst options = { target: 'server' as const };\n\t\tawait Promise.all([\n\t\t\tthis.generators.cron.build(context, input.crons, outputDir, options),\n\t\t\tthis.generators.queue.build(context, input.queues, outputDir, options),\n\t\t\tthis.generators.subscriber.build(\n\t\t\t\tcontext,\n\t\t\t\tinput.subscribers,\n\t\t\t\toutputDir,\n\t\t\t\toptions,\n\t\t\t),\n\t\t]);\n\n\t\tawait writeFile(\n\t\t\tjoin(outputDir, 'app.ts'),\n\t\t\tworkerApp(context, workerId, outputDir),\n\t\t);\n\t\t// The worker's own edge decides, not the app's that carries it.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst entry = join(outputDir, 'worker.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\tworkerEntry(context.production?.healthCheck ?? '/health'),\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * `app.ts`: the worker's runtime — its logger and environment parser off the\n * Worker construct, the drivers its target needs, and a `startWorker` that\n * starts every cron, consumer and subscriber it owns.\n */\nfunction workerApp(\n\tcontext: BuildContext,\n\tworkerId: string,\n\toutputDir: string,\n): string {\n\tconst runtime = runtimeFor(context, outputDir, workerId);\n\n\treturn `/**\n * Generated worker runtime for ${workerId}.\n * Generated by 'gkm build --production'.\n */\nimport { setupCrons, cronsStatus, stopCrons } from './crons.js';\nimport { setupQueues, queuesStatus, stopQueues } from './queues.js';\nimport { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n// Who this worker is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};\n\nexport { logger };\n\n/** What the health check answers, and why. */\nexport interface WorkerHealth {\n healthy: boolean;\n /** The crons, queues and subscribers that could not start. */\n failed: string[];\n /** How many broker connections did not answer. */\n down: number;\n}\n\n/** Whether one broker connection answers: open, and — on pg-boss — a query. */\nasync function answers(connection: unknown): Promise<boolean> {\n const c = connection as {\n isConnected?: () => boolean;\n instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };\n };\n if (c.isConnected && !c.isConnected()) return false;\n const db = c.instance?.getDb?.();\n if (!db) return true;\n try {\n await Promise.race([\n db.executeSql('select 1'),\n new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A request to a route this worker mounted, and what it answered. */\nexport interface WorkerRequest {\n headers: Record<string, string | string[] | undefined>;\n body: string;\n /** The request's query — Mailpit's webhook carries its token there. */\n query?: URLSearchParams;\n}\nexport interface WorkerAnswer {\n status: number;\n body: unknown;\n}\n\n// The routes something pushes to: an SNS subscriber's, and the one a local\n// object store posts a bucket's events to. Mounted by the subscribers, served\n// by the entry's HTTP server beside the health check.\nconst routes = new Map<string, (c: any) => unknown>();\nconst app = {\n post: (path: string, handler: (c: any) => unknown) => {\n routes.set(path, handler);\n },\n};\n\n/** Run one mounted route, as the subscribers' handlers expect to be called. */\nasync function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {\n const handler = routes.get(path);\n if (!handler) return undefined;\n let answer: WorkerAnswer | undefined;\n const c = {\n req: {\n text: async () => request.body,\n query: (name: string) => request.query?.get(name) ?? undefined,\n header: (name: string) => {\n const value = request.headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n },\n },\n json: (body: unknown, status = 200) => {\n answer = { status, body };\n return answer;\n },\n };\n await handler(c);\n return answer ?? { status: 204, body: null };\n}\n\n/** Start everything this worker runs. */\nexport async function startWorker(): Promise<{\n health: () => Promise<WorkerHealth>;\n stop: () => Promise<void>;\n route: typeof route;\n /** Subscribe the pushed routes, once the server answers on \\`port\\`. */\n subscribeForPush: (port: number) => Promise<void>;\n}> {\n const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue consumers');\n });\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];\n\n return {\n route,\n subscribeForPush,\n async health() {\n const all = statuses();\n const failed = all.flatMap((s) => s.failed);\n const alive = await Promise.all(\n all.flatMap((s) => s.connections as unknown[]).map(answers),\n );\n const down = alive.filter((ok) => !ok).length;\n return { healthy: failed.length === 0 && down === 0, failed, down };\n },\n // Each stops pulling, waits for what it has in flight, and closes its\n // broker connection. Together, so one slow handler does not hold the\n // others' connections open.\n async stop() {\n await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);\n },\n };\n}\n`;\n}\n\n/**\n * `worker.ts`: the process. Health first, so the container answers while the\n * consumers connect; then the worker; then a shutdown that drains.\n */\nfunction workerEntry(healthCheck: string): string {\n\treturn `#!/usr/bin/env node\n/**\n * Production worker entry point.\n * Generated by 'gkm build --production'.\n *\n * Runs this worker's crons, queue consumers and topic subscribers, and serves\n * its health check: ${healthCheck}, on PORT — 200 when every consumer started\n * and every broker connection answers, 503 otherwise. Beside it, on the same\n * port, the POST routes its subscribers mounted: where a local object store\n * posts a bucket's events.\n *\n * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers\n * in flight finish, closes its broker connections and database pools, and\n * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's\n * 10s stop timeout).\n */\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\n\n${startTelemetryCode([healthCheck])}\nconst { startWorker, logger } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nlet worker: Awaited<ReturnType<typeof startWorker>> | undefined;\nlet stopping = false;\n\nconst server = createServer((req, res) => {\n // Parsed once: the path routes, the query goes to the route.\n const url = new URL(req.url ?? '/', 'http://localhost');\n const path = url.pathname;\n const answer = (status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json' });\n res.end(JSON.stringify(body));\n };\n\n // A route a subscriber mounted: what SNS pushes to, or what a local object\n // store posts a bucket's events to. Refused while starting or stopping, so\n // the sender keeps the message and sends it again.\n if (req.method === 'POST') {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk) => {\n body += chunk;\n });\n req.on('end', () => {\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(\n (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),\n (error) => {\n logger.error({ err: error, path }, 'Route failed');\n answer(500, { status: 'failed' });\n },\n );\n });\n return;\n }\n\n if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {\n res.writeHead(404).end();\n return;\n }\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.health().then(\n (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),\n (error) => answer(503, { status: 'unhealthy', error: String(error) }),\n );\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n\n // Nothing new is pulled or scheduled; what is in flight finishes.\n await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));\n // Then what the handlers used: database pools.\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n server.close();\n logger.info('Worker stopped');\n process.exit(0);\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nworker = await startWorker();\nlogger.info({ port }, 'Worker started');\nawait worker.subscribeForPush(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n});\n`;\n}\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport {\n\ttype ConstructManifest,\n\tprovideKey,\n\tpublicEnvFor,\n} from '@geekmidas/manifest';\nimport {\n\ttype ProcessorUnit,\n\tprocessorUnits,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadWorkspaceConfig } from '../config';\nimport { GkmError } from '../errors';\nimport { processorBundleName } from '../generators/ProcessorGenerator.js';\nimport { workerBundleName } from '../generators/WorkerGenerator.js';\nimport { output } from '../output';\nimport { dockerfileOf } from '../reconcile/apps.js';\nimport { COMPOSE_PATH } from '../reconcile/index.js';\nimport { reconcileWorkspace } from '../reconcile/workspace.js';\nimport { run } from '../run';\nimport { getPublicUrlArgNames } from '../target/dokploy/domain.js';\nimport { siteClientTelemetry } from '../telemetry/edges.js';\nimport type { CacheBackend, GkmConfig } from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport { validateImageRef } from './imageRef';\nimport { appImageOptions, type ImageLayout, imageLayout } from './layout';\nimport {\n\tgenerateBackendDockerfile,\n\tgenerateDockerignore,\n\tgenerateEntryDockerfile,\n\tgenerateNextjsDockerfile,\n\tgenerateNodeWebDockerfile,\n\tgenerateProcessorDockerfile,\n\tgenerateViteStaticDockerfile,\n\tgenerateWorkerDockerfile,\n\tPROCESSOR_PORT,\n\tresolveDockerConfig,\n\tWORKER_PORT,\n} from './templates';\n\nexport { ImageRefInvalid, validateImageRef } from './imageRef';\nexport {\n\tappImageOptions,\n\tcomposeBuildPaths,\n\tfromBuildRoot,\n\ttype ImageLayout,\n\timageLayout,\n\tMonorepoNeedsTurbo,\n} from './layout';\nexport {\n\tdetectPackageManager,\n\tfindBuildRoot,\n\tfindLockfilePath,\n\thasTurboConfig,\n\tisMonorepo,\n} from './templates';\n\n// Through `output`, so a deploy run that generates a Dockerfile hears it.\nconst logger = output;\n\n/** `docker build` failed; what docker printed above says why. */\nexport class DockerBuildFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerBuildFailed';\n\t}\n}\n\n/** `docker push` failed — usually the registry login or its permissions. */\nexport class DockerPushFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerPushFailed';\n\t}\n}\n\n/** `gkm docker --push` was asked for with nowhere to push to. */\nexport class PushNeedsRegistry extends GkmError {\n\tconstructor(readonly imageName: string) {\n\t\tsuper(\n\t\t\t`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`,\n\t\t);\n\t\tthis.name = 'PushNeedsRegistry';\n\t}\n}\n\nexport interface DockerOptions {\n\t/** Build each app's image after generating files */\n\tbuild?: boolean;\n\t/** Push the images to the registry after building */\n\tpush?: boolean;\n\t/** Image tag (default: 'latest') */\n\ttag?: string;\n\t/** Container registry URL */\n\tregistry?: string;\n\t/**\n\t * The directory to generate for — an app's own, when a deploy builds it.\n\t * Defaults to the process's working directory.\n\t */\n\tcwd?: string;\n\t/**\n\t * The stage the images are for: a site's clients trace at its sample\n\t * rate. The local stage when absent.\n\t */\n\tstage?: string;\n}\n\n/**\n * Docker command implementation: one Dockerfile per deployable app, each\n * building its image inside Docker from a turbo-pruned slice of the build\n * root — nothing is built on the host — plus the build root's\n * `.dockerignore` and `docker-compose.constructs.yml`.\n */\nexport async function dockerCommand(\n\toptions: DockerOptions,\n): Promise<WorkspaceDockerResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst loaded = await loadWorkspaceConfig(cwd);\n\n\t// A single-app config is a workspace of one app at its root; the image is\n\t// named the way its `docker` block says.\n\tconst names: Record<string, string> =\n\t\tloaded.type === 'single'\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.keys(loaded.workspace.apps).map((name) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tresolveDockerConfig(loaded.raw as GkmConfig).imageName,\n\t\t\t\t\t]),\n\t\t\t\t)\n\t\t\t: {};\n\n\tconst result = await workspaceDockerCommand(\n\t\tloaded.workspace,\n\t\tloaded.manifest,\n\t\tnames,\n\t\tloaded.background,\n\t\toptions.stage,\n\t);\n\n\tif (options.build) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait buildDockerImage(app, result.buildRoot, options);\n\t\t}\n\t}\n\tif (options.push) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait pushDockerImage(app.imageName, options, result.buildRoot);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Build one app's image, from the build root.\n * Uses BuildKit for cache mount support\n */\nasync function buildDockerImage(\n\tapp: AppDockerResult,\n\tbuildRoot: string,\n\toptions: DockerOptions,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\t// Before anything runs: a ref docker would misread is refused by name.\n\tconst fullImageName = validateImageRef(\n\t\tregistry\n\t\t\t? `${registry}/${app.imageName}:${tag}`\n\t\t\t: `${app.imageName}:${tag}`,\n\t);\n\n\tlogger.log(`\\n🐳 Building Docker image: ${fullImageName}`);\n\n\ttry {\n\t\t// An argument array, so nothing in the ref is read by a shell, and\n\t\t// `--tag=` so it cannot be read as a flag.\n\t\tawait run(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'build',\n\t\t\t\t`--file=${relative(buildRoot, app.dockerfile)}`,\n\t\t\t\t`--tag=${fullImageName}`,\n\t\t\t\t'.',\n\t\t\t],\n\t\t\t{\n\t\t\t\tcwd: buildRoot,\n\t\t\t\t// BuildKit, for the templates' `RUN --mount=type=cache`.\n\t\t\t\tenv: { ...process.env, DOCKER_BUILDKIT: '1' },\n\t\t\t},\n\t\t);\n\t\tlogger.log(`✅ Docker image built: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerBuildFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Push Docker image to registry\n */\nasync function pushDockerImage(\n\timageName: string,\n\toptions: DockerOptions,\n\tcwd: string,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\tif (!registry) {\n\t\tthrow new PushNeedsRegistry(imageName);\n\t}\n\n\tconst fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);\n\n\tlogger.log(`\\n🚀 Pushing Docker image: ${fullImageName}`);\n\n\ttry {\n\t\tawait run('docker', ['push', fullImageName], { cwd });\n\t\tlogger.log(`✅ Docker image pushed: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerPushFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Result of generating Docker files for a single app in a workspace.\n */\nexport interface AppDockerResult {\n\tappName: string;\n\ttype: 'backend' | 'web' | 'mobile';\n\t/** The Dockerfile, absolute. */\n\tdockerfile: string;\n\timageName: string;\n}\n\n/**\n * Result of workspace docker command.\n */\nexport interface WorkspaceDockerResult {\n\tapps: AppDockerResult[];\n\tdockerCompose: string;\n\tdockerignore: string;\n\t/** Every image's build context, absolute. */\n\tbuildRoot: string;\n}\n\n/**\n * Generate Dockerfiles for all apps in a workspace.\n * @internal Exported for testing\n */\nexport async function workspaceDockerCommand(\n\tworkspace: NormalizedWorkspace,\n\t/** What the workspace declares — where a site's public keys come from. */\n\tmanifest?: ConstructManifest,\n\t/** Image names other than the app's own. */\n\timageNames: Readonly<Record<string, string>> = {},\n\t/** Each Worker's files, from discovery — which app each is built from. */\n\tbackground: Readonly<Record<string, readonly string[]>> = {},\n\t/** The stage a site's clients trace at the rate of — local when absent. */\n\tstage?: string,\n): Promise<WorkspaceDockerResult> {\n\tconst results: AppDockerResult[] = [];\n\tconst layout = imageLayout(workspace);\n\n\tlogger.log(`\\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);\n\tlogger.log(` Build root: ${layout.buildRoot}`);\n\tlogger.log(\n\t\t` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ''}, turbo@${layout.tools.turboVersion}`,\n\t);\n\n\tfor (const [appName, app] of Object.entries(workspace.apps)) {\n\t\t// Mobile apps deploy via their own toolchain (e.g. EAS Build for Expo)\n\t\t// — no Docker image is produced.\n\t\tif (app.type === 'mobile') {\n\t\t\tlogger.log(\n\t\t\t\t`\\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst buildType = app.entry ? 'entry' : app.type;\n\t\tlogger.log(`\\n 📄 Generating Dockerfile for ${appName} (${buildType})`);\n\n\t\tconst dockerfile = appDockerfile(appName, app, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tapps: workspace.apps,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t\tworkspace,\n\t\t\t...(stage ? { stage } : {}),\n\t\t});\n\n\t\tconst path = dockerfileOf(appName, app.path);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName,\n\t\t\ttype: app.type,\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[appName] ?? appName,\n\t\t});\n\t}\n\n\t// Each Worker with background work: an image of its own, built from the\n\t// app whose build writes its entry.\n\tfor (const worker of manifest\n\t\t? workerUnits(workspace, manifest, background)\n\t\t: []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`,\n\t\t);\n\t\tconst dockerfile = workerDockerfile(worker, workspace.apps[worker.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\t// Always named for the worker: an app at the root has the bare\n\t\t// `Dockerfile`, which this must not overwrite.\n\t\tconst path = workerDockerfileOf(worker.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: worker.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[worker.name] ?? worker.name,\n\t\t});\n\t}\n\n\t// Each file server's processors: an image of their own, built from the\n\t// app whose build writes their entry.\n\tfor (const unit of manifest ? processorUnits(workspace, manifest) : []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`,\n\t\t);\n\t\tconst dockerfile = processorDockerfile(unit, workspace.apps[unit.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\tconst path = workerDockerfileOf(unit.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: unit.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[unit.name] ?? unit.name,\n\t\t});\n\t}\n\n\tconst dockerignorePath = await ensureDockerignore(layout.buildRoot);\n\tlogger.log(`\\n Ensured: ${dockerignorePath}`);\n\n\tconst composePath = await writeConstructsCompose(workspace);\n\n\t// Summary\n\tlogger.log(\n\t\t`\\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`,\n\t);\n\tlogger.log(`\\n📋 Build commands (from ${layout.buildRoot}):`);\n\tfor (const result of results) {\n\t\tconst icon =\n\t\t\tresult.type === 'backend' ? '⚙️' : result.type === 'mobile' ? '📱' : '🌐';\n\t\tlogger.log(\n\t\t\t` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`,\n\t\t);\n\t}\n\tprintRunInstructions(workspace);\n\n\treturn {\n\t\tapps: results,\n\t\tdockerCompose: composePath,\n\t\tdockerignore: dockerignorePath,\n\t\tbuildRoot: layout.buildRoot,\n\t};\n}\n\n/**\n * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,\n * a backend with its own entry bundled by esbuild, or a site by its\n * framework. The one choice every builder of images makes.\n */\nexport function appDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/**\n\t\t * Every app in the workspace, so a site's image knows the backends whose\n\t\t * clients it generates.\n\t\t */\n\t\tapps?: Readonly<Record<string, NormalizedAppConfig>>;\n\t\tmanifest?: ConstructManifest;\n\t\t/** The workspace's stages and `deploy.telemetry`, for a site's clients. */\n\t\tworkspace?: Pick<NormalizedWorkspace, 'stages' | 'deploy'>;\n\t\t/** A site's public keys, when the caller resolved them itself. */\n\t\tpublicUrlArgs?: string[];\n\t\t/**\n\t\t * The cache backend a gkm backend's entry registers, where it is not the\n\t\t * deploy target's — the compose stack's own Redis.\n\t\t */\n\t\tcache?: CacheBackend;\n\t\t/**\n\t\t * The stage whose sample rate a site's clients trace at — the local\n\t\t * stage when absent.\n\t\t */\n\t\tstage?: string;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tappName,\n\t\tapp,\n\t\toptions.workspaceRoot,\n\t\toptions.apps,\n\t\tapp.type === 'web' && options.manifest && options.workspace\n\t\t\t? siteClientTelemetry(\n\t\t\t\t\toptions.manifest,\n\t\t\t\t\tappName,\n\t\t\t\t\toptions.workspace,\n\t\t\t\t\toptions.stage,\n\t\t\t\t)\n\t\t\t: undefined,\n\t);\n\n\tif (app.type === 'web') {\n\t\treturn siteDockerfile(appName, app, {\n\t\t\timage,\n\t\t\t...(options.manifest ? { manifest: options.manifest } : {}),\n\t\t\t...(options.publicUrlArgs\n\t\t\t\t? { publicUrlArgs: options.publicUrlArgs }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\tif (app.entry) {\n\t\treturn generateEntryDockerfile({\n\t\t\t...image,\n\t\t\tentry: app.entry,\n\t\t\thealthCheckPath: '/health',\n\t\t});\n\t}\n\treturn generateBackendDockerfile({\n\t\t...image,\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/** Where `gkm docker` writes a worker's Dockerfile. */\nexport function workerDockerfileOf(worker: string): string {\n\treturn `.gkm/docker/Dockerfile.${worker}`;\n}\n\n/**\n * A Worker's Dockerfile: its host app's build, and the worker's bundle as the\n * runner — see `generateWorkerDockerfile`.\n */\nexport function workerDockerfile(\n\tworker: WorkerUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/** As {@link appDockerfile}'s: the cache backend its entry registers. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tworker.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateWorkerDockerfile({\n\t\t...image,\n\t\timageName: worker.name,\n\t\tport: WORKER_PORT,\n\t\tworker: worker.id,\n\t\tbundle: workerBundleName(worker.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A file server's processor unit's Dockerfile: its host app's build, and the\n * unit's bundle as the runner, with its processors' native packages\n * installed beside it — see `generateProcessorDockerfile`.\n */\nexport function processorDockerfile(\n\tunit: ProcessorUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tunit.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateProcessorDockerfile({\n\t\t...image,\n\t\timageName: unit.name,\n\t\tport: PROCESSOR_PORT,\n\t\tfileServer: unit.id,\n\t\tbundle: processorBundleName(unit.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A site's Dockerfile, with an `ARG` for every key its bundler inlines.\n *\n * The keys come from the site's declaration where there is one — every\n * public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an\n * `ARG` the Dockerfile does not declare is a build argument the build drops,\n * leaving the bundle with an empty URL.\n */\nexport function siteDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\timage: ReturnType<typeof appImageOptions>;\n\t\tmanifest?: ConstructManifest;\n\t\tpublicUrlArgs?: string[];\n\t},\n): string {\n\tconst declared = options.manifest\n\t\t? Object.entries(options.manifest).find(\n\t\t\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t\t\t)?.[1]\n\t\t: undefined;\n\tconst publicUrlArgs =\n\t\toptions.publicUrlArgs ??\n\t\t(declared?.kind === 'site' && options.manifest\n\t\t\t? [\n\t\t\t\t\t// Its own address under its own name, for server code that runs\n\t\t\t\t\t// at build — what `publicBuildValues` hands every image build.\n\t\t\t\t\tprovideKey(declared.id, 'url'),\n\t\t\t\t\t...Object.keys(publicEnvFor(declared, options.manifest)),\n\t\t\t\t]\n\t\t\t: getPublicUrlArgNames(app));\n\n\tconst webOpts = {\n\t\t...options.image,\n\t\tpublicUrlArgs,\n\t\t// Built against its stage's running APIs, so not offline.\n\t\t...(declared?.kind === 'site' && declared.prerender === 'stage'\n\t\t\t? { prerender: true }\n\t\t\t: {}),\n\t};\n\n\tswitch (app.framework) {\n\t\tcase 'vite':\n\t\t\treturn generateViteStaticDockerfile(webOpts);\n\t\tcase 'tanstack-start':\n\t\tcase 'remix':\n\t\t\treturn generateNodeWebDockerfile(webOpts);\n\t\tdefault:\n\t\t\t// nextjs (and any unspecified web framework — schema requires a valid\n\t\t\t// framework, so this is just a default).\n\t\t\treturn generateNextjsDockerfile(webOpts);\n\t}\n}\n\n/**\n * What a build root's `.dockerignore` must leave out of every image's\n * context: dependencies installed for another platform, anything built on the\n * host (every image builds from source), git, and gkm's own output —\n * `.gkm/compose`'s env files hold a stage's secrets.\n */\nconst REQUIRED_IGNORES = [\n\t'**/node_modules',\n\t'.git',\n\t'**/dist',\n\t'**/.next',\n\t'**/.turbo',\n\t'**/.gkm',\n\t'**/.gkm/compose',\n];\n\n/**\n * Make sure the build root's `.dockerignore` leaves out what no image may\n * hold: written whole where there is none, and each missing line appended to\n * one the project keeps.\n */\nexport async function ensureDockerignore(buildRoot: string): Promise<string> {\n\tconst path = join(buildRoot, '.dockerignore');\n\tif (!existsSync(path)) {\n\t\tawait writeFile(path, generateDockerignore());\n\t\treturn path;\n\t}\n\n\tconst current = await readFile(path, 'utf-8');\n\tconst lines = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n\tconst missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));\n\tif (missing.length === 0) return path;\n\n\tawait appendFile(\n\t\tpath,\n\t\t`${current.endsWith('\\n') || current === '' ? '' : '\\n'}\\n# gkm: images build from source, and a stack's env files hold its secrets\\n${missing.join('\\n')}\\n`,\n\t);\n\treturn path;\n}\n\n/**\n * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with\n * the apps beside the containers their constructs derive.\n *\n * Through reconcile rather than a second generator, so what `gkm docker`\n * describes and what `gkm dev` runs cannot disagree. Nothing is started.\n */\nasync function writeConstructsCompose(\n\tworkspace: NormalizedWorkspace,\n): Promise<string> {\n\tawait reconcileWorkspace(workspace, {\n\t\tstage: workspace.stages.local,\n\t\tstart: false,\n\t});\n\tlogger.log(` Generated: ${COMPOSE_PATH} (project root)`);\n\treturn join(workspace.root, COMPOSE_PATH);\n}\n\nfunction printRunInstructions(workspace: NormalizedWorkspace): void {\n\tconst project = existsSync(join(workspace.root, 'docker-compose.yml'))\n\t\t? ' -f docker-compose.yml'\n\t\t: '';\n\tlogger.log('\\n📋 Run everything (the apps sit behind the \"apps\" profile):');\n\tlogger.log(\n\t\t' gkm setup # starts the containers and creates what they hold',\n\t);\n\tlogger.log(\n\t\t` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,mBAAmB;AACzB,MAAM,SAAS,GAAG,iBAAiB,QAAQ,iBAAiB;AAC5D,MAAM,iBAAiB;AAKvB,MAAM,YAAY,IAAI,OACrB,OAAO,OAAO,KAAK,eAAe,MAAM,eAAe,uGACxD;;AAGA,MAAM,kBAAkB;;AAGxB,IAAa,kBAAb,cAAqCA,eAAAA,SAAS;CACxB;CAArB,YAAY,KAAsB;EACjC,MACC,IAAI,IAAI,0QACT;EAHoB,KAAA,MAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,iBAAiB,KAAqB;CACrD,MAAM,OAAO,IAAI,MAAM,GAAG,CAA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;;;;;;;AASA,eAAe,uBACd,WACkB;CAClB,MAAMC,aAAAA,mBAAmB,WAAW;EACnC,OAAO,UAAU,OAAO;EACxB,OAAO;CACR,CAAC;CACD,OAAO,IAAI,iBAAiBpB,aAAAA,aAAa,gBAAgB;CACzD,QAAA,GAAON,UAAAA,KAAAA,CAAK,UAAU,MAAMM,aAAAA,YAAY;AACzC;AAEA,SAAS,qBAAqB,WAAsC;CACnE,MAAM,WAAA,GAAUgB,QAAAA,WAAAA,EAAAA,GAAWtB,UAAAA,KAAAA,CAAK,UAAU,MAAM,oBAAoB,CAAC,IAClE,2BACA;CACH,OAAO,IAAI,iEAA+D;CAC1E,OAAO,IACN,mEACD;CACA,OAAO,IACN,wBAAwBM,aAAAA,eAAe,QAAQ,2BAChD;AACD"}
|
|
1
|
+
{"version":3,"file":"docker-BficHJMS.cjs","names":["GkmError","join","processorUnitName","ConstructGenerator","Processor","mkdir","relative","dirname","writeFile","PROCESSORS_DEV_PREFIX","writeTelemetryModule","startTelemetryCode","PROCESSOR_ORIGIN_SECRET_ENV","ORIGIN_VERIFY_HEADER","ConstructGenerator","join","mkdir","relative","Cron","writeFile","dirname","runtimeFor","ConstructGenerator","Queue","join","mkdir","relative","dirname","runtimeFor","writeFile","provideKey","GkmError","join","appKey","SubscriberGenerator","mkdir","writeFile","writeTelemetryModule","runtimeFor","startTelemetryCode","output","GkmError","loadWorkspaceConfig","resolveDockerConfig","run","relative","imageLayout","dockerfileOf","join","mkdir","dirname","writeFile","workerUnits","processorUnits","COMPOSE_PATH","appImageOptions","siteClientTelemetry","generateEntryDockerfile","generateBackendDockerfile","generateWorkerDockerfile","WORKER_PORT","generateProcessorDockerfile","PROCESSOR_PORT","appKey","provideKey","publicEnvFor","getPublicUrlArgNames","generateViteStaticDockerfile","generateNodeWebDockerfile","generateNextjsDockerfile","existsSync","generateDockerignore","readFile","appendFile","reconcileWorkspace"],"sources":["../src/docker/imageRef.ts","../src/generators/ProcessorGenerator.ts","../src/generators/CronGenerator.ts","../src/generators/QueueGenerator.ts","../src/generators/WorkerGenerator.ts","../src/docker/index.ts"],"sourcesContent":["/**\n * An image reference, checked before it reaches `docker`.\n *\n * The parts come from the workspace — a registry in `gkm.config.ts`, an image\n * name from the project, a tag from `--tag` — and an argument array already\n * keeps them out of a shell. What it cannot do is stop `docker` reading a value\n * that starts with `-` as one of its own flags, so a ref is held to Docker's\n * own grammar (distribution/reference) and anything else is refused by name\n * before a build starts.\n */\n\nimport { GkmError } from '../errors';\n\nconst DOMAIN_COMPONENT = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])';\nconst DOMAIN = `${DOMAIN_COMPONENT}(?:\\\\.${DOMAIN_COMPONENT})*(?::[0-9]+)?`;\nconst PATH_COMPONENT = '[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*';\nconst TAG = '[\\\\w][\\\\w.-]{0,127}';\nconst DIGEST =\n\t'[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}';\n\nconst REFERENCE = new RegExp(\n\t`^(?:${DOMAIN}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*(?::${TAG})?(?:@${DIGEST})?$`,\n);\n\n/** Docker refuses a repository name longer than this. */\nconst MAX_NAME_LENGTH = 255;\n\n/** A value that is not an image reference was about to be built or pushed. */\nexport class ImageRefInvalid extends GkmError {\n\tconstructor(readonly ref: string) {\n\t\tsuper(\n\t\t\t`'${ref}' is not a valid image reference. An image is \\`[registry/]name[:tag]\\`: the name lowercase letters, digits and . _ - separators, the tag up to 128 of letters, digits, _ . and -, not starting with . or -. Check docker.registry in gkm.config.ts and the --tag passed.`,\n\t\t);\n\t\tthis.name = 'ImageRefInvalid';\n\t}\n}\n\n/** Throw {@link ImageRefInvalid} unless `ref` is a Docker image reference. */\nexport function validateImageRef(ref: string): string {\n\tconst name = ref.split('@')[0]!.replace(/:[\\w][\\w.-]*$/, '');\n\tif (!REFERENCE.test(ref) || name.length > MAX_NAME_LENGTH) {\n\t\tthrow new ImageRefInvalid(ref);\n\t}\n\treturn ref;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Processor } from '@geekmidas/constructs/processors';\nimport type { ProcessorInfo } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport { processorUnitName } from '../build/workers';\nimport {\n\tORIGIN_VERIFY_HEADER,\n\tPROCESSOR_ORIGIN_SECRET_ENV,\n} from '../providers/processorOrigin';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport { PROCESSORS_DEV_PREFIX } from './processorRoute';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\ntype AnyProcessor = Processor<string, any, any, any>;\n\n/** Where a file server's processor entry lives, under an app's `.gkm/server`. */\nexport function processorEntryDir(\n\tserverDir: string,\n\tfileServerId: string,\n): string {\n\treturn join(serverDir, 'processors', processorUnitName(fileServerId));\n}\n\n/** The file its bundle is written to, beside the server's. */\nexport function processorBundleName(fileServerId: string): string {\n\treturn `${processorUnitName(fileServerId)}.mjs`;\n}\n\n/**\n * A file server's processors, as the build generates them.\n *\n * On AWS each is a Lambda behind a function URL — the CDN's origin for its\n * pattern. On a server they are one process per file server, the processor\n * unit (see {@link ProcessorGenerator.buildEntry}), so the `server` target\n * generates nothing per processor here.\n */\nexport class ProcessorGenerator extends ConstructGenerator<\n\tAnyProcessor,\n\tProcessorInfo[]\n> {\n\tisConstruct(value: unknown): value is AnyProcessor {\n\t\treturn Processor.isProcessor(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<AnyProcessor>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<ProcessorInfo[]> {\n\t\tif ((options?.target ?? 'aws') !== 'aws' || constructs.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst dir = join(outputDir, 'processors');\n\t\tawait mkdir(dir, { recursive: true });\n\n\t\tconst infos: ProcessorInfo[] = [];\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst file = join(dir, `${key}.ts`);\n\t\t\tconst importPath = relative(dirname(file), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tawait writeFile(\n\t\t\t\tfile,\n\t\t\t\t`import { AWSLambdaProcessor } from '@geekmidas/constructs/processors';\nimport { ${key} } from '${importPath}';\n${context.storageDrivers?.imports ?? ''}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaProcessor(${key});\n\nexport const handler = adapter.handler;\n`,\n\t\t\t);\n\t\t\tinfos.push(\n\t\t\t\tawait processorInfo(\n\t\t\t\t\tkey,\n\t\t\t\t\tconstruct,\n\t\t\t\t\trelative(options?.root ?? process.cwd(), file).replace(\n\t\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t\t'.handler',\n\t\t\t\t\t),\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn infos;\n\t}\n\n\t/**\n\t * `gkm dev`'s half: `processors.ts` beside the dev server's app, mounting\n\t * each file server's processors under `/__gkm/processors/<FileServer>`.\n\t * The local edge sends each pattern on the file server's host there, so\n\t * `processedUrl()` answers locally as it does deployed.\n\t *\n\t * In the dev server's own process rather than a unit of its own: locally\n\t * there is no CPU to protect, and the dev server already reloads on change.\n\t */\n\tasync buildDev(\n\t\toutputDir: string,\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst file = join(outputDir, 'processors.ts');\n\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\t\tconst byServer = new Map<string, string[]>();\n\t\tfor (const { key, construct } of processors) {\n\t\t\tbyServer.set(construct.surfaceId, [\n\t\t\t\t...(byServer.get(construct.surfaceId) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst units = [...byServer.entries()]\n\t\t\t.map(([id, keys]) => ` ${JSON.stringify(id)}: [${keys.join(', ')}],`)\n\t\t\t.join('\\n');\n\n\t\tawait writeFile(\n\t\t\tfile,\n\t\t\t`/**\n * Generated processors setup for \\`gkm dev\\`.\n *\n * Each file server's processors, under ${PROCESSORS_DEV_PREFIX}<FileServer>: the\n * local edge rewrites each processor pattern on the file server's host here.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${imports}\n\nexport function setupProcessors(\n app: { all: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n): void {\n const units: Record<string, ReturnType<typeof processorServer>> = Object.fromEntries(\n Object.entries({\n${units}\n }).map(([id, processors]) => [id, processorServer(processors, envParser)]),\n );\n\n app.all('${PROCESSORS_DEV_PREFIX}:server/*', async (c: any) => {\n const server = c.req.param('server') as string;\n const serve = units[server];\n if (!serve) return c.notFound();\n const path = c.req.path.slice(\\`${PROCESSORS_DEV_PREFIX}\\${server}\\`.length) || '/';\n const response = await serve({ method: c.req.method, path });\n if (!response) {\n return new Response(null, {\n status: 404,\n headers: { 'cache-control': 'public, max-age=60' },\n });\n }\n return new Response(c.req.method === 'HEAD' ? null : response.body, {\n status: response.status,\n headers: response.headers,\n });\n });\n}\n`,\n\t\t);\n\t\treturn file;\n\t}\n\n\t/**\n\t * A file server's processor unit: one process answering each of its\n\t * processors' patterns, and `/health`. Returns its entry, `processors.ts`.\n\t *\n\t * Its own process because making a derivative is CPU-bound — a resize\n\t * spike in the API's process would be every request's latency.\n\t */\n\tasync buildEntry(input: {\n\t\tcontext: BuildContext;\n\t\tfileServerId: string;\n\t\toutputDir: string;\n\t\tprocessors: GeneratedConstruct<AnyProcessor>[];\n\t\t/** From the file server's edge to a `Telemetry` node, when it has one. */\n\t\ttelemetry?: TelemetryContext;\n\t}): Promise<string> {\n\t\tconst { context, outputDir, processors } = input;\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\t// The file server's own edge decides; without one the module loads\n\t\t// nothing, and the entry's start-up is the same shape either way.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst healthCheck = context.production?.healthCheck ?? '/health';\n\t\tconst imports = processors\n\t\t\t.map(({ key, path }) => {\n\t\t\t\tconst specifier = relative(outputDir, path.absolute).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.js',\n\t\t\t\t);\n\t\t\t\treturn `import { ${key} } from '${specifier.startsWith('.') ? specifier : `./${specifier}`}';`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\tconst entry = join(outputDir, 'processors.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\t`#!/usr/bin/env node\n/**\n * Production entry for ${input.fileServerId}'s processors.\n * Generated by 'gkm build --production'.\n *\n * Answers each processor's pattern, and ${healthCheck} on PORT. The edge\n * routes only those patterns here; everything else on the file server's\n * domain is the bucket.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\nimport { processorServer } from '@geekmidas/constructs/processors';\n${context.storageDrivers?.imports ?? ''}\n${imports}\n\n${startTelemetryCode([healthCheck])}\n${context.storageDrivers?.setup ? `// The entry point registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(processorUnitName(input.fileServerId))};\n\nconst processors = [${processors.map(({ key }) => key).join(', ')}];\nconst serve = processorServer(processors);\nconst port = Number(process.env.PORT) || 3000;\nlet stopping = false;\n\n${input.telemetry ? REQUEST_SPANS : NO_REQUEST_SPANS}\n// Where the CDN fronts this unit, the secret it adds to every request: one\n// without it is refused here, whatever the edge in front did or could not.\nconst originSecret = process.env.${PROCESSOR_ORIGIN_SECRET_ENV}\n ? Buffer.from(process.env.${PROCESSOR_ORIGIN_SECRET_ENV})\n : undefined;\nconst fromOrigin = (header: string | string[] | undefined) => {\n if (!originSecret) return true;\n const given = Buffer.from(typeof header === 'string' ? header : '');\n return given.length === originSecret.length && timingSafeEqual(given, originSecret);\n};\n\nconst server = createServer(async (req, res) => {\n const method = req.method ?? 'GET';\n const path = (req.url ?? '/').split('?')[0] ?? '/';\n if (path === ${JSON.stringify(healthCheck)}) {\n res.writeHead(stopping ? 503 : 200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: stopping ? 'stopping' : 'ok' }));\n return;\n }\n if (!fromOrigin(req.headers[${JSON.stringify(ORIGIN_VERIFY_HEADER.toLowerCase())}])) {\n res.writeHead(403, { 'cache-control': 'no-store' }).end();\n return;\n }\n await traced(method, path, async () => {\n try {\n const response = await serve({ method, path });\n if (!response) {\n res.writeHead(404, { 'cache-control': 'public, max-age=60' }).end();\n return 404;\n }\n res.writeHead(response.status, response.headers);\n res.end(method === 'HEAD' ? undefined : response.body);\n return response.status;\n } catch (error) {\n console.error(error);\n res.writeHead(500, { 'cache-control': 'no-store' }).end();\n return 500;\n }\n });\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n setTimeout(() => process.exit(1), Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000).unref();\n server.close();\n await runShutdownHooks((error) => console.error(error));\n process.exit(0);\n};\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n`,\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * A SERVER span per request, once telemetry has started — opened by the unit\n * rather than by hooking node:http, which sees nothing inside a bundle. Named\n * after the processor's pattern, never the key, which has no bound.\n *\n * Only in an entry whose file server has a `Telemetry` node: the bundle\n * follows the import, and an app without one need not install the API.\n */\nconst REQUEST_SPANS = `const tracing = requestSpans ? await import('@opentelemetry/api') : undefined;\nconst routeOf = (path: string) =>\n processors.find((processor) => path.startsWith(processor.prefix))?.pattern;\n\nasync function traced(\n method: string,\n path: string,\n run: () => Promise<number>,\n): Promise<void> {\n if (!tracing) {\n await run();\n return;\n }\n const route = routeOf(path);\n await tracing.trace.getTracer('@geekmidas/processors').startActiveSpan(\n route ? \\`\\${method} \\${route}\\` : method,\n {\n kind: tracing.SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': path,\n ...(route ? { 'http.route': route } : {}),\n },\n },\n async (span) => {\n try {\n const status = await run();\n span.setAttribute('http.response.status_code', status);\n if (status >= 500) span.setStatus({ code: tracing.SpanStatusCode.ERROR });\n } finally {\n span.end();\n }\n },\n );\n}\n`;\n\n/** The same shape without telemetry: each request just runs. */\nconst NO_REQUEST_SPANS = `async function traced(\n _method: string,\n _path: string,\n run: () => Promise<number>,\n): Promise<void> {\n await run();\n}\n`;\n\n/** What the manifest records of one processor. */\nexport async function processorInfo(\n\tname: string,\n\tprocessor: AnyProcessor,\n\thandler: string,\n\tcontext: Pick<BuildContext, 'markOptional'>,\n): Promise<ProcessorInfo> {\n\treturn {\n\t\tname,\n\t\thandler,\n\t\tfileServer: processor.surfaceId,\n\t\tpath: processor.pattern,\n\t\tprefix: processor.prefix,\n\t\t...(processor.native.length ? { native: [...processor.native] } : {}),\n\t\t...(processor.timeout !== undefined ? { timeout: processor.timeout } : {}),\n\t\t...(processor.memorySize !== undefined\n\t\t\t? { memorySize: processor.memorySize }\n\t\t\t: {}),\n\t\tenvironment: await processor.getEnvironment({\n\t\t\tmarkOptional: context.markOptional,\n\t\t}),\n\t\tdependencies: processor.constructs,\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Cron } from '@geekmidas/constructs/crons';\nimport type { BuildContext } from '../build/types';\nimport type { CronInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\nexport class CronGenerator extends ConstructGenerator<\n\tCron<any, any, any, any, any, any>,\n\tCronInfo[]\n> {\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<CronInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst cronInfos: CronInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// A server runs its crons itself, the way it already runs its\n\t\t\t// subscribers: one file, wired into the generated entry. Written even\n\t\t\t// when there are none, so the entry can import it unconditionally.\n\t\t\tawait this.generateServerCronsFile(outputDir, constructs);\n\n\t\t\tlogger.log(`Generated server crons file with ${constructs.length} crons`);\n\n\t\t\t// A server cron has no individual handler to point infra at — the\n\t\t\t// process schedules it.\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn cronInfos;\n\t\t}\n\n\t\t// Create crons subdirectory\n\t\tconst cronsDir = join(outputDir, 'crons');\n\t\tawait mkdir(cronsDir, { recursive: true });\n\n\t\t// Generate cron handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateCronHandler(\n\t\t\t\tcronsDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tcronInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tschedule: construct.schedule || 'rate(1 hour)',\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated cron handler: ${key}`);\n\t\t}\n\n\t\treturn cronInfos;\n\t}\n\n\tisConstruct(value: any): value is Cron<any, any, any, any, any, any> {\n\t\treturn Cron.isCron(value);\n\t}\n\n\t/**\n\t * The crons file a server entry imports.\n\t *\n\t * Shaped after `generateServerSubscribersFile`: one module, every cron, a\n\t * `setupCrons` the generated entry calls beside `setupSubscribers`.\n\t *\n\t * It picks its scheduler from what the process can reach. With a Postgres it\n\t * uses pg-boss, whose schedules live in the database — so a deployment\n\t * running four replicas fires each job once, which is the thing a timer in\n\t * every process gets wrong and does not report. With no database it falls\n\t * back to timers and says plainly that it is doing so.\n\t */\n\tprivate async generateServerCronsFile(\n\t\toutputDir: string,\n\t\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst cronsPath = join(outputDir, 'crons.ts');\n\n\t\t// Nothing to schedule, so nothing to import — the entry imports this file\n\t\t// whatever the app declares, and a project with no events must not have\n\t\t// to resolve `@geekmidas/events`.\n\t\tif (crons.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tcronsPath,\n\t\t\t\t`/**\n * Generated cron setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupCrons(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function cronsStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopCrons(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn cronsPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of crons) {\n\t\t\tconst relativePath = relative(dirname(cronsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) importsByFile.set(importPath, []);\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst entries = crons\n\t\t\t.map(({ key }) => ` { name: '${key}', cron: ${key} }`)\n\t\t\t.join(',\\n');\n\n\t\tconst content = `/**\n * Generated cron setup.\n *\n * Schedules every cron this app declares, in the process that serves it.\n *\n * The schedule lives in Postgres, through pg-boss, in the database the worker\n * named with \\`.database(db)\\`. That is what makes running several replicas\n * safe: each job fires once, where a timer in every process fires it once per\n * replica and reports nothing.\n *\n * No connection string appears here. The construct that owns the database is\n * the only thing that knows its key, and it is resolved through service\n * discovery like any other dependency.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runCron, scheduleInProcess, toCronExpression } from '@geekmidas/constructs/crons';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst crons = [\n${entries}\n];\n\ntype Stoppable = { stop: () => Promise<void> | void };\nconst running: Stoppable[] = [];\n// What a worker's health check reads: the crons that cannot be scheduled, and\n// the broker connection the schedule is kept through.\nconst failed: string[] = [];\nconst connections: import('@geekmidas/events').EventConnection[] = [];\n\nexport async function setupCrons(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n if (crons.length === 0) {\n return;\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Resolved once per cron rather than per firing: registering services on\n // every tick would reconnect a database every minute.\n const prepared = [];\n for (const { name, cron } of crons) {\n try {\n const schedule = toCronExpression(cron.schedule);\n const services = cron.services.length > 0\n ? await serviceDiscovery.register(cron.services)\n : {};\n\n prepared.push({ name, cron, schedule, services });\n } catch (error) {\n // An unrepresentable schedule is a build-time mistake, and failing the\n // process for it would take the HTTP server down with it.\n logger.error({ err: error, cron: name }, 'Cron has no runnable schedule, skipping');\n failed.push(name);\n }\n }\n\n const run = async (entry: (typeof prepared)[number]) => {\n try {\n // The cron's own function, the way its Lambda would run it — services,\n // the worker's database as \\`db\\`, its events. It used to call a\n // \\`handler\\` a Cron does not have, so every firing logged a failure.\n await runCron(entry.cron, serviceDiscovery, entry.name);\n } catch (error) {\n logger.error({ err: error, cron: entry.name }, 'Cron failed');\n }\n };\n\n // The app's one pg-boss: the events broker's, as the broker's role, in the\n // broker's schema. A server fires its own crons, and a process scheduling in\n // memory fires each job once per replica — so the schedule lives in\n // Postgres. It used to be a second pg-boss on the worker's database, as the\n // runtime role, which can neither create a schema nor use the broker's.\n const { url, devPid } = envParser\n .create((get) => ({\n url: get('EVENT_PUBLISHER_CONNECTION_STRING').string().optional(),\n // Set by \\`gkm dev\\` on the server it starts, and by nothing deployed.\n devPid: get('GKM_DEV_PID').string().optional(),\n }))\n .parse();\n\n if (!url?.startsWith('pgboss://')) {\n // \\`gkm dev\\` on a target whose crons are infrastructure once deployed —\n // EventBridge rules on AWS — has no broker to keep a schedule in. It is one\n // process, so a timer fires each job once, which is all pg-boss is for\n // here. Only there: a deployed server firing by timer fires once per\n // replica, so outside dev this stays the error below.\n if (devPid) {\n for (const entry of prepared) {\n running.push(scheduleInProcess(entry.schedule, () => run(entry)));\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled in this process');\n }\n return;\n }\n\n logger.error(\n { crons: prepared.map(({ name }) => name) },\n 'These crons have nowhere to keep their schedule. On a server they are ' +\n 'scheduled through the pg-boss events broker ' +\n '(EVENT_PUBLISHER_CONNECTION_STRING), and ' +\n (url ? 'the broker configured is not pg-boss.' : 'none is configured.'),\n );\n failed.push(...prepared.map(({ name }) => name));\n return;\n }\n\n // Through the registered pg-boss driver, which the entry registers for a\n // server whose broker is pg-boss. Naming \\`@geekmidas/events/pgboss\\` here\n // made every bundle with a cron resolve pg-boss, whatever its broker.\n const { EventConnectionFactory } = await import('@geekmidas/events');\n const connection = (await EventConnectionFactory.fromConnectionString(\n url,\n )) as import('@geekmidas/events').EventConnection & { instance?: any };\n const boss = connection.instance!;\n\n // What this app declares now. Anything else under the prefix belonged to a\n // cron since renamed or deleted, and would keep firing at a handler that has\n // gone.\n //\n // The prefix is \\`cron.\\` rather than \\`cron:\\`: pg-boss accepts\n // alphanumerics, underscores, hyphens, periods and slashes in a queue name,\n // and rejects a colon outright.\n const declared = new Set(prepared.map(({ name }) => \\`cron.\\${name}\\`));\n for (const existing of await boss.getSchedules()) {\n if (existing.name.startsWith('cron.') && !declared.has(existing.name)) {\n await boss.unschedule(existing.name);\n logger.info({ cron: existing.name }, 'Removed a schedule nothing declares');\n }\n }\n\n for (const entry of prepared) {\n const queue = \\`cron.\\${entry.name}\\`;\n await boss.createQueue(queue);\n // UTC, so this agrees with the schedule a deploy target would have made.\n await boss.schedule(queue, entry.schedule, undefined, { tz: 'UTC' });\n await boss.work(queue, () => run(entry));\n\n logger.info({ cron: entry.name, schedule: entry.schedule }, 'Cron scheduled');\n }\n\n running.push({ stop: () => connection.close() });\n connections.push(connection);\n logger.info({ count: prepared.length }, 'Crons scheduled');\n}\n\n/** The crons that cannot be scheduled, and the connection that schedules the rest. */\nexport function cronsStatus(): {\n failed: string[];\n connections: import('@geekmidas/events').EventConnection[];\n} {\n return { failed: [...failed], connections: [...connections] };\n}\n\n/**\n * Stop scheduling, let a firing in flight finish, and close the broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopCrons(): Promise<void> {\n const open = [...running];\n running.length = 0;\n connections.length = 0;\n await Promise.all(open.map((r) => r.stop()));\n}\n`;\n\n\t\tawait writeFile(cronsPath, content);\n\n\t\treturn cronsPath;\n\t}\n\n\tprivate async generateCronHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSScheduledFunction } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSScheduledFunction(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Queue } from '@geekmidas/constructs/queue';\nimport { provideKey } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport type { QueueInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\n/**\n * Generates the runtime for queue consumers (`worker.queue(…)`).\n *\n * - **server** (`gkm dev`): a single `queues.ts` exposing `setupQueues()` that\n * polls each queue in-process, alongside the Hono server, through the queue's\n * own connection string — pg-boss by default, SQS on the AWS emulator.\n * - **aws-lambda**: one handler file per queue wrapping `AWSLambdaQueue`, backed\n * by an SQS event-source mapping.\n */\nexport class QueueGenerator extends ConstructGenerator<\n\tQueue<any, any, any, any, any, any>,\n\tQueueInfo[]\n> {\n\tisConstruct(value: any): value is Queue<any, any, any, any, any, any> {\n\t\treturn Queue.isQueue(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<QueueInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst queueInfos: QueueInfo[] = [];\n\n\t\tif (target === 'server') {\n\t\t\t// Generate queues.ts for in-process polling (even if empty, so the\n\t\t\t// server entry can always import setupQueues).\n\t\t\tawait this.generateServerQueuesFile(outputDir, constructs);\n\t\t\tlogger.log(\n\t\t\t\t`Generated server queues file with ${constructs.length} queues (polling mode)`,\n\t\t\t);\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn queueInfos;\n\t\t}\n\n\t\tconst queuesDir = join(outputDir, 'queues');\n\t\tawait mkdir(queuesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateQueueHandler(\n\t\t\t\tqueuesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tqueueInfos.push({\n\t\t\t\tname: construct.name,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tbatchSize: construct.batchSize,\n\t\t\t\tfifo: construct.fifo,\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated queue handler: ${key}`);\n\t\t}\n\n\t\treturn queueInfos;\n\t}\n\n\tprivate async generateQueueHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\t\tconst importPath = relative(dirname(handlerPath), sourceFile).replace(\n\t\t\t/\\.ts$/,\n\t\t\t'.js',\n\t\t);\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaQueue } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaQueue(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerQueuesFile(\n\t\toutputDir: string,\n\t\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[],\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\n\t\tconst queuesPath = join(outputDir, 'queues.ts');\n\n\t\t// Nothing to poll, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (queues.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tqueuesPath,\n\t\t\t\t`/**\n * Generated queues setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupQueues(\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<void> {}\n\nexport function queuesStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopQueues(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn queuesPath;\n\t\t}\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of queues) {\n\t\t\tconst importPath = relative(dirname(queuesPath), path.relative).replace(\n\t\t\t\t/\\.ts$/,\n\t\t\t\t'.js',\n\t\t\t);\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each queue's consumer reaches its own queue, by the queue's own key.\n\t\tconst entries = queues\n\t\t\t.map(\n\t\t\t\t({ key, construct }) =>\n\t\t\t\t\t` { queue: ${key}, connectionKey: '${provideKey(\n\t\t\t\t\t\tconstruct.id,\n\t\t\t\t\t\t'publisherConnectionString',\n\t\t\t\t\t)}' },`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst content = `/**\n * Generated queue consumers setup.\n *\n * Each queue's one consumer polls its own queue, through the queue's own\n * connection string — the one its producers publish on. SQS cannot push, so\n * this is a poller on every transport: pg-boss locally by default, the SQS\n * queue on the AWS emulator.\n *\n * Deployed on Lambda, a queue's consumer is an SQS event source instead.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nconst queues = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\nexport async function setupQueues(\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n for (const { queue, connectionKey } of queues) {\n const connectionString = process.env[connectionKey];\n if (!connectionString) {\n logger.error({ queue: queue.name, connectionKey }, 'No connection string for this queue');\n failed.push(queue.name);\n continue;\n }\n\n try {\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n const eventSubscriber = await Subscriber.fromConnection(connection);\n const services = queue.services.length > 0\n ? await serviceDiscovery.register(queue.services)\n : {};\n // The queue's database — the worker's, or its own — handed over as \\`db\\`.\n const db = queue.databaseService\n ? (await serviceDiscovery.register([queue.databaseService]))[\n queue.databaseService.serviceName\n ]\n : undefined;\n\n // A queue's messages carry one type — its own name.\n await eventSubscriber.subscribe([queue.name], async (message) => {\n try {\n const validation = await queue.messageSchema['~standard'].validate(message.payload);\n if (validation.issues) {\n logger.error({ issues: validation.issues, queue: queue.name }, 'Queue message failed validation');\n return;\n }\n\n await queue.handler({\n messages: [validation.value],\n services: services,\n logger: queue.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to process queue message');\n // Rethrown so the transport keeps the message for a retry.\n throw error;\n }\n });\n logger.info({ queue: queue.name }, 'Queue consumer started polling');\n } catch (error) {\n logger.error({ err: error, queue: queue.name }, 'Failed to set up queue consumer');\n failed.push(queue.name);\n }\n }\n}\n\n/** The consumers that could not start, and the connections that did. */\nexport function queuesStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the messages in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopQueues(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(queuesPath, content);\n\t\treturn queuesPath;\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Cron } from '@geekmidas/constructs/crons';\nimport type { Queue } from '@geekmidas/constructs/queue';\nimport type { Subscriber } from '@geekmidas/constructs/subscribers';\nimport type { BuildContext } from '../build/types';\nimport { GkmError } from '../errors';\nimport { appKey } from '../workspace/derive.js';\nimport { CronGenerator } from './CronGenerator';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport type { GeneratedConstruct } from './Generator';\nimport { QueueGenerator } from './QueueGenerator';\nimport { SubscriberGenerator } from './SubscriberGenerator';\nimport {\n\tstartTelemetryCode,\n\ttype TelemetryContext,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * A worker whose topic subscribers would have to be pushed to over HTTP.\n *\n * On SNS a subscriber is an HTTP endpoint SNS delivers to, and a worker's\n * process serves nothing but its health check. A server target's broker is\n * pg-boss, where each subscriber polls a queue of its own, so this is only\n * reached by building server images for a project that deploys to AWS — where\n * a subscriber is a Lambda instead.\n */\nexport class WorkerSubscribersNeedPush extends GkmError {\n\tconstructor(\n\t\treadonly worker: string,\n\t\treadonly subscribers: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`The worker '${worker}' runs topic subscribers (${subscribers.join(', ')}), ` +\n\t\t\t\t`and this build's broker is SNS, which pushes each event to its ` +\n\t\t\t\t`subscriber over HTTP. A worker image serves only its health check. ` +\n\t\t\t\t`Deploy to a server target, whose broker is pg-boss and whose ` +\n\t\t\t\t`subscribers poll, or to AWS, where each subscriber is a Lambda.`,\n\t\t);\n\t\tthis.name = 'WorkerSubscribersNeedPush';\n\t}\n}\n\n/** Where a worker's generated entry lives, under an app's `.gkm/server`. */\nexport function workerEntryDir(serverDir: string, workerId: string): string {\n\treturn join(serverDir, 'workers', appKey(workerId));\n}\n\n/** The file a worker's bundle is written to, beside the server's. */\nexport function workerBundleName(workerId: string): string {\n\treturn `worker-${appKey(workerId)}.mjs`;\n}\n\nexport interface WorkerEntryInput {\n\tcontext: BuildContext;\n\t/** The worker's construct id, `Jobs`. */\n\tworkerId: string;\n\t/** The worker's own directory — see `workerEntryDir`. */\n\toutputDir: string;\n\t/** Everything built from this worker, and nothing built from another. */\n\tcrons: GeneratedConstruct<Cron<any, any, any, any, any, any>>[];\n\tqueues: GeneratedConstruct<Queue<any, any, any, any, any, any>>[];\n\tsubscribers: GeneratedConstruct<\n\t\tSubscriber<any, any, any, any, any, any, any>\n\t>[];\n\t/** What its process starts OpenTelemetry with — none without an edge. */\n\ttelemetry?: TelemetryContext;\n}\n\n/**\n * A Worker's production entry: the process that runs its crons, its queue\n * consumers and its topic subscribers, and answers nothing but a health check.\n *\n * It is the server's runtime without the server. The `crons.ts`, `queues.ts`\n * and `subscribers.ts` it starts are the files `gkm dev` starts — written by\n * the same generators, given only this worker's constructs — so a consumer\n * runs the same code in development and in the image. What it adds is the\n * process around them: drivers, a health check that says when a consumer or\n * the broker is down, and a shutdown that drains.\n */\nexport class WorkerGenerator {\n\tconstructor(\n\t\tprivate readonly generators = {\n\t\t\tcron: new CronGenerator(),\n\t\t\tqueue: new QueueGenerator(),\n\t\t\tsubscriber: new SubscriberGenerator(),\n\t\t},\n\t) {}\n\n\t/** Write the worker's files; returns its entry, `worker.ts`. */\n\tasync build(input: WorkerEntryInput): Promise<string> {\n\t\tconst { context, workerId, outputDir } = input;\n\n\t\tif (\n\t\t\tinput.subscribers.length > 0 &&\n\t\t\tcontext.eventsBackends?.includes('sns')\n\t\t) {\n\t\t\tthrow new WorkerSubscribersNeedPush(\n\t\t\t\tworkerId,\n\t\t\t\tinput.subscribers.map(({ key }) => key),\n\t\t\t);\n\t\t}\n\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst options = { target: 'server' as const };\n\t\tawait Promise.all([\n\t\t\tthis.generators.cron.build(context, input.crons, outputDir, options),\n\t\t\tthis.generators.queue.build(context, input.queues, outputDir, options),\n\t\t\tthis.generators.subscriber.build(\n\t\t\t\tcontext,\n\t\t\t\tinput.subscribers,\n\t\t\t\toutputDir,\n\t\t\t\toptions,\n\t\t\t),\n\t\t]);\n\n\t\tawait writeFile(\n\t\t\tjoin(outputDir, 'app.ts'),\n\t\t\tworkerApp(context, workerId, outputDir),\n\t\t);\n\t\t// The worker's own edge decides, not the app's that carries it.\n\t\tawait writeTelemetryModule(outputDir, input.telemetry);\n\n\t\tconst entry = join(outputDir, 'worker.ts');\n\t\tawait writeFile(\n\t\t\tentry,\n\t\t\tworkerEntry(context.production?.healthCheck ?? '/health'),\n\t\t);\n\t\treturn entry;\n\t}\n}\n\n/**\n * `app.ts`: the worker's runtime — its logger and environment parser off the\n * Worker construct, the drivers its target needs, and a `startWorker` that\n * starts every cron, consumer and subscriber it owns.\n */\nfunction workerApp(\n\tcontext: BuildContext,\n\tworkerId: string,\n\toutputDir: string,\n): string {\n\tconst runtime = runtimeFor(context, outputDir, workerId);\n\n\treturn `/**\n * Generated worker runtime for ${workerId}.\n * Generated by 'gkm build --production'.\n */\nimport { setupCrons, cronsStatus, stopCrons } from './crons.js';\nimport { setupQueues, queuesStatus, stopQueues } from './queues.js';\nimport { setupSubscribers, subscribersStatus, stopSubscribers } from './subscribers.js';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n// Who this worker is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(workerId)};\n\nexport { logger };\n\n/** What the health check answers, and why. */\nexport interface WorkerHealth {\n healthy: boolean;\n /** The crons, queues and subscribers that could not start. */\n failed: string[];\n /** How many broker connections did not answer. */\n down: number;\n}\n\n/** Whether one broker connection answers: open, and — on pg-boss — a query. */\nasync function answers(connection: unknown): Promise<boolean> {\n const c = connection as {\n isConnected?: () => boolean;\n instance?: { getDb?: () => { executeSql: (sql: string) => Promise<unknown> } };\n };\n if (c.isConnected && !c.isConnected()) return false;\n const db = c.instance?.getDb?.();\n if (!db) return true;\n try {\n await Promise.race([\n db.executeSql('select 1'),\n new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000).unref()),\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A request to a route this worker mounted, and what it answered. */\nexport interface WorkerRequest {\n headers: Record<string, string | string[] | undefined>;\n body: string;\n /** The request's query — Mailpit's webhook carries its token there. */\n query?: URLSearchParams;\n}\nexport interface WorkerAnswer {\n status: number;\n body: unknown;\n}\n\n// The routes something pushes to: an SNS subscriber's, and the one a local\n// object store posts a bucket's events to. Mounted by the subscribers, served\n// by the entry's HTTP server beside the health check.\nconst routes = new Map<string, (c: any) => unknown>();\nconst app = {\n post: (path: string, handler: (c: any) => unknown) => {\n routes.set(path, handler);\n },\n};\n\n/** Run one mounted route, as the subscribers' handlers expect to be called. */\nasync function route(path: string, request: WorkerRequest): Promise<WorkerAnswer | undefined> {\n const handler = routes.get(path);\n if (!handler) return undefined;\n let answer: WorkerAnswer | undefined;\n const c = {\n req: {\n text: async () => request.body,\n query: (name: string) => request.query?.get(name) ?? undefined,\n header: (name: string) => {\n const value = request.headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n },\n },\n json: (body: unknown, status = 200) => {\n answer = { status, body };\n return answer;\n },\n };\n await handler(c);\n return answer ?? { status: 204, body: null };\n}\n\n/** Start everything this worker runs. */\nexport async function startWorker(): Promise<{\n health: () => Promise<WorkerHealth>;\n stop: () => Promise<void>;\n route: typeof route;\n /** Subscribe the pushed routes, once the server answers on \\`port\\`. */\n subscribeForPush: (port: number) => Promise<void>;\n}> {\n const subscribeForPush = await setupSubscribers(app, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue consumers');\n });\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n const statuses = () => [subscribersStatus(), queuesStatus(), cronsStatus()];\n\n return {\n route,\n subscribeForPush,\n async health() {\n const all = statuses();\n const failed = all.flatMap((s) => s.failed);\n const alive = await Promise.all(\n all.flatMap((s) => s.connections as unknown[]).map(answers),\n );\n const down = alive.filter((ok) => !ok).length;\n return { healthy: failed.length === 0 && down === 0, failed, down };\n },\n // Each stops pulling, waits for what it has in flight, and closes its\n // broker connection. Together, so one slow handler does not hold the\n // others' connections open.\n async stop() {\n await Promise.all([stopSubscribers(), stopQueues(), stopCrons()]);\n },\n };\n}\n`;\n}\n\n/**\n * `worker.ts`: the process. Health first, so the container answers while the\n * consumers connect; then the worker; then a shutdown that drains.\n */\nfunction workerEntry(healthCheck: string): string {\n\treturn `#!/usr/bin/env node\n/**\n * Production worker entry point.\n * Generated by 'gkm build --production'.\n *\n * Runs this worker's crons, queue consumers and topic subscribers, and serves\n * its health check: ${healthCheck}, on PORT — 200 when every consumer started\n * and every broker connection answers, 503 otherwise. Beside it, on the same\n * port, the POST routes its subscribers mounted: where a local object store\n * posts a bucket's events.\n *\n * On SIGTERM it stops pulling messages and scheduling crons, lets the handlers\n * in flight finish, closes its broker connections and database pools, and\n * exits 0 — or 1, at GKM_SHUTDOWN_TIMEOUT_MS (8s by default, under Docker's\n * 10s stop timeout).\n */\nimport { createServer } from 'node:http';\nimport { runShutdownHooks } from '@geekmidas/constructs';\n\n${startTelemetryCode([healthCheck])}\nconst { startWorker, logger } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nlet worker: Awaited<ReturnType<typeof startWorker>> | undefined;\nlet stopping = false;\n\nconst server = createServer((req, res) => {\n // Parsed once: the path routes, the query goes to the route.\n const url = new URL(req.url ?? '/', 'http://localhost');\n const path = url.pathname;\n const answer = (status: number, body: unknown) => {\n res.writeHead(status, { 'content-type': 'application/json' });\n res.end(JSON.stringify(body));\n };\n\n // A route a subscriber mounted: what SNS pushes to, or what a local object\n // store posts a bucket's events to. Refused while starting or stopping, so\n // the sender keeps the message and sends it again.\n if (req.method === 'POST') {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk) => {\n body += chunk;\n });\n req.on('end', () => {\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.route(path, { headers: req.headers, body, query: url.searchParams }).then(\n (routed) => (routed ? answer(routed.status, routed.body) : answer(404, { status: 'not found' })),\n (error) => {\n logger.error({ err: error, path }, 'Route failed');\n answer(500, { status: 'failed' });\n },\n );\n });\n return;\n }\n\n if (path !== ${JSON.stringify(healthCheck)} || (req.method !== 'GET' && req.method !== 'HEAD')) {\n res.writeHead(404).end();\n return;\n }\n if (stopping) return answer(503, { status: 'stopping' });\n if (!worker) return answer(503, { status: 'starting' });\n worker.health().then(\n (health) => answer(health.healthy ? 200 : 503, { status: health.healthy ? 'ok' : 'unhealthy', ...health }),\n (error) => answer(503, { status: 'unhealthy', error: String(error) }),\n );\n});\nserver.listen(port);\n\nconst shutdown = async () => {\n if (stopping) return;\n stopping = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n\n // Nothing new is pulled or scheduled; what is in flight finishes.\n await worker?.stop().catch((error) => logger.error({ err: error }, 'Failed to stop the worker'));\n // Then what the handlers used: database pools.\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n server.close();\n logger.info('Worker stopped');\n process.exit(0);\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nworker = await startWorker();\nlogger.info({ port }, 'Worker started');\nawait worker.subscribeForPush(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n});\n`;\n}\n","import { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport {\n\ttype ConstructManifest,\n\tprovideKey,\n\tpublicEnvFor,\n} from '@geekmidas/manifest';\nimport {\n\ttype ProcessorUnit,\n\tprocessorUnits,\n\ttype WorkerUnit,\n\tworkerUnits,\n} from '../build/workers.js';\nimport { loadWorkspaceConfig } from '../config';\nimport { GkmError } from '../errors';\nimport { processorBundleName } from '../generators/ProcessorGenerator.js';\nimport { workerBundleName } from '../generators/WorkerGenerator.js';\nimport { output } from '../output';\nimport { dockerfileOf } from '../reconcile/apps.js';\nimport { COMPOSE_PATH } from '../reconcile/index.js';\nimport { reconcileWorkspace } from '../reconcile/workspace.js';\nimport { run } from '../run';\nimport { getPublicUrlArgNames } from '../target/dokploy/domain.js';\nimport { siteClientTelemetry } from '../telemetry/edges.js';\nimport type { CacheBackend, GkmConfig } from '../types';\nimport { appKey } from '../workspace/derive.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport { validateImageRef } from './imageRef';\nimport { appImageOptions, type ImageLayout, imageLayout } from './layout';\nimport {\n\tgenerateBackendDockerfile,\n\tgenerateDockerignore,\n\tgenerateEntryDockerfile,\n\tgenerateNextjsDockerfile,\n\tgenerateNodeWebDockerfile,\n\tgenerateProcessorDockerfile,\n\tgenerateViteStaticDockerfile,\n\tgenerateWorkerDockerfile,\n\tPROCESSOR_PORT,\n\tresolveDockerConfig,\n\tWORKER_PORT,\n} from './templates';\n\nexport { ImageRefInvalid, validateImageRef } from './imageRef';\nexport {\n\tappImageOptions,\n\tcomposeBuildPaths,\n\tfromBuildRoot,\n\ttype ImageLayout,\n\timageLayout,\n\tMonorepoNeedsTurbo,\n} from './layout';\nexport {\n\tdetectPackageManager,\n\tfindBuildRoot,\n\tfindLockfilePath,\n\thasTurboConfig,\n\tisMonorepo,\n} from './templates';\n\n// Through `output`, so a deploy run that generates a Dockerfile hears it.\nconst logger = output;\n\n/** `docker build` failed; what docker printed above says why. */\nexport class DockerBuildFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to build Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerBuildFailed';\n\t}\n}\n\n/** `docker push` failed — usually the registry login or its permissions. */\nexport class DockerPushFailed extends Error {\n\tconstructor(\n\t\treadonly imageRef: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`Failed to push Docker image: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'DockerPushFailed';\n\t}\n}\n\n/** `gkm docker --push` was asked for with nowhere to push to. */\nexport class PushNeedsRegistry extends GkmError {\n\tconstructor(readonly imageName: string) {\n\t\tsuper(\n\t\t\t`Registry is required to push Docker image '${imageName}'. Use --registry or configure docker.registry in gkm.config.ts`,\n\t\t);\n\t\tthis.name = 'PushNeedsRegistry';\n\t}\n}\n\nexport interface DockerOptions {\n\t/** Build each app's image after generating files */\n\tbuild?: boolean;\n\t/** Push the images to the registry after building */\n\tpush?: boolean;\n\t/** Image tag (default: 'latest') */\n\ttag?: string;\n\t/** Container registry URL */\n\tregistry?: string;\n\t/**\n\t * The directory to generate for — an app's own, when a deploy builds it.\n\t * Defaults to the process's working directory.\n\t */\n\tcwd?: string;\n\t/**\n\t * The stage the images are for: a site's clients trace at its sample\n\t * rate. The local stage when absent.\n\t */\n\tstage?: string;\n}\n\n/**\n * Docker command implementation: one Dockerfile per deployable app, each\n * building its image inside Docker from a turbo-pruned slice of the build\n * root — nothing is built on the host — plus the build root's\n * `.dockerignore` and `docker-compose.constructs.yml`.\n */\nexport async function dockerCommand(\n\toptions: DockerOptions,\n): Promise<WorkspaceDockerResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst loaded = await loadWorkspaceConfig(cwd);\n\n\t// A single-app config is a workspace of one app at its root; the image is\n\t// named the way its `docker` block says.\n\tconst names: Record<string, string> =\n\t\tloaded.type === 'single'\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.keys(loaded.workspace.apps).map((name) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tresolveDockerConfig(loaded.raw as GkmConfig).imageName,\n\t\t\t\t\t]),\n\t\t\t\t)\n\t\t\t: {};\n\n\tconst result = await workspaceDockerCommand(\n\t\tloaded.workspace,\n\t\tloaded.manifest,\n\t\tnames,\n\t\tloaded.background,\n\t\toptions.stage,\n\t);\n\n\tif (options.build) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait buildDockerImage(app, result.buildRoot, options);\n\t\t}\n\t}\n\tif (options.push) {\n\t\tfor (const app of result.apps) {\n\t\t\tawait pushDockerImage(app.imageName, options, result.buildRoot);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Build one app's image, from the build root.\n * Uses BuildKit for cache mount support\n */\nasync function buildDockerImage(\n\tapp: AppDockerResult,\n\tbuildRoot: string,\n\toptions: DockerOptions,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\t// Before anything runs: a ref docker would misread is refused by name.\n\tconst fullImageName = validateImageRef(\n\t\tregistry\n\t\t\t? `${registry}/${app.imageName}:${tag}`\n\t\t\t: `${app.imageName}:${tag}`,\n\t);\n\n\tlogger.log(`\\n🐳 Building Docker image: ${fullImageName}`);\n\n\ttry {\n\t\t// An argument array, so nothing in the ref is read by a shell, and\n\t\t// `--tag=` so it cannot be read as a flag.\n\t\tawait run(\n\t\t\t'docker',\n\t\t\t[\n\t\t\t\t'build',\n\t\t\t\t`--file=${relative(buildRoot, app.dockerfile)}`,\n\t\t\t\t`--tag=${fullImageName}`,\n\t\t\t\t'.',\n\t\t\t],\n\t\t\t{\n\t\t\t\tcwd: buildRoot,\n\t\t\t\t// BuildKit, for the templates' `RUN --mount=type=cache`.\n\t\t\t\tenv: { ...process.env, DOCKER_BUILDKIT: '1' },\n\t\t\t},\n\t\t);\n\t\tlogger.log(`✅ Docker image built: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerBuildFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Push Docker image to registry\n */\nasync function pushDockerImage(\n\timageName: string,\n\toptions: DockerOptions,\n\tcwd: string,\n): Promise<void> {\n\tconst tag = options.tag ?? 'latest';\n\tconst registry = options.registry;\n\n\tif (!registry) {\n\t\tthrow new PushNeedsRegistry(imageName);\n\t}\n\n\tconst fullImageName = validateImageRef(`${registry}/${imageName}:${tag}`);\n\n\tlogger.log(`\\n🚀 Pushing Docker image: ${fullImageName}`);\n\n\ttry {\n\t\tawait run('docker', ['push', fullImageName], { cwd });\n\t\tlogger.log(`✅ Docker image pushed: ${fullImageName}`);\n\t} catch (error) {\n\t\tthrow new DockerPushFailed(fullImageName, error);\n\t}\n}\n\n/**\n * Result of generating Docker files for a single app in a workspace.\n */\nexport interface AppDockerResult {\n\tappName: string;\n\ttype: 'backend' | 'web' | 'mobile';\n\t/** The Dockerfile, absolute. */\n\tdockerfile: string;\n\timageName: string;\n}\n\n/**\n * Result of workspace docker command.\n */\nexport interface WorkspaceDockerResult {\n\tapps: AppDockerResult[];\n\tdockerCompose: string;\n\tdockerignore: string;\n\t/** Every image's build context, absolute. */\n\tbuildRoot: string;\n}\n\n/**\n * Generate Dockerfiles for all apps in a workspace.\n * @internal Exported for testing\n */\nexport async function workspaceDockerCommand(\n\tworkspace: NormalizedWorkspace,\n\t/** What the workspace declares — where a site's public keys come from. */\n\tmanifest?: ConstructManifest,\n\t/** Image names other than the app's own. */\n\timageNames: Readonly<Record<string, string>> = {},\n\t/** Each Worker's files, from discovery — which app each is built from. */\n\tbackground: Readonly<Record<string, readonly string[]>> = {},\n\t/** The stage a site's clients trace at the rate of — local when absent. */\n\tstage?: string,\n): Promise<WorkspaceDockerResult> {\n\tconst results: AppDockerResult[] = [];\n\tconst layout = imageLayout(workspace);\n\n\tlogger.log(`\\n🐳 Generating Dockerfiles for workspace: ${workspace.name}`);\n\tlogger.log(` Build root: ${layout.buildRoot}`);\n\tlogger.log(\n\t\t` Package manager: ${layout.tools.packageManager}${layout.tools.packageManagerVersion ? `@${layout.tools.packageManagerVersion}` : ''}, turbo@${layout.tools.turboVersion}`,\n\t);\n\n\tfor (const [appName, app] of Object.entries(workspace.apps)) {\n\t\t// Mobile apps deploy via their own toolchain (e.g. EAS Build for Expo)\n\t\t// — no Docker image is produced.\n\t\tif (app.type === 'mobile') {\n\t\t\tlogger.log(\n\t\t\t\t`\\n 📱 Skipping Docker for ${appName} (mobile app — deploy via framework toolchain)`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst buildType = app.entry ? 'entry' : app.type;\n\t\tlogger.log(`\\n 📄 Generating Dockerfile for ${appName} (${buildType})`);\n\n\t\tconst dockerfile = appDockerfile(appName, app, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tapps: workspace.apps,\n\t\t\t...(manifest ? { manifest } : {}),\n\t\t\tworkspace,\n\t\t\t...(stage ? { stage } : {}),\n\t\t});\n\n\t\tconst path = dockerfileOf(appName, app.path);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName,\n\t\t\ttype: app.type,\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[appName] ?? appName,\n\t\t});\n\t}\n\n\t// Each Worker with background work: an image of its own, built from the\n\t// app whose build writes its entry.\n\tfor (const worker of manifest\n\t\t? workerUnits(workspace, manifest, background)\n\t\t: []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${worker.name} (worker ${worker.id}, built from ${worker.app})`,\n\t\t);\n\t\tconst dockerfile = workerDockerfile(worker, workspace.apps[worker.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\t// Always named for the worker: an app at the root has the bare\n\t\t// `Dockerfile`, which this must not overwrite.\n\t\tconst path = workerDockerfileOf(worker.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: worker.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[worker.name] ?? worker.name,\n\t\t});\n\t}\n\n\t// Each file server's processors: an image of their own, built from the\n\t// app whose build writes their entry.\n\tfor (const unit of manifest ? processorUnits(workspace, manifest) : []) {\n\t\tlogger.log(\n\t\t\t`\\n 📄 Generating Dockerfile for ${unit.name} (processors of ${unit.id}, built from ${unit.app})`,\n\t\t);\n\t\tconst dockerfile = processorDockerfile(unit, workspace.apps[unit.app]!, {\n\t\t\tlayout,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t});\n\t\tconst path = workerDockerfileOf(unit.name);\n\t\tconst dockerfilePath = join(workspace.root, path);\n\t\tawait mkdir(dirname(dockerfilePath), { recursive: true });\n\t\tawait writeFile(dockerfilePath, dockerfile);\n\t\tlogger.log(` Generated: ${path}`);\n\n\t\tresults.push({\n\t\t\tappName: unit.name,\n\t\t\ttype: 'backend',\n\t\t\tdockerfile: dockerfilePath,\n\t\t\timageName: imageNames[unit.name] ?? unit.name,\n\t\t});\n\t}\n\n\tconst dockerignorePath = await ensureDockerignore(layout.buildRoot);\n\tlogger.log(`\\n Ensured: ${dockerignorePath}`);\n\n\tconst composePath = await writeConstructsCompose(workspace);\n\n\t// Summary\n\tlogger.log(\n\t\t`\\n✅ Generated ${results.length} Dockerfile(s) + ${COMPOSE_PATH}`,\n\t);\n\tlogger.log(`\\n📋 Build commands (from ${layout.buildRoot}):`);\n\tfor (const result of results) {\n\t\tconst icon =\n\t\t\tresult.type === 'backend' ? '⚙️' : result.type === 'mobile' ? '📱' : '🌐';\n\t\tlogger.log(\n\t\t\t` ${icon} docker build -f ${relative(layout.buildRoot, result.dockerfile)} -t ${result.imageName} .`,\n\t\t);\n\t}\n\tprintRunInstructions(workspace);\n\n\treturn {\n\t\tapps: results,\n\t\tdockerCompose: composePath,\n\t\tdockerignore: dockerignorePath,\n\t\tbuildRoot: layout.buildRoot,\n\t};\n}\n\n/**\n * One app's Dockerfile, by what it is: a gkm backend bundled by `gkm build`,\n * a backend with its own entry bundled by esbuild, or a site by its\n * framework. The one choice every builder of images makes.\n */\nexport function appDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/**\n\t\t * Every app in the workspace, so a site's image knows the backends whose\n\t\t * clients it generates.\n\t\t */\n\t\tapps?: Readonly<Record<string, NormalizedAppConfig>>;\n\t\tmanifest?: ConstructManifest;\n\t\t/** The workspace's stages and `deploy.telemetry`, for a site's clients. */\n\t\tworkspace?: Pick<NormalizedWorkspace, 'stages' | 'deploy'>;\n\t\t/** A site's public keys, when the caller resolved them itself. */\n\t\tpublicUrlArgs?: string[];\n\t\t/**\n\t\t * The cache backend a gkm backend's entry registers, where it is not the\n\t\t * deploy target's — the compose stack's own Redis.\n\t\t */\n\t\tcache?: CacheBackend;\n\t\t/**\n\t\t * The stage whose sample rate a site's clients trace at — the local\n\t\t * stage when absent.\n\t\t */\n\t\tstage?: string;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tappName,\n\t\tapp,\n\t\toptions.workspaceRoot,\n\t\toptions.apps,\n\t\tapp.type === 'web' && options.manifest && options.workspace\n\t\t\t? siteClientTelemetry(\n\t\t\t\t\toptions.manifest,\n\t\t\t\t\tappName,\n\t\t\t\t\toptions.workspace,\n\t\t\t\t\toptions.stage,\n\t\t\t\t)\n\t\t\t: undefined,\n\t);\n\n\tif (app.type === 'web') {\n\t\treturn siteDockerfile(appName, app, {\n\t\t\timage,\n\t\t\t...(options.manifest ? { manifest: options.manifest } : {}),\n\t\t\t...(options.publicUrlArgs\n\t\t\t\t? { publicUrlArgs: options.publicUrlArgs }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\tif (app.entry) {\n\t\treturn generateEntryDockerfile({\n\t\t\t...image,\n\t\t\tentry: app.entry,\n\t\t\thealthCheckPath: '/health',\n\t\t});\n\t}\n\treturn generateBackendDockerfile({\n\t\t...image,\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/** Where `gkm docker` writes a worker's Dockerfile. */\nexport function workerDockerfileOf(worker: string): string {\n\treturn `.gkm/docker/Dockerfile.${worker}`;\n}\n\n/**\n * A Worker's Dockerfile: its host app's build, and the worker's bundle as the\n * runner — see `generateWorkerDockerfile`.\n */\nexport function workerDockerfile(\n\tworker: WorkerUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\t/** As {@link appDockerfile}'s: the cache backend its entry registers. */\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tworker.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateWorkerDockerfile({\n\t\t...image,\n\t\timageName: worker.name,\n\t\tport: WORKER_PORT,\n\t\tworker: worker.id,\n\t\tbundle: workerBundleName(worker.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A file server's processor unit's Dockerfile: its host app's build, and the\n * unit's bundle as the runner, with its processors' native packages\n * installed beside it — see `generateProcessorDockerfile`.\n */\nexport function processorDockerfile(\n\tunit: ProcessorUnit,\n\thost: NormalizedAppConfig,\n\toptions: {\n\t\tlayout: ImageLayout;\n\t\tworkspaceRoot: string;\n\t\tcache?: CacheBackend;\n\t},\n): string {\n\tconst image = appImageOptions(\n\t\toptions.layout,\n\t\tunit.app,\n\t\thost,\n\t\toptions.workspaceRoot,\n\t);\n\treturn generateProcessorDockerfile({\n\t\t...image,\n\t\timageName: unit.name,\n\t\tport: PROCESSOR_PORT,\n\t\tfileServer: unit.id,\n\t\tbundle: processorBundleName(unit.id),\n\t\thealthCheckPath: '/health',\n\t\t...(options.cache ? { cache: options.cache } : {}),\n\t});\n}\n\n/**\n * A site's Dockerfile, with an `ARG` for every key its bundler inlines.\n *\n * The keys come from the site's declaration where there is one — every\n * public key its edges give it, `VITE_UPLOADS_SERVER_URL` included — and an\n * `ARG` the Dockerfile does not declare is a build argument the build drops,\n * leaving the bundle with an empty URL.\n */\nexport function siteDockerfile(\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\toptions: {\n\t\timage: ReturnType<typeof appImageOptions>;\n\t\tmanifest?: ConstructManifest;\n\t\tpublicUrlArgs?: string[];\n\t},\n): string {\n\tconst declared = options.manifest\n\t\t? Object.entries(options.manifest).find(\n\t\t\t\t([id, d]) => d.kind === 'site' && appKey(id) === appName,\n\t\t\t)?.[1]\n\t\t: undefined;\n\tconst publicUrlArgs =\n\t\toptions.publicUrlArgs ??\n\t\t(declared?.kind === 'site' && options.manifest\n\t\t\t? [\n\t\t\t\t\t// Its own address under its own name, for server code that runs\n\t\t\t\t\t// at build — what `publicBuildValues` hands every image build.\n\t\t\t\t\tprovideKey(declared.id, 'url'),\n\t\t\t\t\t...Object.keys(publicEnvFor(declared, options.manifest)),\n\t\t\t\t]\n\t\t\t: getPublicUrlArgNames(app));\n\n\tconst webOpts = {\n\t\t...options.image,\n\t\tpublicUrlArgs,\n\t\t// Built against its stage's running APIs, so not offline.\n\t\t...(declared?.kind === 'site' && declared.prerender === 'stage'\n\t\t\t? { prerender: true }\n\t\t\t: {}),\n\t};\n\n\tswitch (app.framework) {\n\t\tcase 'vite':\n\t\t\treturn generateViteStaticDockerfile(webOpts);\n\t\tcase 'tanstack-start':\n\t\tcase 'remix':\n\t\t\treturn generateNodeWebDockerfile(webOpts);\n\t\tdefault:\n\t\t\t// nextjs (and any unspecified web framework — schema requires a valid\n\t\t\t// framework, so this is just a default).\n\t\t\treturn generateNextjsDockerfile(webOpts);\n\t}\n}\n\n/**\n * What a build root's `.dockerignore` must leave out of every image's\n * context: dependencies installed for another platform, anything built on the\n * host (every image builds from source), git, and gkm's own output —\n * `.gkm/compose`'s env files hold a stage's secrets.\n */\nconst REQUIRED_IGNORES = [\n\t'**/node_modules',\n\t'.git',\n\t'**/dist',\n\t'**/.next',\n\t'**/.turbo',\n\t'**/.gkm',\n\t'**/.gkm/compose',\n];\n\n/**\n * Make sure the build root's `.dockerignore` leaves out what no image may\n * hold: written whole where there is none, and each missing line appended to\n * one the project keeps.\n */\nexport async function ensureDockerignore(buildRoot: string): Promise<string> {\n\tconst path = join(buildRoot, '.dockerignore');\n\tif (!existsSync(path)) {\n\t\tawait writeFile(path, generateDockerignore());\n\t\treturn path;\n\t}\n\n\tconst current = await readFile(path, 'utf-8');\n\tconst lines = new Set(current.split(/\\r?\\n/).map((line) => line.trim()));\n\tconst missing = REQUIRED_IGNORES.filter((line) => !lines.has(line));\n\tif (missing.length === 0) return path;\n\n\tawait appendFile(\n\t\tpath,\n\t\t`${current.endsWith('\\n') || current === '' ? '' : '\\n'}\\n# gkm: images build from source, and a stack's env files hold its secrets\\n${missing.join('\\n')}\\n`,\n\t);\n\treturn path;\n}\n\n/**\n * Write `docker-compose.constructs.yml` — the same file `gkm dev` writes, with\n * the apps beside the containers their constructs derive.\n *\n * Through reconcile rather than a second generator, so what `gkm docker`\n * describes and what `gkm dev` runs cannot disagree. Nothing is started.\n */\nasync function writeConstructsCompose(\n\tworkspace: NormalizedWorkspace,\n): Promise<string> {\n\tawait reconcileWorkspace(workspace, {\n\t\tstage: workspace.stages.local,\n\t\tstart: false,\n\t});\n\tlogger.log(` Generated: ${COMPOSE_PATH} (project root)`);\n\treturn join(workspace.root, COMPOSE_PATH);\n}\n\nfunction printRunInstructions(workspace: NormalizedWorkspace): void {\n\tconst project = existsSync(join(workspace.root, 'docker-compose.yml'))\n\t\t? ' -f docker-compose.yml'\n\t\t: '';\n\tlogger.log('\\n📋 Run everything (the apps sit behind the \"apps\" profile):');\n\tlogger.log(\n\t\t' gkm setup # starts the containers and creates what they hold',\n\t);\n\tlogger.log(\n\t\t` docker compose -f ${COMPOSE_PATH}${project} --profile apps up --build`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,mBAAmB;AACzB,MAAM,SAAS,GAAG,iBAAiB,QAAQ,iBAAiB;AAC5D,MAAM,iBAAiB;AAKvB,MAAM,YAAY,IAAI,OACrB,OAAO,OAAO,KAAK,eAAe,MAAM,eAAe,uGACxD;;AAGA,MAAM,kBAAkB;;AAGxB,IAAa,kBAAb,cAAqCA,eAAAA,SAAS;CACxB;CAArB,YAAY,KAAsB;EACjC,MACC,IAAI,IAAI,0QACT;EAHoB,KAAA,MAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,iBAAiB,KAAqB;CACrD,MAAM,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,QAAQ,iBAAiB,EAAE;CAC3D,IAAI,CAAC,UAAU,KAAK,GAAG,KAAK,KAAK,SAAS,iBACzC,MAAM,IAAI,gBAAgB,GAAG;CAE9B,OAAO;AACR;;;;ACnBA,SAAgB,kBACf,WACA,cACS;CACT,QAAA,GAAOC,UAAAA,KAAAA,CAAK,WAAW,cAAcC,aAAAA,kBAAkB,YAAY,CAAC;AACrE;;AAGA,SAAgB,oBAAoB,cAA8B;CACjE,OAAO,GAAGA,aAAAA,kBAAkB,YAAY,EAAE;AAC3C;;;;;;;;;AAUA,IAAa,qBAAb,cAAwCC,iBAAAA,mBAGtC;CACD,YAAY,OAAuC;EAClD,OAAOC,iCAAAA,UAAU,YAAY,KAAK;CACnC;CAEA,MAAM,MACL,SACA,YACA,WACA,SAC2B;EAC3B,KAAK,SAAS,UAAU,WAAW,SAAS,WAAW,WAAW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
|
|
2
|
-
import { a as dokployResult, c as releaseDokploy, d as validateDokploy, f as verifyDokploy, o as planDokploy, s as provisionDokploy, u as rollbackDokploy } from "./engine-
|
|
2
|
+
import { a as dokployResult, c as releaseDokploy, d as validateDokploy, f as verifyDokploy, o as planDokploy, s as provisionDokploy, u as rollbackDokploy } from "./engine-DBimzOpv.mjs";
|
|
3
3
|
//#region src/target/dokploy/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* The built-in `dokploy` target: the Dokploy engine `gkm deploy` has always
|
|
@@ -35,4 +35,4 @@ const dokployTarget = defineTarget({
|
|
|
35
35
|
//#endregion
|
|
36
36
|
export { dokployTarget };
|
|
37
37
|
|
|
38
|
-
//# sourceMappingURL=dokploy-
|
|
38
|
+
//# sourceMappingURL=dokploy-BLZlrTf7.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dokploy-
|
|
1
|
+
{"version":3,"file":"dokploy-BLZlrTf7.mjs","names":[],"sources":["../src/target/dokploy/index.ts"],"sourcesContent":["/**\n * The built-in `dokploy` target: the Dokploy engine `gkm deploy` has always\n * run, behind the phases.\n *\n * - `provision`: the project, environment and registry, and what the\n * manifest declares — its databases' roles applied over a port published\n * for the purpose.\n * - `release`: the stage's migrations, then each image built and pushed\n * beside its application and deployed, waited on until Dokploy has\n * finished; backends first and checked before any site is released.\n * - `verify`: each site answering its health check.\n * - `rollback`: what failed — or, `--atomic`, everything the run released —\n * pointed back at the image it ran before.\n */\n\nimport { defineTarget } from '../define';\nimport {\n\ttype DokployRun,\n\tdokployResult,\n\tplanDokploy,\n\tprovisionDokploy,\n\treleaseDokploy,\n\trollbackDokploy,\n\tvalidateDokploy,\n\tverifyDokploy,\n} from './engine';\n\nexport const dokployTarget = defineTarget<undefined, DokployRun>({\n\tname: 'dokploy',\n\truntime: 'server',\n\tcapabilities: { rollback: true, migrations: 'target', images: true },\n\tcredentials: ['dokploy', 'registry'],\n\tvalidate: (ctx) => validateDokploy(ctx),\n\tplan: (_ctx, run) => planDokploy(run),\n\tprovision: (_ctx, run) => provisionDokploy(run),\n\trelease: (_ctx, run) => releaseDokploy(run),\n\tverify: (_ctx, run) => verifyDokploy(run),\n\trollback: (_ctx, run, failure) => rollbackDokploy(run, failure),\n\tresult: (_ctx, run) => dokployResult(run),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB,aAAoC;CAChE,MAAM;CACN,SAAS;CACT,cAAc;EAAE,UAAU;EAAM,YAAY;EAAU,QAAQ;CAAK;CACnE,aAAa,CAAC,WAAW,UAAU;CACnC,WAAW,QAAQ,gBAAgB,GAAG;CACtC,OAAO,MAAM,QAAQ,YAAY,GAAG;CACpC,YAAY,MAAM,QAAQ,iBAAiB,GAAG;CAC9C,UAAU,MAAM,QAAQ,eAAe,GAAG;CAC1C,SAAS,MAAM,QAAQ,cAAc,GAAG;CACxC,WAAW,MAAM,KAAK,YAAY,gBAAgB,KAAK,OAAO;CAC9D,SAAS,MAAM,QAAQ,cAAc,GAAG;AACzC,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const require_define = require("./define-crmMcXFS.cjs");
|
|
2
|
-
const require_engine = require("./engine-
|
|
2
|
+
const require_engine = require("./engine-DPVbMn1R.cjs");
|
|
3
3
|
//#region src/target/dokploy/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* The built-in `dokploy` target: the Dokploy engine `gkm deploy` has always
|
|
@@ -35,4 +35,4 @@ const dokployTarget = require_define.defineTarget({
|
|
|
35
35
|
//#endregion
|
|
36
36
|
exports.dokployTarget = dokployTarget;
|
|
37
37
|
|
|
38
|
-
//# sourceMappingURL=dokploy-
|
|
38
|
+
//# sourceMappingURL=dokploy-D6ktFzjP.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dokploy-
|
|
1
|
+
{"version":3,"file":"dokploy-D6ktFzjP.cjs","names":["defineTarget","validateDokploy","planDokploy","provisionDokploy","releaseDokploy","verifyDokploy","rollbackDokploy","dokployResult"],"sources":["../src/target/dokploy/index.ts"],"sourcesContent":["/**\n * The built-in `dokploy` target: the Dokploy engine `gkm deploy` has always\n * run, behind the phases.\n *\n * - `provision`: the project, environment and registry, and what the\n * manifest declares — its databases' roles applied over a port published\n * for the purpose.\n * - `release`: the stage's migrations, then each image built and pushed\n * beside its application and deployed, waited on until Dokploy has\n * finished; backends first and checked before any site is released.\n * - `verify`: each site answering its health check.\n * - `rollback`: what failed — or, `--atomic`, everything the run released —\n * pointed back at the image it ran before.\n */\n\nimport { defineTarget } from '../define';\nimport {\n\ttype DokployRun,\n\tdokployResult,\n\tplanDokploy,\n\tprovisionDokploy,\n\treleaseDokploy,\n\trollbackDokploy,\n\tvalidateDokploy,\n\tverifyDokploy,\n} from './engine';\n\nexport const dokployTarget = defineTarget<undefined, DokployRun>({\n\tname: 'dokploy',\n\truntime: 'server',\n\tcapabilities: { rollback: true, migrations: 'target', images: true },\n\tcredentials: ['dokploy', 'registry'],\n\tvalidate: (ctx) => validateDokploy(ctx),\n\tplan: (_ctx, run) => planDokploy(run),\n\tprovision: (_ctx, run) => provisionDokploy(run),\n\trelease: (_ctx, run) => releaseDokploy(run),\n\tverify: (_ctx, run) => verifyDokploy(run),\n\trollback: (_ctx, run, failure) => rollbackDokploy(run, failure),\n\tresult: (_ctx, run) => dokployResult(run),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgBA,eAAAA,aAAoC;CAChE,MAAM;CACN,SAAS;CACT,cAAc;EAAE,UAAU;EAAM,YAAY;EAAU,QAAQ;CAAK;CACnE,aAAa,CAAC,WAAW,UAAU;CACnC,WAAW,QAAQC,eAAAA,gBAAgB,GAAG;CACtC,OAAO,MAAM,QAAQC,eAAAA,YAAY,GAAG;CACpC,YAAY,MAAM,QAAQC,eAAAA,iBAAiB,GAAG;CAC9C,UAAU,MAAM,QAAQC,eAAAA,eAAe,GAAG;CAC1C,SAAS,MAAM,QAAQC,eAAAA,cAAc,GAAG;CACxC,WAAW,MAAM,KAAK,YAAYC,eAAAA,gBAAgB,KAAK,OAAO;CAC9D,SAAS,MAAM,QAAQC,eAAAA,cAAc,GAAG;AACzC,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
|
|
2
2
|
import { g as appKey } from "./config-BLrAd7Of.mjs";
|
|
3
3
|
import { i as easWorkflowPath, n as mobileStage, r as easWorkflow } from "./index.mjs";
|
|
4
|
-
import { t as loadStage } from "./stage-
|
|
4
|
+
import { t as loadStage } from "./stage-DfDPXyKq.mjs";
|
|
5
5
|
import { delimiter, dirname, join } from "node:path";
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
@@ -331,4 +331,4 @@ async function easSync(options, eas) {
|
|
|
331
331
|
//#endregion
|
|
332
332
|
export { chooseMobileApp, easCli, easSync, withStageProfiles };
|
|
333
333
|
|
|
334
|
-
//# sourceMappingURL=eas-
|
|
334
|
+
//# sourceMappingURL=eas-DdE1PH-Z.mjs.map
|