@supatype/cli 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-test.log +221 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/assets/supatype-logo-wordmark.ascii.txt +6 -0
- package/bin/dev-entry.ts +2 -0
- package/bin/supatype.js +5 -0
- package/dist/app/framework.d.ts +44 -0
- package/dist/app/framework.d.ts.map +1 -0
- package/dist/app/framework.js +200 -0
- package/dist/app/framework.js.map +1 -0
- package/dist/app/proxy-dev-app.d.ts +13 -0
- package/dist/app/proxy-dev-app.d.ts.map +1 -0
- package/dist/app/proxy-dev-app.js +54 -0
- package/dist/app/proxy-dev-app.js.map +1 -0
- package/dist/app-config.d.ts +7 -0
- package/dist/app-config.d.ts.map +1 -0
- package/dist/app-config.js +113 -0
- package/dist/app-config.js.map +1 -0
- package/dist/assets/supatype-logo-wordmark.ascii.txt +6 -0
- package/dist/augmentation-generator.d.ts +2 -0
- package/dist/augmentation-generator.d.ts.map +1 -0
- package/dist/augmentation-generator.js +111 -0
- package/dist/augmentation-generator.js.map +1 -0
- package/dist/binary-cache.d.ts +98 -0
- package/dist/binary-cache.d.ts.map +1 -0
- package/dist/binary-cache.js +687 -0
- package/dist/binary-cache.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +61 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/admin.d.ts +4 -0
- package/dist/commands/admin.d.ts.map +1 -0
- package/dist/commands/admin.js +271 -0
- package/dist/commands/admin.js.map +1 -0
- package/dist/commands/app.d.ts +3 -0
- package/dist/commands/app.d.ts.map +1 -0
- package/dist/commands/app.js +82 -0
- package/dist/commands/app.js.map +1 -0
- package/dist/commands/cache.d.ts +6 -0
- package/dist/commands/cache.d.ts.map +1 -0
- package/dist/commands/cache.js +105 -0
- package/dist/commands/cache.js.map +1 -0
- package/dist/commands/cloud.d.ts +23 -0
- package/dist/commands/cloud.d.ts.map +1 -0
- package/dist/commands/cloud.js +254 -0
- package/dist/commands/cloud.js.map +1 -0
- package/dist/commands/db.d.ts +8 -0
- package/dist/commands/db.d.ts.map +1 -0
- package/dist/commands/db.js +116 -0
- package/dist/commands/db.js.map +1 -0
- package/dist/commands/deploy-types.d.ts +14 -0
- package/dist/commands/deploy-types.d.ts.map +1 -0
- package/dist/commands/deploy-types.js +38 -0
- package/dist/commands/deploy-types.js.map +1 -0
- package/dist/commands/deploy.d.ts +15 -0
- package/dist/commands/deploy.d.ts.map +1 -0
- package/dist/commands/deploy.js +322 -0
- package/dist/commands/deploy.js.map +1 -0
- package/dist/commands/dev.d.ts +14 -0
- package/dist/commands/dev.d.ts.map +1 -0
- package/dist/commands/dev.js +806 -0
- package/dist/commands/dev.js.map +1 -0
- package/dist/commands/diff.d.ts +3 -0
- package/dist/commands/diff.d.ts.map +1 -0
- package/dist/commands/diff.js +54 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/engine.d.ts +7 -0
- package/dist/commands/engine.d.ts.map +1 -0
- package/dist/commands/engine.js +27 -0
- package/dist/commands/engine.js.map +1 -0
- package/dist/commands/functions.d.ts +3 -0
- package/dist/commands/functions.d.ts.map +1 -0
- package/dist/commands/functions.js +749 -0
- package/dist/commands/functions.js.map +1 -0
- package/dist/commands/generate.d.ts +3 -0
- package/dist/commands/generate.d.ts.map +1 -0
- package/dist/commands/generate.js +38 -0
- package/dist/commands/generate.js.map +1 -0
- package/dist/commands/init.d.ts +7 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +228 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/keys.d.ts +4 -0
- package/dist/commands/keys.d.ts.map +1 -0
- package/dist/commands/keys.js +57 -0
- package/dist/commands/keys.js.map +1 -0
- package/dist/commands/logs.d.ts +6 -0
- package/dist/commands/logs.d.ts.map +1 -0
- package/dist/commands/logs.js +52 -0
- package/dist/commands/logs.js.map +1 -0
- package/dist/commands/migrate-from-v1.d.ts +5 -0
- package/dist/commands/migrate-from-v1.d.ts.map +1 -0
- package/dist/commands/migrate-from-v1.js +125 -0
- package/dist/commands/migrate-from-v1.js.map +1 -0
- package/dist/commands/migrate.d.ts +3 -0
- package/dist/commands/migrate.d.ts.map +1 -0
- package/dist/commands/migrate.js +75 -0
- package/dist/commands/migrate.js.map +1 -0
- package/dist/commands/pg.d.ts +8 -0
- package/dist/commands/pg.d.ts.map +1 -0
- package/dist/commands/pg.js +102 -0
- package/dist/commands/pg.js.map +1 -0
- package/dist/commands/plugins.d.ts +3 -0
- package/dist/commands/plugins.d.ts.map +1 -0
- package/dist/commands/plugins.js +431 -0
- package/dist/commands/plugins.js.map +1 -0
- package/dist/commands/pull.d.ts +3 -0
- package/dist/commands/pull.d.ts.map +1 -0
- package/dist/commands/pull.js +12 -0
- package/dist/commands/pull.js.map +1 -0
- package/dist/commands/push.d.ts +3 -0
- package/dist/commands/push.d.ts.map +1 -0
- package/dist/commands/push.js +179 -0
- package/dist/commands/push.js.map +1 -0
- package/dist/commands/seed.d.ts +5 -0
- package/dist/commands/seed.d.ts.map +1 -0
- package/dist/commands/seed.js +55 -0
- package/dist/commands/seed.js.map +1 -0
- package/dist/commands/self-host.d.ts +9 -0
- package/dist/commands/self-host.d.ts.map +1 -0
- package/dist/commands/self-host.js +310 -0
- package/dist/commands/self-host.js.map +1 -0
- package/dist/commands/self-update.d.ts +9 -0
- package/dist/commands/self-update.d.ts.map +1 -0
- package/dist/commands/self-update.js +33 -0
- package/dist/commands/self-update.js.map +1 -0
- package/dist/commands/status.d.ts +6 -0
- package/dist/commands/status.d.ts.map +1 -0
- package/dist/commands/status.js +70 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/commands/types.d.ts +3 -0
- package/dist/commands/types.d.ts.map +1 -0
- package/dist/commands/types.js +62 -0
- package/dist/commands/types.js.map +1 -0
- package/dist/commands/update.d.ts +7 -0
- package/dist/commands/update.d.ts.map +1 -0
- package/dist/commands/update.js +118 -0
- package/dist/commands/update.js.map +1 -0
- package/dist/components.d.ts +5 -0
- package/dist/components.d.ts.map +1 -0
- package/dist/components.js +3 -0
- package/dist/components.js.map +1 -0
- package/dist/config.d.ts +65 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +134 -0
- package/dist/config.js.map +1 -0
- package/dist/dev-compose.d.ts +19 -0
- package/dist/dev-compose.d.ts.map +1 -0
- package/dist/dev-compose.js +468 -0
- package/dist/dev-compose.js.map +1 -0
- package/dist/dev-log-bus.d.ts +30 -0
- package/dist/dev-log-bus.d.ts.map +1 -0
- package/dist/dev-log-bus.js +87 -0
- package/dist/dev-log-bus.js.map +1 -0
- package/dist/dev-log-filter.d.ts +10 -0
- package/dist/dev-log-filter.d.ts.map +1 -0
- package/dist/dev-log-filter.js +36 -0
- package/dist/dev-log-filter.js.map +1 -0
- package/dist/dev-logo.d.ts +12 -0
- package/dist/dev-logo.d.ts.map +1 -0
- package/dist/dev-logo.js +57 -0
- package/dist/dev-logo.js.map +1 -0
- package/dist/dev-session.d.ts +26 -0
- package/dist/dev-session.d.ts.map +1 -0
- package/dist/dev-session.js +106 -0
- package/dist/dev-session.js.map +1 -0
- package/dist/dev-shutdown.d.ts +9 -0
- package/dist/dev-shutdown.d.ts.map +1 -0
- package/dist/dev-shutdown.js +50 -0
- package/dist/dev-shutdown.js.map +1 -0
- package/dist/dev-task-colors.d.ts +14 -0
- package/dist/dev-task-colors.d.ts.map +1 -0
- package/dist/dev-task-colors.js +44 -0
- package/dist/dev-task-colors.js.map +1 -0
- package/dist/dev-tui.d.ts +24 -0
- package/dist/dev-tui.d.ts.map +1 -0
- package/dist/dev-tui.js +188 -0
- package/dist/dev-tui.js.map +1 -0
- package/dist/diff-output.d.ts +4 -0
- package/dist/diff-output.d.ts.map +1 -0
- package/dist/diff-output.js +12 -0
- package/dist/diff-output.js.map +1 -0
- package/dist/docker-postgres.d.ts +57 -0
- package/dist/docker-postgres.d.ts.map +1 -0
- package/dist/docker-postgres.js +208 -0
- package/dist/docker-postgres.js.map +1 -0
- package/dist/engine-client.d.ts +69 -0
- package/dist/engine-client.d.ts.map +1 -0
- package/dist/engine-client.js +157 -0
- package/dist/engine-client.js.map +1 -0
- package/dist/engine-push-output.d.ts +16 -0
- package/dist/engine-push-output.d.ts.map +1 -0
- package/dist/engine-push-output.js +61 -0
- package/dist/engine-push-output.js.map +1 -0
- package/dist/ensure-binary.d.ts +7 -0
- package/dist/ensure-binary.d.ts.map +1 -0
- package/dist/ensure-binary.js +17 -0
- package/dist/ensure-binary.js.map +1 -0
- package/dist/functions-router-gen.d.ts +14 -0
- package/dist/functions-router-gen.d.ts.map +1 -0
- package/dist/functions-router-gen.js +199 -0
- package/dist/functions-router-gen.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/jwt.d.ts +3 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +13 -0
- package/dist/jwt.js.map +1 -0
- package/dist/kong-config.d.ts +25 -0
- package/dist/kong-config.d.ts.map +1 -0
- package/dist/kong-config.js +71 -0
- package/dist/kong-config.js.map +1 -0
- package/dist/local-gateway.d.ts +7 -0
- package/dist/local-gateway.d.ts.map +1 -0
- package/dist/local-gateway.js +9 -0
- package/dist/local-gateway.js.map +1 -0
- package/dist/local-storage.d.ts +8 -0
- package/dist/local-storage.d.ts.map +1 -0
- package/dist/local-storage.js +14 -0
- package/dist/local-storage.js.map +1 -0
- package/dist/pgbouncer-userlist.d.ts +5 -0
- package/dist/pgbouncer-userlist.d.ts.map +1 -0
- package/dist/pgbouncer-userlist.js +14 -0
- package/dist/pgbouncer-userlist.js.map +1 -0
- package/dist/postgres-ctl.d.ts +44 -0
- package/dist/postgres-ctl.d.ts.map +1 -0
- package/dist/postgres-ctl.js +137 -0
- package/dist/postgres-ctl.js.map +1 -0
- package/dist/process-manager.d.ts +49 -0
- package/dist/process-manager.d.ts.map +1 -0
- package/dist/process-manager.js +177 -0
- package/dist/process-manager.js.map +1 -0
- package/dist/project-config.d.ts +238 -0
- package/dist/project-config.d.ts.map +1 -0
- package/dist/project-config.js +159 -0
- package/dist/project-config.js.map +1 -0
- package/dist/pull-utils.d.ts +31 -0
- package/dist/pull-utils.d.ts.map +1 -0
- package/dist/pull-utils.js +77 -0
- package/dist/pull-utils.js.map +1 -0
- package/dist/release-pins.d.ts +7 -0
- package/dist/release-pins.d.ts.map +1 -0
- package/dist/release-pins.js +27 -0
- package/dist/release-pins.js.map +1 -0
- package/dist/release-public-key.d.ts +8 -0
- package/dist/release-public-key.d.ts.map +1 -0
- package/dist/release-public-key.js +13 -0
- package/dist/release-public-key.js.map +1 -0
- package/dist/restore-system-relation-targets.d.ts +3 -0
- package/dist/restore-system-relation-targets.d.ts.map +1 -0
- package/dist/restore-system-relation-targets.js +45 -0
- package/dist/restore-system-relation-targets.js.map +1 -0
- package/dist/runtime-routes.d.ts +34 -0
- package/dist/runtime-routes.d.ts.map +1 -0
- package/dist/runtime-routes.js +252 -0
- package/dist/runtime-routes.js.map +1 -0
- package/dist/schema-ast-v2.d.ts +127 -0
- package/dist/schema-ast-v2.d.ts.map +1 -0
- package/dist/schema-ast-v2.js +226 -0
- package/dist/schema-ast-v2.js.map +1 -0
- package/dist/scripts/postinstall.d.ts +11 -0
- package/dist/scripts/postinstall.d.ts.map +1 -0
- package/dist/scripts/postinstall.js +47 -0
- package/dist/scripts/postinstall.js.map +1 -0
- package/dist/seed.d.ts +8 -0
- package/dist/seed.d.ts.map +1 -0
- package/dist/seed.js +32 -0
- package/dist/seed.js.map +1 -0
- package/dist/self-host-compose.d.ts +43 -0
- package/dist/self-host-compose.d.ts.map +1 -0
- package/dist/self-host-compose.js +400 -0
- package/dist/self-host-compose.js.map +1 -0
- package/dist/storage-provision.d.ts +24 -0
- package/dist/storage-provision.d.ts.map +1 -0
- package/dist/storage-provision.js +44 -0
- package/dist/storage-provision.js.map +1 -0
- package/dist/studio-admin-roles.d.ts +7 -0
- package/dist/studio-admin-roles.d.ts.map +1 -0
- package/dist/studio-admin-roles.js +14 -0
- package/dist/studio-admin-roles.js.map +1 -0
- package/dist/studio-dev-server.d.ts +22 -0
- package/dist/studio-dev-server.d.ts.map +1 -0
- package/dist/studio-dev-server.js +28 -0
- package/dist/studio-dev-server.js.map +1 -0
- package/dist/supatype-eval-1781522769253.d.mts +2 -0
- package/dist/supatype-eval-1781522769253.d.mts.map +1 -0
- package/dist/supatype-eval-1781522769253.mjs +3 -0
- package/dist/supatype-eval-1781522769253.mjs.map +1 -0
- package/dist/systemd.d.ts +26 -0
- package/dist/systemd.d.ts.map +1 -0
- package/dist/systemd.js +102 -0
- package/dist/systemd.js.map +1 -0
- package/dist/tsx-runner.d.ts +18 -0
- package/dist/tsx-runner.d.ts.map +1 -0
- package/dist/tsx-runner.js +69 -0
- package/dist/tsx-runner.js.map +1 -0
- package/dist/type-extractor.d.ts +4 -0
- package/dist/type-extractor.d.ts.map +1 -0
- package/dist/type-extractor.js +1213 -0
- package/dist/type-extractor.js.map +1 -0
- package/dist/type-resolver.d.ts +33 -0
- package/dist/type-resolver.d.ts.map +1 -0
- package/dist/type-resolver.js +338 -0
- package/dist/type-resolver.js.map +1 -0
- package/package.json +41 -0
- package/releases/deno/VERSION +1 -0
- package/scripts/mirror-deno-release.sh +76 -0
- package/src/TYPE-RESOLUTION.md +294 -0
- package/src/app/framework.ts +249 -0
- package/src/app/proxy-dev-app.ts +68 -0
- package/src/app-config.ts +128 -0
- package/src/augmentation-generator.ts +126 -0
- package/src/binary-cache.ts +845 -0
- package/src/cli.ts +63 -0
- package/src/commands/admin.ts +372 -0
- package/src/commands/app.ts +97 -0
- package/src/commands/cache.ts +117 -0
- package/src/commands/cloud.ts +325 -0
- package/src/commands/db.ts +136 -0
- package/src/commands/deploy-types.ts +49 -0
- package/src/commands/deploy.ts +400 -0
- package/src/commands/dev.ts +1009 -0
- package/src/commands/diff.ts +63 -0
- package/src/commands/engine.ts +30 -0
- package/src/commands/functions.ts +901 -0
- package/src/commands/generate.ts +44 -0
- package/src/commands/init.ts +253 -0
- package/src/commands/keys.ts +66 -0
- package/src/commands/logs.ts +58 -0
- package/src/commands/migrate-from-v1.ts +131 -0
- package/src/commands/migrate.ts +87 -0
- package/src/commands/pg.ts +133 -0
- package/src/commands/plugins.ts +508 -0
- package/src/commands/pull.ts +17 -0
- package/src/commands/push.ts +226 -0
- package/src/commands/seed.ts +68 -0
- package/src/commands/self-host.ts +364 -0
- package/src/commands/self-update.ts +45 -0
- package/src/commands/status.ts +84 -0
- package/src/commands/types.ts +76 -0
- package/src/commands/update.ts +136 -0
- package/src/components.ts +6 -0
- package/src/config.ts +223 -0
- package/src/dev-compose.ts +583 -0
- package/src/dev-log-bus.ts +101 -0
- package/src/dev-log-filter.ts +32 -0
- package/src/dev-logo.ts +62 -0
- package/src/dev-session.ts +130 -0
- package/src/dev-shutdown.ts +54 -0
- package/src/dev-task-colors.ts +47 -0
- package/src/dev-tui.ts +232 -0
- package/src/diff-output.ts +12 -0
- package/src/docker-postgres.ts +295 -0
- package/src/engine-client.ts +236 -0
- package/src/engine-push-output.ts +71 -0
- package/src/ensure-binary.ts +28 -0
- package/src/functions-router-gen.ts +224 -0
- package/src/index.ts +11 -0
- package/src/jwt.ts +14 -0
- package/src/kong-config.ts +93 -0
- package/src/local-gateway.ts +9 -0
- package/src/local-storage.ts +14 -0
- package/src/pgbouncer-userlist.ts +15 -0
- package/src/postgres-ctl.ts +171 -0
- package/src/process-manager.ts +220 -0
- package/src/project-config.ts +388 -0
- package/src/pull-utils.ts +81 -0
- package/src/release-pins.ts +31 -0
- package/src/release-public-key.ts +12 -0
- package/src/restore-system-relation-targets.ts +45 -0
- package/src/runtime-routes.ts +291 -0
- package/src/schema-ast-v2.ts +324 -0
- package/src/scripts/postinstall.ts +51 -0
- package/src/seed.ts +43 -0
- package/src/self-host-compose.ts +452 -0
- package/src/storage-provision.ts +58 -0
- package/src/studio-admin-roles.ts +16 -0
- package/src/studio-dev-server.ts +53 -0
- package/src/supatype-eval-1781522769253.mts +1 -0
- package/src/systemd.ts +137 -0
- package/src/tsx-runner.ts +89 -0
- package/src/type-extractor.ts +1479 -0
- package/src/type-resolver.ts +457 -0
- package/tests/app-command.test.ts +54 -0
- package/tests/augmentation-generator.test.ts +59 -0
- package/tests/binary-cache-cloud-overrides.test.ts +123 -0
- package/tests/cached-artifact-format.test.ts +84 -0
- package/tests/cli-help.test.ts +133 -0
- package/tests/config.test.ts +252 -0
- package/tests/dev-ui.test.ts +139 -0
- package/tests/docker-postgres.test.ts +39 -0
- package/tests/engine-distribution.test.ts +418 -0
- package/tests/engine-push-output.test.ts +67 -0
- package/tests/ensure-binary.test.ts +59 -0
- package/tests/init.test.ts +127 -0
- package/tests/keys.test.ts +160 -0
- package/tests/migrate-from-v1.test.ts +29 -0
- package/tests/normalize-admin-config.test.ts +48 -0
- package/tests/pg-spawn-env.test.ts +18 -0
- package/tests/postgres-archive-tag.test.ts +9 -0
- package/tests/proxy-dev-app.test.ts +33 -0
- package/tests/pull-utils.test.ts +150 -0
- package/tests/release-pins.test.ts +28 -0
- package/tests/runtime-contract.test.ts +370 -0
- package/tests/seed-discover.test.ts +31 -0
- package/tests/studio-admin-roles.test.ts +27 -0
- package/tests/tsconfig.json +9 -0
- package/tests/tsx-runner.test.ts +66 -0
- package/tests/type-extractor.test.ts +985 -0
- package/tests/type-resolver.test.ts +59 -0
- package/tsconfig.json +10 -0
- package/tsconfig.tsbuildinfo +1 -0
- package/vitest.config.ts +12 -0
|
@@ -0,0 +1,1009 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* supatype dev — start local Postgres, apply schema, run supatype-server.
|
|
3
|
+
*
|
|
4
|
+
* Runtime provider (top-level `provider` or legacy `database.provider`):
|
|
5
|
+
* native — host Postgres + host server + host engine (default)
|
|
6
|
+
* docker — full self-host Compose stack (Kong :18473); see dev-compose.ts
|
|
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
|
+
|
|
13
|
+
import type { Command } from "commander"
|
|
14
|
+
import { spawnSync } from "node:child_process"
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
16
|
+
import { homedir } from "node:os"
|
|
17
|
+
import { isAbsolute, join, relative, resolve } from "node:path"
|
|
18
|
+
import { loadConfig } from "../config.js"
|
|
19
|
+
import {
|
|
20
|
+
functionsPathCandidatesFromProject,
|
|
21
|
+
resolveRuntimeProvider,
|
|
22
|
+
schemaPathFromProject,
|
|
23
|
+
type SupatypeProjectConfig,
|
|
24
|
+
} from "../project-config.js"
|
|
25
|
+
import { discoverTsFunctionsInDir, writeDevFunctionsRouter } from "../functions-router-gen.js"
|
|
26
|
+
import { signJwt } from "../jwt.js"
|
|
27
|
+
import {
|
|
28
|
+
normalisePlatformPath,
|
|
29
|
+
cachePath,
|
|
30
|
+
currentPlatform,
|
|
31
|
+
hasMeaningfulOverrides,
|
|
32
|
+
describeActiveOverrides,
|
|
33
|
+
postgresArchiveTag,
|
|
34
|
+
} from "../binary-cache.js"
|
|
35
|
+
import { ensureBinary } from "../ensure-binary.js"
|
|
36
|
+
import { startProxyDevApp } from "../app/proxy-dev-app.js"
|
|
37
|
+
import { ProcessManager } from "../process-manager.js"
|
|
38
|
+
import { startStudioViteDevServer } from "../studio-dev-server.js"
|
|
39
|
+
import { restoreSystemRelationTargets } from "../restore-system-relation-targets.js"
|
|
40
|
+
import { localStorageEnv } from "../local-storage.js"
|
|
41
|
+
import { beginDevSession, endDevSession, resolveDevUiMode, startDevSession } from "../dev-session.js"
|
|
42
|
+
import { registerDevShutdown } from "../dev-shutdown.js"
|
|
43
|
+
import {
|
|
44
|
+
initdb,
|
|
45
|
+
start as pgStart,
|
|
46
|
+
stop as pgStop,
|
|
47
|
+
waitReady as pgWaitReady,
|
|
48
|
+
isPortInUse,
|
|
49
|
+
pgSpawnEnv,
|
|
50
|
+
} from "../postgres-ctl.js"
|
|
51
|
+
/** Map `email.smtp` from supatype.config.ts into GOTRUE_SMTP_* for the embedded GoTrue process. */
|
|
52
|
+
function gotrueSMTPFromEmailConfig(email: SupatypeProjectConfig["email"] | undefined): Record<string, string> {
|
|
53
|
+
const s = email?.smtp
|
|
54
|
+
if (!s) return {}
|
|
55
|
+
const out: Record<string, string> = {}
|
|
56
|
+
const host = s.host?.trim()
|
|
57
|
+
if (host) out.GOTRUE_SMTP_HOST = host
|
|
58
|
+
if (s.port !== undefined) out.GOTRUE_SMTP_PORT = String(s.port)
|
|
59
|
+
const user = s.user?.trim()
|
|
60
|
+
if (user) out.GOTRUE_SMTP_USER = user
|
|
61
|
+
if (s.pass !== undefined && s.pass !== "") out.GOTRUE_SMTP_PASS = s.pass
|
|
62
|
+
const admin = s.admin_email?.trim()
|
|
63
|
+
if (admin) out.GOTRUE_SMTP_ADMIN_EMAIL = admin
|
|
64
|
+
const sender = s.sender_name?.trim()
|
|
65
|
+
if (sender) out.GOTRUE_SMTP_SENDER_NAME = sender
|
|
66
|
+
return out
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function registerDev(program: Command): void {
|
|
70
|
+
program
|
|
71
|
+
.command("dev")
|
|
72
|
+
.description("Start local Postgres, apply schema, and run supatype-server")
|
|
73
|
+
.option("--no-watch", "Start services but do not watch for schema changes")
|
|
74
|
+
.option("--stream", "Print interleaved logs instead of the interactive TUI")
|
|
75
|
+
.option("--port <port>", "Port for supatype-server (overrides config)", String)
|
|
76
|
+
.action(async (opts: { watch: boolean; stream?: boolean; port?: string }) => {
|
|
77
|
+
const cwd = process.cwd()
|
|
78
|
+
beginDevSession(resolveDevUiMode(opts.stream === true))
|
|
79
|
+
|
|
80
|
+
// ── 1. Load project config ─────────────────────────────────────────────
|
|
81
|
+
const config = loadConfig(cwd)
|
|
82
|
+
|
|
83
|
+
startDevSession()
|
|
84
|
+
if (hasMeaningfulOverrides(config)) {
|
|
85
|
+
console.warn("[supatype] Local binary overrides active:")
|
|
86
|
+
for (const line of describeActiveOverrides(config)) {
|
|
87
|
+
console.warn(line)
|
|
88
|
+
}
|
|
89
|
+
console.warn("")
|
|
90
|
+
}
|
|
91
|
+
const projectName = config.project.name
|
|
92
|
+
const serverPort = opts.port ?? String(config.server.port ?? 54321)
|
|
93
|
+
const postgrestPort = String(config.server.postgrestPort ?? 3001)
|
|
94
|
+
const provider = resolveRuntimeProvider(config)
|
|
95
|
+
|
|
96
|
+
if (provider === "docker") {
|
|
97
|
+
const { runDevCompose } = await import("../dev-compose.js")
|
|
98
|
+
await runDevCompose(cwd, config, { watch: opts.watch !== false })
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── 2. Resolve engine + server binaries ──────────────────────────────
|
|
103
|
+
console.log(`[supatype] Resolving component binaries for "${projectName}"...`)
|
|
104
|
+
const [engineBin, serverBin] = await Promise.all([
|
|
105
|
+
ensureBinary("engine", config),
|
|
106
|
+
ensureBinary("server", config),
|
|
107
|
+
])
|
|
108
|
+
|
|
109
|
+
// ── 3. Per-project state directories ─────────────────────────────────
|
|
110
|
+
const stateRoot = join(homedir(), ".supatype", "projects", projectName)
|
|
111
|
+
const pidDir = join(stateRoot, "pid")
|
|
112
|
+
const logsDir = join(stateRoot, "logs")
|
|
113
|
+
const tmpDir = join(stateRoot, "tmp")
|
|
114
|
+
|
|
115
|
+
for (const d of [pidDir, logsDir, tmpDir]) {
|
|
116
|
+
mkdirSync(d, { recursive: true })
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ── 4. Port collision check ───────────────────────────────────────────
|
|
120
|
+
const pgPort = 5432
|
|
121
|
+
if (await isPortInUse(pgPort)) {
|
|
122
|
+
console.error(
|
|
123
|
+
`[supatype] Port ${pgPort} is already in use. Another Postgres instance may be running.\n` +
|
|
124
|
+
` Check: lsof -i :${pgPort}`,
|
|
125
|
+
)
|
|
126
|
+
endDevSession()
|
|
127
|
+
process.exit(1)
|
|
128
|
+
}
|
|
129
|
+
if (await isPortInUse(Number(serverPort))) {
|
|
130
|
+
console.error(
|
|
131
|
+
`[supatype] Port ${serverPort} is already in use. Another supatype-server may be running.\n` +
|
|
132
|
+
` Check: lsof -i :${serverPort}`,
|
|
133
|
+
)
|
|
134
|
+
endDevSession()
|
|
135
|
+
process.exit(1)
|
|
136
|
+
}
|
|
137
|
+
if (await isPortInUse(Number(postgrestPort))) {
|
|
138
|
+
console.error(
|
|
139
|
+
`[supatype] Port ${postgrestPort} is already in use. Another service may be running.\n` +
|
|
140
|
+
` Check: lsof -i :${postgrestPort}`,
|
|
141
|
+
)
|
|
142
|
+
endDevSession()
|
|
143
|
+
process.exit(1)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ── 5–7. Start Postgres ───────────────────────────────────────────────
|
|
147
|
+
let dbURL: string
|
|
148
|
+
let stopPostgres: () => void | Promise<void>
|
|
149
|
+
const pgPassword = "postgres"
|
|
150
|
+
// pgBinDir is set on the native path and used to add DLL search path for
|
|
151
|
+
// PostgREST on Windows (PostgREST links against libpq + SSL from MinGW).
|
|
152
|
+
let pgBinDir: string | null = null
|
|
153
|
+
|
|
154
|
+
{
|
|
155
|
+
// native — resolve pg bin dir and manage with pg_ctl
|
|
156
|
+
pgBinDir = await resolvePgBinDir(config)
|
|
157
|
+
const dataDir = config.database.data_dir ?? join(stateRoot, "data")
|
|
158
|
+
mkdirSync(dataDir, { recursive: true })
|
|
159
|
+
const pgOpts = { pgBinDir, dataDir, port: pgPort, logPath: join(logsDir, "postgres.log") }
|
|
160
|
+
|
|
161
|
+
console.log("[supatype] Initialising Postgres data directory...")
|
|
162
|
+
initdb(pgOpts)
|
|
163
|
+
console.log("[supatype] Starting Postgres...")
|
|
164
|
+
pgStart(pgOpts)
|
|
165
|
+
await pgWaitReady(pgOpts, 15_000)
|
|
166
|
+
console.log("[supatype] Postgres is ready.")
|
|
167
|
+
dbURL = `postgres://postgres:postgres@127.0.0.1:${pgPort}/${projectName}?sslmode=disable`
|
|
168
|
+
stopPostgres = () => pgStop(pgOpts)
|
|
169
|
+
|
|
170
|
+
// Create project database if it doesn't exist (native only).
|
|
171
|
+
const psqlBin = join(pgBinDir, process.platform === "win32" ? "psql.exe" : "psql")
|
|
172
|
+
const createdbBin = join(pgBinDir, process.platform === "win32" ? "createdb.exe" : "createdb")
|
|
173
|
+
const pgConnArgs = ["-h", "127.0.0.1", "-p", String(pgPort), "-U", "postgres"]
|
|
174
|
+
const pgEnv = pgSpawnEnv(pgBinDir)
|
|
175
|
+
const createDbResult = spawnSync(
|
|
176
|
+
createdbBin,
|
|
177
|
+
[...pgConnArgs, projectName],
|
|
178
|
+
{ stdio: "pipe", encoding: "utf8", env: pgEnv },
|
|
179
|
+
)
|
|
180
|
+
if (createDbResult.status !== 0) {
|
|
181
|
+
const stderr = createDbResult.stderr ?? ""
|
|
182
|
+
if (!stderr.includes("already exists")) {
|
|
183
|
+
throw new Error(`Failed to create database "${projectName}": ${stderr}`)
|
|
184
|
+
}
|
|
185
|
+
} else {
|
|
186
|
+
console.log(`[supatype] Created database "${projectName}".`)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Create roles required by PostgREST and grant them to postgres so
|
|
190
|
+
// PostgREST can SET ROLE when processing requests.
|
|
191
|
+
// anon – unauthenticated requests (RLS enforced)
|
|
192
|
+
// authenticated – signed-in user requests (RLS enforced)
|
|
193
|
+
// service_role – developer/admin bypass (BYPASSRLS)
|
|
194
|
+
const rolesSql = `
|
|
195
|
+
CREATE SCHEMA IF NOT EXISTS auth;
|
|
196
|
+
DO $$ BEGIN
|
|
197
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'anon')
|
|
198
|
+
THEN CREATE ROLE anon NOLOGIN; END IF;
|
|
199
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'authenticated')
|
|
200
|
+
THEN CREATE ROLE authenticated NOLOGIN; END IF;
|
|
201
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'service_role')
|
|
202
|
+
THEN CREATE ROLE service_role NOLOGIN BYPASSRLS; END IF;
|
|
203
|
+
END $$;
|
|
204
|
+
GRANT anon, authenticated, service_role TO postgres;
|
|
205
|
+
GRANT USAGE ON SCHEMA public TO anon, authenticated, service_role;
|
|
206
|
+
-- Table-level privileges (RLS restricts rows; roles still need table access)
|
|
207
|
+
GRANT SELECT ON ALL TABLES IN SCHEMA public TO anon;
|
|
208
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO authenticated;
|
|
209
|
+
GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role;
|
|
210
|
+
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO authenticated, service_role;
|
|
211
|
+
-- Default privileges so tables created by the engine push inherit these grants
|
|
212
|
+
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO anon;
|
|
213
|
+
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO authenticated;
|
|
214
|
+
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO service_role;
|
|
215
|
+
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO authenticated, service_role;
|
|
216
|
+
`
|
|
217
|
+
spawnSync(psqlBin, [...pgConnArgs, "-d", projectName, "-c", rolesSql],
|
|
218
|
+
{ stdio: "pipe", encoding: "utf8", env: pgEnv })
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const LOCAL_JWT_SECRET = "super-secret-jwt-token-with-at-least-32-characters-long"
|
|
222
|
+
const authDbURL = dbURL.includes("?")
|
|
223
|
+
? `${dbURL}&search_path=auth`
|
|
224
|
+
: `${dbURL}?search_path=auth`
|
|
225
|
+
|
|
226
|
+
// ── 8. GoTrue migrations (auth.users before engine studio SQL) ─────────
|
|
227
|
+
console.log("[supatype] Running GoTrue migrations...")
|
|
228
|
+
const migrateEnv = gotrueMigrateEnv(serverPort, dbURL, LOCAL_JWT_SECRET)
|
|
229
|
+
runGotrueMigrations(serverBin, migrateEnv)
|
|
230
|
+
|
|
231
|
+
// ── 9. Engine: apply schema ───────────────────────────────────────────
|
|
232
|
+
const schemaPath = schemaPathFromProject(config, cwd)
|
|
233
|
+
const supatypeDir = join(cwd, ".supatype")
|
|
234
|
+
const manifestPath = join(supatypeDir, "manifest.json")
|
|
235
|
+
const adminConfigPath = join(supatypeDir, "admin-config.json")
|
|
236
|
+
mkdirSync(supatypeDir, { recursive: true })
|
|
237
|
+
|
|
238
|
+
const localStoragePath = config.storage?.provider !== "s3" ? join(stateRoot, "storage") : undefined
|
|
239
|
+
// Native Postgres builds don't include PostGIS — skip geo fields rather than failing.
|
|
240
|
+
const skipFieldKinds: ReadonlySet<string> = new Set(["geo", "vector"])
|
|
241
|
+
|
|
242
|
+
await runSchemaPush(cwd, engineBin, schemaPath, dbURL, manifestPath, adminConfigPath, localStoragePath, skipFieldKinds, config).catch(
|
|
243
|
+
(e: unknown) => console.error("[supatype] Initial schema push failed:", (e as Error).message),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
// ── 10. Spawn supatype-server ─────────────────────────────────────────
|
|
247
|
+
|
|
248
|
+
// Resolve edge functions config: only enable Deno if a functions dir exists.
|
|
249
|
+
const functionsDir = functionsPathCandidatesFromProject(config, cwd).find(dir => existsSync(dir))
|
|
250
|
+
const hasFunctionsDir = functionsDir !== undefined
|
|
251
|
+
/** Always set when a functions dir exists so Studio admin API can list functions; Deno runtime is separate. */
|
|
252
|
+
const denoFunctionsDir = hasFunctionsDir ? functionsDir : ""
|
|
253
|
+
const functionRoutes = hasFunctionsDir && functionsDir !== undefined
|
|
254
|
+
? discoverTsFunctionsInDir(functionsDir)
|
|
255
|
+
: []
|
|
256
|
+
const denoServeScriptAbs = hasFunctionsDir && functionsDir !== undefined
|
|
257
|
+
? (writeDevFunctionsRouter(cwd, functionsDir, functionRoutes) ?? "")
|
|
258
|
+
: ""
|
|
259
|
+
|
|
260
|
+
let denoBinPath: string | undefined
|
|
261
|
+
if (hasFunctionsDir) {
|
|
262
|
+
console.log(`[supatype] Edge functions enabled (${functionsDir})`)
|
|
263
|
+
try {
|
|
264
|
+
denoBinPath = await ensureBinary("deno", config)
|
|
265
|
+
const denoVersion = await (await import("../binary-cache.js")).resolveVersionFor("deno", config)
|
|
266
|
+
console.log(`[supatype] Deno runtime: ${denoBinPath} (v${denoVersion})`)
|
|
267
|
+
if (functionRoutes.length > 0) {
|
|
268
|
+
console.log(
|
|
269
|
+
`[supatype] Edge functions router: ${relative(cwd, denoServeScriptAbs) || ".supatype/functions-router.ts"} ` +
|
|
270
|
+
`(${functionRoutes.length} function(s): ${functionRoutes.map(fn => fn.name).join(", ")})`,
|
|
271
|
+
)
|
|
272
|
+
} else {
|
|
273
|
+
console.log("[supatype] Edge functions router not generated (no handler files discovered yet)")
|
|
274
|
+
}
|
|
275
|
+
} catch (err) {
|
|
276
|
+
console.warn(
|
|
277
|
+
`[supatype] ⚠ Found ${functionsDir} but could not provision Deno — edge functions will not run.\n` +
|
|
278
|
+
` ${(err as Error).message}\n` +
|
|
279
|
+
" (Functions still appear in Studio; invocations need Deno.)",
|
|
280
|
+
)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Matches GOTRUE_HOOK_SEND_EMAIL_SECRETS symmetric format (dev only). Override via .env.
|
|
285
|
+
const LOCAL_SEND_EMAIL_HOOK_SECRETS =
|
|
286
|
+
"v1,whsec_abcdefghijklmnopqrstuvwxyz01234567"
|
|
287
|
+
const now = Math.floor(Date.now() / 1000)
|
|
288
|
+
const jwtBase = { iss: "supatype", iat: now, exp: now + 315_360_000 }
|
|
289
|
+
const anonKey = signJwt({ ...jwtBase, role: "anon" }, LOCAL_JWT_SECRET)
|
|
290
|
+
const serviceRoleKey = signJwt({ ...jwtBase, role: "service_role" }, LOCAL_JWT_SECRET)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
const emailProvider = config.email?.provider ?? "console"
|
|
294
|
+
const gotrueMailerProvider =
|
|
295
|
+
emailProvider === "console"
|
|
296
|
+
? "console"
|
|
297
|
+
: emailProvider === "resend"
|
|
298
|
+
? "resend"
|
|
299
|
+
: emailProvider === "ses"
|
|
300
|
+
? "ses"
|
|
301
|
+
: "smtp"
|
|
302
|
+
|
|
303
|
+
const serverEnv: Record<string, string> = {
|
|
304
|
+
// supatype-server outer layer
|
|
305
|
+
SUPATYPE_MODE: config.server.mode ?? "dev",
|
|
306
|
+
SUPATYPE_MANIFEST_PATH: manifestPath,
|
|
307
|
+
SUPATYPE_ADMIN_CONFIG_PATH: adminConfigPath,
|
|
308
|
+
SUPATYPE_POSTGREST_URL: `http://127.0.0.1:${postgrestPort}`,
|
|
309
|
+
SUPATYPE_DENO_FUNCTIONS_DIR: denoFunctionsDir,
|
|
310
|
+
...(denoFunctionsDir !== "" ? { SUPATYPE_SHARED_ENV_FILE: resolve(denoFunctionsDir, ".env.local") } : {}),
|
|
311
|
+
...(denoBinPath !== undefined ? { SUPATYPE_DENO_PATH: denoBinPath } : {}),
|
|
312
|
+
...(denoServeScriptAbs !== ""
|
|
313
|
+
? { SUPATYPE_DENO_SERVE_SCRIPT: denoServeScriptAbs }
|
|
314
|
+
: {}),
|
|
315
|
+
SUPATYPE_URL: `http://localhost:${serverPort}`,
|
|
316
|
+
SUPATYPE_ANON_KEY: anonKey,
|
|
317
|
+
SUPATYPE_SERVICE_ROLE_KEY: serviceRoleKey,
|
|
318
|
+
PORT: serverPort,
|
|
319
|
+
SUPATYPE_APP_MODE: config.app.mode ?? "none",
|
|
320
|
+
...(config.app.mode === "static" && config.app.static_dir?.trim()
|
|
321
|
+
? { SUPATYPE_APP_STATIC_DIR: resolve(cwd, config.app.static_dir.trim()) }
|
|
322
|
+
: {}),
|
|
323
|
+
...(config.app.mode === "proxy" && config.app.upstream?.trim()
|
|
324
|
+
? { SUPATYPE_APP_UPSTREAM: config.app.upstream.trim() }
|
|
325
|
+
: {}),
|
|
326
|
+
...(config.app.vite_dev_url !== undefined && config.app.vite_dev_url.trim() !== ""
|
|
327
|
+
? { SUPATYPE_VITE_DEV_URL: config.app.vite_dev_url.trim() }
|
|
328
|
+
: {}),
|
|
329
|
+
// GoTrue required fields (sensible local-dev defaults)
|
|
330
|
+
GOTRUE_DB_DATABASE_URL: authDbURL,
|
|
331
|
+
DATABASE_URL: authDbURL,
|
|
332
|
+
SUPATYPE_SQL_DATABASE_URL: dbURL,
|
|
333
|
+
PGSSLMODE: "disable",
|
|
334
|
+
GOTRUE_DB_NAMESPACE: "auth",
|
|
335
|
+
GOTRUE_DB_DRIVER: "postgres",
|
|
336
|
+
GOTRUE_JWT_SECRET: LOCAL_JWT_SECRET,
|
|
337
|
+
GOTRUE_JWT_EXP: "3600",
|
|
338
|
+
GOTRUE_JWT_AUD: "authenticated",
|
|
339
|
+
GOTRUE_JWT_ADMIN_ROLES: "supatype_admin,service_role",
|
|
340
|
+
API_EXTERNAL_URL: `http://localhost:${serverPort}/auth/v1`,
|
|
341
|
+
GOTRUE_API_HOST: "localhost",
|
|
342
|
+
GOTRUE_SITE_URL: `http://localhost:${serverPort}`,
|
|
343
|
+
GOTRUE_MAILER_MAILER_PROVIDER: gotrueMailerProvider,
|
|
344
|
+
GOTRUE_MAILER_AUTOCONFIRM: "true",
|
|
345
|
+
GOTRUE_LOG_LEVEL: "info",
|
|
346
|
+
GOTRUE_DISABLE_SIGNUP: "false",
|
|
347
|
+
...(config.email?.resend_api_key !== undefined && config.email.resend_api_key !== ""
|
|
348
|
+
? { RESEND_API_KEY: config.email.resend_api_key }
|
|
349
|
+
: {}),
|
|
350
|
+
...(gotrueMailerProvider === "resend" &&
|
|
351
|
+
config.email?.resend_from !== undefined &&
|
|
352
|
+
config.email.resend_from.trim() !== ""
|
|
353
|
+
? { RESEND_FROM: config.email.resend_from.trim() }
|
|
354
|
+
: {}),
|
|
355
|
+
...(gotrueMailerProvider === "ses" &&
|
|
356
|
+
config.email?.ses_from !== undefined &&
|
|
357
|
+
config.email.ses_from.trim() !== ""
|
|
358
|
+
? { SES_FROM: config.email.ses_from.trim() }
|
|
359
|
+
: {}),
|
|
360
|
+
...(gotrueMailerProvider === "smtp" ? gotrueSMTPFromEmailConfig(config.email) : {}),
|
|
361
|
+
...(config.email?.send_email_hook === true
|
|
362
|
+
? {
|
|
363
|
+
GOTRUE_HOOK_SEND_EMAIL_ENABLED: "true",
|
|
364
|
+
GOTRUE_HOOK_SEND_EMAIL_URI:
|
|
365
|
+
config.email?.send_email_hook_uri !== undefined &&
|
|
366
|
+
config.email.send_email_hook_uri.trim() !== ""
|
|
367
|
+
? config.email.send_email_hook_uri.trim()
|
|
368
|
+
: `http://127.0.0.1:${serverPort}/internal/v0hooks/send-email`,
|
|
369
|
+
GOTRUE_HOOK_SEND_EMAIL_SECRETS:
|
|
370
|
+
config.email?.send_email_hook_secrets !== undefined &&
|
|
371
|
+
config.email.send_email_hook_secrets.trim() !== ""
|
|
372
|
+
? config.email.send_email_hook_secrets.trim()
|
|
373
|
+
: LOCAL_SEND_EMAIL_HOOK_SECRETS,
|
|
374
|
+
}
|
|
375
|
+
: {}),
|
|
376
|
+
...(config.storage?.provider !== "s3" ? localStorageEnv(stateRoot) : {}),
|
|
377
|
+
...loadDotEnv(cwd),
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const serverProc = new ProcessManager(serverBin, [], {
|
|
381
|
+
label: "server",
|
|
382
|
+
pidDir,
|
|
383
|
+
colour: "\x1b[32m",
|
|
384
|
+
env: serverEnv,
|
|
385
|
+
})
|
|
386
|
+
serverProc.start()
|
|
387
|
+
|
|
388
|
+
// ── 9b. PostgREST ────────────────────────────────────────────────────
|
|
389
|
+
let postgrestProc: ProcessManager | null = null
|
|
390
|
+
const postgrestBin = await resolvePostgrestBin(config.overrides?.postgrest)
|
|
391
|
+
if (postgrestBin) {
|
|
392
|
+
// Windows PostgREST builds are dynamically linked and require libpq/OpenSSL
|
|
393
|
+
// DLLs from a Postgres bin directory, even when the database runs in Docker.
|
|
394
|
+
let postgrestRuntimeBinDir = pgBinDir
|
|
395
|
+
if (process.platform === "win32" && postgrestRuntimeBinDir === null) {
|
|
396
|
+
try {
|
|
397
|
+
postgrestRuntimeBinDir = await resolvePgBinDir(config)
|
|
398
|
+
} catch (error) {
|
|
399
|
+
console.warn(
|
|
400
|
+
`[supatype] ⚠ Could not resolve Postgres runtime DLL directory for PostgREST: ${(error as Error).message}\n` +
|
|
401
|
+
" PostgREST may fail to start on Windows until Postgres binaries are available locally.",
|
|
402
|
+
)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const postgrestEnv: Record<string, string> = {
|
|
407
|
+
PGRST_DB_URI: dbURL,
|
|
408
|
+
PGRST_DB_SCHEMA: "public, supatype, graphql_public",
|
|
409
|
+
PGRST_DB_ANON_ROLE: "anon",
|
|
410
|
+
PGRST_SERVER_PORT: postgrestPort,
|
|
411
|
+
PGRST_SERVER_HOST: "127.0.0.1",
|
|
412
|
+
PGRST_JWT_SECRET: serverEnv["GOTRUE_JWT_SECRET"] ?? "",
|
|
413
|
+
PGRST_LOG_LEVEL: "warn",
|
|
414
|
+
// On Windows, PostgREST (MinGW/GHC binary) needs libpq.dll and
|
|
415
|
+
// OpenSSL DLLs. Prepend a Postgres bin dir which bundles these
|
|
416
|
+
// runtime dependencies.
|
|
417
|
+
...(process.platform === "win32" && postgrestRuntimeBinDir !== null
|
|
418
|
+
? { PATH: `${postgrestRuntimeBinDir};${process.env["PATH"] ?? ""}` }
|
|
419
|
+
: {}),
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const preflight = spawnSync(
|
|
423
|
+
postgrestBin,
|
|
424
|
+
["--help"],
|
|
425
|
+
{ env: { ...process.env, ...postgrestEnv }, stdio: "pipe", encoding: "utf8" },
|
|
426
|
+
)
|
|
427
|
+
if (preflight.status !== 0) {
|
|
428
|
+
const detail = (preflight.stderr || preflight.stdout || "").trim()
|
|
429
|
+
console.warn(
|
|
430
|
+
`[supatype] ⚠ PostgREST failed preflight (exit ${preflight.status}). ` +
|
|
431
|
+
"Skipping /rest/v1 startup to avoid crash loop.",
|
|
432
|
+
)
|
|
433
|
+
if (detail) {
|
|
434
|
+
console.warn(`[supatype] PostgREST preflight output:\n${detail}`)
|
|
435
|
+
}
|
|
436
|
+
} else {
|
|
437
|
+
postgrestProc = new ProcessManager(postgrestBin, [], {
|
|
438
|
+
label: "postgrest",
|
|
439
|
+
pidDir,
|
|
440
|
+
colour: "\x1b[36m",
|
|
441
|
+
env: postgrestEnv,
|
|
442
|
+
})
|
|
443
|
+
postgrestProc.start()
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ── 9d. Studio (optional) ─────────────────────────────────────────────
|
|
448
|
+
const studioPort = 3002
|
|
449
|
+
let studioProc: ProcessManager | null = null
|
|
450
|
+
|
|
451
|
+
const studioOverride = config.overrides?.studio
|
|
452
|
+
if (studioOverride) {
|
|
453
|
+
studioProc = startStudioViteDevServer({
|
|
454
|
+
cwd,
|
|
455
|
+
studioOverride,
|
|
456
|
+
pidDir,
|
|
457
|
+
serviceRoleKey,
|
|
458
|
+
proxyTarget: `http://localhost:${serverPort}`,
|
|
459
|
+
viteSupatypeUrl: `http://localhost:${studioPort}`,
|
|
460
|
+
})
|
|
461
|
+
studioProc?.start()
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const appProc = startProxyDevApp(cwd, config, pidDir)
|
|
465
|
+
|
|
466
|
+
// ── Print status ──────────────────────────────────────────────────────
|
|
467
|
+
console.log(`
|
|
468
|
+
[supatype] Services running:
|
|
469
|
+
Postgres ${dbURL}
|
|
470
|
+
supatype-server http://localhost:${serverPort}
|
|
471
|
+
REST API http://localhost:${serverPort}/rest/v1/
|
|
472
|
+
Auth http://localhost:${serverPort}/auth/v1/
|
|
473
|
+
Storage http://localhost:${serverPort}/storage/v1/
|
|
474
|
+
Realtime ws://localhost:${serverPort}/realtime/v1/${studioProc ? `\n Studio http://localhost:${studioPort}` : ""}
|
|
475
|
+
|
|
476
|
+
API keys (local dev only):
|
|
477
|
+
anon key ${anonKey}
|
|
478
|
+
service_role ${serviceRoleKey}
|
|
479
|
+
|
|
480
|
+
JWT secret: ${LOCAL_JWT_SECRET}
|
|
481
|
+
|
|
482
|
+
Press Ctrl+C to stop.
|
|
483
|
+
`)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
// ── Shutdown handler ──────────────────────────────────────────────────
|
|
487
|
+
registerDevShutdown(async () => {
|
|
488
|
+
console.log("[supatype] Shutting down...")
|
|
489
|
+
await Promise.all([
|
|
490
|
+
serverProc.stop(),
|
|
491
|
+
postgrestProc?.stop(),
|
|
492
|
+
studioProc?.stop(),
|
|
493
|
+
appProc?.stop(),
|
|
494
|
+
])
|
|
495
|
+
await stopPostgres()
|
|
496
|
+
})
|
|
497
|
+
|
|
498
|
+
// ── 10. Schema watch ──────────────────────────────────────────────────
|
|
499
|
+
if (opts.watch) {
|
|
500
|
+
const schemaDir = resolve(cwd, schemaPath, "..")
|
|
501
|
+
console.log(`[supatype] Watching ${schemaDir} for changes...`)
|
|
502
|
+
|
|
503
|
+
const { watch } = await import("node:fs")
|
|
504
|
+
// Debounce: Windows fs.watch fires multiple events per save.
|
|
505
|
+
// Wait 300 ms after the last event before pushing.
|
|
506
|
+
let debounceTimer: ReturnType<typeof setTimeout> | null = null
|
|
507
|
+
watch(schemaDir, { recursive: true }, (_eventType, filename) => {
|
|
508
|
+
if (!filename?.endsWith(".ts")) return
|
|
509
|
+
if (debounceTimer) clearTimeout(debounceTimer)
|
|
510
|
+
debounceTimer = setTimeout(() => {
|
|
511
|
+
debounceTimer = null
|
|
512
|
+
console.log(`\n[supatype] Change detected in ${filename}, checking schema...`)
|
|
513
|
+
runSchemaPush(cwd, engineBin, schemaPath, dbURL, manifestPath, adminConfigPath, localStoragePath, skipFieldKinds, config).catch((e: unknown) =>
|
|
514
|
+
console.error("[supatype] Schema push failed:", (e as Error).message),
|
|
515
|
+
)
|
|
516
|
+
}, 300)
|
|
517
|
+
})
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Block until killed.
|
|
521
|
+
await new Promise<never>(() => undefined)
|
|
522
|
+
})
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ---------------------------------------------------------------------------
|
|
526
|
+
// Schema push (engine subprocess)
|
|
527
|
+
// ---------------------------------------------------------------------------
|
|
528
|
+
|
|
529
|
+
// Last successfully-pushed AST JSON — used to skip no-op re-fires.
|
|
530
|
+
let _lastPushedAst: string | null = null
|
|
531
|
+
// AST that failed on its last attempt — always retried even if content is unchanged.
|
|
532
|
+
let _lastFailedAst: string | null = null
|
|
533
|
+
|
|
534
|
+
async function runSchemaPush(
|
|
535
|
+
cwd: string,
|
|
536
|
+
engineBin: string,
|
|
537
|
+
schemaPath: string,
|
|
538
|
+
dbURL: string,
|
|
539
|
+
manifestPath: string,
|
|
540
|
+
adminConfigPath?: string,
|
|
541
|
+
storagePath?: string,
|
|
542
|
+
skipFieldKinds?: ReadonlySet<string>,
|
|
543
|
+
config?: import("../project-config.js").SupatypeProjectConfig,
|
|
544
|
+
): Promise<void> {
|
|
545
|
+
// Build AST JSON from schema file.
|
|
546
|
+
const { loadSchemaAst } = await import("../config.js")
|
|
547
|
+
let ast = loadSchemaAst(schemaPath, cwd)
|
|
548
|
+
|
|
549
|
+
// Strip fields whose kind requires an unavailable Postgres extension.
|
|
550
|
+
if (skipFieldKinds && skipFieldKinds.size > 0) {
|
|
551
|
+
const { filtered, adapted } = adaptUnsupportedKinds(ast, skipFieldKinds)
|
|
552
|
+
ast = filtered
|
|
553
|
+
if (adapted.length > 0) {
|
|
554
|
+
console.warn(
|
|
555
|
+
`[supatype] ⚠ ${adapted.length} field(s) replaced with JSONB — required extensions not available:\n` +
|
|
556
|
+
adapted.map((s: string) => ` ${s}`).join("\n"),
|
|
557
|
+
)
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const astJson = JSON.stringify(ast)
|
|
562
|
+
|
|
563
|
+
// Skip only when the last push of this exact AST succeeded.
|
|
564
|
+
// If it previously failed we always retry so the user can trigger a re-run
|
|
565
|
+
// by simply saving the file again without needing to make a content change.
|
|
566
|
+
if (astJson === _lastPushedAst && astJson !== _lastFailedAst) {
|
|
567
|
+
return
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const astPath = join(cwd, ".supatype", "schema.ast.json")
|
|
571
|
+
writeFileSync(astPath, astJson)
|
|
572
|
+
|
|
573
|
+
// Push schema.
|
|
574
|
+
console.log("[supatype] Applying schema...")
|
|
575
|
+
const pushResult = spawnSync(
|
|
576
|
+
engineBin,
|
|
577
|
+
["push", "-i", astPath, "--database-url", dbURL, "--force", "--non-interactive"],
|
|
578
|
+
{ cwd, stdio: "inherit", encoding: "utf8" },
|
|
579
|
+
)
|
|
580
|
+
if (pushResult.status !== 0) {
|
|
581
|
+
_lastFailedAst = astJson
|
|
582
|
+
throw new Error(`Engine schema push failed (exit ${pushResult.status})`)
|
|
583
|
+
}
|
|
584
|
+
_lastPushedAst = astJson
|
|
585
|
+
_lastFailedAst = null
|
|
586
|
+
|
|
587
|
+
// Provision storage buckets declared in the schema.
|
|
588
|
+
if (storagePath) {
|
|
589
|
+
const parseResult = spawnSync(engineBin, ["parse", "-i", astPath], { cwd, stdio: "pipe", encoding: "utf8" })
|
|
590
|
+
if (parseResult.status === 0 && parseResult.stdout) {
|
|
591
|
+
try {
|
|
592
|
+
const resolvedAst = JSON.parse(parseResult.stdout) as {
|
|
593
|
+
storageBuckets?: Array<{
|
|
594
|
+
id: string
|
|
595
|
+
public: boolean
|
|
596
|
+
allowedMimeTypes?: string[]
|
|
597
|
+
fileSizeLimit?: number
|
|
598
|
+
accessMode?: string
|
|
599
|
+
s3BucketPolicy?: string | null
|
|
600
|
+
}>
|
|
601
|
+
}
|
|
602
|
+
if (resolvedAst.storageBuckets && resolvedAst.storageBuckets.length > 0) {
|
|
603
|
+
provisionStorageBuckets(resolvedAst.storageBuckets, storagePath)
|
|
604
|
+
}
|
|
605
|
+
} catch { /* ignore parse errors */ }
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// Generate manifest.
|
|
610
|
+
const genResult = spawnSync(
|
|
611
|
+
engineBin,
|
|
612
|
+
["generate", "-i", astPath, "-o", manifestPath],
|
|
613
|
+
{ cwd, stdio: "pipe", encoding: "utf8" },
|
|
614
|
+
)
|
|
615
|
+
if (genResult.status !== 0) {
|
|
616
|
+
console.warn("[supatype] Manifest generation failed — server routing may be stale.")
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Generate admin config (for Studio). Engine writes to stdout.
|
|
620
|
+
if (adminConfigPath) {
|
|
621
|
+
const adminResult = spawnSync(
|
|
622
|
+
engineBin,
|
|
623
|
+
["admin", "-i", astPath],
|
|
624
|
+
{ cwd, stdio: "pipe", encoding: "utf8" },
|
|
625
|
+
)
|
|
626
|
+
if (adminResult.status === 0 && adminResult.stdout) {
|
|
627
|
+
const { withAdminRoles } = await import("../studio-admin-roles.js")
|
|
628
|
+
let admin: unknown
|
|
629
|
+
try {
|
|
630
|
+
admin = JSON.parse(adminResult.stdout) as unknown
|
|
631
|
+
} catch {
|
|
632
|
+
admin = adminResult.stdout
|
|
633
|
+
}
|
|
634
|
+
restoreSystemRelationTargets(admin, ast)
|
|
635
|
+
const merged = config ? withAdminRoles(admin, config) : admin
|
|
636
|
+
writeFileSync(adminConfigPath, `${JSON.stringify(merged, null, 2)}\n`)
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
console.log("[supatype] Schema applied.")
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function provisionStorageBuckets(
|
|
644
|
+
declared: Array<{
|
|
645
|
+
id: string
|
|
646
|
+
public: boolean
|
|
647
|
+
allowedMimeTypes?: string[]
|
|
648
|
+
fileSizeLimit?: number
|
|
649
|
+
accessMode?: string
|
|
650
|
+
s3BucketPolicy?: string | null
|
|
651
|
+
}>,
|
|
652
|
+
storagePath: string,
|
|
653
|
+
): void {
|
|
654
|
+
const bucketsDir = join(storagePath, ".supatype")
|
|
655
|
+
const bucketsFile = join(bucketsDir, "buckets.json")
|
|
656
|
+
mkdirSync(bucketsDir, { recursive: true })
|
|
657
|
+
|
|
658
|
+
let existing: Array<Record<string, unknown>> = []
|
|
659
|
+
try {
|
|
660
|
+
existing = JSON.parse(readFileSync(bucketsFile, "utf8")) as Array<Record<string, unknown>>
|
|
661
|
+
} catch { /* file doesn't exist yet */ }
|
|
662
|
+
|
|
663
|
+
const existingIds = new Set(existing.map((b) => b["id"] as string))
|
|
664
|
+
let added = 0
|
|
665
|
+
|
|
666
|
+
for (const bucket of declared) {
|
|
667
|
+
if (existingIds.has(bucket.id)) continue
|
|
668
|
+
const now = new Date().toISOString()
|
|
669
|
+
existing.push({
|
|
670
|
+
id: bucket.id,
|
|
671
|
+
name: bucket.id,
|
|
672
|
+
public: bucket.public,
|
|
673
|
+
file_size_limit: bucket.fileSizeLimit ?? null,
|
|
674
|
+
allowed_mime_types: bucket.allowedMimeTypes ?? null,
|
|
675
|
+
access_mode:
|
|
676
|
+
bucket.accessMode ?? (bucket.public ? "public" : "private"),
|
|
677
|
+
s3_bucket_policy: bucket.s3BucketPolicy ?? null,
|
|
678
|
+
created_at: now,
|
|
679
|
+
updated_at: now,
|
|
680
|
+
})
|
|
681
|
+
mkdirSync(join(storagePath, bucket.id), { recursive: true })
|
|
682
|
+
added++
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
if (added > 0) {
|
|
686
|
+
writeFileSync(bucketsFile, JSON.stringify(existing, null, 2))
|
|
687
|
+
console.log(`[supatype] Storage: provisioned ${added} bucket(s).`)
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// ---------------------------------------------------------------------------
|
|
692
|
+
// Resolve Postgres bin dir
|
|
693
|
+
// ---------------------------------------------------------------------------
|
|
694
|
+
|
|
695
|
+
async function resolvePgBinDir(config: Awaited<ReturnType<typeof loadConfig>>): Promise<string> {
|
|
696
|
+
const override = config.overrides?.postgres_dir
|
|
697
|
+
if (override) {
|
|
698
|
+
// Normalize Git Bash (/c/Users/...) paths to Win32 form (C:\Users\...) on Windows.
|
|
699
|
+
const normalised = normalisePlatformPath(override)
|
|
700
|
+
const resolved = resolve(process.cwd(), normalised)
|
|
701
|
+
const binDir = join(resolved, "bin")
|
|
702
|
+
if (!existsSync(binDir)) {
|
|
703
|
+
throw new Error(`[overrides] postgres_dir does not contain a bin/ directory: ${resolved}`)
|
|
704
|
+
}
|
|
705
|
+
console.warn(`\u26a0 Using local Postgres build: ${resolved}`)
|
|
706
|
+
return binDir
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// Locate cached Postgres archive.
|
|
710
|
+
const { cachePath, currentPlatform, resolveVersionFor } = await import("../binary-cache.js")
|
|
711
|
+
const platform = currentPlatform()
|
|
712
|
+
const version = await resolveVersionFor("postgres", config)
|
|
713
|
+
|
|
714
|
+
const pgCacheDir = cachePath("postgres", version)
|
|
715
|
+
const extractedDir = join(pgCacheDir, `pg-${version}`)
|
|
716
|
+
|
|
717
|
+
const pgCtlName = platform.os === "windows" ? "pg_ctl.exe" : "pg_ctl"
|
|
718
|
+
if (!existsSync(join(extractedDir, "bin", pgCtlName))) {
|
|
719
|
+
// Try to extract the cached archive.
|
|
720
|
+
await extractPostgresArchive(pgCacheDir, version, platform, extractedDir)
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
return join(extractedDir, "bin")
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
async function extractPostgresArchive(
|
|
727
|
+
pgCacheDir: string,
|
|
728
|
+
version: string,
|
|
729
|
+
platform: { os: string; arch: string },
|
|
730
|
+
extractDir: string,
|
|
731
|
+
): Promise<void> {
|
|
732
|
+
const ext = platform.os === "windows" ? ".zip" : ".tar.gz"
|
|
733
|
+
const archiveName = `supatype-pg-${postgresArchiveTag(version)}-${platform.os}-${platform.arch}${ext}`
|
|
734
|
+
const archivePath = join(pgCacheDir, archiveName)
|
|
735
|
+
|
|
736
|
+
if (!existsSync(archivePath)) {
|
|
737
|
+
throw new Error(
|
|
738
|
+
`Postgres ${version} archive not found. Run: supatype update`,
|
|
739
|
+
)
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
mkdirSync(extractDir, { recursive: true })
|
|
743
|
+
|
|
744
|
+
// On Windows, Git Bash tar is typically first in PATH and chokes on drive-letter
|
|
745
|
+
// paths (C:\...). Use PowerShell's Expand-Archive instead, which handles Windows
|
|
746
|
+
// paths natively. On Linux/macOS, use tar as normal.
|
|
747
|
+
const result = platform.os === "windows"
|
|
748
|
+
? spawnSync(
|
|
749
|
+
"powershell.exe",
|
|
750
|
+
["-NoProfile", "-Command", `Expand-Archive -Path '${archivePath}' -DestinationPath '${extractDir}' -Force`],
|
|
751
|
+
{ stdio: "inherit" },
|
|
752
|
+
)
|
|
753
|
+
: spawnSync("tar", ["-xzf", archivePath, "-C", extractDir], { stdio: "inherit" })
|
|
754
|
+
|
|
755
|
+
if (result.status !== 0) {
|
|
756
|
+
throw new Error(`Failed to extract Postgres archive: ${archivePath}`)
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// ---------------------------------------------------------------------------
|
|
761
|
+
// PostgREST resolver — downloads from GitHub releases if not cached
|
|
762
|
+
// ---------------------------------------------------------------------------
|
|
763
|
+
|
|
764
|
+
const POSTGREST_DEFAULT_VERSION = "12.2.3"
|
|
765
|
+
const POSTGREST_GITHUB = "https://github.com/PostgREST/postgrest/releases/download"
|
|
766
|
+
|
|
767
|
+
async function resolvePostgrestBin(overridePath?: string): Promise<string | null> {
|
|
768
|
+
// Honour local override (same pattern as engine/server).
|
|
769
|
+
if (overridePath) {
|
|
770
|
+
let p = resolve(process.cwd(), normalisePlatformPath(overridePath))
|
|
771
|
+
if (process.platform === "win32" && !p.endsWith(".exe") && !existsSync(p)) {
|
|
772
|
+
const withExe = p + ".exe"
|
|
773
|
+
if (existsSync(withExe)) p = withExe
|
|
774
|
+
}
|
|
775
|
+
if (existsSync(p)) return p
|
|
776
|
+
console.warn(`[supatype] ⚠ PostgREST override not found at ${p}`)
|
|
777
|
+
return null
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const version = POSTGREST_DEFAULT_VERSION
|
|
781
|
+
const platform = currentPlatform()
|
|
782
|
+
const arch = platform.arch === "arm64" ? "aarch64" : "x86_64"
|
|
783
|
+
const binName = platform.os === "windows" ? "postgrest.exe" : "postgrest"
|
|
784
|
+
const cacheDir = cachePath("postgres", version).replace(/postgres/, "postgrest")
|
|
785
|
+
const binPath = join(cacheDir, binName)
|
|
786
|
+
const archiveName = platform.os === "windows"
|
|
787
|
+
? `postgrest-v${version}-windows-x64.zip`
|
|
788
|
+
: platform.os === "darwin"
|
|
789
|
+
? `postgrest-v${version}-macos-${arch}.tar.xz`
|
|
790
|
+
: `postgrest-v${version}-linux-static-${arch}.tar.xz`
|
|
791
|
+
const archivePath = join(cacheDir, archiveName)
|
|
792
|
+
|
|
793
|
+
if (existsSync(binPath)) {
|
|
794
|
+
// Backfill DLLs for older cached Windows installs where only postgrest.exe
|
|
795
|
+
// was copied from the release archive.
|
|
796
|
+
if (platform.os === "windows" && !hasLikelyWindowsRuntimeDlls(cacheDir) && existsSync(archivePath)) {
|
|
797
|
+
const repaired = repairWindowsPostgrestRuntime(cacheDir, archivePath, binPath)
|
|
798
|
+
if (!repaired) {
|
|
799
|
+
console.warn("[supatype] ⚠ PostgREST runtime DLL repair failed; REST API may be unavailable.")
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return binPath
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Download from GitHub releases.
|
|
806
|
+
const url = `${POSTGREST_GITHUB}/v${version}/${archiveName}`
|
|
807
|
+
|
|
808
|
+
console.log(`[supatype] Downloading PostgREST v${version}...`)
|
|
809
|
+
mkdirSync(cacheDir, { recursive: true })
|
|
810
|
+
|
|
811
|
+
let resp: Response
|
|
812
|
+
try {
|
|
813
|
+
resp = await fetch(url)
|
|
814
|
+
} catch (e) {
|
|
815
|
+
console.warn(
|
|
816
|
+
`[supatype] ⚠ Could not download PostgREST (${(e as Error).message}).\n` +
|
|
817
|
+
` REST API (/rest/v1/) will be unavailable until the download succeeds.\n` +
|
|
818
|
+
` Re-run 'supatype dev' once network access to github.com:443 is restored.`,
|
|
819
|
+
)
|
|
820
|
+
return null
|
|
821
|
+
}
|
|
822
|
+
if (!resp.ok) {
|
|
823
|
+
console.warn(`[supatype] ⚠ Could not download PostgREST: HTTP ${resp.status}. REST API will be unavailable.`)
|
|
824
|
+
return null
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const buf = Buffer.from(await resp.arrayBuffer())
|
|
828
|
+
writeFileSync(archivePath, buf)
|
|
829
|
+
|
|
830
|
+
// Extract. The Windows zip may nest postgrest.exe inside a subdirectory, so
|
|
831
|
+
// after Expand-Archive we copy postgrest.exe and sibling DLLs to cacheDir.
|
|
832
|
+
if (platform.os === "windows") {
|
|
833
|
+
const r = spawnSync(
|
|
834
|
+
"powershell.exe",
|
|
835
|
+
[
|
|
836
|
+
"-NoProfile", "-Command",
|
|
837
|
+
`Expand-Archive -Path '${archivePath}' -DestinationPath '${cacheDir}' -Force; ` +
|
|
838
|
+
`$exe = Get-ChildItem -Path '${cacheDir}' -Recurse -Filter 'postgrest.exe' | Select-Object -First 1; ` +
|
|
839
|
+
`if ($exe) { ` +
|
|
840
|
+
` Copy-Item -Path $exe.FullName -Destination '${binPath}' -Force; ` +
|
|
841
|
+
` Get-ChildItem -Path $exe.Directory.FullName -Filter '*.dll' | ` +
|
|
842
|
+
` ForEach-Object { Copy-Item -Path $_.FullName -Destination '${cacheDir}' -Force }; ` +
|
|
843
|
+
`}`,
|
|
844
|
+
],
|
|
845
|
+
{ stdio: "pipe", encoding: "utf8" },
|
|
846
|
+
)
|
|
847
|
+
if (r.status !== 0) {
|
|
848
|
+
console.warn(`[supatype] ⚠ PostgREST extraction failed: ${r.stderr?.trim() ?? "unknown error"}. REST API will be unavailable.`)
|
|
849
|
+
return null
|
|
850
|
+
}
|
|
851
|
+
} else {
|
|
852
|
+
const r = spawnSync("tar", ["-xJf", archivePath, "-C", cacheDir], { stdio: "pipe" })
|
|
853
|
+
if (r.status !== 0) {
|
|
854
|
+
console.warn("[supatype] ⚠ PostgREST extraction failed. REST API will be unavailable.")
|
|
855
|
+
return null
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
if (!existsSync(binPath)) {
|
|
860
|
+
console.warn("[supatype] ⚠ PostgREST binary not found after extraction. REST API will be unavailable.")
|
|
861
|
+
return null
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
if (platform.os !== "windows") {
|
|
865
|
+
const { chmod } = await import("node:fs/promises")
|
|
866
|
+
await chmod(binPath, 0o755)
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
console.log(`[supatype] PostgREST v${version} ready.`)
|
|
870
|
+
return binPath
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function hasLikelyWindowsRuntimeDlls(dir: string): boolean {
|
|
874
|
+
if (process.platform !== "win32") return true
|
|
875
|
+
return (
|
|
876
|
+
existsSync(join(dir, "libpq.dll")) ||
|
|
877
|
+
existsSync(join(dir, "libpq-5.dll")) ||
|
|
878
|
+
existsSync(join(dir, "libssl-3-x64.dll"))
|
|
879
|
+
)
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function repairWindowsPostgrestRuntime(cacheDir: string, archivePath: string, binPath: string): boolean {
|
|
883
|
+
const r = spawnSync(
|
|
884
|
+
"powershell.exe",
|
|
885
|
+
[
|
|
886
|
+
"-NoProfile",
|
|
887
|
+
"-Command",
|
|
888
|
+
`Expand-Archive -Path '${archivePath}' -DestinationPath '${cacheDir}' -Force; ` +
|
|
889
|
+
`$exe = Get-ChildItem -Path '${cacheDir}' -Recurse -Filter 'postgrest.exe' | Select-Object -First 1; ` +
|
|
890
|
+
`if ($exe) { ` +
|
|
891
|
+
` Copy-Item -Path $exe.FullName -Destination '${binPath}' -Force; ` +
|
|
892
|
+
` Get-ChildItem -Path $exe.Directory.FullName -Filter '*.dll' | ` +
|
|
893
|
+
` ForEach-Object { Copy-Item -Path $_.FullName -Destination '${cacheDir}' -Force }; ` +
|
|
894
|
+
`}`,
|
|
895
|
+
],
|
|
896
|
+
{ stdio: "pipe", encoding: "utf8" },
|
|
897
|
+
)
|
|
898
|
+
return r.status === 0
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// ---------------------------------------------------------------------------
|
|
902
|
+
// Local-dev JWT generator (no external dep — pure crypto)
|
|
903
|
+
// ---------------------------------------------------------------------------
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
// ---------------------------------------------------------------------------
|
|
907
|
+
// AST adaptation — replace extension-dependent fields with JSONB fallbacks
|
|
908
|
+
// ---------------------------------------------------------------------------
|
|
909
|
+
|
|
910
|
+
interface AstField { kind: string; required?: boolean; [k: string]: unknown }
|
|
911
|
+
interface AstModel { name: string; fields?: Record<string, AstField> }
|
|
912
|
+
interface AstSchema { models?: AstModel[] }
|
|
913
|
+
|
|
914
|
+
// Field kinds that require Postgres extensions not available in all builds.
|
|
915
|
+
// Maps kind → { extension name, JSONB fallback AST }
|
|
916
|
+
const EXTENSION_FIELDS: Record<string, { ext: string; fallback: AstField }> = {
|
|
917
|
+
geo: { ext: "PostGIS", fallback: { kind: "json", pgType: "JSONB" } },
|
|
918
|
+
vector: { ext: "pgvector", fallback: { kind: "json", pgType: "JSONB" } },
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function adaptUnsupportedKinds(
|
|
922
|
+
ast: unknown,
|
|
923
|
+
skipKinds: ReadonlySet<string>,
|
|
924
|
+
): { filtered: unknown; adapted: string[] } {
|
|
925
|
+
const adapted: string[] = []
|
|
926
|
+
if (!ast || typeof ast !== "object") return { filtered: ast, adapted }
|
|
927
|
+
const schema = ast as AstSchema
|
|
928
|
+
if (!Array.isArray(schema.models)) return { filtered: ast, adapted }
|
|
929
|
+
|
|
930
|
+
const models = schema.models.map((model) => {
|
|
931
|
+
const fields: Record<string, AstField> = {}
|
|
932
|
+
for (const [name, field] of Object.entries(model.fields ?? {})) {
|
|
933
|
+
const info = skipKinds.has(field.kind) ? EXTENSION_FIELDS[field.kind] : undefined
|
|
934
|
+
if (info) {
|
|
935
|
+
fields[name] = { ...info.fallback, required: field.required ?? false }
|
|
936
|
+
adapted.push(`${model.name}.${name} (${info.ext} → JSONB)`)
|
|
937
|
+
} else {
|
|
938
|
+
fields[name] = field
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
return { ...model, fields }
|
|
942
|
+
})
|
|
943
|
+
|
|
944
|
+
return { filtered: { ...schema, models }, adapted }
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// ---------------------------------------------------------------------------
|
|
948
|
+
// .env loader
|
|
949
|
+
// ---------------------------------------------------------------------------
|
|
950
|
+
|
|
951
|
+
/** Minimal GoTrue env for `migrate` (matches required fields in serverEnv below). */
|
|
952
|
+
function gotrueMigrateEnv(
|
|
953
|
+
serverPort: string,
|
|
954
|
+
sqlDbURL: string,
|
|
955
|
+
jwtSecret: string,
|
|
956
|
+
): Record<string, string> {
|
|
957
|
+
const base = `http://localhost:${serverPort}`
|
|
958
|
+
return {
|
|
959
|
+
// envconfig: gotrue + DB.DATABASE_URL → GOTRUE_DB_DATABASE_URL
|
|
960
|
+
GOTRUE_DB_DATABASE_URL: sqlDbURL,
|
|
961
|
+
DATABASE_URL: sqlDbURL,
|
|
962
|
+
GOTRUE_DB_DRIVER: "postgres",
|
|
963
|
+
GOTRUE_DB_NAMESPACE: "auth",
|
|
964
|
+
PGSSLMODE: "disable",
|
|
965
|
+
GOTRUE_JWT_SECRET: jwtSecret,
|
|
966
|
+
API_EXTERNAL_URL: `${base}/auth/v1`,
|
|
967
|
+
GOTRUE_API_HOST: "localhost",
|
|
968
|
+
GOTRUE_SITE_URL: base,
|
|
969
|
+
GOTRUE_MAILER_AUTOCONFIRM: "true",
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** Apply GoTrue DDL (auth.users, etc.) before engine push references auth schema. */
|
|
974
|
+
function runGotrueMigrations(
|
|
975
|
+
serverBin: string,
|
|
976
|
+
migrateEnv: Record<string, string>,
|
|
977
|
+
): void {
|
|
978
|
+
const result = spawnSync(serverBin, ["migrate"], {
|
|
979
|
+
stdio: "pipe",
|
|
980
|
+
encoding: "utf8",
|
|
981
|
+
env: {
|
|
982
|
+
...process.env,
|
|
983
|
+
...migrateEnv,
|
|
984
|
+
},
|
|
985
|
+
})
|
|
986
|
+
if (result.status !== 0) {
|
|
987
|
+
const detail = (result.stderr ?? result.stdout ?? "").trim()
|
|
988
|
+
throw new Error(
|
|
989
|
+
`GoTrue migrations failed (exit ${result.status ?? "unknown"})` +
|
|
990
|
+
(detail ? `:\n${detail}` : ""),
|
|
991
|
+
)
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function loadDotEnv(cwd: string): Record<string, string> {
|
|
996
|
+
const candidates = [resolve(cwd, ".env"), resolve(cwd, ".env.local")]
|
|
997
|
+
const vars: Record<string, string> = {}
|
|
998
|
+
for (const envPath of candidates) {
|
|
999
|
+
if (!existsSync(envPath)) continue
|
|
1000
|
+
for (const line of readFileSync(envPath, "utf8").split("\n")) {
|
|
1001
|
+
const trimmed = line.trim()
|
|
1002
|
+
if (!trimmed || trimmed.startsWith("#")) continue
|
|
1003
|
+
const eq = trimmed.indexOf("=")
|
|
1004
|
+
if (eq === -1) continue
|
|
1005
|
+
vars[trimmed.slice(0, eq)] = trimmed.slice(eq + 1)
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
return vars
|
|
1009
|
+
}
|