@supatype/cli 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +174 -164
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +36 -0
  5. package/dist/adopt-walkthrough.d.ts +40 -0
  6. package/dist/adopt-walkthrough.d.ts.map +1 -0
  7. package/dist/adopt-walkthrough.js +113 -0
  8. package/dist/adopt-walkthrough.js.map +1 -0
  9. package/dist/cli-version-embedded.js +1 -1
  10. package/dist/commands/admin.d.ts.map +1 -1
  11. package/dist/commands/admin.js +7 -16
  12. package/dist/commands/admin.js.map +1 -1
  13. package/dist/commands/adopt.d.ts.map +1 -1
  14. package/dist/commands/adopt.js +5 -6
  15. package/dist/commands/adopt.js.map +1 -1
  16. package/dist/commands/db.js +3 -3
  17. package/dist/commands/db.js.map +1 -1
  18. package/dist/commands/deploy.d.ts.map +1 -1
  19. package/dist/commands/deploy.js +7 -4
  20. package/dist/commands/deploy.js.map +1 -1
  21. package/dist/commands/dev.d.ts.map +1 -1
  22. package/dist/commands/dev.js +20 -5
  23. package/dist/commands/dev.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +5 -7
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/init.js +1 -1
  28. package/dist/commands/init.js.map +1 -1
  29. package/dist/commands/migrate.d.ts.map +1 -1
  30. package/dist/commands/migrate.js +6 -3
  31. package/dist/commands/migrate.js.map +1 -1
  32. package/dist/commands/push.d.ts.map +1 -1
  33. package/dist/commands/push.js +10 -6
  34. package/dist/commands/push.js.map +1 -1
  35. package/dist/commands/seed.js +2 -2
  36. package/dist/commands/seed.js.map +1 -1
  37. package/dist/dev-compose.d.ts +42 -0
  38. package/dist/dev-compose.d.ts.map +1 -1
  39. package/dist/dev-compose.js +128 -81
  40. package/dist/dev-compose.js.map +1 -1
  41. package/dist/dev-db-reset.d.ts +19 -0
  42. package/dist/dev-db-reset.d.ts.map +1 -0
  43. package/dist/dev-db-reset.js +75 -0
  44. package/dist/dev-db-reset.js.map +1 -0
  45. package/dist/dev-initial-push.d.ts +37 -0
  46. package/dist/dev-initial-push.d.ts.map +1 -0
  47. package/dist/dev-initial-push.js +91 -0
  48. package/dist/dev-initial-push.js.map +1 -0
  49. package/dist/dev-ports.d.ts.map +1 -1
  50. package/dist/dev-ports.js +1 -1
  51. package/dist/dev-ports.js.map +1 -1
  52. package/dist/diff-output.d.ts +2 -2
  53. package/dist/diff-output.d.ts.map +1 -1
  54. package/dist/diff-output.js +1 -1
  55. package/dist/diff-output.js.map +1 -1
  56. package/dist/engine-client.d.ts +5 -1
  57. package/dist/engine-client.d.ts.map +1 -1
  58. package/dist/engine-client.js +8 -6
  59. package/dist/engine-client.js.map +1 -1
  60. package/dist/engine-push-output.d.ts +10 -0
  61. package/dist/engine-push-output.d.ts.map +1 -1
  62. package/dist/engine-push-output.js +12 -0
  63. package/dist/engine-push-output.js.map +1 -1
  64. package/dist/{seed-connection.d.ts → host-database.d.ts} +20 -10
  65. package/dist/host-database.d.ts.map +1 -0
  66. package/dist/{seed-connection.js → host-database.js} +40 -14
  67. package/dist/host-database.js.map +1 -0
  68. package/dist/resolve-target.d.ts +2 -2
  69. package/dist/resolve-target.d.ts.map +1 -1
  70. package/dist/resolve-target.js +15 -11
  71. package/dist/resolve-target.js.map +1 -1
  72. package/dist/retired-no-cache.d.ts +18 -0
  73. package/dist/retired-no-cache.d.ts.map +1 -0
  74. package/dist/retired-no-cache.js +21 -0
  75. package/dist/retired-no-cache.js.map +1 -0
  76. package/dist/self-host-compose.d.ts +21 -0
  77. package/dist/self-host-compose.d.ts.map +1 -1
  78. package/dist/self-host-compose.js +27 -4
  79. package/dist/self-host-compose.js.map +1 -1
  80. package/dist/type-extractor.d.ts.map +1 -1
  81. package/dist/type-extractor.js +12 -6
  82. package/dist/type-extractor.js.map +1 -1
  83. package/package.json +2 -2
  84. package/src/adopt-walkthrough.ts +142 -0
  85. package/src/cli-version-embedded.ts +1 -1
  86. package/src/commands/admin.ts +7 -20
  87. package/src/commands/adopt.ts +5 -6
  88. package/src/commands/db.ts +3 -3
  89. package/src/commands/deploy.ts +7 -4
  90. package/src/commands/dev.ts +22 -6
  91. package/src/commands/doctor.ts +5 -7
  92. package/src/commands/init.ts +1 -1
  93. package/src/commands/migrate.ts +7 -4
  94. package/src/commands/push.ts +28 -10
  95. package/src/commands/seed.ts +2 -2
  96. package/src/dev-compose.ts +178 -88
  97. package/src/dev-db-reset.ts +95 -0
  98. package/src/dev-initial-push.ts +134 -0
  99. package/src/dev-ports.ts +1 -1
  100. package/src/diff-output.ts +2 -2
  101. package/src/engine-client.ts +5 -4
  102. package/src/engine-push-output.ts +19 -0
  103. package/src/{seed-connection.ts → host-database.ts} +42 -12
  104. package/src/resolve-target.ts +20 -14
  105. package/src/retired-no-cache.ts +27 -0
  106. package/src/self-host-compose.ts +29 -4
  107. package/src/type-extractor.ts +15 -5
  108. package/tests/adopt-result.test.ts +27 -0
  109. package/tests/adopt-walkthrough.test.ts +129 -0
  110. package/tests/db-published-and-addressable.test.ts +69 -0
  111. package/tests/dev-db-reset.test.ts +162 -0
  112. package/tests/dev-initial-push.test.ts +142 -0
  113. package/tests/engine-push-output.test.ts +30 -1
  114. package/tests/host-connection-targets.test.ts +84 -0
  115. package/tests/{seed-connection.test.ts → host-database.test.ts} +33 -15
  116. package/tests/retired-no-cache.test.ts +46 -0
  117. package/tests/type-extractor.test.ts +44 -0
  118. package/tsconfig.tsbuildinfo +1 -1
  119. package/dist/seed-connection.d.ts.map +0 -1
  120. package/dist/seed-connection.js.map +0 -1
@@ -39,6 +39,7 @@ import {
39
39
  composeDockerImageEnv,
40
40
  composeProjectName,
41
41
  exitComposeFailed,
42
+ publishesDbToHost,
42
43
  runDockerCompose,
43
44
  schemaEngineImageForPush,
44
45
  writeSelfHostCompose,
@@ -70,6 +71,8 @@ import {
70
71
  formatEnginePushMessage,
71
72
  parseEngineJsonOutput,
72
73
  parseEnginePushOutput,
74
+ printPushWarnings,
75
+ type EnginePushResult,
73
76
  } from "./engine-push-output.js"
74
77
  import { withAdminRoles } from "./studio-admin-roles.js"
75
78
  import { restoreSystemRelationTargets } from "./restore-system-relation-targets.js"
@@ -77,9 +80,10 @@ import { provisionBucketsFromAst } from "./storage-provision.js"
77
80
  import type { ExtractedSchemaAstV2 } from "./schema-ast-v2.js"
78
81
  import { ensureFirstAdminUserForProject } from "./commands/admin.js"
79
82
  import { publishDevReady } from "./dev-ready-panel.js"
80
-
81
- /** Default host port for compose Postgres when `overrides.engine` is set (devLocal). */
82
- const COMPOSE_DEV_DB_PORT = 54329
83
+ import { exitInitialPushFailed, pushInitialSchema, type InitialPushSteps } from "./dev-initial-push.js"
84
+ import { offerAdoption, unmanagedTables, type AdoptionSteps } from "./adopt-walkthrough.js"
85
+ import { resetDevDatabase } from "./dev-db-reset.js"
86
+ import { hostComposeDbUrl, resolveHostDatabaseUrl } from "./host-database.js"
83
87
 
84
88
  /** Sync optional Docker image pins from config into `.env` (no JWT rotation). */
85
89
  export function syncComposeImagePins(cwd: string, config: SupatypeProjectConfig): void {
@@ -95,6 +99,10 @@ export function syncComposeImagePins(cwd: string, config: SupatypeProjectConfig)
95
99
 
96
100
  export interface DevComposeOptions {
97
101
  watch: boolean
102
+ /** Remove the Postgres data volume before starting, after confirmation. Never implied. */
103
+ resetDb: boolean
104
+ /** The reset was already confirmed on the command line, so do not prompt for it. */
105
+ yes: boolean
98
106
  }
99
107
 
100
108
  /** In-compose Postgres URL (SCRAM; not published to the host). */
@@ -117,22 +125,14 @@ async function resolveDevDbPort(cwd: string): Promise<number> {
117
125
  *
118
126
  * The compose helpers below describe the `db` *container*, on the host at
119
127
  * `SUPATYPE_DEV_DB_PORT`, or in-network at `db:5432`. Neither exists for a project pointed at an
120
- * external database, and passing one produced "pool timed out while waiting for an open connection"
121
- *- a message with nothing in it about the URL being wrong.
128
+ * external database, and passing one produced "pool timed out while waiting for an open connection",
129
+ * a message with nothing in it about the URL being wrong.
122
130
  */
123
131
  function projectDatabaseUrl(cwd: string, config: SupatypeProjectConfig, inNetwork = false): string {
124
132
  if (usesExternalDatabase(config)) return connectionString(config)
125
133
  return inNetwork ? composeDbUrl(cwd) : hostComposeDbUrl(cwd)
126
134
  }
127
135
 
128
- function hostComposeDbUrl(cwd: string): string {
129
- const port = readEnvValue(cwd, "SUPATYPE_DEV_DB_PORT", String(COMPOSE_DEV_DB_PORT))
130
- const user = readEnvValue(cwd, "POSTGRES_USER", "supatype_admin")
131
- const pass = devPostgresPassword(cwd)
132
- const db = readEnvValue(cwd, "POSTGRES_DB", "supatype")
133
- return `postgresql://${user}:${pass}@127.0.0.1:${port}/${db}?sslmode=disable`
134
- }
135
-
136
136
  /**
137
137
  * When `provider: docker` and `overrides.engine` is set, ensure Postgres is published
138
138
  * on the host (SUPATYPE_DEV_DB_PORT) so the local engine binary can connect.
@@ -145,10 +145,10 @@ export async function ensureDockerDbPublishedForHostEngine(
145
145
  if (resolveRuntimeProvider(config) !== "docker") {
146
146
  throw new Error("ensureDockerDbPublishedForHostEngine requires provider: docker")
147
147
  }
148
- if (!hasEngineOverride(config)) {
148
+ if (!publishesDbToHost(config)) {
149
149
  throw new Error(
150
- "Docker Postgres is not published to the host without overrides.engine. " +
151
- "Set overrides.engine in supatype.local.config.ts or pass --connection.",
150
+ "This project uses an external database, so there is no Docker Postgres to publish. " +
151
+ "Point DATABASE_URL at it, or pass --connection.",
152
152
  )
153
153
  }
154
154
 
@@ -192,13 +192,12 @@ export async function resolveHostEngineDatabaseUrl(
192
192
  config: SupatypeProjectConfig,
193
193
  explicit?: string,
194
194
  ): Promise<string> {
195
- if (explicit?.trim()) return explicit
196
- if (config.connection?.trim()) return config.connection
197
- if (usesLocalDockerEngineDb(config)) {
195
+ // Published first, when this project's Postgres is the local docker one, so the URL below
196
+ // reaches something. The URL itself comes from the one resolver every host-side command uses.
197
+ if (usesLocalDockerEngineDb(config, explicit)) {
198
198
  await ensureDockerDbPublishedForHostEngine(cwd, config)
199
- return hostComposeDbUrl(cwd)
200
199
  }
201
- return connectionString(config)
200
+ return resolveHostDatabaseUrl(cwd, config, { connection: explicit, allowDerived: true }).dsn
202
201
  }
203
202
 
204
203
  /**
@@ -762,7 +761,7 @@ async function runComposeSchemaPush(
762
761
  const pgSchema = config.schema?.pg_schema ?? "public"
763
762
  const sources = writeSchemaSourcePushArtifacts(cwd)
764
763
  try {
765
- await engineRequest("/push", {
764
+ const result = await engineRequest<EnginePushResult>("/push", {
766
765
  ast,
767
766
  database_url: projectDatabaseUrl(cwd, config),
768
767
  schema: pgSchema,
@@ -774,6 +773,7 @@ async function runComposeSchemaPush(
774
773
  }
775
774
  : {}),
776
775
  })
776
+ printPushWarnings(result)
777
777
  } catch (err) {
778
778
  _lastFailedAst = astJson
779
779
  throw err
@@ -897,6 +897,7 @@ async function runComposeEnginePush(
897
897
  if (exitStatus === 0) {
898
898
  if (pushResult) {
899
899
  console.log(`[supatype] ${formatEnginePushMessage(pushResult)}`)
900
+ printPushWarnings(pushResult)
900
901
  } else {
901
902
  console.log("[supatype] Schema applied.")
902
903
  }
@@ -905,13 +906,38 @@ async function runComposeEnginePush(
905
906
  return { status: exitStatus, output }
906
907
  }
907
908
 
908
- async function runComposeEngineDiff(
909
+ /**
910
+ * One schema-engine subcommand in the compose `tools` profile, against the stack's own database.
911
+ *
912
+ * In a container, so it reaches Postgres at the compose-internal address and needs nothing
913
+ * published to the host. That is what a host-side `supatype adopt` got wrong on a docker project
914
+ * (supatype#85), and why the push walkthrough runs adopt this way instead.
915
+ */
916
+ /** One engine run: its exit, what it printed on stdout alone, and everything it printed. */
917
+ export interface EngineRun {
918
+ status: number
919
+ stdout: string
920
+ output: string
921
+ }
922
+
923
+ /**
924
+ * The adopt result from one engine run, or null when there is none to read.
925
+ *
926
+ * From stdout alone. The engine prints the preview as multi-line JSON, which only parses as a
927
+ * whole, and with stderr joined on (a compose warning about an unset variable, an engine log line)
928
+ * it did not parse at all, so a preview that worked was reported as a failed adopt.
929
+ */
930
+ export function adoptResultFrom(run: EngineRun): AdoptResult | null {
931
+ return run.status === 0 ? parseEngineJsonOutput<AdoptResult>(run.stdout) : null
932
+ }
933
+
934
+ async function runComposeEngineCommand(
909
935
  paths: SelfHostComposePaths,
910
936
  cwd: string,
911
937
  composeProject: string,
912
938
  config: SupatypeProjectConfig,
913
- pgSchema: string,
914
- ): Promise<{ status: number; output: string; diff: DiffResult | null }> {
939
+ command: readonly string[],
940
+ ): Promise<EngineRun> {
915
941
  const envFile = resolve(cwd, ".env")
916
942
  const composeArgs = ["compose", "--progress", "quiet"]
917
943
  if (composeProject) composeArgs.push("-p", composeProject)
@@ -926,33 +952,85 @@ async function runComposeEngineDiff(
926
952
  "run",
927
953
  "--rm",
928
954
  "schema-engine",
929
- "diff",
955
+ ...command,
930
956
  "-i",
931
957
  "/project/.supatype/schema.ast.json",
932
958
  "--database-url",
933
959
  projectDatabaseUrl(cwd, config, true),
934
960
  "--schema",
935
- pgSchema,
961
+ config.schema?.pg_schema ?? "public",
936
962
  )
937
- const diffEnv: NodeJS.ProcessEnv = {
938
- ...process.env,
939
- COMPOSE_PROGRESS: "quiet",
940
- }
963
+ const env: NodeJS.ProcessEnv = { ...process.env, COMPOSE_PROGRESS: "quiet" }
941
964
  const engineImage = await schemaEngineImageForPush(config)
942
- if (engineImage) {
943
- diffEnv.SUPATYPE_ENGINE_IMAGE = engineImage
944
- }
965
+ if (engineImage) env.SUPATYPE_ENGINE_IMAGE = engineImage
945
966
  const result = spawnSync("docker", composeArgs, {
946
967
  cwd,
947
968
  encoding: "utf8",
948
969
  maxBuffer: 10 * 1024 * 1024,
949
- env: diffEnv,
970
+ env,
950
971
  })
951
- const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim()
952
- const exitStatus = result.status ?? 1
953
- const diff = parseEngineJsonOutput<DiffResult>(output)
972
+ return {
973
+ status: result.status ?? 1,
974
+ stdout: result.stdout ?? "",
975
+ output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(),
976
+ }
977
+ }
978
+
979
+ async function runComposeEngineDiff(
980
+ paths: SelfHostComposePaths,
981
+ cwd: string,
982
+ composeProject: string,
983
+ config: SupatypeProjectConfig,
984
+ ): Promise<{ status: number; output: string; diff: DiffResult | null }> {
985
+ const result = await runComposeEngineCommand(paths, cwd, composeProject, config, ["diff"])
986
+ return { ...result, diff: parseEngineJsonOutput<DiffResult>(result.output) }
987
+ }
988
+
989
+ /** Adoption against a docker project's own database, for the push walkthrough. */
990
+ export function dockerAdoptionSteps(cwd: string, config: SupatypeProjectConfig): AdoptionSteps {
991
+ return {
992
+ preview: async () => (await adoptSchemaDocker(cwd, config, false)).stampStatements ?? [],
993
+ apply: async () => (await adoptSchemaDocker(cwd, config, true)).stamped ?? 0,
994
+ }
995
+ }
954
996
 
955
- return { status: exitStatus, output, diff }
997
+ /** What `adopt` reports, previewing or applying. */
998
+ export interface AdoptResult {
999
+ status?: string
1000
+ stampStatements?: string[]
1001
+ stamped?: number
1002
+ }
1003
+
1004
+ /**
1005
+ * Adopt on a docker project's own database: the stamp preview, or with `yes`, the stamps applied.
1006
+ *
1007
+ * Through the compose schema-engine, or the local engine binary when `overrides.engine` is set,
1008
+ * the same way `diffSchemaDocker` reaches the database. The stack's database must be running,
1009
+ * which it is whenever a push has just been refused by it.
1010
+ */
1011
+ export async function adoptSchemaDocker(
1012
+ cwd: string,
1013
+ config: SupatypeProjectConfig,
1014
+ yes: boolean,
1015
+ ): Promise<AdoptResult> {
1016
+ const project = composeProjectName(config.project.name)
1017
+ if (hasEngineOverride(config)) {
1018
+ await ensureDockerDbPublishedForHostEngine(cwd, config, { intro: "Adopt" })
1019
+ await ensureEngine()
1020
+ return engineRequest<AdoptResult>("/adopt", {
1021
+ ast: withPublishing(loadSchemaAst(schemaPathFromProject(config, cwd), cwd), config),
1022
+ database_url: projectDatabaseUrl(cwd, config),
1023
+ schema: config.schema?.pg_schema ?? "public",
1024
+ yes,
1025
+ })
1026
+ }
1027
+ const paths = writeSelfHostCompose(cwd, config, { devLocal: true })
1028
+ const result = await runComposeEngineCommand(paths, cwd, project, config, yes ? ["adopt", "--yes"] : ["adopt"])
1029
+ const parsed = adoptResultFrom(result)
1030
+ if (parsed === null) {
1031
+ throw new Error(filterComposeNoise(result.output) || `Engine adopt failed (exit ${result.status})`)
1032
+ }
1033
+ return parsed
956
1034
  }
957
1035
 
958
1036
  /**
@@ -1000,11 +1078,11 @@ export async function diffSchemaDocker(cwd: string, config: SupatypeProjectConfi
1000
1078
  const astPath = join(supatypeDir, "schema.ast.json")
1001
1079
  writeFileSync(astPath, JSON.stringify(ast))
1002
1080
 
1003
- let result = await runComposeEngineDiff(paths, cwd, project, config, pgSchema)
1081
+ let result = await runComposeEngineDiff(paths, cwd, project, config)
1004
1082
  // Windows Docker bind mounts can lag briefly after the host write.
1005
1083
  if (result.status !== 0) {
1006
1084
  await new Promise((r) => setTimeout(r, 250))
1007
- result = await runComposeEngineDiff(paths, cwd, project, config, pgSchema)
1085
+ result = await runComposeEngineDiff(paths, cwd, project, config)
1008
1086
  }
1009
1087
  if (result.status !== 0) {
1010
1088
  const detail = filterComposeNoise(result.output) || result.output
@@ -1039,10 +1117,10 @@ export async function pushSchemaDocker(cwd: string, config: SupatypeProjectConfi
1039
1117
  // No dev db port for an external database: `ensureDevDbPort` allocates a host port for the `db`
1040
1118
  // container *and persists a matching DATABASE_URL*, which overwrote the operator's own URL, the
1041
1119
  // one the whole stack and every CLI command reads.
1042
- const devDbPort =
1043
- hasEngineOverride(config) && !usesExternalDatabase(config)
1044
- ? await resolveDevDbPort(cwd)
1045
- : undefined
1120
+ // Whatever compose publishes, `DATABASE_URL` has to point at. Gating this on
1121
+ // `overrides.engine` while the compose file published unconditionally is what left a project
1122
+ // with a database on 54329 and a URL still saying 5432.
1123
+ const devDbPort = publishesDbToHost(config) ? await resolveDevDbPort(cwd) : undefined
1046
1124
 
1047
1125
  const now = Math.floor(Date.now() / 1000)
1048
1126
  const jwtBase = { iss: "supatype", iat: now, exp: now + 315_360_000 }
@@ -1078,6 +1156,41 @@ export async function pushSchemaDocker(cwd: string, config: SupatypeProjectConfi
1078
1156
  console.log("[supatype] Schema pushed.")
1079
1157
  }
1080
1158
 
1159
+ /**
1160
+ * The first push of a `dev` session. A retry only ever brings Postgres back up: it never removes
1161
+ * a volume, so a refused push leaves the developer's database exactly as it found it.
1162
+ */
1163
+ async function applyInitialSchema(
1164
+ cwd: string,
1165
+ config: SupatypeProjectConfig,
1166
+ paths: SelfHostComposePaths,
1167
+ schemaPath: string,
1168
+ project: string,
1169
+ brand: DockerBrandOptions,
1170
+ ): Promise<void> {
1171
+ const steps: InitialPushSteps = {
1172
+ push: () => runComposeSchemaPush(cwd, config, paths, schemaPath, project),
1173
+ recoverDatabase: () => startComposeDatabase(config, paths, cwd, project, brand, undefined, endDevSession),
1174
+ dumpLogs: (reason) => dumpComposeDbLogs(paths, cwd, project, reason),
1175
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1176
+ }
1177
+ let outcome = await pushInitialSchema(steps)
1178
+ if (outcome.kind === "refused" && outcome.reason === "unmanaged-tables") {
1179
+ // Offered rather than only named: the stack's database is up, so adoption can run against it
1180
+ // here, and a push straight after it is the one that was just refused.
1181
+ const tables = unmanagedTables(outcome.message) ?? []
1182
+ const adopted = await offerAdoption(tables, dockerAdoptionSteps(cwd, config), {
1183
+ yes: false,
1184
+ retry: "supatype dev",
1185
+ })
1186
+ if (adopted === "adopted") outcome = await pushInitialSchema(steps)
1187
+ }
1188
+ if (outcome.kind === "applied") return
1189
+ // Before the message, so it reaches the real terminal rather than a TUI that is going away.
1190
+ endDevSession()
1191
+ exitInitialPushFailed(outcome, brand)
1192
+ }
1193
+
1081
1194
  export async function runDevCompose(cwd: string, config: SupatypeProjectConfig, opts: DevComposeOptions): Promise<void> {
1082
1195
  if (resolveRuntimeProvider(config) !== "docker") {
1083
1196
  throw new Error("runDevCompose requires provider: docker")
@@ -1090,10 +1203,10 @@ export async function runDevCompose(cwd: string, config: SupatypeProjectConfig,
1090
1203
  // No dev db port for an external database: `ensureDevDbPort` allocates a host port for the `db`
1091
1204
  // container *and persists a matching DATABASE_URL*, which overwrote the operator's own URL, the
1092
1205
  // one the whole stack and every CLI command reads.
1093
- const devDbPort =
1094
- hasEngineOverride(config) && !usesExternalDatabase(config)
1095
- ? await resolveDevDbPort(cwd)
1096
- : undefined
1206
+ // Whatever compose publishes, `DATABASE_URL` has to point at. Gating this on
1207
+ // `overrides.engine` while the compose file published unconditionally is what left a project
1208
+ // with a database on 54329 and a URL still saying 5432.
1209
+ const devDbPort = publishesDbToHost(config) ? await resolveDevDbPort(cwd) : undefined
1097
1210
 
1098
1211
  const now = Math.floor(Date.now() / 1000)
1099
1212
  const jwtBase = { iss: "supatype", iat: now, exp: now + 315_360_000 }
@@ -1149,6 +1262,21 @@ export async function runDevCompose(cwd: string, config: SupatypeProjectConfig,
1149
1262
  await recoverStaleDevSession(cwd)
1150
1263
  await handleComposeProjectRename(cwd, config.project.name, paths)
1151
1264
 
1265
+ // Only on request, and before Postgres starts, so it comes up on an empty volume.
1266
+ if (opts.resetDb) {
1267
+ await resetDevDatabase(
1268
+ {
1269
+ composePath: paths.composePath,
1270
+ cwd,
1271
+ project,
1272
+ external: usesExternalDatabase(config),
1273
+ brand: devBrand,
1274
+ onFailure: endDevSession,
1275
+ },
1276
+ { yes: opts.yes },
1277
+ )
1278
+ }
1279
+
1152
1280
  if (!usesExternalDatabase(config)) {
1153
1281
  console.log("[supatype] Bringing up Postgres (compose db)...")
1154
1282
  }
@@ -1162,45 +1290,7 @@ export async function runDevCompose(cwd: string, config: SupatypeProjectConfig,
1162
1290
 
1163
1291
  // A: apply schema before realtime (and the rest of the stack) starts decoding WAL.
1164
1292
  const schemaPath = schemaPathFromProject(config, cwd)
1165
- {
1166
- const maxAttempts = 3
1167
- let lastErr: unknown
1168
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1169
- try {
1170
- await runComposeSchemaPush(cwd, config, paths, schemaPath, project)
1171
- lastErr = undefined
1172
- break
1173
- } catch (e: unknown) {
1174
- lastErr = e
1175
- console.error(
1176
- `[supatype] Initial schema push failed (attempt ${attempt}/${maxAttempts}):`,
1177
- (e as Error).message,
1178
- )
1179
- dumpComposeDbLogs(paths, cwd, project, `schema push attempt ${attempt}/${maxAttempts}`)
1180
- if (attempt < maxAttempts) {
1181
- // Only for a database Supatype created. Tearing down an external one is not ours to do,
1182
- // and `down -v` would destroy the stack's other volumes for a failure that was never
1183
- // about Postgres.
1184
- if (!usesExternalDatabase(config)) {
1185
- console.log("[supatype] Resetting Postgres after failed schema push...")
1186
- runDockerCompose(paths.composePath, ["down", "-v"], cwd, project, {
1187
- quiet: true,
1188
- brand: devBrand,
1189
- })
1190
- await startComposeDatabase(config, paths, cwd, project, devBrand)
1191
- }
1192
- await new Promise((r) => setTimeout(r, 3000 * attempt))
1193
- }
1194
- }
1195
- }
1196
- if (lastErr) {
1197
- dumpComposeDbLogs(paths, cwd, project, "initial schema push exhausted")
1198
- endDevSession()
1199
- throw new Error(
1200
- `Initial schema push failed after ${maxAttempts} attempts: ${(lastErr as Error).message}`,
1201
- )
1202
- }
1203
- }
1293
+ await applyInitialSchema(cwd, config, paths, schemaPath, project, devBrand)
1204
1294
 
1205
1295
  console.log("[supatype] Bringing up Docker Compose services...")
1206
1296
  const upStatus = runDockerCompose(paths.composePath, ["up", "-d"], cwd, project, {
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `supatype dev --reset-db`: start again from an empty local database, on request only.
3
+ *
4
+ * The one place `dev` removes data, and it removes exactly one volume. Storage and the cache keep
5
+ * the developer's uploaded files and warm keys, and nothing about a database reset is a reason to
6
+ * lose those, which is what `docker compose down -v` used to do whenever a push failed.
7
+ *
8
+ * Confirmed by a prompt that names the volume. With no TTY there is nobody to answer it, so the
9
+ * flag is refused unless `--yes` says the caller has already decided.
10
+ */
11
+ import { spawnSync } from "node:child_process"
12
+ import type { DockerBrandOptions } from "./docker-runtime.js"
13
+ import { DB_VOLUME_KEY, exitComposeFailed, runDockerCompose } from "./self-host-compose.js"
14
+ import { confirm } from "./ui/confirm.js"
15
+ import { fatalError } from "./ui/fatal.js"
16
+ import { isInteractive } from "./ui/interactive.js"
17
+
18
+ export interface DevDbResetTarget {
19
+ composePath: string
20
+ cwd: string
21
+ /** The compose project name, which Docker prefixes every volume with. */
22
+ project: string
23
+ /** True when the project points at a database Supatype does not run. */
24
+ external: boolean
25
+ brand?: DockerBrandOptions
26
+ /** Runs before any exit, so the message reaches the terminal rather than the dev TUI. */
27
+ onFailure?: () => void
28
+ }
29
+
30
+ /** The Docker volume holding this project's Postgres data. */
31
+ export function devDbVolumeName(composeProject: string): string {
32
+ return `${composeProject}_${DB_VOLUME_KEY}`
33
+ }
34
+
35
+ function brandOpts(target: DevDbResetTarget): { brand?: DockerBrandOptions } {
36
+ return target.brand !== undefined ? { brand: target.brand } : {}
37
+ }
38
+
39
+ function fail(target: DevDbResetTarget, message: string, hints: string[]): never {
40
+ target.onFailure?.()
41
+ fatalError(message, hints, brandOpts(target))
42
+ }
43
+
44
+ function volumeExists(volume: string): boolean {
45
+ return spawnSync("docker", ["volume", "inspect", volume], { encoding: "utf8" }).status === 0
46
+ }
47
+
48
+ /** Returns once the developer has agreed to lose the volume, and exits otherwise. */
49
+ async function requireApproval(target: DevDbResetTarget, volume: string, yes: boolean): Promise<void> {
50
+ if (yes) return
51
+ if (!isInteractive()) {
52
+ fail(target, `--reset-db would remove the Postgres data volume ${volume}, and there is no terminal to confirm it.`, [
53
+ "Re-run with --yes to remove it without a prompt. Nothing was removed.",
54
+ ])
55
+ }
56
+ const approved = await confirm(
57
+ `Remove the Postgres data volume ${volume}? Every row in the local database is deleted. Storage and other volumes are kept.`,
58
+ { default: false },
59
+ )
60
+ if (!approved) fail(target, "Reset cancelled. Nothing was removed.", [])
61
+ }
62
+
63
+ function removeDbVolume(target: DevDbResetTarget, volume: string): void {
64
+ // The volume cannot be removed while a container holds it, so the db container goes first, and
65
+ // alone. No `-v` anywhere: the one volume that goes is named explicitly below.
66
+ const rm = runDockerCompose(target.composePath, ["rm", "--stop", "--force", "db"], target.cwd, target.project, {
67
+ quiet: true,
68
+ ...brandOpts(target),
69
+ })
70
+ if (rm !== 0) {
71
+ target.onFailure?.()
72
+ exitComposeFailed(rm, "Could not stop the Postgres container. Nothing was removed.", target.brand)
73
+ }
74
+ const removed = spawnSync("docker", ["volume", "rm", volume], { encoding: "utf8" })
75
+ if (removed.status !== 0) {
76
+ fail(target, `Could not remove the Postgres data volume ${volume}.`, [String(removed.stderr ?? "").trim()])
77
+ }
78
+ }
79
+
80
+ /** Remove the Postgres data volume, and nothing else, once the developer has agreed to it. */
81
+ export async function resetDevDatabase(target: DevDbResetTarget, opts: { yes: boolean }): Promise<void> {
82
+ if (target.external) {
83
+ fail(target, "--reset-db only resets a database Supatype runs.", [
84
+ "This project points at an external database (database.external). Nothing was removed.",
85
+ ])
86
+ }
87
+ const volume = devDbVolumeName(target.project)
88
+ if (!volumeExists(volume)) {
89
+ console.log(`[supatype] No Postgres data volume ${volume} yet, nothing to reset.`)
90
+ return
91
+ }
92
+ await requireApproval(target, volume, opts.yes)
93
+ removeDbVolume(target, volume)
94
+ console.log(`[supatype] Removed the Postgres data volume ${volume}. Postgres starts empty.`)
95
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The first schema push of `supatype dev`, and what a failed one is allowed to do.
3
+ *
4
+ * This loop used to answer every failure the same way: `docker compose down -v`, start Postgres
5
+ * again, push again. `-v` removes every volume in the stack, so a push the engine refused on
6
+ * purpose (a table Supatype does not manage, a destructive change) cost the developer their local
7
+ * database and their uploaded files, and the second attempt then succeeded against an empty one.
8
+ * A refusal is deterministic. The same schema against the same database is refused again, and the
9
+ * only thing a reset changed was that there was no longer anything to refuse.
10
+ *
11
+ * So a failure is classified before anything else happens. A database that is not reachable yet is
12
+ * retried, and the retry never removes anything. Everything else is the engine's answer, and `dev`
13
+ * stops with it. Resetting the database is `supatype dev --reset-db`, which is asked for, confirmed,
14
+ * and removes only Postgres's volume.
15
+ */
16
+ import { unmanagedTables } from "./adopt-walkthrough.js"
17
+ import { fatalError } from "./ui/fatal.js"
18
+ import type { DockerBrandOptions } from "./docker-runtime.js"
19
+
20
+ /** What one failed push means for the next step. */
21
+ export type PushFailureKind = "transient" | "unmanaged-tables" | "engine"
22
+
23
+ /**
24
+ * How the initial push ended.
25
+ *
26
+ * A refusal is its own outcome rather than a thrown error so a caller can act on it: the
27
+ * unmanaged-tables case is the one an adopt walkthrough will pick up.
28
+ */
29
+ export type InitialPushOutcome =
30
+ | { kind: "applied" }
31
+ | { kind: "refused"; reason: Exclude<PushFailureKind, "transient">; message: string }
32
+ | { kind: "exhausted"; attempts: number; message: string }
33
+
34
+ export type InitialPushFailure = Exclude<InitialPushOutcome, { kind: "applied" }>
35
+
36
+ export interface InitialPushSteps {
37
+ /** One push. Throws with the engine's output when it fails. */
38
+ push: () => Promise<void>
39
+ /** Start Postgres if it is not running and wait for it. Must never remove anything. */
40
+ recoverDatabase: () => Promise<void>
41
+ /** Capture the database logs while they still describe the failure. */
42
+ dumpLogs: (reason: string) => void
43
+ sleep: (ms: number) => Promise<void>
44
+ }
45
+
46
+ /**
47
+ * Output that means "Postgres is not reachable yet", not "the schema is wrong".
48
+ *
49
+ * The same vocabulary as `packages/realtime/src/db-retry.ts` and its storage twin, which match a
50
+ * driver's error codes. The engine reports through its exit output rather than an error object, so
51
+ * here the codes and their messages are matched as text. Narrow on purpose: whatever matches is
52
+ * retried, and a loose pattern would turn a refusal back into the retry that hid it.
53
+ */
54
+ const TRANSIENT_PATTERNS: readonly RegExp[] = [
55
+ /\b(ECONNREFUSED|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EPIPE|EAI_AGAIN)\b/,
56
+ /connection (refused|reset)/i,
57
+ /connection terminated unexpectedly/i,
58
+ /the database system is (starting up|shutting down|in recovery)/i,
59
+ /too many clients already/i,
60
+ /timeout expired|timed out/i,
61
+ ]
62
+
63
+ function classifyPushFailure(message: string): PushFailureKind {
64
+ // Checked first: the refusal is long prose, and it must not be retried because a word in it
65
+ // happens to look like a connection error. Read from the engine's JSON reason, with its wording
66
+ // only as the fallback for an engine that predates the JSON.
67
+ if (unmanagedTables(message) !== null) return "unmanaged-tables"
68
+ if (TRANSIENT_PATTERNS.some((pattern) => pattern.test(message))) return "transient"
69
+ return "engine"
70
+ }
71
+
72
+ /** Run one push, returning the failure message instead of throwing it. */
73
+ async function attemptPush(push: () => Promise<void>): Promise<string | null> {
74
+ try {
75
+ await push()
76
+ return null
77
+ } catch (err: unknown) {
78
+ return err instanceof Error ? err.message : String(err)
79
+ }
80
+ }
81
+
82
+ /** Push the schema, retrying only while Postgres is unreachable. */
83
+ export async function pushInitialSchema(
84
+ steps: InitialPushSteps,
85
+ maxAttempts = 3,
86
+ ): Promise<InitialPushOutcome> {
87
+ let message = ""
88
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
89
+ const failure = await attemptPush(steps.push)
90
+ if (failure === null) return { kind: "applied" }
91
+ message = failure
92
+ console.error(`[supatype] Initial schema push failed (attempt ${attempt}/${maxAttempts}):`, failure)
93
+ steps.dumpLogs(`schema push attempt ${attempt}/${maxAttempts}`)
94
+
95
+ const kind = classifyPushFailure(failure)
96
+ if (kind !== "transient") return { kind: "refused", reason: kind, message }
97
+ if (attempt < maxAttempts) {
98
+ await steps.recoverDatabase()
99
+ await steps.sleep(3000 * attempt)
100
+ }
101
+ }
102
+ return { kind: "exhausted", attempts: maxAttempts, message }
103
+ }
104
+
105
+ /** Every refusal ends with this, because the old loop taught people a failure meant data loss. */
106
+ const DATABASE_KEPT = "Your local database was left as it was."
107
+
108
+ /** End `dev` with what the engine said, and what to do about it. */
109
+ export function exitInitialPushFailed(failure: InitialPushFailure, brand?: DockerBrandOptions): never {
110
+ const opts = { ...(brand !== undefined && { brand }) }
111
+ if (failure.kind === "exhausted") {
112
+ fatalError(
113
+ `Initial schema push failed after ${failure.attempts} attempts: ${failure.message}`,
114
+ ["Postgres did not become reachable. Check logs: supatype self-host compose logs db", DATABASE_KEPT],
115
+ opts,
116
+ )
117
+ }
118
+ if (failure.reason === "unmanaged-tables") {
119
+ fatalError(
120
+ "The engine refused the schema push. Nothing was applied.",
121
+ [
122
+ failure.message,
123
+ "Run `supatype adopt` to bring those tables under management, then run `supatype dev` again.",
124
+ DATABASE_KEPT,
125
+ ],
126
+ opts,
127
+ )
128
+ }
129
+ fatalError(
130
+ "The engine refused the schema push.",
131
+ [failure.message, "Fix the schema and run `supatype dev` again.", DATABASE_KEPT],
132
+ opts,
133
+ )
134
+ }
package/src/dev-ports.ts CHANGED
@@ -11,6 +11,7 @@ import { isPortInUse } from "./postgres-ctl.js"
11
11
  import { readEnvInt, upsertEnvFile } from "./env-file.js"
12
12
  import { isInteractive } from "./ui/interactive.js"
13
13
  import { fatalError } from "./ui/fatal.js"
14
+ import { COMPOSE_DEV_DB_PORT } from "./host-database.js"
14
15
 
15
16
  const MIN_PORT = 1024
16
17
  const MAX_PORT = 65535
@@ -240,7 +241,6 @@ async function promptPortConflictWithoutPersist(
240
241
  return port
241
242
  }
242
243
 
243
- const COMPOSE_DEV_DB_PORT = 54329
244
244
 
245
245
  function devDbConnectionUrl(port: number): string {
246
246
  return `postgresql://supatype_admin:postgres@localhost:${port}/supatype?sslmode=disable`
@@ -40,8 +40,8 @@ export function formatOperation(op: Operation): string {
40
40
  return kind
41
41
  }
42
42
 
43
- /** Print engine diff warnings before the operation list. */
44
- export function printDiffWarnings(diff: DiffResult): void {
43
+ /** Print engine warnings: a diff's before its operation list, or a push's once it has run. */
44
+ export function printDiffWarnings(diff: Pick<DiffResult, "warnings">): void {
45
45
  const warnings = diff.warnings ?? []
46
46
  if (warnings.length === 0) return
47
47
  console.log(`\n${warnings.length} warning(s):\n`)