@geekmidas/cli 10.0.0-alpha.96 → 10.0.0-alpha.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GoDaddyProvider-BsUKjGcg.mjs → GoDaddyProvider-AqNu60WQ.mjs} +2 -2
- package/dist/{GoDaddyProvider-BsUKjGcg.mjs.map → GoDaddyProvider-AqNu60WQ.mjs.map} +1 -1
- package/dist/{GoDaddyProvider-DyHXHDHe.cjs → GoDaddyProvider-B4R_QFl8.cjs} +2 -2
- package/dist/{GoDaddyProvider-DyHXHDHe.cjs.map → GoDaddyProvider-B4R_QFl8.cjs.map} +1 -1
- package/dist/{LegacyStateStore-B6SOqRFi.mjs → LegacyStateStore-8F05-BOo.mjs} +3 -3
- package/dist/{LegacyStateStore-B6SOqRFi.mjs.map → LegacyStateStore-8F05-BOo.mjs.map} +1 -1
- package/dist/{LegacyStateStore-BnMcONE0.cjs → LegacyStateStore-B-aRqRdD.cjs} +3 -3
- package/dist/{LegacyStateStore-BnMcONE0.cjs.map → LegacyStateStore-B-aRqRdD.cjs.map} +1 -1
- package/dist/{LocalStateStore-pd4bbdJJ.cjs → LocalStateStore-B_bRI8M7.cjs} +2 -2
- package/dist/{LocalStateStore-pd4bbdJJ.cjs.map → LocalStateStore-B_bRI8M7.cjs.map} +1 -1
- package/dist/{LocalStateStore-6CrsZzqI.mjs → LocalStateStore-B_mfgcO8.mjs} +2 -2
- package/dist/{LocalStateStore-6CrsZzqI.mjs.map → LocalStateStore-B_mfgcO8.mjs.map} +1 -1
- package/dist/{S3StateStore-DP_7Q4yb.mjs → S3StateStore-CMN0Uzdp.mjs} +69 -8
- package/dist/S3StateStore-CMN0Uzdp.mjs.map +1 -0
- package/dist/{S3StateStore-CoGk6ZKU.cjs → S3StateStore-zK9zcd9f.cjs} +69 -8
- package/dist/S3StateStore-zK9zcd9f.cjs.map +1 -0
- package/dist/{SSMStateStore-D9s4_Do3.cjs → SSMStateStore-C489DnR6.cjs} +58 -7
- package/dist/SSMStateStore-C489DnR6.cjs.map +1 -0
- package/dist/{SSMStateStore-Bo6_KDYY.mjs → SSMStateStore-Cv7VcMak.mjs} +58 -7
- package/dist/SSMStateStore-Cv7VcMak.mjs.map +1 -0
- package/dist/{add-BQS2QZHp.mjs → add-BA5d4pA0.mjs} +4 -4
- package/dist/{add-BQS2QZHp.mjs.map → add-BA5d4pA0.mjs.map} +1 -1
- package/dist/{add-CjURJ-vI.cjs → add-HXzTCy_I.cjs} +4 -4
- package/dist/{add-CjURJ-vI.cjs.map → add-HXzTCy_I.cjs.map} +1 -1
- package/dist/{bundler-BMM3UsGm.mjs → bundler-CBomFsnd.mjs} +5 -5
- package/dist/{bundler-BMM3UsGm.mjs.map → bundler-CBomFsnd.mjs.map} +1 -1
- package/dist/{bundler-DmLJQ7AY.cjs → bundler-SX3Uy8qT.cjs} +5 -5
- package/dist/{bundler-DmLJQ7AY.cjs.map → bundler-SX3Uy8qT.cjs.map} +1 -1
- package/dist/{cli-C2c-jOVK.cjs → cli-1l0L9LCA.cjs} +2 -2
- package/dist/{cli-C2c-jOVK.cjs.map → cli-1l0L9LCA.cjs.map} +1 -1
- package/dist/{cli-Ce6NgaQF.mjs → cli-D7z1lQtO.mjs} +2 -2
- package/dist/{cli-Ce6NgaQF.mjs.map → cli-D7z1lQtO.mjs.map} +1 -1
- package/dist/{compose-ETFKqkTu.cjs → compose-C39XupJu.cjs} +7 -7
- package/dist/{compose-ETFKqkTu.cjs.map → compose-C39XupJu.cjs.map} +1 -1
- package/dist/{compose-BJDPFBAN.mjs → compose-DgWrNd2k.mjs} +7 -7
- package/dist/{compose-BJDPFBAN.mjs.map → compose-DgWrNd2k.mjs.map} +1 -1
- package/dist/{config-C8NPCn1l.d.mts → config-D-k0gaAr.d.mts} +4 -4
- package/dist/{config-4yirvxS8.d.cts.map → config-D-k0gaAr.d.mts.map} +1 -1
- package/dist/{config-4yirvxS8.d.cts → config-xIWIaDhW.d.cts} +4 -4
- package/dist/{config-C8NPCn1l.d.mts.map → config-xIWIaDhW.d.cts.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.d.cts +3 -3
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/deploy/public.cjs +7 -7
- package/dist/deploy/public.d.cts +5 -5
- package/dist/deploy/public.d.cts.map +1 -1
- package/dist/deploy/public.d.mts +5 -5
- package/dist/deploy/public.d.mts.map +1 -1
- package/dist/deploy/public.mjs +7 -7
- package/dist/{deploy-BdN0ym2i.cjs → deploy-Cu_HyWoJ.cjs} +19 -8
- package/dist/deploy-Cu_HyWoJ.cjs.map +1 -0
- package/dist/{deploy-DktQl7ti.mjs → deploy-LY-20Yeb.mjs} +19 -8
- package/dist/{deploy-DktQl7ti.mjs.map → deploy-LY-20Yeb.mjs.map} +1 -1
- package/dist/{discover-D-MdXZgm.d.mts → discover-CbJCQq4J.d.mts} +2 -2
- package/dist/{discover-BtFofyQB.d.cts.map → discover-CbJCQq4J.d.mts.map} +1 -1
- package/dist/{discover-BtFofyQB.d.cts → discover-RCW5mBXb.d.cts} +2 -2
- package/dist/{discover-D-MdXZgm.d.mts.map → discover-RCW5mBXb.d.cts.map} +1 -1
- package/dist/{dns-C-X6PLkV.cjs → dns-BFnoawgh.cjs} +3 -3
- package/dist/{dns-C-X6PLkV.cjs.map → dns-BFnoawgh.cjs.map} +1 -1
- package/dist/{dns-C2EeR6n2.mjs → dns-BbTOzmVp.mjs} +3 -3
- package/dist/{dns-C2EeR6n2.mjs.map → dns-BbTOzmVp.mjs.map} +1 -1
- package/dist/{dns-BjHECDO7.mjs → dns-Bmbhmz41.mjs} +5 -5
- package/dist/{dns-BjHECDO7.mjs.map → dns-Bmbhmz41.mjs.map} +1 -1
- package/dist/{dns-ClI7-d5g.cjs → dns-Dro_vbk9.cjs} +5 -5
- package/dist/{dns-ClI7-d5g.cjs.map → dns-Dro_vbk9.cjs.map} +1 -1
- package/dist/{dokploy-CD_Bc4EV.cjs → dokploy-CKgSww82.cjs} +2 -2
- package/dist/{dokploy-CD_Bc4EV.cjs.map → dokploy-CKgSww82.cjs.map} +1 -1
- package/dist/{dokploy-CxtkS5hl.mjs → dokploy-LR94sBVI.mjs} +2 -2
- package/dist/{dokploy-CxtkS5hl.mjs.map → dokploy-LR94sBVI.mjs.map} +1 -1
- package/dist/{encryption-BgQd4f2S.mjs → encryption-C0plOf4a.mjs} +3 -3
- package/dist/{encryption-BgQd4f2S.mjs.map → encryption-C0plOf4a.mjs.map} +1 -1
- package/dist/{encryption-CqVfz-m7.cjs → encryption-CUyw-8sc.cjs} +3 -3
- package/dist/{encryption-CqVfz-m7.cjs.map → encryption-CUyw-8sc.cjs.map} +1 -1
- package/dist/{engine-OVVKtPmW.cjs → engine-D8TeraDK.cjs} +4 -4
- package/dist/{engine-OVVKtPmW.cjs.map → engine-D8TeraDK.cjs.map} +1 -1
- package/dist/{engine-YlXzlTUl.mjs → engine-DqbqQhck.mjs} +4 -4
- package/dist/{engine-YlXzlTUl.mjs.map → engine-DqbqQhck.mjs.map} +1 -1
- package/dist/{github-CsMloeSL.cjs → github-DC4SIqV1.cjs} +35 -20
- package/dist/github-DC4SIqV1.cjs.map +1 -0
- package/dist/{github-DuuvqI3Z.mjs → github-zgaBOQvh.mjs} +35 -20
- package/dist/github-zgaBOQvh.mjs.map +1 -0
- package/dist/{index-5eL8rM6H.d.mts → index-ClqOsbBl.d.mts} +2 -2
- package/dist/{index-5eL8rM6H.d.mts.map → index-ClqOsbBl.d.mts.map} +1 -1
- package/dist/{index-Dz-gyjm_.d.cts → index-DgOBAEl5.d.cts} +2 -2
- package/dist/{index-Dz-gyjm_.d.cts.map → index-DgOBAEl5.d.cts.map} +1 -1
- package/dist/index.cjs +56 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +56 -52
- package/dist/index.mjs.map +1 -1
- package/dist/{migrate-CB8B6W9y.mjs → migrate-BJ8aLOWk.mjs} +3 -3
- package/dist/{migrate-CB8B6W9y.mjs.map → migrate-BJ8aLOWk.mjs.map} +1 -1
- package/dist/{migrate-CsPFHgTs.mjs → migrate-C230QeXU.mjs} +3 -3
- package/dist/{migrate-CsPFHgTs.mjs.map → migrate-C230QeXU.mjs.map} +1 -1
- package/dist/{migrate-BAmJeVq1.cjs → migrate-CWq8-s21.cjs} +3 -3
- package/dist/{migrate-BAmJeVq1.cjs.map → migrate-CWq8-s21.cjs.map} +1 -1
- package/dist/{migrate-BdkoNdIu.cjs → migrate-CsMrI7Dk.cjs} +3 -3
- package/dist/{migrate-BdkoNdIu.cjs.map → migrate-CsMrI7Dk.cjs.map} +1 -1
- package/dist/openapi.cjs +1 -1
- package/dist/openapi.d.cts +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/openapi.mjs +1 -1
- package/dist/projectBucket-BFp-SFee.mjs +177 -0
- package/dist/projectBucket-BFp-SFee.mjs.map +1 -0
- package/dist/projectBucket-Cho9DpSh.cjs +206 -0
- package/dist/projectBucket-Cho9DpSh.cjs.map +1 -0
- package/dist/reconcile/public.d.cts +2 -2
- package/dist/reconcile/public.d.mts +2 -2
- package/dist/{resolve-CUne0qOm.mjs → resolve-6EYNqYdr.mjs} +3 -3
- package/dist/{resolve-CUne0qOm.mjs.map → resolve-6EYNqYdr.mjs.map} +1 -1
- package/dist/{resolve-BDatNOoG.cjs → resolve-C8VkR4oW.cjs} +3 -3
- package/dist/{resolve-BDatNOoG.cjs.map → resolve-C8VkR4oW.cjs.map} +1 -1
- package/dist/{rollback-CCdEEEcF.mjs → rollback-BsThTeSN.mjs} +7 -6
- package/dist/{rollback-CCdEEEcF.mjs.map → rollback-BsThTeSN.mjs.map} +1 -1
- package/dist/{rollback-CuG3DkTY.cjs → rollback-CvGfm4DX.cjs} +7 -6
- package/dist/{rollback-CuG3DkTY.cjs.map → rollback-CvGfm4DX.cjs.map} +1 -1
- package/dist/{runtime-Vr6mleo2.d.mts → runtime-CaW4QqF2.d.cts} +2 -2
- package/dist/{runtime-DUQdM-mW.d.cts.map → runtime-CaW4QqF2.d.cts.map} +1 -1
- package/dist/{runtime-DUQdM-mW.d.cts → runtime-K5uxp6HE.d.mts} +2 -2
- package/dist/{runtime-Vr6mleo2.d.mts.map → runtime-K5uxp6HE.d.mts.map} +1 -1
- package/dist/{sandbox-DGOsMPMf.d.mts → sandbox-B_BkfmTP.d.mts} +2 -2
- package/dist/{sandbox-BbJmh2rI.d.cts.map → sandbox-B_BkfmTP.d.mts.map} +1 -1
- package/dist/{sandbox-BbJmh2rI.d.cts → sandbox-D8cfZUAA.d.cts} +2 -2
- package/dist/{sandbox-DGOsMPMf.d.mts.map → sandbox-D8cfZUAA.d.cts.map} +1 -1
- package/dist/{secrets-C5qROlbp.cjs → secrets-BTY6JhTp.cjs} +3 -3
- package/dist/{secrets-C5qROlbp.cjs.map → secrets-BTY6JhTp.cjs.map} +1 -1
- package/dist/{secrets-ZikTIxEm.mjs → secrets-HzKNTWg9.mjs} +3 -3
- package/dist/{secrets-ZikTIxEm.mjs.map → secrets-HzKNTWg9.mjs.map} +1 -1
- package/dist/{seeds-BjXW-Krf.cjs → seeds-BQlj9Fsg.cjs} +4 -4
- package/dist/{seeds-BjXW-Krf.cjs.map → seeds-BQlj9Fsg.cjs.map} +1 -1
- package/dist/{seeds-CbJSne1A.mjs → seeds-BsJRUL1K.mjs} +4 -4
- package/dist/{seeds-CbJSne1A.mjs.map → seeds-BsJRUL1K.mjs.map} +1 -1
- package/dist/{sniffer-NPD1dyab.cjs → sniffer-CeUKUoHn.cjs} +100 -10
- package/dist/sniffer-CeUKUoHn.cjs.map +1 -0
- package/dist/{sniffer-DQGBYY8i.mjs → sniffer-DVsvP8s-.mjs} +77 -11
- package/dist/sniffer-DVsvP8s-.mjs.map +1 -0
- package/dist/{stack-BFq3K-_z.mjs → stack-BQOyqaVG.mjs} +3 -3
- package/dist/{stack-BFq3K-_z.mjs.map → stack-BQOyqaVG.mjs.map} +1 -1
- package/dist/{stack-DOVvEd1T.cjs → stack-Clzi40EE.cjs} +3 -3
- package/dist/{stack-DOVvEd1T.cjs.map → stack-Clzi40EE.cjs.map} +1 -1
- package/dist/{stages-Cw6urZyJ.cjs → stages-BpDXFPGg.cjs} +4 -4
- package/dist/{stages-Cw6urZyJ.cjs.map → stages-BpDXFPGg.cjs.map} +1 -1
- package/dist/{stages-BEn2ArJZ.mjs → stages-DEmn7qI8.mjs} +4 -4
- package/dist/{stages-BEn2ArJZ.mjs.map → stages-DEmn7qI8.mjs.map} +1 -1
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.d.cts +2 -2
- package/dist/target/public.d.mts +2 -2
- package/dist/target/public.mjs +1 -1
- package/dist/{types-dipJRmKV.d.cts → types-4vPS_YFX.d.cts} +21 -4
- package/dist/types-4vPS_YFX.d.cts.map +1 -0
- package/dist/{types-bkqVscdN.d.mts → types-CFsEyFb1.d.mts} +21 -4
- package/dist/types-CFsEyFb1.d.mts.map +1 -0
- package/dist/workspace/index.cjs +1 -1
- package/dist/workspace/index.d.cts +2 -2
- package/dist/workspace/index.d.mts +2 -2
- package/dist/workspace/index.mjs +1 -1
- package/dist/{workspace-CqFUjObk.mjs → workspace-Bv4xROeu.mjs} +8 -4
- package/dist/workspace-Bv4xROeu.mjs.map +1 -0
- package/dist/{workspace-DDkm4y6D.cjs → workspace-C1M-S4al.cjs} +8 -4
- package/dist/workspace-C1M-S4al.cjs.map +1 -0
- package/package.json +16 -15
- package/dist/S3StateStore-CoGk6ZKU.cjs.map +0 -1
- package/dist/S3StateStore-DP_7Q4yb.mjs.map +0 -1
- package/dist/SSMStateStore-Bo6_KDYY.mjs.map +0 -1
- package/dist/SSMStateStore-D9s4_Do3.cjs.map +0 -1
- package/dist/deploy-BdN0ym2i.cjs.map +0 -1
- package/dist/github-CsMloeSL.cjs.map +0 -1
- package/dist/github-DuuvqI3Z.mjs.map +0 -1
- package/dist/sniffer-DQGBYY8i.mjs.map +0 -1
- package/dist/sniffer-NPD1dyab.cjs.map +0 -1
- package/dist/types-bkqVscdN.d.mts.map +0 -1
- package/dist/types-dipJRmKV.d.cts.map +0 -1
- package/dist/workspace-CqFUjObk.mjs.map +0 -1
- package/dist/workspace-DDkm4y6D.cjs.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
|
|
2
2
|
import { r as discover } from "./discover-qjFapetL.mjs";
|
|
3
|
-
import { j as TEST_STAGE } from "./workspace-
|
|
3
|
+
import { j as TEST_STAGE } from "./workspace-Bv4xROeu.mjs";
|
|
4
4
|
import { loadWorkspaceConfig } from "./config.mjs";
|
|
5
|
-
import { On as secretsStoreFor, Tn as loadSecretsForApp, ct as constructGlobs, ut as reconcileWorkspace } from "./seeds-
|
|
5
|
+
import { On as secretsStoreFor, Tn as loadSecretsForApp, ct as constructGlobs, ut as reconcileWorkspace } from "./seeds-BsJRUL1K.mjs";
|
|
6
6
|
import { a as NoSuchMigrationTarget, d as pendingMigrations, l as migrateAndSeed, u as migrateDatabases } from "./databases-BeGP5eDh.mjs";
|
|
7
7
|
import { n as slug, r as stamp } from "./index.mjs";
|
|
8
8
|
import { join } from "node:path";
|
|
@@ -263,4 +263,4 @@ function ids(targets) {
|
|
|
263
263
|
//#endregion
|
|
264
264
|
export { migrateAndSeed, migrateCommand, migrationCommand, prepareDevDatabases, reportPendingMigrations, seedCommand };
|
|
265
265
|
|
|
266
|
-
//# sourceMappingURL=migrate-
|
|
266
|
+
//# sourceMappingURL=migrate-BJ8aLOWk.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-CB8B6W9y.mjs","names":[],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { GkmError } from '../errors';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends GkmError {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets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AAM,OAAO,UAAU;CAC3C,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;CACvC,MAAM,UAAU,KAAK,QAAQ,IAAI,GAAG,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,OAAO,GAAG,OAAO,WAAW,GAAG;AAChC;AAEA,SAAS,IAAI,SAA+C;CAC3D,OAAO,QAAQ,KAAK,WAAW,OAAO,EAAE;AACzC"}
|
|
1
|
+
{"version":3,"file":"migrate-BJ8aLOWk.mjs","names":[],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { GkmError } from '../errors';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends GkmError {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets.map((target) => target.id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiEA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0C,SAAS;CAExC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,IAAI,MAAM,8EACe,MAAM,gEACG,MAAM,QAAQ,WAAW,GAC5D;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,SAAS;CAC3B;CAArB,YAAY,WAA4B;EACvC,MACC,uCAAuC,UAAU,yEAElD;EAJoB,KAAA,YAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;;;;AA2BA,eAAsB,WACrB,KACA,OACsB;CACtB,MAAM,EAAE,cAAc,MAAM,oBAAoB,GAAG;CACnD,MAAM,QAAQ,UAAU,OAAO;CAC/B,MAAM,SAAS,SAAS;CACxB,IAAI,WAAW,SAAS,WAAA,QACvB,MAAM,IAAI,qBAAqB,QAAQ,KAAK;CAG7C,MAAM,UAA2C,CAAC;CAClD,MAAM,WAAW,MAAM,SAAS;EAC/B,UAA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,WAAW,KAAK,GAC5C,KACD;CACA,MAAM,UAAU,MAAM,KAAK,iBAAiB;EAC3C,WAAW,IAAI,kBAAkB;GAAE,GAAG;GAAS,GAAG,MAAM;EAAI,CAAC;EAC7D,SAAS;CACV,CAAC;CAED,IAAI,CAAC,SAAS;EACb,OAAO,IAAI,KAAK,OAAO,WAAW,IAAI,KAAK,GAAG,eAAe;EAC7D;CACD;CAEA,MAAM,OAAO,MAAM,MAClB,MAAM,UAAU,MAChB,QACA,GAAG,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,QAAQ,QAAQ,aAAa,EAAE,OAC7D,GAAG,QAAQ,KAAK,EAAE,GACnB;CACA,OAAO,IAAI,MAAM,MAAM;CACvB,OAAO;AACR;AAEA,MAAM,OAAO;;;;;;;;;;AAWb,eAAe,MACd,MACA,QACA,MACA,SACkB;CAClB,MAAM,SAAS,KAAK,MAAM,OAAO,UAAU;CAC3C,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;CACvC,MAAM,UAAU,KAAK,QAAQ,IAAI,GAAG,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,OAAO,GAAG,OAAO,WAAW,GAAG;AAChC;AAEA,SAAS,IAAI,SAA+C;CAC3D,OAAO,QAAQ,KAAK,WAAW,OAAO,EAAE;AACzC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
|
|
2
|
-
import { N as assertDeployedStage, dt as SECRETS_STORE_PROVIDERS, ft as UnknownSecretsStoreProvider } from "./workspace-
|
|
2
|
+
import { N as assertDeployedStage, dt as SECRETS_STORE_PROVIDERS, ft as UnknownSecretsStoreProvider } from "./workspace-Bv4xROeu.mjs";
|
|
3
3
|
import { loadWorkspaceSettings } from "./config.mjs";
|
|
4
|
-
import { On as secretsStoreFor, kn as storeFromConfig } from "./seeds-
|
|
4
|
+
import { On as secretsStoreFor, kn as storeFromConfig } from "./seeds-BsJRUL1K.mjs";
|
|
5
5
|
//#region src/secrets/migrate.ts
|
|
6
6
|
/**
|
|
7
7
|
* `gkm secrets:migrate` — copy a deployed stage's secrets from the store
|
|
@@ -91,4 +91,4 @@ async function secretsMigrateCommand(options) {
|
|
|
91
91
|
//#endregion
|
|
92
92
|
export { secretsMigrateCommand };
|
|
93
93
|
|
|
94
|
-
//# sourceMappingURL=migrate-
|
|
94
|
+
//# sourceMappingURL=migrate-C230QeXU.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-
|
|
1
|
+
{"version":3,"file":"migrate-C230QeXU.mjs","names":[],"sources":["../src/secrets/migrate.ts"],"sourcesContent":["/**\n * `gkm secrets:migrate` — copy a deployed stage's secrets from the store\n * `secrets.store` names to another one, whole: service passwords, URLs and\n * custom keys alike, so nothing is regenerated and running services keep\n * their credentials.\n *\n * It copies and nothing more. The source is left as it was, and gkm.config.ts\n * is not edited: pointing `secrets.store` at the new store is the switch, and\n * the old copy is deleted by hand once deploys read from the new one.\n */\n\nimport { loadWorkspaceSettings } from '../config.js';\nimport { GkmError } from '../errors';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport {\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreConfig,\n\ttype SecretsStoreOptions,\n\ttype SecretsStoreProvider,\n\tsecretsStoreFor,\n\tstoreFromConfig,\n\tUnknownSecretsStoreProvider,\n} from './store.js';\n\nconst logger = console;\n\nexport interface SecretsMigrateOptions {\n\tstage: string;\n\t/** The store to copy to: `'file'`, `'ssm'` or `'secrets-manager'`. */\n\tto: string;\n\t/** The target's AWS region; defaults to the configured store's. */\n\tregion?: string;\n\t/** Overwrite a stage the target already holds. */\n\tforce?: boolean;\n\t/** The AWS profile for the stage's account, for both stores. */\n\tprofile?: string;\n}\n\n/** An AWS store to copy to, with no region given and none configured. */\nexport class MigrateTargetNeedsRegion extends GkmError {\n\tconstructor(readonly to: string) {\n\t\tsuper(\n\t\t\t`Copying to ${to} needs a region, and secrets.store has none to reuse. ` +\n\t\t\t\t`Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`,\n\t\t);\n\t\tthis.name = 'MigrateTargetNeedsRegion';\n\t}\n}\n\n/** The target is the store the stage is already read from. */\nexport class MigrateTargetIsSource extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`Stage \"${stage}\" is already kept in ${to}, so there is nothing to copy. ` +\n\t\t\t\t'Name a different store with --to, or a different region with --region.',\n\t\t);\n\t\tthis.name = 'MigrateTargetIsSource';\n\t}\n}\n\n/** The configured store holds nothing for the stage. */\nexport class NoSecretsToMigrate extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${store} store holds no secrets for stage \"${stage}\", so there is nothing to copy. ` +\n\t\t\t\t`Check secrets.store in gkm.config.ts still names the store the stage is in, ` +\n\t\t\t\t`or create the stage there with gkm secrets:init --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'NoSecretsToMigrate';\n\t}\n}\n\n/** The target already holds the stage, and `--force` was not given. */\nexport class MigrateTargetHoldsStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${to} store already holds secrets for stage \"${stage}\". ` +\n\t\t\t\t'Pass --force to replace them with the ones being copied.',\n\t\t);\n\t\tthis.name = 'MigrateTargetHoldsStage';\n\t}\n}\n\n/** The store a `--to` name and region describe. */\nfunction targetConfig(\n\tto: string,\n\tregion: string | undefined,\n\tconfigured: SecretsStoreConfig,\n): SecretsStoreConfig {\n\tif (!(SECRETS_STORE_PROVIDERS as readonly string[]).includes(to)) {\n\t\tthrow new UnknownSecretsStoreProvider(to);\n\t}\n\tconst provider = to as SecretsStoreProvider;\n\tif (provider === 'file') return 'file';\n\n\tconst fallback =\n\t\ttypeof configured === 'object' && 'region' in configured\n\t\t\t? configured.region\n\t\t\t: undefined;\n\tconst resolved = region ?? fallback;\n\tif (!resolved) throw new MigrateTargetNeedsRegion(provider);\n\treturn { provider, region: resolved };\n}\n\nexport async function secretsMigrateCommand(\n\toptions: SecretsMigrateOptions,\n): Promise<void> {\n\tconst { stage, to } = options;\n\tconst workspace = await loadWorkspaceSettings();\n\tassertDeployedStage(workspace.stages, stage);\n\n\tconst configured = workspace.secrets.store ?? 'file';\n\tconst target = targetConfig(to, options.region, configured);\n\tconst sameStore =\n\t\ttypeof configured === 'string' || typeof target === 'string'\n\t\t\t? configured === target\n\t\t\t: configured.provider === target.provider &&\n\t\t\t\t'region' in configured &&\n\t\t\t\t'region' in target &&\n\t\t\t\tconfigured.region === target.region;\n\tif (sameStore) throw new MigrateTargetIsSource(stage, to);\n\n\tconst storeOptions: SecretsStoreOptions = options.profile\n\t\t? { profile: options.profile }\n\t\t: {};\n\tconst source = await secretsStoreFor(workspace, stage, storeOptions);\n\tconst destination = await storeFromConfig(workspace, target, storeOptions);\n\n\tconst secrets = await source.read(stage);\n\tif (!secrets) throw new NoSecretsToMigrate(stage, source.name);\n\n\tif (!options.force && (await destination.read(stage))) {\n\t\tthrow new MigrateTargetHoldsStage(stage, destination.name);\n\t}\n\n\tawait destination.write(stage, secrets);\n\n\tconst shape =\n\t\ttypeof target === 'object' && 'region' in target\n\t\t\t? `{ provider: '${target.provider}', region: '${target.region}' }`\n\t\t\t: `'file'`;\n\tlogger.log(\n\t\t`\\n✓ Copied the secrets for stage \"${stage}\" from ${source.name} to ${destination.name}`,\n\t);\n\tlogger.log(\n\t\t`\\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`,\n\t);\n\tlogger.log(\n\t\t` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAM,SAAS;;AAef,IAAa,2BAAb,cAA8C,SAAS;CACjC;CAArB,YAAY,IAAqB;EAChC,MACC,cAAc,GAAG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AO,YAChC,YAAY,cACZ,YAAY,UACZ,WAAW,WAAW,OAAO,QACjB,MAAM,IAAI,sBAAsB,OAAO,EAAE;CAExD,MAAM,eAAoC,QAAQ,UAC/C,EAAE,SAAS,QAAQ,QAAQ,IAC3B,CAAC;CACJ,MAAM,SAAS,MAAM,gBAAgB,WAAW,OAAO,YAAY;CACnE,MAAM,cAAc,MAAM,gBAAgB,WAAW,QAAQ,YAAY;CAEzE,MAAM,UAAU,MAAM,OAAO,KAAK,KAAK;CACvC,IAAI,CAAC,SAAS,MAAM,IAAI,mBAAmB,OAAO,OAAO,IAAI;CAE7D,IAAI,CAAC,QAAQ,SAAU,MAAM,YAAY,KAAK,KAAK,GAClD,MAAM,IAAI,wBAAwB,OAAO,YAAY,IAAI;CAG1D,MAAM,YAAY,MAAM,OAAO,OAAO;CAEtC,MAAM,QACL,OAAO,WAAW,YAAY,YAAY,SACvC,gBAAgB,OAAO,SAAS,cAAc,OAAO,OAAO,OAC5D;CACJ,OAAO,IACN,qCAAqC,MAAM,SAAS,OAAO,KAAK,MAAM,YAAY,MACnF;CACA,OAAO,IACN,kCAAkC,MAAM,uDAAuD,YAAY,KAAK,EACjH;CACA,OAAO,IACN,iBAAiB,OAAO,KAAK,uDAAuD,YAAY,KAAK,EACtG;AACD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const require_errors = require("./errors-DMC4Umsb.cjs");
|
|
2
2
|
const require_discover = require("./discover-DPgu-ScS.cjs");
|
|
3
|
-
const require_workspace = require("./workspace-
|
|
3
|
+
const require_workspace = require("./workspace-C1M-S4al.cjs");
|
|
4
4
|
const require_config = require("./config.cjs");
|
|
5
|
-
const require_seeds = require("./seeds-
|
|
5
|
+
const require_seeds = require("./seeds-BQlj9Fsg.cjs");
|
|
6
6
|
const require_databases = require("./databases-DGALFDG3.cjs");
|
|
7
7
|
const require_index = require("./index.cjs");
|
|
8
8
|
let node_path = require("node:path");
|
|
@@ -268,4 +268,4 @@ exports.prepareDevDatabases = prepareDevDatabases;
|
|
|
268
268
|
exports.reportPendingMigrations = reportPendingMigrations;
|
|
269
269
|
exports.seedCommand = seedCommand;
|
|
270
270
|
|
|
271
|
-
//# sourceMappingURL=migrate-
|
|
271
|
+
//# sourceMappingURL=migrate-CWq8-s21.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-BAmJeVq1.cjs","names":["GkmError","TEST_STAGE","loadWorkspaceConfig","discover","constructGlobs","reconcileWorkspace","migrateDatabases","migrateAndSeed","pendingMigrations","migrationTargets","canonicalId","NoSuchMigrationTarget","stamp","slug","loadSecretsForApp","secretsStoreFor","EnvironmentParser","serviceContext","join","mkdir","writeFile"],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { GkmError } from '../errors';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends GkmError {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets.map((target) => target.id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiEA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0CA,eAAAA,SAAS;CAExC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,IAAI,MAAM,8EACe,MAAM,gEACG,MAAM,QAAQC,kBAAAA,WAAW,GAC5D;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwCD,eAAAA,SAAS;CAC3B;CAArB,YAAY,WAA4B;EACvC,MACC,uCAAuC,UAAU,yEAElD;EAJoB,KAAA,YAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;;;;AA2BA,eAAsB,WACrB,KACA,OACsB;CACtB,MAAM,EAAE,cAAc,MAAME,eAAAA,oBAAoB,GAAG;CACnD,MAAM,QAAQ,UAAU,OAAO;CAC/B,MAAM,S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AS,IAAI,SAA+C;CAC3D,OAAO,QAAQ,KAAK,WAAW,OAAO,EAAE;AACzC"}
|
|
1
|
+
{"version":3,"file":"migrate-CWq8-s21.cjs","names":["GkmError","TEST_STAGE","loadWorkspaceConfig","discover","constructGlobs","reconcileWorkspace","migrateDatabases","migrateAndSeed","pendingMigrations","migrationTargets","canonicalId","NoSuchMigrationTarget","stamp","slug","loadSecretsForApp","secretsStoreFor","EnvironmentParser","serviceContext","join","mkdir","writeFile"],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { GkmError } from '../errors';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends GkmError {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets.map((target) => target.id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiEA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0CA,eAAAA,SAAS;CAExC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,IAAI,MAAM,8EACe,MAAM,gEACG,MAAM,QAAQC,kBAAAA,WAAW,GAC5D;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwCD,eAAAA,SAAS;CAC3B;CAArB,YAAY,WAA4B;EACvC,MACC,uCAAuC,UAAU,yEAElD;EAJoB,KAAA,YAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;;;;AA2BA,eAAsB,WACrB,KACA,OACsB;CACtB,MAAM,EAAE,cAAc,MAAME,eAAAA,oBAAoB,GAAG;CACnD,MAAM,QAAQ,UAAU,OAAO;CAC/B,MAAM,SAAS,SAAS;CACxB,IAAI,WAAW,SAAS,WAAA,QACvB,MAAM,IAAI,qBAAqB,QAAQ,KAAK;CAG7C,MAAM,UAA2C,CAAC;CAClD,MAAM,WAAW,MAAM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sb.cjs");
|
|
2
|
-
const require_workspace = require("./workspace-
|
|
2
|
+
const require_workspace = require("./workspace-C1M-S4al.cjs");
|
|
3
3
|
const require_config = require("./config.cjs");
|
|
4
|
-
const require_seeds = require("./seeds-
|
|
4
|
+
const require_seeds = require("./seeds-BQlj9Fsg.cjs");
|
|
5
5
|
//#region src/secrets/migrate.ts
|
|
6
6
|
/**
|
|
7
7
|
* `gkm secrets:migrate` — copy a deployed stage's secrets from the store
|
|
@@ -91,4 +91,4 @@ async function secretsMigrateCommand(options) {
|
|
|
91
91
|
//#endregion
|
|
92
92
|
exports.secretsMigrateCommand = secretsMigrateCommand;
|
|
93
93
|
|
|
94
|
-
//# sourceMappingURL=migrate-
|
|
94
|
+
//# sourceMappingURL=migrate-CsMrI7Dk.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-
|
|
1
|
+
{"version":3,"file":"migrate-CsMrI7Dk.cjs","names":["GkmError","SECRETS_STORE_PROVIDERS","UnknownSecretsStoreProvider","loadWorkspaceSettings","secretsStoreFor","storeFromConfig"],"sources":["../src/secrets/migrate.ts"],"sourcesContent":["/**\n * `gkm secrets:migrate` — copy a deployed stage's secrets from the store\n * `secrets.store` names to another one, whole: service passwords, URLs and\n * custom keys alike, so nothing is regenerated and running services keep\n * their credentials.\n *\n * It copies and nothing more. The source is left as it was, and gkm.config.ts\n * is not edited: pointing `secrets.store` at the new store is the switch, and\n * the old copy is deleted by hand once deploys read from the new one.\n */\n\nimport { loadWorkspaceSettings } from '../config.js';\nimport { GkmError } from '../errors';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport {\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreConfig,\n\ttype SecretsStoreOptions,\n\ttype SecretsStoreProvider,\n\tsecretsStoreFor,\n\tstoreFromConfig,\n\tUnknownSecretsStoreProvider,\n} from './store.js';\n\nconst logger = console;\n\nexport interface SecretsMigrateOptions {\n\tstage: string;\n\t/** The store to copy to: `'file'`, `'ssm'` or `'secrets-manager'`. */\n\tto: string;\n\t/** The target's AWS region; defaults to the configured store's. */\n\tregion?: string;\n\t/** Overwrite a stage the target already holds. */\n\tforce?: boolean;\n\t/** The AWS profile for the stage's account, for both stores. */\n\tprofile?: string;\n}\n\n/** An AWS store to copy to, with no region given and none configured. */\nexport class MigrateTargetNeedsRegion extends GkmError {\n\tconstructor(readonly to: string) {\n\t\tsuper(\n\t\t\t`Copying to ${to} needs a region, and secrets.store has none to reuse. ` +\n\t\t\t\t`Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`,\n\t\t);\n\t\tthis.name = 'MigrateTargetNeedsRegion';\n\t}\n}\n\n/** The target is the store the stage is already read from. */\nexport class MigrateTargetIsSource extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`Stage \"${stage}\" is already kept in ${to}, so there is nothing to copy. ` +\n\t\t\t\t'Name a different store with --to, or a different region with --region.',\n\t\t);\n\t\tthis.name = 'MigrateTargetIsSource';\n\t}\n}\n\n/** The configured store holds nothing for the stage. */\nexport class NoSecretsToMigrate extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${store} store holds no secrets for stage \"${stage}\", so there is nothing to copy. ` +\n\t\t\t\t`Check secrets.store in gkm.config.ts still names the store the stage is in, ` +\n\t\t\t\t`or create the stage there with gkm secrets:init --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'NoSecretsToMigrate';\n\t}\n}\n\n/** The target already holds the stage, and `--force` was not given. */\nexport class MigrateTargetHoldsStage extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${to} store already holds secrets for stage \"${stage}\". ` +\n\t\t\t\t'Pass --force to replace them with the ones being copied.',\n\t\t);\n\t\tthis.name = 'MigrateTargetHoldsStage';\n\t}\n}\n\n/** The store a `--to` name and region describe. */\nfunction targetConfig(\n\tto: string,\n\tregion: string | undefined,\n\tconfigured: SecretsStoreConfig,\n): SecretsStoreConfig {\n\tif (!(SECRETS_STORE_PROVIDERS as readonly string[]).includes(to)) {\n\t\tthrow new UnknownSecretsStoreProvider(to);\n\t}\n\tconst provider = to as SecretsStoreProvider;\n\tif (provider === 'file') return 'file';\n\n\tconst fallback =\n\t\ttypeof configured === 'object' && 'region' in configured\n\t\t\t? configured.region\n\t\t\t: undefined;\n\tconst resolved = region ?? fallback;\n\tif (!resolved) throw new MigrateTargetNeedsRegion(provider);\n\treturn { provider, region: resolved };\n}\n\nexport async function secretsMigrateCommand(\n\toptions: SecretsMigrateOptions,\n): Promise<void> {\n\tconst { stage, to } = options;\n\tconst workspace = await loadWorkspaceSettings();\n\tassertDeployedStage(workspace.stages, stage);\n\n\tconst configured = workspace.secrets.store ?? 'file';\n\tconst target = targetConfig(to, options.region, configured);\n\tconst sameStore =\n\t\ttypeof configured === 'string' || typeof target === 'string'\n\t\t\t? configured === target\n\t\t\t: configured.provider === target.provider &&\n\t\t\t\t'region' in configured &&\n\t\t\t\t'region' in target &&\n\t\t\t\tconfigured.region === target.region;\n\tif (sameStore) throw new MigrateTargetIsSource(stage, to);\n\n\tconst storeOptions: SecretsStoreOptions = options.profile\n\t\t? { profile: options.profile }\n\t\t: {};\n\tconst source = await secretsStoreFor(workspace, stage, storeOptions);\n\tconst destination = await storeFromConfig(workspace, target, storeOptions);\n\n\tconst secrets = await source.read(stage);\n\tif (!secrets) throw new NoSecretsToMigrate(stage, source.name);\n\n\tif (!options.force && (await destination.read(stage))) {\n\t\tthrow new MigrateTargetHoldsStage(stage, destination.name);\n\t}\n\n\tawait destination.write(stage, secrets);\n\n\tconst shape =\n\t\ttypeof target === 'object' && 'region' in target\n\t\t\t? `{ provider: '${target.provider}', region: '${target.region}' }`\n\t\t\t: `'file'`;\n\tlogger.log(\n\t\t`\\n✓ Copied the secrets for stage \"${stage}\" from ${source.name} to ${destination.name}`,\n\t);\n\tlogger.log(\n\t\t`\\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`,\n\t);\n\tlogger.log(\n\t\t` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAM,SAAS;;AAef,IAAa,2BAAb,cAA8CA,eAAAA,SAAS;CACjC;CAArB,YAAY,IAAqB;EAChC,MACC,cAAc,GAAG,0FACqB,GAAG,oCAC1C;EAJoB,KAAA,KAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wBAAb,cAA2CA,eAAAA,SAAS;CAEzC;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,UAAU,MAAM,uBAAuB,GAAG,sGAE3C;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwCA,eAAAA,SAAS;CAEtC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,OAAO,MAAM,qCAAqC,MAAM,sKAEI,MAAM,EACnE;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,0BAAb,cAA6CA,eAAAA,SAAS;CAE3C;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,OAAO,GAAG,0CAA0C,MAAM,4DAE3D;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,aACR,IACA,QACA,YACqB;CACrB,IAAI,CAAEC,kBAAAA,wBAA8C,SAAS,EAAE,GAC9D,MAAM,IAAIC,kBAAAA,4BAA4B,EAAE;CAEzC,MAAM,WAAW;CACjB,IAAI,aAAa,QAAQ,OAAO;CAEhC,MAAM,WACL,OAAO,eAAe,YAAY,YAAY,aAC3C,WAAW,SACX,KAAA;CACJ,MAAM,WAAW,UAAU;CAC3B,IAAI,CAAC,UAAU,MAAM,IAA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
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const require_derive = require("./derive-DAbo49sm.cjs");
|
|
4
|
-
const require_workspace = require("./workspace-
|
|
4
|
+
const require_workspace = require("./workspace-C1M-S4al.cjs");
|
|
5
5
|
const require_config = require("./config.cjs");
|
|
6
6
|
const require_EndpointGenerator = require("./EndpointGenerator-De03t1hd.cjs");
|
|
7
7
|
const require_OpenApiTsGenerator = require("./OpenApiTsGenerator-CS_RtWOz.cjs");
|
package/dist/openapi.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as Routes, i as OpenApiConfig } from "./types-
|
|
1
|
+
import { a as Routes, i as OpenApiConfig } from "./types-4vPS_YFX.cjs";
|
|
2
2
|
import { Endpoint } from "@geekmidas/constructs/endpoints";
|
|
3
3
|
//#region src/generators/clientTelemetry.d.ts
|
|
4
4
|
type ClientTelemetryDefault = boolean | {
|
package/dist/openapi.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as Routes, i as OpenApiConfig } from "./types-
|
|
1
|
+
import { a as Routes, i as OpenApiConfig } from "./types-CFsEyFb1.mjs";
|
|
2
2
|
import { Endpoint } from "@geekmidas/constructs/endpoints";
|
|
3
3
|
//#region src/generators/clientTelemetry.d.ts
|
|
4
4
|
type ClientTelemetryDefault = boolean | {
|
package/dist/openapi.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
2
|
import { t as appKey } from "./derive-B4vDpzgP.mjs";
|
|
3
|
-
import { o as appConstructGlobs } from "./workspace-
|
|
3
|
+
import { o as appConstructGlobs } from "./workspace-Bv4xROeu.mjs";
|
|
4
4
|
import { loadWorkspaceConfig } from "./config.mjs";
|
|
5
5
|
import { a as telemetryArgs, r as parseTelemetryFlag, t as EndpointGenerator } from "./EndpointGenerator-Bor2tZCm.mjs";
|
|
6
6
|
import { t as OpenApiTsGenerator } from "./OpenApiTsGenerator-DWAF-7Fu.mjs";
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
|
|
2
|
+
import "./seeds-BsJRUL1K.mjs";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
//#region src/providers/projectBucket.ts
|
|
5
|
+
/**
|
|
6
|
+
* The project bucket: one S3 bucket per project and AWS account, created and
|
|
7
|
+
* owned by gkm, that holds what gkm keeps for every stage — the deploy state
|
|
8
|
+
* under `<prefix>/<project>/<stage>/`, and anything else gkm writes per stage
|
|
9
|
+
* beside it.
|
|
10
|
+
*
|
|
11
|
+
* Nothing can record its name — the deploy state lives in it — so the name is
|
|
12
|
+
* worked out the same way every time: `gkm-<scope>-<account id>`, the scope
|
|
13
|
+
* being the one the `s3` objects provider names its buckets with. The account
|
|
14
|
+
* id keeps it from clashing with another account's project of the same name
|
|
15
|
+
* without a random suffix; a clash that happens anyway (HeadBucket 403) is
|
|
16
|
+
* refused, never adopted.
|
|
17
|
+
*
|
|
18
|
+
* Created with versioning, SSE-S3, every public access blocked, ownership
|
|
19
|
+
* enforced for the bucket owner, a lifecycle that expires old versions, and
|
|
20
|
+
* the tag `gkm:project=<identity key>`.
|
|
21
|
+
*/
|
|
22
|
+
/** What the project part may take: 63 less `gkm-`, `-` and a 12-digit id. */
|
|
23
|
+
const SCOPE_MAX = 46;
|
|
24
|
+
/** The tag the bucket is created with, as the `s3` provider tags its own. */
|
|
25
|
+
const PROJECT_BUCKET_TAG = "gkm:project";
|
|
26
|
+
/** The bucket's name is held by another account, or cannot be reached. */
|
|
27
|
+
var ProjectBucketTaken = class extends GkmError {
|
|
28
|
+
bucket;
|
|
29
|
+
status;
|
|
30
|
+
constructor(bucket, status) {
|
|
31
|
+
super(`The project bucket '${bucket}' ${status === 301 ? "is in another region than the one configured" : "exists and this account cannot reach it — another account holds the name"} (HTTP ${status}). Name a bucket you own instead — in gkm.config.ts: state: { provider: 's3', bucket: '<your bucket>', region: '<its region>' } — or run with the credentials of the account the name is for.`);
|
|
32
|
+
this.bucket = bucket;
|
|
33
|
+
this.status = status;
|
|
34
|
+
this.name = "ProjectBucketTaken";
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** The running credentials may not create the project bucket. */
|
|
38
|
+
var ProjectBucketNotCreatable = class extends GkmError {
|
|
39
|
+
bucket;
|
|
40
|
+
reason;
|
|
41
|
+
constructor(bucket, reason) {
|
|
42
|
+
super(`The project bucket '${bucket}' does not exist yet, and these credentials cannot create it (${reason}). Run the first deploy with credentials allowed s3:CreateBucket and the bucket put-config actions on it — \`gkm deploy:github\` grants them to the CI role — or name an existing bucket: state: { provider: 's3', bucket, region }.`);
|
|
43
|
+
this.bucket = bucket;
|
|
44
|
+
this.reason = reason;
|
|
45
|
+
this.name = "ProjectBucketNotCreatable";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** {@link projectBucket}, from a deploy identity's scope. */
|
|
49
|
+
function projectBucketName(scope, accountId) {
|
|
50
|
+
let part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
51
|
+
if (part.length > SCOPE_MAX) {
|
|
52
|
+
const hash = createHash("sha256").update(scope).digest("hex").slice(0, 6);
|
|
53
|
+
part = `${part.slice(0, 39).replace(/-+$/, "")}-${hash}`;
|
|
54
|
+
}
|
|
55
|
+
return `gkm-${part}-${accountId}`;
|
|
56
|
+
}
|
|
57
|
+
/** The account the credentials are in — what the bucket is named by. */
|
|
58
|
+
async function callerAccountId(sts) {
|
|
59
|
+
const { GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
60
|
+
const { Account } = await sts.send(new GetCallerIdentityCommand({}));
|
|
61
|
+
return Account ?? "";
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The bucket's whole lifecycle configuration. A put replaces every rule the
|
|
65
|
+
* bucket has, so this is the one place the set is built: the bucket's own
|
|
66
|
+
* noncurrent-version expiry, and any per-prefix expiry passed in.
|
|
67
|
+
*/
|
|
68
|
+
function projectBucketLifecycle(expiries = []) {
|
|
69
|
+
return [{
|
|
70
|
+
ID: "gkm-noncurrent-versions",
|
|
71
|
+
Status: "Enabled",
|
|
72
|
+
Filter: { Prefix: "" },
|
|
73
|
+
NoncurrentVersionExpiration: { NoncurrentDays: 90 },
|
|
74
|
+
Expiration: { ExpiredObjectDeleteMarker: true }
|
|
75
|
+
}, ...expiries.map((expiry) => ({
|
|
76
|
+
ID: expiry.id,
|
|
77
|
+
Status: "Enabled",
|
|
78
|
+
Filter: { Prefix: expiry.prefix },
|
|
79
|
+
Expiration: { Days: expiry.days }
|
|
80
|
+
}))];
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Whether `bucket` is this account's (`ours`) or does not exist (`none`).
|
|
84
|
+
* Mapped by status: a HEAD has no body, so SDK v3 names a 301, 400 or 403
|
|
85
|
+
* `Unknown`.
|
|
86
|
+
*
|
|
87
|
+
* @throws {ProjectBucketTaken} on a 403 or 301
|
|
88
|
+
*/
|
|
89
|
+
async function findProjectBucket(s3, bucket) {
|
|
90
|
+
const { HeadBucketCommand } = await import("@aws-sdk/client-s3");
|
|
91
|
+
try {
|
|
92
|
+
await s3.send(new HeadBucketCommand({ Bucket: bucket }));
|
|
93
|
+
return "ours";
|
|
94
|
+
} catch (error) {
|
|
95
|
+
const status = error.$metadata?.httpStatusCode;
|
|
96
|
+
if (status === 404) return "none";
|
|
97
|
+
if (status === 403 || status === 301) throw new ProjectBucketTaken(bucket, status);
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The project bucket, created and configured if it does not exist yet.
|
|
103
|
+
* Returns whether this call created it. One that exists is used as it is.
|
|
104
|
+
*
|
|
105
|
+
* @throws {ProjectBucketTaken} when another account holds the name
|
|
106
|
+
* @throws {ProjectBucketNotCreatable} when the credentials may not create it
|
|
107
|
+
*/
|
|
108
|
+
async function ensureProjectBucket(s3, options) {
|
|
109
|
+
const { bucket: Bucket, region } = options;
|
|
110
|
+
if (await findProjectBucket(s3, Bucket) === "ours") return { created: false };
|
|
111
|
+
const S3 = await import("@aws-sdk/client-s3");
|
|
112
|
+
try {
|
|
113
|
+
await s3.send(new S3.CreateBucketCommand({
|
|
114
|
+
Bucket,
|
|
115
|
+
ObjectOwnership: "BucketOwnerEnforced",
|
|
116
|
+
...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
|
|
117
|
+
}));
|
|
118
|
+
} catch (error) {
|
|
119
|
+
const failure = error;
|
|
120
|
+
const code = failure.Code ?? failure.name;
|
|
121
|
+
if (code !== "BucketAlreadyOwnedByYou") {
|
|
122
|
+
if (code === "BucketAlreadyExists") throw new ProjectBucketTaken(Bucket, 409);
|
|
123
|
+
if (code === "AccessDenied" || failure.$metadata?.httpStatusCode === 403) throw new ProjectBucketNotCreatable(Bucket, failure.message ?? "AccessDenied");
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
await s3.send(new S3.PutPublicAccessBlockCommand({
|
|
128
|
+
Bucket,
|
|
129
|
+
PublicAccessBlockConfiguration: {
|
|
130
|
+
BlockPublicAcls: true,
|
|
131
|
+
IgnorePublicAcls: true,
|
|
132
|
+
BlockPublicPolicy: true,
|
|
133
|
+
RestrictPublicBuckets: true
|
|
134
|
+
}
|
|
135
|
+
}));
|
|
136
|
+
await s3.send(new S3.PutBucketOwnershipControlsCommand({
|
|
137
|
+
Bucket,
|
|
138
|
+
OwnershipControls: { Rules: [{ ObjectOwnership: "BucketOwnerEnforced" }] }
|
|
139
|
+
}));
|
|
140
|
+
await s3.send(new S3.PutBucketEncryptionCommand({
|
|
141
|
+
Bucket,
|
|
142
|
+
ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
|
|
143
|
+
}));
|
|
144
|
+
await s3.send(new S3.PutBucketVersioningCommand({
|
|
145
|
+
Bucket,
|
|
146
|
+
VersioningConfiguration: { Status: "Enabled" }
|
|
147
|
+
}));
|
|
148
|
+
await s3.send(new S3.PutBucketLifecycleConfigurationCommand({
|
|
149
|
+
Bucket,
|
|
150
|
+
LifecycleConfiguration: { Rules: projectBucketLifecycle(options.expiries) }
|
|
151
|
+
}));
|
|
152
|
+
await s3.send(new S3.PutBucketTaggingCommand({
|
|
153
|
+
Bucket,
|
|
154
|
+
Tagging: { TagSet: [{
|
|
155
|
+
Key: PROJECT_BUCKET_TAG,
|
|
156
|
+
Value: options.identity.key
|
|
157
|
+
}] }
|
|
158
|
+
}));
|
|
159
|
+
return { created: true };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The IAM actions creating and configuring the project bucket takes — what a
|
|
163
|
+
* role that runs the first deploy needs on it, beside object access.
|
|
164
|
+
*/
|
|
165
|
+
const PROJECT_BUCKET_CREATE_ACTIONS = [
|
|
166
|
+
"s3:CreateBucket",
|
|
167
|
+
"s3:PutBucketVersioning",
|
|
168
|
+
"s3:PutEncryptionConfiguration",
|
|
169
|
+
"s3:PutBucketPublicAccessBlock",
|
|
170
|
+
"s3:PutBucketOwnershipControls",
|
|
171
|
+
"s3:PutLifecycleConfiguration",
|
|
172
|
+
"s3:PutBucketTagging"
|
|
173
|
+
];
|
|
174
|
+
//#endregion
|
|
175
|
+
export { projectBucketName as a, findProjectBucket as i, callerAccountId as n, ensureProjectBucket as r, PROJECT_BUCKET_CREATE_ACTIONS as t };
|
|
176
|
+
|
|
177
|
+
//# sourceMappingURL=projectBucket-BFp-SFee.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"projectBucket-BFp-SFee.mjs","names":[],"sources":["../src/providers/projectBucket.ts"],"sourcesContent":["/**\n * The project bucket: one S3 bucket per project and AWS account, created and\n * owned by gkm, that holds what gkm keeps for every stage — the deploy state\n * under `<prefix>/<project>/<stage>/`, and anything else gkm writes per stage\n * beside it.\n *\n * Nothing can record its name — the deploy state lives in it — so the name is\n * worked out the same way every time: `gkm-<scope>-<account id>`, the scope\n * being the one the `s3` objects provider names its buckets with. The account\n * id keeps it from clashing with another account's project of the same name\n * without a random suffix; a clash that happens anyway (HeadBucket 403) is\n * refused, never adopted.\n *\n * Created with versioning, SSE-S3, every public access blocked, ownership\n * enforced for the bucket owner, a lifecycle that expires old versions, and\n * the tag `gkm:project=<identity key>`.\n */\n\nimport { createHash } from 'node:crypto';\nimport type {\n\tBucketLocationConstraint,\n\tLifecycleRule,\n\tS3Client,\n} from '@aws-sdk/client-s3';\nimport type { STSClient } from '@aws-sdk/client-sts';\nimport { type DeployIdentity, deployIdentity } from '../deploy/identity.js';\nimport { GkmError } from '../errors';\n\n/** S3's limit on a bucket name. */\nconst BUCKET_NAME_MAX = 63;\n/** What the project part may take: 63 less `gkm-`, `-` and a 12-digit id. */\nconst SCOPE_MAX = BUCKET_NAME_MAX - 'gkm-'.length - 1 - 12;\n\n/** The tag the bucket is created with, as the `s3` provider tags its own. */\nexport const PROJECT_BUCKET_TAG = 'gkm:project';\n\n/** How long a replaced or deleted object's old version is kept. */\nexport const NONCURRENT_VERSION_DAYS = 90;\n\n/** The bucket's name is held by another account, or cannot be reached. */\nexport class ProjectBucketTaken extends GkmError {\n\tconstructor(\n\t\treadonly bucket: string,\n\t\t/** HeadBucket's status: 403 another account's, 301 another region's. */\n\t\treadonly status: number,\n\t) {\n\t\tconst why =\n\t\t\tstatus === 301\n\t\t\t\t? 'is in another region than the one configured'\n\t\t\t\t: 'exists and this account cannot reach it — another account holds the name';\n\t\tsuper(\n\t\t\t`The project bucket '${bucket}' ${why} (HTTP ${status}). Name a bucket ` +\n\t\t\t\t\"you own instead — in gkm.config.ts: state: { provider: 's3', \" +\n\t\t\t\t\"bucket: '<your bucket>', region: '<its region>' } — or run with the \" +\n\t\t\t\t'credentials of the account the name is for.',\n\t\t);\n\t\tthis.name = 'ProjectBucketTaken';\n\t}\n}\n\n/** The running credentials may not create the project bucket. */\nexport class ProjectBucketNotCreatable extends GkmError {\n\tconstructor(\n\t\treadonly bucket: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The project bucket '${bucket}' does not exist yet, and these ` +\n\t\t\t\t`credentials cannot create it (${reason}). Run the first deploy with ` +\n\t\t\t\t'credentials allowed s3:CreateBucket and the bucket put-config ' +\n\t\t\t\t'actions on it — `gkm deploy:github` grants them to the CI role — ' +\n\t\t\t\t\"or name an existing bucket: state: { provider: 's3', bucket, region }.\",\n\t\t);\n\t\tthis.name = 'ProjectBucketNotCreatable';\n\t}\n}\n\n/**\n * The project bucket's name: `gkm-<scope>-<account id>`, lowercase and\n * DNS-safe. A scope too long to fit keeps its start and ends in a hash of\n * the whole, so two long scopes never share a name.\n */\nexport function projectBucket(\n\tworkspace: { name: string; deploy?: { namespace?: string } },\n\toptions: { accountId: string },\n): string {\n\tconst { scope } = deployIdentity(workspace, '');\n\treturn projectBucketName(scope, options.accountId);\n}\n\n/** {@link projectBucket}, from a deploy identity's scope. */\nexport function projectBucketName(scope: string, accountId: string): string {\n\tlet part = scope\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '');\n\tif (part.length > SCOPE_MAX) {\n\t\tconst hash = createHash('sha256').update(scope).digest('hex').slice(0, 6);\n\t\tpart = `${part.slice(0, SCOPE_MAX - 7).replace(/-+$/, '')}-${hash}`;\n\t}\n\treturn `gkm-${part}-${accountId}`;\n}\n\n/** The account the credentials are in — what the bucket is named by. */\nexport async function callerAccountId(sts: STSClient): Promise<string> {\n\tconst { GetCallerIdentityCommand } = await import('@aws-sdk/client-sts');\n\tconst { Account } = await sts.send(new GetCallerIdentityCommand({}));\n\treturn Account ?? '';\n}\n\n/** An expiry for one stage's prefix, added beside the bucket's own rule. */\nexport interface PrefixExpiry {\n\t/** Rule id, unique in the bucket — e.g. `backups-production`. */\n\tid: string;\n\t/** Key prefix it applies to — e.g. `gkm/acme/production/backups/`. */\n\tprefix: string;\n\t/** Days after which a current object expires. */\n\tdays: number;\n}\n\n/**\n * The bucket's whole lifecycle configuration. A put replaces every rule the\n * bucket has, so this is the one place the set is built: the bucket's own\n * noncurrent-version expiry, and any per-prefix expiry passed in.\n */\nexport function projectBucketLifecycle(\n\texpiries: readonly PrefixExpiry[] = [],\n): LifecycleRule[] {\n\treturn [\n\t\t{\n\t\t\tID: 'gkm-noncurrent-versions',\n\t\t\tStatus: 'Enabled',\n\t\t\tFilter: { Prefix: '' },\n\t\t\tNoncurrentVersionExpiration: { NoncurrentDays: NONCURRENT_VERSION_DAYS },\n\t\t\t// A lock is deleted every run; its markers go once nothing is under them.\n\t\t\tExpiration: { ExpiredObjectDeleteMarker: true },\n\t\t},\n\t\t...expiries.map(\n\t\t\t(expiry): LifecycleRule => ({\n\t\t\t\tID: expiry.id,\n\t\t\t\tStatus: 'Enabled',\n\t\t\t\tFilter: { Prefix: expiry.prefix },\n\t\t\t\tExpiration: { Days: expiry.days },\n\t\t\t}),\n\t\t),\n\t];\n}\n\ninterface S3Failure {\n\tname?: string;\n\tCode?: string;\n\tmessage?: string;\n\t$metadata?: { httpStatusCode?: number };\n}\n\n/**\n * Whether `bucket` is this account's (`ours`) or does not exist (`none`).\n * Mapped by status: a HEAD has no body, so SDK v3 names a 301, 400 or 403\n * `Unknown`.\n *\n * @throws {ProjectBucketTaken} on a 403 or 301\n */\nexport async function findProjectBucket(\n\ts3: S3Client,\n\tbucket: string,\n): Promise<'ours' | 'none'> {\n\tconst { HeadBucketCommand } = await import('@aws-sdk/client-s3');\n\ttry {\n\t\tawait s3.send(new HeadBucketCommand({ Bucket: bucket }));\n\t\treturn 'ours';\n\t} catch (error) {\n\t\tconst status = (error as S3Failure).$metadata?.httpStatusCode;\n\t\tif (status === 404) return 'none';\n\t\tif (status === 403 || status === 301) {\n\t\t\tthrow new ProjectBucketTaken(bucket, status);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport interface EnsureProjectBucketOptions {\n\tbucket: string;\n\tregion: string;\n\t/** The deploy identity the bucket is tagged with. */\n\tidentity: Pick<DeployIdentity, 'key'>;\n\t/** Per-prefix expiries beside the bucket's own rule. */\n\texpiries?: readonly PrefixExpiry[];\n}\n\n/**\n * The project bucket, created and configured if it does not exist yet.\n * Returns whether this call created it. One that exists is used as it is.\n *\n * @throws {ProjectBucketTaken} when another account holds the name\n * @throws {ProjectBucketNotCreatable} when the credentials may not create it\n */\nexport async function ensureProjectBucket(\n\ts3: S3Client,\n\toptions: EnsureProjectBucketOptions,\n): Promise<{ created: boolean }> {\n\tconst { bucket: Bucket, region } = options;\n\tif ((await findProjectBucket(s3, Bucket)) === 'ours') {\n\t\treturn { created: false };\n\t}\n\n\tconst S3 = await import('@aws-sdk/client-s3');\n\ttry {\n\t\tawait s3.send(\n\t\t\tnew S3.CreateBucketCommand({\n\t\t\t\tBucket,\n\t\t\t\tObjectOwnership: 'BucketOwnerEnforced',\n\t\t\t\t// us-east-1 is the one region named by leaving it out.\n\t\t\t\t...(region === 'us-east-1'\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tCreateBucketConfiguration: {\n\t\t\t\t\t\t\t\tLocationConstraint: region as BucketLocationConstraint,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t}),\n\t\t);\n\t} catch (error) {\n\t\tconst failure = error as S3Failure;\n\t\tconst code = failure.Code ?? failure.name;\n\t\t// Another run created it a moment ago: configure it all the same.\n\t\tif (code !== 'BucketAlreadyOwnedByYou') {\n\t\t\tif (code === 'BucketAlreadyExists') {\n\t\t\t\tthrow new ProjectBucketTaken(Bucket, 409);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcode === 'AccessDenied' ||\n\t\t\t\tfailure.$metadata?.httpStatusCode === 403\n\t\t\t) {\n\t\t\t\tthrow new ProjectBucketNotCreatable(\n\t\t\t\t\tBucket,\n\t\t\t\t\tfailure.message ?? 'AccessDenied',\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tawait s3.send(\n\t\tnew S3.PutPublicAccessBlockCommand({\n\t\t\tBucket,\n\t\t\tPublicAccessBlockConfiguration: {\n\t\t\t\tBlockPublicAcls: true,\n\t\t\t\tIgnorePublicAcls: true,\n\t\t\t\tBlockPublicPolicy: true,\n\t\t\t\tRestrictPublicBuckets: true,\n\t\t\t},\n\t\t}),\n\t);\n\tawait s3.send(\n\t\tnew S3.PutBucketOwnershipControlsCommand({\n\t\t\tBucket,\n\t\t\tOwnershipControls: {\n\t\t\t\tRules: [{ ObjectOwnership: 'BucketOwnerEnforced' }],\n\t\t\t},\n\t\t}),\n\t);\n\tawait s3.send(\n\t\tnew S3.PutBucketEncryptionCommand({\n\t\t\tBucket,\n\t\t\tServerSideEncryptionConfiguration: {\n\t\t\t\tRules: [\n\t\t\t\t\t{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' } },\n\t\t\t\t],\n\t\t\t},\n\t\t}),\n\t);\n\tawait s3.send(\n\t\tnew S3.PutBucketVersioningCommand({\n\t\t\tBucket,\n\t\t\tVersioningConfiguration: { Status: 'Enabled' },\n\t\t}),\n\t);\n\tawait s3.send(\n\t\tnew S3.PutBucketLifecycleConfigurationCommand({\n\t\t\tBucket,\n\t\t\tLifecycleConfiguration: {\n\t\t\t\tRules: projectBucketLifecycle(options.expiries),\n\t\t\t},\n\t\t}),\n\t);\n\tawait s3.send(\n\t\tnew S3.PutBucketTaggingCommand({\n\t\t\tBucket,\n\t\t\tTagging: {\n\t\t\t\tTagSet: [{ Key: PROJECT_BUCKET_TAG, Value: options.identity.key }],\n\t\t\t},\n\t\t}),\n\t);\n\treturn { created: true };\n}\n\n/**\n * The IAM actions creating and configuring the project bucket takes — what a\n * role that runs the first deploy needs on it, beside object access.\n */\nexport const PROJECT_BUCKET_CREATE_ACTIONS = [\n\t's3:CreateBucket',\n\t's3:PutBucketVersioning',\n\t's3:PutEncryptionConfiguration',\n\t's3:PutBucketPublicAccessBlock',\n\t's3:PutBucketOwnershipControls',\n\t's3:PutLifecycleConfiguration',\n\t's3:PutBucketTagging',\n] as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,YAAY;;AAGlB,MAAa,qBAAqB;;AAMlC,IAAa,qBAAb,cAAwC,SAAS;CAEtC;CAEA;CAHV,YACC,QAEA,QACC;EAKD,MACC,uBAAuB,OAAO,IAJ9B,WAAW,MACR,iDACA,2EAEmC,SAAS,OAAO,8LAIvD;EAbS,KAAA,SAAA;EAEA,KAAA,SAAA;EAYT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,4BAAb,cAA+C,SAAS;CAE7C;CACA;CAFV,YACC,QACA,QACC;EACD,MACC,uBAAuB,OAAO,gEACI,OAAO,qOAI1C;EATS,KAAA,SAAA;EACA,KAAA,SAAA;EAST,KAAK,OAAO;CACb;AACD;;AAgBA,SAAgB,kBAAkB,OAAe,WAA2B;CAC3E,IAAI,OAAO,MACT,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,YAAY,EAAE;CACxB,IAAI,KAAK,SAAS,WAAW;EAC5B,MAAM,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;EACxE,OAAO,GAAG,KAAK,MAAM,GAAG,EAAa,CAAC,CAAC,QAAQ,OAAO,EAAE,EAAE,GAAG;CAC9D;CACA,OAAO,OAAO,KAAK,GAAG;AACvB;;AAGA,eAAsB,gBAAgB,KAAiC;CACtE,MAAM,EAAE,6BAA6B,MAAM,OAAO;CAClD,MAAM,EAAE,YAAY,MAAM,IAAI,KAAK,IAAI,yBAAyB,CAAC,CAAC,CAAC;CACnE,OAAO,WAAW;AACnB;;;;;;AAiBA,SAAgB,uBACf,WAAoC,CAAC,GACnB;CAClB,OAAO,CACN;EACC,I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