@supatype/cli 0.1.0-alpha.6 → 0.1.0-alpha.7

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 (309) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +203 -1
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/dist/app-config.d.ts +7 -0
  5. package/dist/app-config.d.ts.map +1 -0
  6. package/dist/app-config.js +113 -0
  7. package/dist/app-config.js.map +1 -0
  8. package/dist/augmentation-generator.d.ts +2 -0
  9. package/dist/augmentation-generator.d.ts.map +1 -0
  10. package/dist/augmentation-generator.js +111 -0
  11. package/dist/augmentation-generator.js.map +1 -0
  12. package/dist/binary-cache.d.ts +89 -0
  13. package/dist/binary-cache.d.ts.map +1 -0
  14. package/dist/binary-cache.js +656 -0
  15. package/dist/binary-cache.js.map +1 -0
  16. package/dist/cli.d.ts.map +1 -1
  17. package/dist/cli.js +13 -7
  18. package/dist/cli.js.map +1 -1
  19. package/dist/commands/admin.d.ts.map +1 -1
  20. package/dist/commands/admin.js +4 -3
  21. package/dist/commands/admin.js.map +1 -1
  22. package/dist/commands/app.d.ts.map +1 -1
  23. package/dist/commands/app.js +56 -209
  24. package/dist/commands/app.js.map +1 -1
  25. package/dist/commands/cache.d.ts +6 -0
  26. package/dist/commands/cache.d.ts.map +1 -0
  27. package/dist/commands/cache.js +105 -0
  28. package/dist/commands/cache.js.map +1 -0
  29. package/dist/commands/cloud.d.ts +12 -0
  30. package/dist/commands/cloud.d.ts.map +1 -1
  31. package/dist/commands/cloud.js +36 -46
  32. package/dist/commands/cloud.js.map +1 -1
  33. package/dist/commands/db.d.ts.map +1 -1
  34. package/dist/commands/db.js +47 -54
  35. package/dist/commands/db.js.map +1 -1
  36. package/dist/commands/deploy.d.ts +2 -1
  37. package/dist/commands/deploy.d.ts.map +1 -1
  38. package/dist/commands/deploy.js +92 -51
  39. package/dist/commands/deploy.js.map +1 -1
  40. package/dist/commands/dev.d.ts +11 -0
  41. package/dist/commands/dev.d.ts.map +1 -1
  42. package/dist/commands/dev.js +751 -384
  43. package/dist/commands/dev.js.map +1 -1
  44. package/dist/commands/diff.d.ts.map +1 -1
  45. package/dist/commands/diff.js +20 -15
  46. package/dist/commands/diff.js.map +1 -1
  47. package/dist/commands/engine.d.ts +1 -3
  48. package/dist/commands/engine.d.ts.map +1 -1
  49. package/dist/commands/engine.js +13 -85
  50. package/dist/commands/engine.js.map +1 -1
  51. package/dist/commands/functions.d.ts.map +1 -1
  52. package/dist/commands/functions.js +92 -105
  53. package/dist/commands/functions.js.map +1 -1
  54. package/dist/commands/generate.d.ts.map +1 -1
  55. package/dist/commands/generate.js +22 -12
  56. package/dist/commands/generate.js.map +1 -1
  57. package/dist/commands/init.d.ts +1 -1
  58. package/dist/commands/init.d.ts.map +1 -1
  59. package/dist/commands/init.js +124 -410
  60. package/dist/commands/init.js.map +1 -1
  61. package/dist/commands/migrate-from-v1.d.ts +5 -0
  62. package/dist/commands/migrate-from-v1.d.ts.map +1 -0
  63. package/dist/commands/migrate-from-v1.js +125 -0
  64. package/dist/commands/migrate-from-v1.js.map +1 -0
  65. package/dist/commands/migrate.d.ts.map +1 -1
  66. package/dist/commands/migrate.js +27 -23
  67. package/dist/commands/migrate.js.map +1 -1
  68. package/dist/commands/pg.d.ts +8 -0
  69. package/dist/commands/pg.d.ts.map +1 -0
  70. package/dist/commands/pg.js +102 -0
  71. package/dist/commands/pg.js.map +1 -0
  72. package/dist/commands/pull.d.ts.map +1 -1
  73. package/dist/commands/pull.js +5 -66
  74. package/dist/commands/pull.js.map +1 -1
  75. package/dist/commands/push.d.ts.map +1 -1
  76. package/dist/commands/push.js +99 -39
  77. package/dist/commands/push.js.map +1 -1
  78. package/dist/commands/seed.d.ts +2 -0
  79. package/dist/commands/seed.d.ts.map +1 -1
  80. package/dist/commands/seed.js +44 -11
  81. package/dist/commands/seed.js.map +1 -1
  82. package/dist/commands/self-host.d.ts +7 -1
  83. package/dist/commands/self-host.d.ts.map +1 -1
  84. package/dist/commands/self-host.js +272 -758
  85. package/dist/commands/self-host.js.map +1 -1
  86. package/dist/commands/self-update.d.ts +9 -0
  87. package/dist/commands/self-update.d.ts.map +1 -0
  88. package/dist/commands/self-update.js +33 -0
  89. package/dist/commands/self-update.js.map +1 -0
  90. package/dist/commands/status.d.ts.map +1 -1
  91. package/dist/commands/status.js +4 -3
  92. package/dist/commands/status.js.map +1 -1
  93. package/dist/commands/types.d.ts +3 -0
  94. package/dist/commands/types.d.ts.map +1 -0
  95. package/dist/commands/types.js +62 -0
  96. package/dist/commands/types.js.map +1 -0
  97. package/dist/commands/update.d.ts +7 -0
  98. package/dist/commands/update.d.ts.map +1 -0
  99. package/dist/commands/update.js +77 -0
  100. package/dist/commands/update.js.map +1 -0
  101. package/dist/components.d.ts +5 -0
  102. package/dist/components.d.ts.map +1 -0
  103. package/dist/components.js +3 -0
  104. package/dist/components.js.map +1 -0
  105. package/dist/config.d.ts +10 -51
  106. package/dist/config.d.ts.map +1 -1
  107. package/dist/config.js +101 -33
  108. package/dist/config.js.map +1 -1
  109. package/dist/docker-postgres.d.ts +39 -0
  110. package/dist/docker-postgres.d.ts.map +1 -0
  111. package/dist/docker-postgres.js +96 -0
  112. package/dist/docker-postgres.js.map +1 -0
  113. package/dist/engine-client.d.ts +67 -0
  114. package/dist/engine-client.d.ts.map +1 -0
  115. package/dist/engine-client.js +156 -0
  116. package/dist/engine-client.js.map +1 -0
  117. package/dist/ensure-binary.d.ts +7 -0
  118. package/dist/ensure-binary.d.ts.map +1 -0
  119. package/dist/ensure-binary.js +17 -0
  120. package/dist/ensure-binary.js.map +1 -0
  121. package/dist/functions-router-gen.d.ts +14 -0
  122. package/dist/functions-router-gen.d.ts.map +1 -0
  123. package/dist/functions-router-gen.js +199 -0
  124. package/dist/functions-router-gen.js.map +1 -0
  125. package/dist/index.d.ts +4 -5
  126. package/dist/index.d.ts.map +1 -1
  127. package/dist/index.js +2 -3
  128. package/dist/index.js.map +1 -1
  129. package/dist/kong-config.d.ts +21 -0
  130. package/dist/kong-config.d.ts.map +1 -0
  131. package/dist/kong-config.js +60 -0
  132. package/dist/kong-config.js.map +1 -0
  133. package/dist/local-gateway.d.ts +7 -0
  134. package/dist/local-gateway.d.ts.map +1 -0
  135. package/dist/local-gateway.js +9 -0
  136. package/dist/local-gateway.js.map +1 -0
  137. package/dist/local-storage.d.ts +8 -0
  138. package/dist/local-storage.d.ts.map +1 -0
  139. package/dist/local-storage.js +14 -0
  140. package/dist/local-storage.js.map +1 -0
  141. package/dist/pgbouncer-userlist.d.ts +5 -0
  142. package/dist/pgbouncer-userlist.d.ts.map +1 -0
  143. package/dist/pgbouncer-userlist.js +14 -0
  144. package/dist/pgbouncer-userlist.js.map +1 -0
  145. package/dist/postgres-ctl.d.ts +44 -0
  146. package/dist/postgres-ctl.d.ts.map +1 -0
  147. package/dist/postgres-ctl.js +137 -0
  148. package/dist/postgres-ctl.js.map +1 -0
  149. package/dist/process-manager.d.ts +41 -0
  150. package/dist/process-manager.d.ts.map +1 -0
  151. package/dist/process-manager.js +120 -0
  152. package/dist/process-manager.js.map +1 -0
  153. package/dist/project-config.d.ts +215 -0
  154. package/dist/project-config.d.ts.map +1 -0
  155. package/dist/project-config.js +145 -0
  156. package/dist/project-config.js.map +1 -0
  157. package/dist/pull-utils.d.ts +15 -0
  158. package/dist/pull-utils.d.ts.map +1 -1
  159. package/dist/pull-utils.js +12 -0
  160. package/dist/pull-utils.js.map +1 -1
  161. package/dist/release-pins.d.ts +7 -0
  162. package/dist/release-pins.d.ts.map +1 -0
  163. package/dist/release-pins.js +27 -0
  164. package/dist/release-pins.js.map +1 -0
  165. package/dist/release-public-key.d.ts +8 -0
  166. package/dist/release-public-key.d.ts.map +1 -0
  167. package/dist/release-public-key.js +13 -0
  168. package/dist/release-public-key.js.map +1 -0
  169. package/dist/runtime-routes.d.ts +25 -0
  170. package/dist/runtime-routes.d.ts.map +1 -0
  171. package/dist/runtime-routes.js +189 -0
  172. package/dist/runtime-routes.js.map +1 -0
  173. package/dist/scripts/postinstall.d.ts +5 -6
  174. package/dist/scripts/postinstall.d.ts.map +1 -1
  175. package/dist/scripts/postinstall.js +36 -20
  176. package/dist/scripts/postinstall.js.map +1 -1
  177. package/dist/self-host-compose.d.ts +14 -0
  178. package/dist/self-host-compose.d.ts.map +1 -0
  179. package/dist/self-host-compose.js +236 -0
  180. package/dist/self-host-compose.js.map +1 -0
  181. package/dist/storage-provision.d.ts +24 -0
  182. package/dist/storage-provision.d.ts.map +1 -0
  183. package/dist/storage-provision.js +44 -0
  184. package/dist/storage-provision.js.map +1 -0
  185. package/dist/systemd.d.ts +26 -0
  186. package/dist/systemd.d.ts.map +1 -0
  187. package/dist/systemd.js +102 -0
  188. package/dist/systemd.js.map +1 -0
  189. package/dist/tsx-runner.d.ts.map +1 -1
  190. package/dist/tsx-runner.js +9 -2
  191. package/dist/tsx-runner.js.map +1 -1
  192. package/dist/type-extractor.d.ts +31 -0
  193. package/dist/type-extractor.d.ts.map +1 -0
  194. package/dist/type-extractor.js +876 -0
  195. package/dist/type-extractor.js.map +1 -0
  196. package/package.json +4 -3
  197. package/releases/deno/VERSION +1 -0
  198. package/scripts/mirror-deno-release.sh +76 -0
  199. package/src/app-config.ts +128 -0
  200. package/src/augmentation-generator.ts +126 -0
  201. package/src/binary-cache.ts +802 -0
  202. package/src/cli.ts +13 -8
  203. package/src/commands/admin.ts +4 -3
  204. package/src/commands/app.ts +67 -231
  205. package/src/commands/cache.ts +117 -0
  206. package/src/commands/cloud.ts +46 -57
  207. package/src/commands/db.ts +54 -63
  208. package/src/commands/deploy.ts +110 -61
  209. package/src/commands/dev.ts +930 -405
  210. package/src/commands/diff.ts +21 -29
  211. package/src/commands/engine.ts +13 -116
  212. package/src/commands/functions.ts +97 -115
  213. package/src/commands/generate.ts +23 -10
  214. package/src/commands/init.ts +136 -414
  215. package/src/commands/migrate-from-v1.ts +131 -0
  216. package/src/commands/migrate.ts +27 -23
  217. package/src/commands/pg.ts +133 -0
  218. package/src/commands/pull.ts +6 -85
  219. package/src/commands/push.ts +128 -59
  220. package/src/commands/seed.ts +54 -12
  221. package/src/commands/self-host.ts +312 -880
  222. package/src/commands/self-update.ts +45 -0
  223. package/src/commands/status.ts +4 -3
  224. package/src/commands/types.ts +76 -0
  225. package/src/commands/update.ts +92 -0
  226. package/src/components.ts +6 -0
  227. package/src/config.ts +127 -94
  228. package/src/docker-postgres.ts +138 -0
  229. package/src/engine-client.ts +231 -0
  230. package/src/ensure-binary.ts +28 -0
  231. package/src/functions-router-gen.ts +224 -0
  232. package/src/index.ts +4 -12
  233. package/src/kong-config.ts +78 -0
  234. package/src/local-gateway.ts +9 -0
  235. package/src/local-storage.ts +14 -0
  236. package/src/pgbouncer-userlist.ts +15 -0
  237. package/src/postgres-ctl.ts +171 -0
  238. package/src/process-manager.ts +151 -0
  239. package/src/project-config.ts +353 -0
  240. package/src/pull-utils.ts +24 -0
  241. package/src/release-pins.ts +31 -0
  242. package/src/release-public-key.ts +12 -0
  243. package/src/runtime-routes.ts +216 -0
  244. package/src/scripts/postinstall.ts +36 -25
  245. package/src/self-host-compose.ts +257 -0
  246. package/src/storage-provision.ts +58 -0
  247. package/src/systemd.ts +137 -0
  248. package/src/tsx-runner.ts +11 -1
  249. package/src/type-extractor.ts +1016 -0
  250. package/tests/app-command.test.ts +54 -0
  251. package/tests/augmentation-generator.test.ts +59 -0
  252. package/tests/binary-cache-cloud-overrides.test.ts +123 -0
  253. package/tests/cached-artifact-format.test.ts +84 -0
  254. package/tests/cli-help.test.ts +40 -14
  255. package/tests/config.test.ts +140 -37
  256. package/tests/engine-distribution.test.ts +3 -3
  257. package/tests/ensure-binary.test.ts +59 -0
  258. package/tests/init.test.ts +28 -86
  259. package/tests/migrate-from-v1.test.ts +29 -0
  260. package/tests/pg-spawn-env.test.ts +18 -0
  261. package/tests/postgres-archive-tag.test.ts +9 -0
  262. package/tests/pull-utils.test.ts +36 -1
  263. package/tests/release-pins.test.ts +28 -0
  264. package/tests/runtime-contract.test.ts +236 -0
  265. package/tests/seed-discover.test.ts +31 -0
  266. package/tests/tsconfig.json +9 -0
  267. package/tests/type-extractor.test.ts +401 -0
  268. package/tsconfig.tsbuildinfo +1 -1
  269. package/vitest.config.ts +12 -0
  270. package/dist/engine/cache.d.ts +0 -37
  271. package/dist/engine/cache.d.ts.map +0 -1
  272. package/dist/engine/cache.js +0 -121
  273. package/dist/engine/cache.js.map +0 -1
  274. package/dist/engine/download.d.ts +0 -19
  275. package/dist/engine/download.d.ts.map +0 -1
  276. package/dist/engine/download.js +0 -108
  277. package/dist/engine/download.js.map +0 -1
  278. package/dist/engine/platform.d.ts +0 -24
  279. package/dist/engine/platform.d.ts.map +0 -1
  280. package/dist/engine/platform.js +0 -50
  281. package/dist/engine/platform.js.map +0 -1
  282. package/dist/engine/resolve.d.ts +0 -37
  283. package/dist/engine/resolve.d.ts.map +0 -1
  284. package/dist/engine/resolve.js +0 -133
  285. package/dist/engine/resolve.js.map +0 -1
  286. package/dist/engine/update-notify.d.ts +0 -11
  287. package/dist/engine/update-notify.d.ts.map +0 -1
  288. package/dist/engine/update-notify.js +0 -43
  289. package/dist/engine/update-notify.js.map +0 -1
  290. package/dist/engine/verify.d.ts +0 -50
  291. package/dist/engine/verify.d.ts.map +0 -1
  292. package/dist/engine/verify.js +0 -161
  293. package/dist/engine/verify.js.map +0 -1
  294. package/dist/engine-version.d.ts +0 -35
  295. package/dist/engine-version.d.ts.map +0 -1
  296. package/dist/engine-version.js +0 -35
  297. package/dist/engine-version.js.map +0 -1
  298. package/dist/engine.d.ts +0 -34
  299. package/dist/engine.d.ts.map +0 -1
  300. package/dist/engine.js +0 -76
  301. package/dist/engine.js.map +0 -1
  302. package/src/engine/cache.ts +0 -135
  303. package/src/engine/download.ts +0 -143
  304. package/src/engine/platform.ts +0 -66
  305. package/src/engine/resolve.ts +0 -197
  306. package/src/engine/update-notify.ts +0 -50
  307. package/src/engine/verify.ts +0 -206
  308. package/src/engine-version.ts +0 -39
  309. package/src/engine.ts +0 -99
@@ -1,428 +1,795 @@
1
- import { spawnSync, spawn } from "node:child_process";
1
+ /**
2
+ * supatype dev — start local Postgres, apply schema, run supatype-server.
3
+ *
4
+ * Supports two database providers (set in supatype.config.ts):
5
+ * provider = "native" — manages a native Postgres binary from the supatype cache (default when omitted)
6
+ * provider = "docker" — runs supatype/postgres via Docker (includes all extensions)
7
+ *
8
+ * Edge functions (when a functions/ dir exists): Deno is resolved from the CDN cache
9
+ * (auto-download on miss). Self-host/cloud Docker stacks use supatype-server in-container;
10
+ * Deno is not provisioned by the CLI on those paths.
11
+ */
12
+ import { spawnSync } from "node:child_process";
2
13
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { resolve } from "node:path";
14
+ import { homedir } from "node:os";
15
+ import { join, relative, resolve } from "node:path";
4
16
  import { loadConfig } from "../config.js";
5
- import { ensureEngine, invokeEngine } from "../engine.js";
6
- const POSTGREST_URL = "http://localhost:3000";
7
- const HEALTH_TIMEOUT_MS = 60_000;
8
- const HEALTH_POLL_MS = 2_000;
17
+ import { functionsPathCandidatesFromProject, schemaPathFromProject, } from "../project-config.js";
18
+ import { discoverTsFunctionsInDir, writeDevFunctionsRouter } from "../functions-router-gen.js";
19
+ import { signJwt } from "../jwt.js";
20
+ import { normalisePlatformPath, cachePath, currentPlatform, hasMeaningfulOverrides, describeActiveOverrides, postgresArchiveTag, } from "../binary-cache.js";
21
+ import { ensureBinary } from "../ensure-binary.js";
22
+ import { ProcessManager } from "../process-manager.js";
23
+ import { localStorageEnv } from "../local-storage.js";
24
+ import { initdb, start as pgStart, stop as pgStop, waitReady as pgWaitReady, isPortInUse, pgSpawnEnv, } from "../postgres-ctl.js";
25
+ import { dockerPgStart, dockerPgStop, dockerPgWaitReady, dockerDbUrl, } from "../docker-postgres.js";
26
+ const DEFAULT_DOCKER_IMAGE = "supatype/postgres:17-latest";
27
+ /** Map `email.smtp` from supatype.config.ts into GOTRUE_SMTP_* for the embedded GoTrue process. */
28
+ function gotrueSMTPFromEmailConfig(email) {
29
+ const s = email?.smtp;
30
+ if (!s)
31
+ return {};
32
+ const out = {};
33
+ const host = s.host?.trim();
34
+ if (host)
35
+ out.GOTRUE_SMTP_HOST = host;
36
+ if (s.port !== undefined)
37
+ out.GOTRUE_SMTP_PORT = String(s.port);
38
+ const user = s.user?.trim();
39
+ if (user)
40
+ out.GOTRUE_SMTP_USER = user;
41
+ if (s.pass !== undefined && s.pass !== "")
42
+ out.GOTRUE_SMTP_PASS = s.pass;
43
+ const admin = s.admin_email?.trim();
44
+ if (admin)
45
+ out.GOTRUE_SMTP_ADMIN_EMAIL = admin;
46
+ const sender = s.sender_name?.trim();
47
+ if (sender)
48
+ out.GOTRUE_SMTP_SENDER_NAME = sender;
49
+ return out;
50
+ }
9
51
  export function registerDev(program) {
10
52
  program
11
53
  .command("dev")
12
- .description("Start local Postgres, PostgREST, and Kong via Docker Compose, then watch for schema changes")
54
+ .description("Start local Postgres, apply schema, and run supatype-server")
13
55
  .option("--no-watch", "Start services but do not watch for schema changes")
14
- .option("--local", "Run storage, realtime, and studio from source (monorepo dev)")
56
+ .option("--port <port>", "Port for supatype-server (overrides config)", String)
15
57
  .action(async (opts) => {
16
58
  const cwd = process.cwd();
17
- // Generate .env with local defaults if missing
18
- ensureDevEnv(cwd);
19
- if (opts.local) {
20
- // Monorepo dev generate an infra-only compose if needed, then start
21
- const composePath = resolve(cwd, "docker-compose.yml");
22
- if (!existsSync(composePath)) {
23
- ensureInfraCompose(cwd);
24
- }
25
- console.log("Starting infra services...");
26
- const up = spawnSync("docker", ["compose", "up", "-d", "--wait", "db", "pgbouncer", "gotrue", "postgrest", "minio", "kong"], { cwd, stdio: "inherit" });
27
- if (up.status !== 0) {
28
- console.error("docker compose up failed.");
29
- process.exit(1);
59
+ // ── 1. Load project config ─────────────────────────────────────────────
60
+ const config = loadConfig(cwd);
61
+ if (hasMeaningfulOverrides(config)) {
62
+ console.warn("[supatype] Local binary overrides active:");
63
+ for (const line of describeActiveOverrides(config)) {
64
+ console.warn(line);
30
65
  }
66
+ console.warn("");
67
+ }
68
+ const projectName = config.project.name;
69
+ const serverPort = opts.port ?? String(config.server.port ?? 54321);
70
+ const postgrestPort = String(config.server.postgrestPort ?? 3001);
71
+ const provider = config.database.provider ?? "native";
72
+ // ── 2. Resolve engine + server binaries ──────────────────────────────
73
+ console.log(`[supatype] Resolving component binaries for "${projectName}"...`);
74
+ const [engineBin, serverBin] = await Promise.all([
75
+ ensureBinary("engine", config),
76
+ ensureBinary("server", config),
77
+ ]);
78
+ // ── 3. Per-project state directories ─────────────────────────────────
79
+ const stateRoot = join(homedir(), ".supatype", "projects", projectName);
80
+ const pidDir = join(stateRoot, "pid");
81
+ const logsDir = join(stateRoot, "logs");
82
+ const tmpDir = join(stateRoot, "tmp");
83
+ for (const d of [pidDir, logsDir, tmpDir]) {
84
+ mkdirSync(d, { recursive: true });
85
+ }
86
+ // ── 4. Port collision check ───────────────────────────────────────────
87
+ const pgPort = 5432;
88
+ if (await isPortInUse(pgPort)) {
89
+ console.error(`[supatype] Port ${pgPort} is already in use. Another Postgres instance may be running.\n` +
90
+ ` Check: lsof -i :${pgPort}`);
91
+ process.exit(1);
92
+ }
93
+ if (await isPortInUse(Number(serverPort))) {
94
+ console.error(`[supatype] Port ${serverPort} is already in use. Another supatype-server may be running.\n` +
95
+ ` Check: lsof -i :${serverPort}`);
96
+ process.exit(1);
97
+ }
98
+ if (await isPortInUse(Number(postgrestPort))) {
99
+ console.error(`[supatype] Port ${postgrestPort} is already in use. Another service may be running.\n` +
100
+ ` Check: lsof -i :${postgrestPort}`);
101
+ process.exit(1);
102
+ }
103
+ // ── 5–7. Start Postgres ───────────────────────────────────────────────
104
+ let dbURL;
105
+ let stopPostgres;
106
+ // pgBinDir is set on the native path and used to add DLL search path for
107
+ // PostgREST on Windows (PostgREST links against libpq + SSL from MinGW).
108
+ let pgBinDir = null;
109
+ if (provider === "docker") {
110
+ console.log("[supatype] database.provider \"docker\" — Postgres runs in Docker; engine and supatype-server stay native.");
111
+ const image = config.database.image ?? DEFAULT_DOCKER_IMAGE;
112
+ console.log(`[supatype] Starting Postgres via Docker (${image})...`);
113
+ dockerPgStart({ image, projectName, port: pgPort });
114
+ await dockerPgWaitReady(projectName, 90_000);
115
+ console.log("[supatype] Postgres is ready.");
116
+ dbURL = dockerDbUrl(projectName, pgPort);
117
+ stopPostgres = () => dockerPgStop(projectName);
31
118
  }
32
119
  else {
33
- if (!existsSync(resolve(cwd, "docker-compose.yml"))) {
34
- console.error("docker-compose.yml not found. Run: supatype init");
35
- process.exit(1);
120
+ // native — resolve pg bin dir and manage with pg_ctl
121
+ pgBinDir = await resolvePgBinDir(config);
122
+ const dataDir = config.database.data_dir ?? join(stateRoot, "data");
123
+ mkdirSync(dataDir, { recursive: true });
124
+ const pgOpts = { pgBinDir, dataDir, port: pgPort, logPath: join(logsDir, "postgres.log") };
125
+ console.log("[supatype] Initialising Postgres data directory...");
126
+ initdb(pgOpts);
127
+ console.log("[supatype] Starting Postgres...");
128
+ pgStart(pgOpts);
129
+ await pgWaitReady(pgOpts, 15_000);
130
+ console.log("[supatype] Postgres is ready.");
131
+ dbURL = `postgres://postgres:postgres@127.0.0.1:${pgPort}/${projectName}?sslmode=disable`;
132
+ stopPostgres = () => pgStop(pgOpts);
133
+ // Create project database if it doesn't exist.
134
+ const psqlBin = join(pgBinDir, process.platform === "win32" ? "psql.exe" : "psql");
135
+ const createdbBin = join(pgBinDir, process.platform === "win32" ? "createdb.exe" : "createdb");
136
+ const pgConnArgs = ["-h", "127.0.0.1", "-p", String(pgPort), "-U", "postgres"];
137
+ const pgEnv = pgSpawnEnv(pgBinDir);
138
+ const createDbResult = spawnSync(createdbBin, [...pgConnArgs, projectName], { stdio: "pipe", encoding: "utf8", env: pgEnv });
139
+ if (createDbResult.status !== 0) {
140
+ const stderr = createDbResult.stderr ?? "";
141
+ if (!stderr.includes("already exists")) {
142
+ throw new Error(`Failed to create database "${projectName}": ${stderr}`);
143
+ }
36
144
  }
37
- console.log("Starting services...");
38
- const up = spawnSync("docker", ["compose", "up", "-d", "--wait"], { cwd, stdio: "inherit" });
39
- if (up.status !== 0) {
40
- console.error("docker compose up failed.");
41
- process.exit(1);
145
+ else {
146
+ console.log(`[supatype] Created database "${projectName}".`);
42
147
  }
148
+ // Create roles required by PostgREST and grant them to postgres so
149
+ // PostgREST can SET ROLE when processing requests.
150
+ // anon – unauthenticated requests (RLS enforced)
151
+ // authenticated – signed-in user requests (RLS enforced)
152
+ // service_role – developer/admin bypass (BYPASSRLS)
153
+ const rolesSql = `
154
+ CREATE SCHEMA IF NOT EXISTS auth;
155
+ DO $$ BEGIN
156
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon')
157
+ THEN CREATE ROLE anon NOLOGIN; END IF;
158
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated')
159
+ THEN CREATE ROLE authenticated NOLOGIN; END IF;
160
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'service_role')
161
+ THEN CREATE ROLE service_role NOLOGIN BYPASSRLS; END IF;
162
+ END $$;
163
+ GRANT anon, authenticated, service_role TO postgres;
164
+ GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role;
165
+ -- Table-level privileges (RLS restricts rows; roles still need table access)
166
+ GRANT SELECT ON ALL TABLES IN SCHEMA public TO anon;
167
+ GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO authenticated;
168
+ GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role;
169
+ GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO authenticated, service_role;
170
+ -- Default privileges so tables created by the engine push inherit these grants
171
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO anon;
172
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO authenticated;
173
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO service_role;
174
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated, service_role;
175
+ `;
176
+ spawnSync(psqlBin, [...pgConnArgs, "-d", projectName, "-c", rolesSql], { stdio: "pipe", encoding: "utf8", env: pgEnv });
43
177
  }
44
- console.log("Waiting for PostgREST to be ready...");
45
- await waitForPostgREST();
46
- const children = [];
47
- if (opts.local) {
48
- console.log("\nStarting local services from source...");
49
- children.push(...startLocalServices(cwd));
178
+ const LOCAL_JWT_SECRET = "super-secret-jwt-token-with-at-least-32-characters-long";
179
+ const authDbURL = dbURL.includes("?")
180
+ ? `${dbURL}&search_path=auth`
181
+ : `${dbURL}?search_path=auth`;
182
+ // ── 8. GoTrue migrations (auth.users before engine studio SQL) ─────────
183
+ console.log("[supatype] Running GoTrue migrations...");
184
+ runGotrueMigrations(serverBin, authDbURL, LOCAL_JWT_SECRET);
185
+ // ── 9. Engine: apply schema ───────────────────────────────────────────
186
+ const schemaPath = schemaPathFromProject(config, cwd);
187
+ const supatypeDir = join(cwd, ".supatype");
188
+ const manifestPath = join(supatypeDir, "manifest.json");
189
+ const adminConfigPath = join(supatypeDir, "admin-config.json");
190
+ mkdirSync(supatypeDir, { recursive: true });
191
+ const localStoragePath = config.storage?.provider !== "s3" ? join(stateRoot, "storage") : undefined;
192
+ // Native Postgres builds don't include PostGIS — skip geo fields rather than failing.
193
+ const skipFieldKinds = provider === "native" ? new Set(["geo", "vector"]) : new Set();
194
+ await runSchemaPush(cwd, engineBin, schemaPath, dbURL, manifestPath, adminConfigPath, localStoragePath, skipFieldKinds).catch((e) => console.error("[supatype] Initial schema push failed:", e.message));
195
+ // ── 10. Spawn supatype-server ─────────────────────────────────────────
196
+ // Resolve edge functions config: only enable Deno if a functions dir exists.
197
+ const functionsDir = functionsPathCandidatesFromProject(config, cwd).find(dir => existsSync(dir));
198
+ const hasFunctionsDir = functionsDir !== undefined;
199
+ /** Always set when a functions dir exists so Studio admin API can list functions; Deno runtime is separate. */
200
+ const denoFunctionsDir = hasFunctionsDir ? functionsDir : "";
201
+ const functionRoutes = hasFunctionsDir && functionsDir !== undefined
202
+ ? discoverTsFunctionsInDir(functionsDir)
203
+ : [];
204
+ const denoServeScriptAbs = hasFunctionsDir && functionsDir !== undefined
205
+ ? (writeDevFunctionsRouter(cwd, functionsDir, functionRoutes) ?? "")
206
+ : "";
207
+ let denoBinPath;
208
+ if (hasFunctionsDir) {
209
+ console.log(`[supatype] Edge functions enabled (${functionsDir})`);
210
+ try {
211
+ denoBinPath = await ensureBinary("deno", config);
212
+ console.log(`[supatype] Deno runtime: ${denoBinPath} (v${config.versions.deno})`);
213
+ if (functionRoutes.length > 0) {
214
+ console.log(`[supatype] Edge functions router: ${relative(cwd, denoServeScriptAbs) || ".supatype/functions-router.ts"} ` +
215
+ `(${functionRoutes.length} function(s): ${functionRoutes.map(fn => fn.name).join(", ")})`);
216
+ }
217
+ else {
218
+ console.log("[supatype] Edge functions router not generated (no handler files discovered yet)");
219
+ }
220
+ }
221
+ catch (err) {
222
+ console.warn(`[supatype] ⚠ Found ${functionsDir} but could not provision Deno v${config.versions.deno} — edge functions will not run.\n` +
223
+ ` ${err.message}\n` +
224
+ " (Functions still appear in Studio; invocations need Deno.)");
225
+ }
50
226
  }
51
- console.log("\nServices running:");
52
- console.log(" Postgres postgresql://localhost:5432");
53
- console.log(" PostgREST http://localhost:3000");
54
- console.log(" Kong http://localhost:8000");
55
- console.log(" REST API http://localhost:8000/rest/v1/");
56
- console.log(" GraphQL http://localhost:8000/graphql/v1");
57
- if (opts.local) {
58
- console.log(" Storage http://localhost:5000 (from source)");
59
- console.log(" Realtime http://localhost:4000 (from source)");
60
- console.log(" Studio http://localhost:3002 (from source)");
227
+ // Matches GOTRUE_HOOK_SEND_EMAIL_SECRETS symmetric format (dev only). Override via .env.
228
+ const LOCAL_SEND_EMAIL_HOOK_SECRETS = "v1,whsec_abcdefghijklmnopqrstuvwxyz01234567";
229
+ const now = Math.floor(Date.now() / 1000);
230
+ const jwtBase = { iss: "supatype", iat: now, exp: now + 315_360_000 };
231
+ const anonKey = signJwt({ ...jwtBase, role: "anon" }, LOCAL_JWT_SECRET);
232
+ const serviceRoleKey = signJwt({ ...jwtBase, role: "service_role" }, LOCAL_JWT_SECRET);
233
+ const emailProvider = config.email?.provider ?? "console";
234
+ const gotrueMailerProvider = emailProvider === "console"
235
+ ? "console"
236
+ : emailProvider === "resend"
237
+ ? "resend"
238
+ : emailProvider === "ses"
239
+ ? "ses"
240
+ : "smtp";
241
+ const serverEnv = {
242
+ // supatype-server outer layer
243
+ SUPATYPE_MODE: config.server.mode ?? "dev",
244
+ SUPATYPE_MANIFEST_PATH: manifestPath,
245
+ SUPATYPE_ADMIN_CONFIG_PATH: adminConfigPath,
246
+ SUPATYPE_POSTGREST_URL: `http://127.0.0.1:${postgrestPort}`,
247
+ SUPATYPE_DENO_FUNCTIONS_DIR: denoFunctionsDir,
248
+ ...(denoFunctionsDir !== "" ? { SUPATYPE_SHARED_ENV_FILE: resolve(denoFunctionsDir, ".env.local") } : {}),
249
+ ...(denoBinPath !== undefined ? { SUPATYPE_DENO_PATH: denoBinPath } : {}),
250
+ ...(denoServeScriptAbs !== ""
251
+ ? { SUPATYPE_DENO_SERVE_SCRIPT: denoServeScriptAbs }
252
+ : {}),
253
+ SUPATYPE_URL: `http://localhost:${serverPort}`,
254
+ SUPATYPE_ANON_KEY: anonKey,
255
+ SUPATYPE_SERVICE_ROLE_KEY: serviceRoleKey,
256
+ PORT: serverPort,
257
+ SUPATYPE_APP_MODE: config.app.mode ?? "none",
258
+ ...(config.app.mode === "static" && config.app.static_dir?.trim()
259
+ ? { SUPATYPE_APP_STATIC_DIR: resolve(cwd, config.app.static_dir.trim()) }
260
+ : {}),
261
+ ...(config.app.mode === "proxy" && config.app.upstream?.trim()
262
+ ? { SUPATYPE_APP_UPSTREAM: config.app.upstream.trim() }
263
+ : {}),
264
+ ...(config.app.vite_dev_url !== undefined && config.app.vite_dev_url.trim() !== ""
265
+ ? { SUPATYPE_VITE_DEV_URL: config.app.vite_dev_url.trim() }
266
+ : {}),
267
+ // GoTrue required fields (sensible local-dev defaults)
268
+ DATABASE_URL: authDbURL,
269
+ SUPATYPE_SQL_DATABASE_URL: dbURL,
270
+ GOTRUE_DB_DRIVER: "postgres",
271
+ GOTRUE_JWT_SECRET: LOCAL_JWT_SECRET,
272
+ GOTRUE_JWT_EXP: "3600",
273
+ GOTRUE_JWT_AUD: "authenticated",
274
+ GOTRUE_JWT_ADMIN_ROLES: "supatype_admin,service_role",
275
+ API_EXTERNAL_URL: `http://localhost:${serverPort}/auth/v1`,
276
+ GOTRUE_API_HOST: "localhost",
277
+ GOTRUE_SITE_URL: `http://localhost:${serverPort}`,
278
+ GOTRUE_MAILER_MAILER_PROVIDER: gotrueMailerProvider,
279
+ GOTRUE_MAILER_AUTOCONFIRM: "true",
280
+ GOTRUE_LOG_LEVEL: "info",
281
+ GOTRUE_DISABLE_SIGNUP: "false",
282
+ ...(config.email?.resend_api_key !== undefined && config.email.resend_api_key !== ""
283
+ ? { RESEND_API_KEY: config.email.resend_api_key }
284
+ : {}),
285
+ ...(gotrueMailerProvider === "resend" &&
286
+ config.email?.resend_from !== undefined &&
287
+ config.email.resend_from.trim() !== ""
288
+ ? { RESEND_FROM: config.email.resend_from.trim() }
289
+ : {}),
290
+ ...(gotrueMailerProvider === "ses" &&
291
+ config.email?.ses_from !== undefined &&
292
+ config.email.ses_from.trim() !== ""
293
+ ? { SES_FROM: config.email.ses_from.trim() }
294
+ : {}),
295
+ ...(gotrueMailerProvider === "smtp" ? gotrueSMTPFromEmailConfig(config.email) : {}),
296
+ ...(config.email?.send_email_hook === true
297
+ ? {
298
+ GOTRUE_HOOK_SEND_EMAIL_ENABLED: "true",
299
+ GOTRUE_HOOK_SEND_EMAIL_URI: config.email?.send_email_hook_uri !== undefined &&
300
+ config.email.send_email_hook_uri.trim() !== ""
301
+ ? config.email.send_email_hook_uri.trim()
302
+ : `http://127.0.0.1:${serverPort}/internal/v0hooks/send-email`,
303
+ GOTRUE_HOOK_SEND_EMAIL_SECRETS: config.email?.send_email_hook_secrets !== undefined &&
304
+ config.email.send_email_hook_secrets.trim() !== ""
305
+ ? config.email.send_email_hook_secrets.trim()
306
+ : LOCAL_SEND_EMAIL_HOOK_SECRETS,
307
+ }
308
+ : {}),
309
+ ...(config.storage?.provider !== "s3" ? localStorageEnv(stateRoot) : {}),
310
+ ...loadDotEnv(cwd),
311
+ };
312
+ const serverProc = new ProcessManager(serverBin, [], {
313
+ label: "server",
314
+ pidDir,
315
+ colour: "\x1b[32m",
316
+ env: serverEnv,
317
+ });
318
+ serverProc.start();
319
+ // ── 9b. PostgREST ────────────────────────────────────────────────────
320
+ let postgrestProc = null;
321
+ const postgrestBin = await resolvePostgrestBin(config.overrides?.postgrest);
322
+ if (postgrestBin) {
323
+ // Windows PostgREST builds are dynamically linked and require libpq/OpenSSL
324
+ // DLLs from a Postgres bin directory, even when the database runs in Docker.
325
+ let postgrestRuntimeBinDir = pgBinDir;
326
+ if (process.platform === "win32" && postgrestRuntimeBinDir === null) {
327
+ try {
328
+ postgrestRuntimeBinDir = await resolvePgBinDir(config);
329
+ }
330
+ catch (error) {
331
+ console.warn(`[supatype] ⚠ Could not resolve Postgres runtime DLL directory for PostgREST: ${error.message}\n` +
332
+ " PostgREST may fail to start on Windows until Postgres binaries are available locally.");
333
+ }
334
+ }
335
+ const postgrestEnv = {
336
+ PGRST_DB_URI: dbURL,
337
+ PGRST_DB_SCHEMA: "public, supatype",
338
+ PGRST_DB_ANON_ROLE: "anon",
339
+ PGRST_SERVER_PORT: postgrestPort,
340
+ PGRST_SERVER_HOST: "127.0.0.1",
341
+ PGRST_JWT_SECRET: serverEnv["GOTRUE_JWT_SECRET"] ?? "",
342
+ PGRST_LOG_LEVEL: "warn",
343
+ // On Windows, PostgREST (MinGW/GHC binary) needs libpq.dll and
344
+ // OpenSSL DLLs. Prepend a Postgres bin dir which bundles these
345
+ // runtime dependencies.
346
+ ...(process.platform === "win32" && postgrestRuntimeBinDir !== null
347
+ ? { PATH: `${postgrestRuntimeBinDir};${process.env["PATH"] ?? ""}` }
348
+ : {}),
349
+ };
350
+ const preflight = spawnSync(postgrestBin, ["--help"], { env: { ...process.env, ...postgrestEnv }, stdio: "pipe", encoding: "utf8" });
351
+ if (preflight.status !== 0) {
352
+ const detail = (preflight.stderr || preflight.stdout || "").trim();
353
+ console.warn(`[supatype] ⚠ PostgREST failed preflight (exit ${preflight.status}). ` +
354
+ "Skipping /rest/v1 startup to avoid crash loop.");
355
+ if (detail) {
356
+ console.warn(`[supatype] PostgREST preflight output:\n${detail}`);
357
+ }
358
+ }
359
+ else {
360
+ postgrestProc = new ProcessManager(postgrestBin, [], {
361
+ label: "postgrest",
362
+ pidDir,
363
+ colour: "\x1b[36m",
364
+ env: postgrestEnv,
365
+ });
366
+ postgrestProc.start();
367
+ }
61
368
  }
62
- console.log();
63
- // Clean shutdown on Ctrl+C
64
- const cleanup = () => {
65
- for (const child of children) {
66
- child.kill();
369
+ // ── 9d. Studio (optional) ─────────────────────────────────────────────
370
+ const studioPort = 3002;
371
+ let studioProc = null;
372
+ const studioOverride = config.overrides?.studio;
373
+ if (studioOverride) {
374
+ const studioDir = resolve(cwd, studioOverride);
375
+ // Run vite's JS entry directly via node — avoids .cmd/.sh wrapper spawn issues on Windows.
376
+ const viteJs = join(studioDir, "node_modules", "vite", "bin", "vite.js");
377
+ if (existsSync(viteJs)) {
378
+ studioProc = new ProcessManager(process.execPath, [viteJs, "--port", String(studioPort), "--strictPort"], {
379
+ label: "studio",
380
+ pidDir,
381
+ cwd: studioDir,
382
+ colour: "\x1b[35m",
383
+ env: {
384
+ // Point the studio at the Vite dev server (same origin as the
385
+ // browser) so all API requests are same-origin — CORS never fires.
386
+ // Vite's dev proxy (configured via SUPATYPE_PROXY_TARGET) then
387
+ // forwards those requests server-side to the actual backend.
388
+ VITE_SUPATYPE_URL: `http://localhost:${studioPort}`,
389
+ SUPATYPE_PROXY_TARGET: `http://localhost:${serverPort}`,
390
+ // Studio is a developer tool — use service_role key to bypass
391
+ // RLS so all tables and rows are visible regardless of policies.
392
+ VITE_SUPATYPE_ANON_KEY: serviceRoleKey,
393
+ VITE_SUPATYPE_SERVICE_ROLE_KEY: serviceRoleKey,
394
+ VITE_BASE_PATH: "/",
395
+ },
396
+ });
397
+ studioProc.start();
398
+ }
399
+ else {
400
+ console.warn(`[supatype] ⚠ Studio override set but vite not found at ${viteJs}. Run: pnpm install`);
67
401
  }
402
+ }
403
+ // ── Print status ──────────────────────────────────────────────────────
404
+ console.log(`
405
+ [supatype] Services running:
406
+ Postgres ${dbURL}
407
+ supatype-server http://localhost:${serverPort}
408
+ REST API http://localhost:${serverPort}/rest/v1/
409
+ Auth http://localhost:${serverPort}/auth/v1/
410
+ Storage http://localhost:${serverPort}/storage/v1/
411
+ Realtime ws://localhost:${serverPort}/realtime/v1/${studioProc ? `\n Studio http://localhost:${studioPort}` : ""}
412
+
413
+ API keys (local dev only):
414
+ anon key ${anonKey}
415
+ service_role ${serviceRoleKey}
416
+
417
+ JWT secret: ${LOCAL_JWT_SECRET}
418
+
419
+ Press Ctrl+C to stop.
420
+ `);
421
+ // ── Shutdown handler ──────────────────────────────────────────────────
422
+ const cleanup = async () => {
423
+ console.log("\n[supatype] Shutting down...");
424
+ await Promise.all([
425
+ serverProc.stop(),
426
+ postgrestProc?.stop(),
427
+ studioProc?.stop(),
428
+ ]);
429
+ await stopPostgres();
68
430
  process.exit(0);
69
431
  };
70
- process.on("SIGINT", cleanup);
71
- process.on("SIGTERM", cleanup);
432
+ process.once("SIGINT", cleanup);
433
+ process.once("SIGTERM", cleanup);
434
+ // ── 10. Schema watch ──────────────────────────────────────────────────
72
435
  if (opts.watch) {
73
- await watchAndPush(cwd);
436
+ const schemaDir = resolve(cwd, schemaPath, "..");
437
+ console.log(`[supatype] Watching ${schemaDir} for changes...`);
438
+ const { watch } = await import("node:fs");
439
+ // Debounce: Windows fs.watch fires multiple events per save.
440
+ // Wait 300 ms after the last event before pushing.
441
+ let debounceTimer = null;
442
+ watch(schemaDir, { recursive: true }, (_eventType, filename) => {
443
+ if (!filename?.endsWith(".ts"))
444
+ return;
445
+ if (debounceTimer)
446
+ clearTimeout(debounceTimer);
447
+ debounceTimer = setTimeout(() => {
448
+ debounceTimer = null;
449
+ console.log(`\n[supatype] Change detected in ${filename}, checking schema...`);
450
+ runSchemaPush(cwd, engineBin, schemaPath, dbURL, manifestPath, adminConfigPath, localStoragePath, skipFieldKinds).catch((e) => console.error("[supatype] Schema push failed:", e.message));
451
+ }, 300);
452
+ });
74
453
  }
454
+ // Block until killed.
455
+ await new Promise(() => undefined);
75
456
  });
76
457
  }
77
- function ensureInfraCompose(cwd) {
78
- const projectName = resolve(cwd).split(/[\\/]/).pop() ?? "supatype";
79
- const content = `# Generated by supatype dev --local — infra services only
80
- services:
81
- db:
82
- image: supatype/postgres:17-latest
83
- environment:
84
- POSTGRES_PASSWORD: \${POSTGRES_PASSWORD:-postgres}
85
- POSTGRES_DB: \${POSTGRES_DB:-${projectName}}
86
- ports:
87
- - "5432:5432"
88
- volumes:
89
- - db-data:/var/lib/postgresql/data
90
- healthcheck:
91
- test: ["CMD-SHELL", "pg_isready -U postgres"]
92
- interval: 5s
93
- timeout: 5s
94
- retries: 20
95
-
96
- pgbouncer:
97
- image: pgbouncer/pgbouncer:latest
98
- volumes:
99
- - ./.supatype/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro
100
- - ./.supatype/userlist.txt:/etc/pgbouncer/userlist.txt:ro
101
- depends_on:
102
- db:
103
- condition: service_healthy
104
- healthcheck:
105
- test: ["CMD", "pg_isready", "-h", "localhost", "-p", "6432", "-U", "postgres"]
106
- interval: 5s
107
- timeout: 5s
108
- retries: 10
109
-
110
- gotrue:
111
- image: supatype/auth:v1.0.0
112
- environment:
113
- GOTRUE_API_HOST: 0.0.0.0
114
- GOTRUE_API_PORT: 9999
115
- GOTRUE_DB_DRIVER: postgres
116
- GOTRUE_DB_DATABASE_URL: "postgres://postgres:\${POSTGRES_PASSWORD:-postgres}@pgbouncer:6432/\${POSTGRES_DB:-${projectName}}?search_path=auth"
117
- GOTRUE_SITE_URL: \${SITE_URL:-http://localhost:3000}
118
- GOTRUE_JWT_SECRET: \${JWT_SECRET:-super-secret-jwt-token-change-in-production}
119
- GOTRUE_JWT_EXP: 3600
120
- GOTRUE_JWT_AUD: authenticated
121
- GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
122
- GOTRUE_JWT_ADMIN_ROLES: service_role
123
- GOTRUE_MAILER_AUTOCONFIRM: \${GOTRUE_MAILER_AUTOCONFIRM:-true}
124
- GOTRUE_DISABLE_SIGNUP: \${DISABLE_SIGNUP:-false}
125
- ports:
126
- - "9999:9999"
127
- depends_on:
128
- pgbouncer:
129
- condition: service_healthy
130
-
131
- postgrest:
132
- image: postgrest/postgrest:v12.2.8
133
- environment:
134
- PGRST_DB_URI: postgresql://authenticator:\${POSTGRES_PASSWORD:-postgres}@pgbouncer:6432/\${POSTGRES_DB:-${projectName}}
135
- PGRST_DB_SCHEMA: public
136
- PGRST_DB_ANON_ROLE: anon
137
- PGRST_JWT_SECRET: \${JWT_SECRET:-super-secret-jwt-token-change-in-production}
138
- PGRST_DB_EXTRA_SEARCH_PATH: public,extensions
139
- PGRST_DB_POOL: 3
140
- ports:
141
- - "3000:3000"
142
- depends_on:
143
- pgbouncer:
144
- condition: service_healthy
145
-
146
- minio:
147
- image: minio/minio:RELEASE.2024-11-07T00-52-20Z
148
- command: server /data --console-address ":9001"
149
- environment:
150
- MINIO_ROOT_USER: supatype
151
- MINIO_ROOT_PASSWORD: supatype-secret
152
- ports:
153
- - "9000:9000"
154
- - "9001:9001"
155
- volumes:
156
- - minio-data:/data
157
- healthcheck:
158
- test: ["CMD", "mc", "ready", "local"]
159
- interval: 5s
160
- timeout: 5s
161
- retries: 10
162
-
163
- kong:
164
- image: kong:3.6
165
- environment:
166
- KONG_DATABASE: "off"
167
- KONG_DECLARATIVE_CONFIG: /etc/kong/kong.yml
168
- KONG_PROXY_ACCESS_LOG: /dev/stdout
169
- KONG_ADMIN_ACCESS_LOG: /dev/stdout
170
- KONG_PROXY_ERROR_LOG: /dev/stderr
171
- KONG_ADMIN_ERROR_LOG: /dev/stderr
172
- volumes:
173
- - ./.supatype/kong.yml:/etc/kong/kong.yml:ro
174
- ports:
175
- - "8000:8000"
176
- depends_on:
177
- - postgrest
178
- - gotrue
179
-
180
- volumes:
181
- db-data:
182
- minio-data:
183
- `;
184
- writeFileSync(resolve(cwd, "docker-compose.yml"), content, "utf8");
185
- console.log(" created docker-compose.yml (infra only)\n");
186
- // Also ensure pgbouncer config exists
187
- const supatypeDir = resolve(cwd, ".supatype");
188
- mkdirSync(supatypeDir, { recursive: true });
189
- if (!existsSync(resolve(supatypeDir, "pgbouncer.ini"))) {
190
- writeFileSync(resolve(supatypeDir, "pgbouncer.ini"), `[databases]
191
- * = host=db port=5432
192
-
193
- [pgbouncer]
194
- listen_addr = 0.0.0.0
195
- listen_port = 6432
196
- auth_type = trust
197
- auth_file = /etc/pgbouncer/userlist.txt
198
- pool_mode = transaction
199
- default_pool_size = 20
200
- max_db_connections = 60
201
- max_client_conn = 100
202
- server_reset_query = DEALLOCATE ALL
203
- ignore_startup_parameters = extra_float_digits
204
- `, "utf8");
458
+ // ---------------------------------------------------------------------------
459
+ // Schema push (engine subprocess)
460
+ // ---------------------------------------------------------------------------
461
+ // Last successfully-pushed AST JSON — used to skip no-op re-fires.
462
+ let _lastPushedAst = null;
463
+ // AST that failed on its last attempt — always retried even if content is unchanged.
464
+ let _lastFailedAst = null;
465
+ async function runSchemaPush(cwd, engineBin, schemaPath, dbURL, manifestPath, adminConfigPath, storagePath, skipFieldKinds) {
466
+ // Build AST JSON from schema file.
467
+ const { loadSchemaAst } = await import("../config.js");
468
+ let ast = loadSchemaAst(schemaPath, cwd);
469
+ // Strip fields whose kind requires an unavailable Postgres extension.
470
+ if (skipFieldKinds && skipFieldKinds.size > 0) {
471
+ const { filtered, adapted } = adaptUnsupportedKinds(ast, skipFieldKinds);
472
+ ast = filtered;
473
+ if (adapted.length > 0) {
474
+ console.warn(`[supatype] ⚠ ${adapted.length} field(s) replaced with JSONB — required extensions not available:\n` +
475
+ adapted.map((s) => ` ${s}`).join("\n"));
476
+ }
205
477
  }
206
- if (!existsSync(resolve(supatypeDir, "userlist.txt"))) {
207
- writeFileSync(resolve(supatypeDir, "userlist.txt"), "", "utf8");
478
+ const astJson = JSON.stringify(ast);
479
+ // Skip only when the last push of this exact AST succeeded.
480
+ // If it previously failed we always retry so the user can trigger a re-run
481
+ // by simply saving the file again without needing to make a content change.
482
+ if (astJson === _lastPushedAst && astJson !== _lastFailedAst) {
483
+ return;
208
484
  }
209
- if (!existsSync(resolve(supatypeDir, "kong.yml"))) {
210
- writeFileSync(resolve(supatypeDir, "kong.yml"), `_format_version: "3.0"
211
-
212
- services:
213
- - name: rest-v1
214
- url: http://postgrest:3000
215
- routes:
216
- - name: rest-v1-all
217
- strip_path: true
218
- paths:
219
- - /rest/v1/
220
- - name: auth-v1
221
- url: http://gotrue:9999
222
- routes:
223
- - name: auth-v1-all
224
- strip_path: true
225
- paths:
226
- - /auth/v1/
227
- - name: storage-v1
228
- url: http://host.docker.internal:5000
229
- routes:
230
- - name: storage-v1-all
231
- strip_path: true
232
- paths:
233
- - /storage/v1/
234
- - name: realtime-v1
235
- url: http://host.docker.internal:4000
236
- routes:
237
- - name: realtime-v1-all
238
- strip_path: true
239
- paths:
240
- - /realtime/v1/
241
- protocols:
242
- - http
243
- - https
244
- - ws
245
- - wss
246
- - name: functions-v1
247
- url: http://host.docker.internal:54321
248
- routes:
249
- - name: functions-v1-all
250
- strip_path: false
251
- paths:
252
- - /functions/v1/
253
- - name: studio
254
- url: http://host.docker.internal:3002
255
- routes:
256
- - name: studio-all
257
- strip_path: true
258
- paths:
259
- - /studio/
260
- `, "utf8");
485
+ const astPath = join(cwd, ".supatype", "schema.ast.json");
486
+ writeFileSync(astPath, astJson);
487
+ // Push schema.
488
+ console.log("[supatype] Applying schema...");
489
+ const pushResult = spawnSync(engineBin, ["push", "-i", astPath, "--database-url", dbURL, "--force"], { cwd, stdio: "inherit", encoding: "utf8" });
490
+ if (pushResult.status !== 0) {
491
+ _lastFailedAst = astJson;
492
+ throw new Error(`Engine schema push failed (exit ${pushResult.status})`);
261
493
  }
494
+ _lastPushedAst = astJson;
495
+ _lastFailedAst = null;
496
+ // Provision storage buckets declared in the schema.
497
+ if (storagePath) {
498
+ const parseResult = spawnSync(engineBin, ["parse", "-i", astPath], { cwd, stdio: "pipe", encoding: "utf8" });
499
+ if (parseResult.status === 0 && parseResult.stdout) {
500
+ try {
501
+ const resolvedAst = JSON.parse(parseResult.stdout);
502
+ if (resolvedAst.storageBuckets && resolvedAst.storageBuckets.length > 0) {
503
+ provisionStorageBuckets(resolvedAst.storageBuckets, storagePath);
504
+ }
505
+ }
506
+ catch { /* ignore parse errors */ }
507
+ }
508
+ }
509
+ // Generate manifest.
510
+ const genResult = spawnSync(engineBin, ["generate", "-i", astPath, "-o", manifestPath], { cwd, stdio: "pipe", encoding: "utf8" });
511
+ if (genResult.status !== 0) {
512
+ console.warn("[supatype] Manifest generation failed — server routing may be stale.");
513
+ }
514
+ // Generate admin config (for Studio). Engine writes to stdout.
515
+ if (adminConfigPath) {
516
+ const adminResult = spawnSync(engineBin, ["admin", "-i", astPath], { cwd, stdio: "pipe", encoding: "utf8" });
517
+ if (adminResult.status === 0 && adminResult.stdout) {
518
+ writeFileSync(adminConfigPath, adminResult.stdout);
519
+ }
520
+ }
521
+ console.log("[supatype] Schema applied.");
262
522
  }
263
- function ensureDevEnv(cwd) {
264
- const envPath = resolve(cwd, ".env");
265
- if (existsSync(envPath))
266
- return;
267
- const projectName = resolve(cwd).split(/[\\/]/).pop() ?? "supatype";
268
- const content = `# Generated by supatype dev — all defaults for local development
269
- DATABASE_URL=postgresql://postgres:postgres@localhost:5432/${projectName}
270
- POSTGRES_PASSWORD=postgres
271
- POSTGRES_DB=${projectName}
272
-
273
- JWT_SECRET=super-secret-jwt-token-change-in-production
274
- ANON_KEY=
275
- SERVICE_ROLE_KEY=
276
-
277
- SITE_URL=http://localhost:3000
278
-
279
- # Storage (MinIO)
280
- S3_ENDPOINT=http://localhost:9000
281
- S3_REGION=us-east-1
282
- S3_ACCESS_KEY=supatype
283
- S3_SECRET_KEY=supatype-secret
284
- S3_FORCE_PATH_STYLE=true
285
-
286
- # SMTP — leave empty for email autoconfirm in dev
287
- SMTP_HOST=
288
- SMTP_PORT=
289
- SMTP_USER=
290
- SMTP_PASS=
291
- `;
292
- writeFileSync(envPath, content, "utf8");
293
- console.log(" created .env (local dev defaults)\n");
294
- }
295
- function loadDotEnv(cwd) {
296
- const envPath = resolve(cwd, ".env");
297
- if (!existsSync(envPath))
298
- return {};
299
- const vars = {};
300
- for (const line of readFileSync(envPath, "utf8").split("\n")) {
301
- const trimmed = line.trim();
302
- if (!trimmed || trimmed.startsWith("#"))
303
- continue;
304
- const eq = trimmed.indexOf("=");
305
- if (eq === -1)
523
+ // ---------------------------------------------------------------------------
524
+ // Storage bucket provisioning (local dev only)
525
+ // ---------------------------------------------------------------------------
526
+ function provisionStorageBuckets(declared, storagePath) {
527
+ const bucketsDir = join(storagePath, ".supatype");
528
+ const bucketsFile = join(bucketsDir, "buckets.json");
529
+ mkdirSync(bucketsDir, { recursive: true });
530
+ let existing = [];
531
+ try {
532
+ existing = JSON.parse(readFileSync(bucketsFile, "utf8"));
533
+ }
534
+ catch { /* file doesn't exist yet */ }
535
+ const existingIds = new Set(existing.map((b) => b["id"]));
536
+ let added = 0;
537
+ for (const bucket of declared) {
538
+ if (existingIds.has(bucket.id))
306
539
  continue;
307
- const key = trimmed.slice(0, eq);
308
- const value = trimmed.slice(eq + 1);
309
- vars[key] = value;
540
+ const now = new Date().toISOString();
541
+ existing.push({
542
+ id: bucket.id,
543
+ name: bucket.id,
544
+ public: bucket.public,
545
+ file_size_limit: bucket.fileSizeLimit ?? null,
546
+ allowed_mime_types: bucket.allowedMimeTypes ?? null,
547
+ access_mode: bucket.accessMode ?? (bucket.public ? "public" : "private"),
548
+ s3_bucket_policy: bucket.s3BucketPolicy ?? null,
549
+ created_at: now,
550
+ updated_at: now,
551
+ });
552
+ mkdirSync(join(storagePath, bucket.id), { recursive: true });
553
+ added++;
310
554
  }
311
- return vars;
555
+ if (added > 0) {
556
+ writeFileSync(bucketsFile, JSON.stringify(existing, null, 2));
557
+ console.log(`[supatype] Storage: provisioned ${added} bucket(s).`);
558
+ }
559
+ }
560
+ // ---------------------------------------------------------------------------
561
+ // Resolve Postgres bin dir
562
+ // ---------------------------------------------------------------------------
563
+ async function resolvePgBinDir(config) {
564
+ const override = config.overrides?.postgres_dir;
565
+ if (override) {
566
+ // Normalize Git Bash (/c/Users/...) paths to Win32 form (C:\Users\...) on Windows.
567
+ const normalised = normalisePlatformPath(override);
568
+ const resolved = resolve(process.cwd(), normalised);
569
+ const binDir = join(resolved, "bin");
570
+ if (!existsSync(binDir)) {
571
+ throw new Error(`[overrides] postgres_dir does not contain a bin/ directory: ${resolved}`);
572
+ }
573
+ console.warn(`\u26a0 Using local Postgres build: ${resolved}`);
574
+ return binDir;
575
+ }
576
+ // Locate cached Postgres archive.
577
+ const { cachePath } = await import("../binary-cache.js");
578
+ const version = config.versions.postgres;
579
+ const { currentPlatform } = await import("../binary-cache.js");
580
+ const platform = currentPlatform();
581
+ const pgCacheDir = cachePath("postgres", version);
582
+ const extractedDir = join(pgCacheDir, `pg-${version}`);
583
+ const pgCtlName = platform.os === "windows" ? "pg_ctl.exe" : "pg_ctl";
584
+ if (!existsSync(join(extractedDir, "bin", pgCtlName))) {
585
+ // Try to extract the cached archive.
586
+ await extractPostgresArchive(pgCacheDir, version, platform, extractedDir);
587
+ }
588
+ return join(extractedDir, "bin");
312
589
  }
313
- function localDevDefaults(cwd) {
314
- const projectName = resolve(cwd).split(/[\\/]/).pop() ?? "supatype";
315
- // Known defaults that match docker-compose local dev setup
316
- const defaults = {
317
- DATABASE_URL: `postgresql://postgres:postgres@localhost:5432/${projectName}`,
318
- POSTGRES_PASSWORD: "postgres",
319
- POSTGRES_DB: projectName,
320
- JWT_SECRET: "super-secret-jwt-token-change-in-production",
321
- SITE_URL: "http://localhost:3000",
322
- S3_ENDPOINT: "http://localhost:9000",
323
- S3_REGION: "us-east-1",
324
- S3_ACCESS_KEY: "supatype",
325
- S3_SECRET_KEY: "supatype-secret",
326
- S3_FORCE_PATH_STYLE: "true",
327
- SLOT_NAME: "realtime_slot",
328
- REPLICATION_POLL_INTERVAL: "100",
329
- SECURE_CHANNELS: "true",
330
- };
331
- // .env file values override defaults
332
- const dotEnv = loadDotEnv(cwd);
333
- return { ...defaults, ...dotEnv };
590
+ async function extractPostgresArchive(pgCacheDir, version, platform, extractDir) {
591
+ const ext = platform.os === "windows" ? ".zip" : ".tar.gz";
592
+ const archiveName = `supatype-pg-${postgresArchiveTag(version)}-${platform.os}-${platform.arch}${ext}`;
593
+ const archivePath = join(pgCacheDir, archiveName);
594
+ if (!existsSync(archivePath)) {
595
+ throw new Error(`Postgres ${version} archive not found. Run: supatype update`);
596
+ }
597
+ mkdirSync(extractDir, { recursive: true });
598
+ // On Windows, Git Bash tar is typically first in PATH and chokes on drive-letter
599
+ // paths (C:\...). Use PowerShell's Expand-Archive instead, which handles Windows
600
+ // paths natively. On Linux/macOS, use tar as normal.
601
+ const result = platform.os === "windows"
602
+ ? spawnSync("powershell.exe", ["-NoProfile", "-Command", `Expand-Archive -Path '${archivePath}' -DestinationPath '${extractDir}' -Force`], { stdio: "inherit" })
603
+ : spawnSync("tar", ["-xzf", archivePath, "-C", extractDir], { stdio: "inherit" });
604
+ if (result.status !== 0) {
605
+ throw new Error(`Failed to extract Postgres archive: ${archivePath}`);
606
+ }
334
607
  }
335
- function startLocalServices(cwd) {
336
- const children = [];
337
- const devEnv = localDevDefaults(cwd);
338
- const services = [
339
- { name: "storage", filter: "@supatype/storage", color: "\x1b[34m" },
340
- { name: "realtime", filter: "@supatype/realtime", color: "\x1b[35m" },
341
- { name: "studio", filter: "@supatype/studio", color: "\x1b[36m" },
342
- ];
343
- for (const svc of services) {
344
- const pkgDir = resolve(cwd, "..", "packages", svc.name);
345
- if (!existsSync(resolve(pkgDir, "package.json"))) {
346
- console.warn(` Skipping ${svc.name} — not found at ${pkgDir}`);
347
- continue;
608
+ // ---------------------------------------------------------------------------
609
+ // PostgREST resolver — downloads from GitHub releases if not cached
610
+ // ---------------------------------------------------------------------------
611
+ const POSTGREST_DEFAULT_VERSION = "12.2.3";
612
+ const POSTGREST_GITHUB = "https://github.com/PostgREST/postgrest/releases/download";
613
+ async function resolvePostgrestBin(overridePath) {
614
+ // Honour local override (same pattern as engine/server).
615
+ if (overridePath) {
616
+ let p = resolve(process.cwd(), normalisePlatformPath(overridePath));
617
+ if (process.platform === "win32" && !p.endsWith(".exe") && !existsSync(p)) {
618
+ const withExe = p + ".exe";
619
+ if (existsSync(withExe))
620
+ p = withExe;
348
621
  }
349
- const reset = "\x1b[0m";
350
- const prefix = `${svc.color}[${svc.name}]${reset}`;
351
- const child = spawn("pnpm", ["dev"], {
352
- cwd: pkgDir,
353
- stdio: ["ignore", "pipe", "pipe"],
354
- shell: true,
355
- env: {
356
- ...process.env,
357
- ...devEnv,
358
- PORT: svc.name === "storage" ? "5000" : svc.name === "realtime" ? "4000" : "3002",
359
- },
360
- });
361
- child.stdout?.on("data", (data) => {
362
- for (const line of data.toString().trimEnd().split("\n")) {
363
- console.log(`${prefix} ${line}`);
364
- }
365
- });
366
- child.stderr?.on("data", (data) => {
367
- for (const line of data.toString().trimEnd().split("\n")) {
368
- console.error(`${prefix} ${line}`);
369
- }
370
- });
371
- child.on("exit", (code) => {
372
- if (code !== 0 && code !== null) {
373
- console.error(`${prefix} exited with code ${code}`);
622
+ if (existsSync(p))
623
+ return p;
624
+ console.warn(`[supatype] ⚠ PostgREST override not found at ${p}`);
625
+ return null;
626
+ }
627
+ const version = POSTGREST_DEFAULT_VERSION;
628
+ const platform = currentPlatform();
629
+ const arch = platform.arch === "arm64" ? "aarch64" : "x86_64";
630
+ const binName = platform.os === "windows" ? "postgrest.exe" : "postgrest";
631
+ const cacheDir = cachePath("postgres", version).replace(/postgres/, "postgrest");
632
+ const binPath = join(cacheDir, binName);
633
+ const archiveName = platform.os === "windows"
634
+ ? `postgrest-v${version}-windows-x64.zip`
635
+ : platform.os === "darwin"
636
+ ? `postgrest-v${version}-macos-${arch}.tar.xz`
637
+ : `postgrest-v${version}-linux-static-${arch}.tar.xz`;
638
+ const archivePath = join(cacheDir, archiveName);
639
+ if (existsSync(binPath)) {
640
+ // Backfill DLLs for older cached Windows installs where only postgrest.exe
641
+ // was copied from the release archive.
642
+ if (platform.os === "windows" && !hasLikelyWindowsRuntimeDlls(cacheDir) && existsSync(archivePath)) {
643
+ const repaired = repairWindowsPostgrestRuntime(cacheDir, archivePath, binPath);
644
+ if (!repaired) {
645
+ console.warn("[supatype] ⚠ PostgREST runtime DLL repair failed; REST API may be unavailable.");
374
646
  }
375
- });
376
- children.push(child);
377
- console.log(` ${prefix} started (pnpm dev)`);
647
+ }
648
+ return binPath;
378
649
  }
379
- return children;
380
- }
381
- async function waitForPostgREST() {
382
- const deadline = Date.now() + HEALTH_TIMEOUT_MS;
383
- while (Date.now() < deadline) {
384
- try {
385
- const res = await fetch(POSTGREST_URL, { signal: AbortSignal.timeout(2000) });
386
- if (res.ok || res.status === 401)
387
- return; // 401 = JWT required = server up
650
+ // Download from GitHub releases.
651
+ const url = `${POSTGREST_GITHUB}/v${version}/${archiveName}`;
652
+ console.log(`[supatype] Downloading PostgREST v${version}...`);
653
+ mkdirSync(cacheDir, { recursive: true });
654
+ let resp;
655
+ try {
656
+ resp = await fetch(url);
657
+ }
658
+ catch (e) {
659
+ console.warn(`[supatype] ⚠ Could not download PostgREST (${e.message}).\n` +
660
+ ` REST API (/rest/v1/) will be unavailable until the download succeeds.\n` +
661
+ ` Re-run 'supatype dev' once network access to github.com:443 is restored.`);
662
+ return null;
663
+ }
664
+ if (!resp.ok) {
665
+ console.warn(`[supatype] ⚠ Could not download PostgREST: HTTP ${resp.status}. REST API will be unavailable.`);
666
+ return null;
667
+ }
668
+ const buf = Buffer.from(await resp.arrayBuffer());
669
+ writeFileSync(archivePath, buf);
670
+ // Extract. The Windows zip may nest postgrest.exe inside a subdirectory, so
671
+ // after Expand-Archive we copy postgrest.exe and sibling DLLs to cacheDir.
672
+ if (platform.os === "windows") {
673
+ const r = spawnSync("powershell.exe", [
674
+ "-NoProfile", "-Command",
675
+ `Expand-Archive -Path '${archivePath}' -DestinationPath '${cacheDir}' -Force; ` +
676
+ `$exe = Get-ChildItem -Path '${cacheDir}' -Recurse -Filter 'postgrest.exe' | Select-Object -First 1; ` +
677
+ `if ($exe) { ` +
678
+ ` Copy-Item -Path $exe.FullName -Destination '${binPath}' -Force; ` +
679
+ ` Get-ChildItem -Path $exe.Directory.FullName -Filter '*.dll' | ` +
680
+ ` ForEach-Object { Copy-Item -Path $_.FullName -Destination '${cacheDir}' -Force }; ` +
681
+ `}`,
682
+ ], { stdio: "pipe", encoding: "utf8" });
683
+ if (r.status !== 0) {
684
+ console.warn(`[supatype] ⚠ PostgREST extraction failed: ${r.stderr?.trim() ?? "unknown error"}. REST API will be unavailable.`);
685
+ return null;
388
686
  }
389
- catch {
390
- // not ready yet
687
+ }
688
+ else {
689
+ const r = spawnSync("tar", ["-xJf", archivePath, "-C", cacheDir], { stdio: "pipe" });
690
+ if (r.status !== 0) {
691
+ console.warn("[supatype] ⚠ PostgREST extraction failed. REST API will be unavailable.");
692
+ return null;
391
693
  }
392
- await sleep(HEALTH_POLL_MS);
393
694
  }
394
- throw new Error(`PostgREST did not become healthy within ${HEALTH_TIMEOUT_MS / 1000}s.\n` +
395
- "Check: docker compose logs postgrest");
695
+ if (!existsSync(binPath)) {
696
+ console.warn("[supatype] ⚠ PostgREST binary not found after extraction. REST API will be unavailable.");
697
+ return null;
698
+ }
699
+ if (platform.os !== "windows") {
700
+ const { chmod } = await import("node:fs/promises");
701
+ await chmod(binPath, 0o755);
702
+ }
703
+ console.log(`[supatype] PostgREST v${version} ready.`);
704
+ return binPath;
705
+ }
706
+ function hasLikelyWindowsRuntimeDlls(dir) {
707
+ if (process.platform !== "win32")
708
+ return true;
709
+ return (existsSync(join(dir, "libpq.dll")) ||
710
+ existsSync(join(dir, "libpq-5.dll")) ||
711
+ existsSync(join(dir, "libssl-3-x64.dll")));
712
+ }
713
+ function repairWindowsPostgrestRuntime(cacheDir, archivePath, binPath) {
714
+ const r = spawnSync("powershell.exe", [
715
+ "-NoProfile",
716
+ "-Command",
717
+ `Expand-Archive -Path '${archivePath}' -DestinationPath '${cacheDir}' -Force; ` +
718
+ `$exe = Get-ChildItem -Path '${cacheDir}' -Recurse -Filter 'postgrest.exe' | Select-Object -First 1; ` +
719
+ `if ($exe) { ` +
720
+ ` Copy-Item -Path $exe.FullName -Destination '${binPath}' -Force; ` +
721
+ ` Get-ChildItem -Path $exe.Directory.FullName -Filter '*.dll' | ` +
722
+ ` ForEach-Object { Copy-Item -Path $_.FullName -Destination '${cacheDir}' -Force }; ` +
723
+ `}`,
724
+ ], { stdio: "pipe", encoding: "utf8" });
725
+ return r.status === 0;
396
726
  }
397
- async function watchAndPush(cwd) {
398
- const config = loadConfig(cwd);
399
- const schemaDir = resolve(cwd, config.schema, "..");
400
- console.log(`Watching ${schemaDir} for changes... (Ctrl+C to stop)\n`);
401
- // Initial push on start
402
- await runPush(cwd);
403
- const { watch } = await import("node:fs");
404
- watch(schemaDir, { recursive: true }, (eventType, filename) => {
405
- if (!filename?.endsWith(".ts"))
406
- return;
407
- console.log(`\nChange detected in ${filename}, pushing...`);
408
- runPush(cwd).catch((e) => console.error("Push failed:", e.message));
727
+ // Field kinds that require Postgres extensions not available in all builds.
728
+ // Maps kind → { extension name, JSONB fallback AST }
729
+ const EXTENSION_FIELDS = {
730
+ geo: { ext: "PostGIS", fallback: { kind: "json", pgType: "JSONB" } },
731
+ vector: { ext: "pgvector", fallback: { kind: "json", pgType: "JSONB" } },
732
+ };
733
+ function adaptUnsupportedKinds(ast, skipKinds) {
734
+ const adapted = [];
735
+ if (!ast || typeof ast !== "object")
736
+ return { filtered: ast, adapted };
737
+ const schema = ast;
738
+ if (!Array.isArray(schema.models))
739
+ return { filtered: ast, adapted };
740
+ const models = schema.models.map((model) => {
741
+ const fields = {};
742
+ for (const [name, field] of Object.entries(model.fields ?? {})) {
743
+ const info = skipKinds.has(field.kind) ? EXTENSION_FIELDS[field.kind] : undefined;
744
+ if (info) {
745
+ fields[name] = { ...info.fallback, required: field.required ?? false };
746
+ adapted.push(`${model.name}.${name} (${info.ext} → JSONB)`);
747
+ }
748
+ else {
749
+ fields[name] = field;
750
+ }
751
+ }
752
+ return { ...model, fields };
409
753
  });
410
- // Block forever
411
- await new Promise(() => undefined);
754
+ return { filtered: { ...schema, models }, adapted };
412
755
  }
413
- async function runPush(cwd) {
414
- const { loadConfig, loadSchemaAst } = await import("../config.js");
415
- const config = loadConfig(cwd);
416
- const ast = loadSchemaAst(config.schema, cwd);
417
- await ensureEngine();
418
- const result = invokeEngine(["migrate", "--connection", config.connection], JSON.stringify(ast));
419
- if (result.exitCode !== 0) {
420
- console.error(result.stderr || result.stdout);
421
- return;
756
+ // ---------------------------------------------------------------------------
757
+ // .env loader
758
+ // ---------------------------------------------------------------------------
759
+ /** Apply GoTrue DDL (auth.users, etc.) before engine push references auth schema. */
760
+ function runGotrueMigrations(serverBin, authDbURL, jwtSecret) {
761
+ const result = spawnSync(serverBin, ["migrate"], {
762
+ stdio: "pipe",
763
+ encoding: "utf8",
764
+ env: {
765
+ ...process.env,
766
+ DATABASE_URL: authDbURL,
767
+ GOTRUE_DB_DRIVER: "postgres",
768
+ GOTRUE_JWT_SECRET: jwtSecret,
769
+ },
770
+ });
771
+ if (result.status !== 0) {
772
+ const detail = (result.stderr ?? result.stdout ?? "").trim();
773
+ throw new Error(`GoTrue migrations failed (exit ${result.status ?? "unknown"})` +
774
+ (detail ? `:\n${detail}` : ""));
422
775
  }
423
- console.log(result.stdout || "Schema up to date.");
424
776
  }
425
- function sleep(ms) {
426
- return new Promise((r) => setTimeout(r, ms));
777
+ function loadDotEnv(cwd) {
778
+ const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")];
779
+ const vars = {};
780
+ for (const envPath of candidates) {
781
+ if (!existsSync(envPath))
782
+ continue;
783
+ for (const line of readFileSync(envPath, "utf8").split("\n")) {
784
+ const trimmed = line.trim();
785
+ if (!trimmed || trimmed.startsWith("#"))
786
+ continue;
787
+ const eq = trimmed.indexOf("=");
788
+ if (eq === -1)
789
+ continue;
790
+ vars[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
791
+ }
792
+ }
793
+ return vars;
427
794
  }
428
795
  //# sourceMappingURL=dev.js.map