@supatype/cli 0.3.4 → 0.3.6

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 (119) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +168 -158
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +36 -0
  5. package/dist/adopt-walkthrough.d.ts +40 -0
  6. package/dist/adopt-walkthrough.d.ts.map +1 -0
  7. package/dist/adopt-walkthrough.js +113 -0
  8. package/dist/adopt-walkthrough.js.map +1 -0
  9. package/dist/cli-version-embedded.js +1 -1
  10. package/dist/commands/admin.d.ts.map +1 -1
  11. package/dist/commands/admin.js +7 -16
  12. package/dist/commands/admin.js.map +1 -1
  13. package/dist/commands/adopt.d.ts.map +1 -1
  14. package/dist/commands/adopt.js +5 -6
  15. package/dist/commands/adopt.js.map +1 -1
  16. package/dist/commands/db.js +3 -3
  17. package/dist/commands/db.js.map +1 -1
  18. package/dist/commands/deploy.d.ts.map +1 -1
  19. package/dist/commands/deploy.js +7 -4
  20. package/dist/commands/deploy.js.map +1 -1
  21. package/dist/commands/dev.d.ts.map +1 -1
  22. package/dist/commands/dev.js +20 -5
  23. package/dist/commands/dev.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +5 -7
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/init.js +1 -1
  28. package/dist/commands/init.js.map +1 -1
  29. package/dist/commands/migrate.d.ts.map +1 -1
  30. package/dist/commands/migrate.js +6 -3
  31. package/dist/commands/migrate.js.map +1 -1
  32. package/dist/commands/push.d.ts.map +1 -1
  33. package/dist/commands/push.js +10 -6
  34. package/dist/commands/push.js.map +1 -1
  35. package/dist/commands/seed.js +2 -2
  36. package/dist/commands/seed.js.map +1 -1
  37. package/dist/dev-compose.d.ts +42 -0
  38. package/dist/dev-compose.d.ts.map +1 -1
  39. package/dist/dev-compose.js +116 -71
  40. package/dist/dev-compose.js.map +1 -1
  41. package/dist/dev-db-reset.d.ts +19 -0
  42. package/dist/dev-db-reset.d.ts.map +1 -0
  43. package/dist/dev-db-reset.js +75 -0
  44. package/dist/dev-db-reset.js.map +1 -0
  45. package/dist/dev-initial-push.d.ts +37 -0
  46. package/dist/dev-initial-push.d.ts.map +1 -0
  47. package/dist/dev-initial-push.js +91 -0
  48. package/dist/dev-initial-push.js.map +1 -0
  49. package/dist/dev-ports.d.ts.map +1 -1
  50. package/dist/dev-ports.js +1 -1
  51. package/dist/dev-ports.js.map +1 -1
  52. package/dist/diff-output.d.ts +2 -2
  53. package/dist/diff-output.d.ts.map +1 -1
  54. package/dist/diff-output.js +1 -1
  55. package/dist/diff-output.js.map +1 -1
  56. package/dist/engine-client.d.ts +5 -1
  57. package/dist/engine-client.d.ts.map +1 -1
  58. package/dist/engine-client.js +8 -6
  59. package/dist/engine-client.js.map +1 -1
  60. package/dist/engine-push-output.d.ts +10 -0
  61. package/dist/engine-push-output.d.ts.map +1 -1
  62. package/dist/engine-push-output.js +12 -0
  63. package/dist/engine-push-output.js.map +1 -1
  64. package/dist/{seed-connection.d.ts → host-database.d.ts} +20 -10
  65. package/dist/host-database.d.ts.map +1 -0
  66. package/dist/{seed-connection.js → host-database.js} +40 -14
  67. package/dist/host-database.js.map +1 -0
  68. package/dist/resolve-target.d.ts +2 -2
  69. package/dist/resolve-target.d.ts.map +1 -1
  70. package/dist/resolve-target.js +15 -11
  71. package/dist/resolve-target.js.map +1 -1
  72. package/dist/retired-no-cache.d.ts +18 -0
  73. package/dist/retired-no-cache.d.ts.map +1 -0
  74. package/dist/retired-no-cache.js +21 -0
  75. package/dist/retired-no-cache.js.map +1 -0
  76. package/dist/self-host-compose.d.ts +6 -0
  77. package/dist/self-host-compose.d.ts.map +1 -1
  78. package/dist/self-host-compose.js +9 -3
  79. package/dist/self-host-compose.js.map +1 -1
  80. package/dist/type-extractor.d.ts.map +1 -1
  81. package/dist/type-extractor.js +31 -25
  82. package/dist/type-extractor.js.map +1 -1
  83. package/package.json +2 -2
  84. package/src/adopt-walkthrough.ts +142 -0
  85. package/src/cli-version-embedded.ts +1 -1
  86. package/src/commands/admin.ts +7 -20
  87. package/src/commands/adopt.ts +5 -6
  88. package/src/commands/db.ts +3 -3
  89. package/src/commands/deploy.ts +7 -4
  90. package/src/commands/dev.ts +22 -6
  91. package/src/commands/doctor.ts +5 -7
  92. package/src/commands/init.ts +1 -1
  93. package/src/commands/migrate.ts +7 -4
  94. package/src/commands/push.ts +28 -10
  95. package/src/commands/seed.ts +2 -2
  96. package/src/dev-compose.ts +166 -77
  97. package/src/dev-db-reset.ts +95 -0
  98. package/src/dev-initial-push.ts +134 -0
  99. package/src/dev-ports.ts +1 -1
  100. package/src/diff-output.ts +2 -2
  101. package/src/engine-client.ts +5 -4
  102. package/src/engine-push-output.ts +19 -0
  103. package/src/{seed-connection.ts → host-database.ts} +42 -12
  104. package/src/resolve-target.ts +20 -14
  105. package/src/retired-no-cache.ts +27 -0
  106. package/src/self-host-compose.ts +10 -3
  107. package/src/type-extractor.ts +39 -42
  108. package/tests/adopt-result.test.ts +27 -0
  109. package/tests/adopt-walkthrough.test.ts +129 -0
  110. package/tests/dev-db-reset.test.ts +162 -0
  111. package/tests/dev-initial-push.test.ts +142 -0
  112. package/tests/engine-push-output.test.ts +30 -1
  113. package/tests/host-connection-targets.test.ts +84 -0
  114. package/tests/{seed-connection.test.ts → host-database.test.ts} +33 -15
  115. package/tests/retired-no-cache.test.ts +46 -0
  116. package/tests/type-extractor.test.ts +80 -0
  117. package/tsconfig.tsbuildinfo +1 -1
  118. package/dist/seed-connection.d.ts.map +0 -1
  119. package/dist/seed-connection.js.map +0 -1
@@ -2,11 +2,30 @@
2
2
  * Parse and format schema-engine push output (compose subprocess or HTTP).
3
3
  */
4
4
 
5
+ import { printDiffWarnings } from "./diff-output.js"
6
+
7
+ /**
8
+ * Print what a push warned about, less anything the diff before it already showed.
9
+ *
10
+ * Every caller of `/push` reports through here. The warnings used to reach only `supatype diff`, so
11
+ * a push said nothing about a bucket operation it had just made unreachable, and the ones found
12
+ * after applying were not shown anywhere.
13
+ */
14
+ export function printPushWarnings(
15
+ result: Pick<EnginePushResult, "warnings">,
16
+ alreadyShown: readonly string[] = [],
17
+ ): void {
18
+ const shown = new Set(alreadyShown)
19
+ printDiffWarnings({ warnings: (result.warnings ?? []).filter((w) => !shown.has(w)) })
20
+ }
21
+
5
22
  export interface EnginePushResult {
6
23
  status?: string
7
24
  operations?: number
8
25
  admin_refreshed?: boolean
9
26
  message?: string
27
+ /** The schema's warnings (a bucket rule left out, say), then any found once applied. */
28
+ warnings?: string[]
10
29
  }
11
30
 
12
31
  /** Extract the engine JSON object from mixed docker compose stdout/stderr. */
@@ -1,26 +1,56 @@
1
1
  /**
2
- * Which database a seed run targets, and how that was decided.
2
+ * Which database a command run on the host connects to, and how that was decided.
3
3
  *
4
- * Its own file so the failure is testable without spawning anything. The failure is the
5
- * point: the old seed template carried a hardcoded fallback DSN, so a project with no
6
- * `.env` did not fail, it silently tried `localhost:5432` with a guessed password and
7
- * reported a connection error that named none of the things it had looked at. Someone
8
- * reading that has no way to tell "I have not set DATABASE_URL" from "the stack is not
9
- * running".
4
+ * One resolver for every host-side command: seed, adopt, introspect, migrate, doctor, pull, and
5
+ * any target resolved in direct mode. They used to find the database three different ways, and
6
+ * the one most of them used took `.supatype/environment.json`'s URL, which describes the docker
7
+ * `db` *container*, so `supatype adopt` on a docker project failed looking up the host `db`
8
+ * (supatype#85). Another read `process.env` and never the project's `.env`, where `supatype dev`
9
+ * writes the host-published URL. Seed's order was the one that worked, so it is this one.
10
10
  *
11
- * So every source is recorded whether it was found or not, and the error prints the lot.
11
+ * Its own file so the failure is testable without spawning anything. The failure is the point: a
12
+ * hardcoded fallback DSN meant a project with no `.env` silently tried `localhost:5432` with a
13
+ * guessed password and reported a connection error that named none of the things it had looked
14
+ * at. So every source is recorded whether it was found or not, and the error prints the lot.
12
15
  */
13
16
 
14
17
  import { existsSync } from "node:fs"
15
18
  import { join } from "node:path"
16
- import { readEnvFile } from "./env-file.js"
19
+ import { readEnvFile, readEnvValue } from "./env-file.js"
20
+ import { devPostgresPassword } from "./local-secrets.js"
17
21
  import {
18
22
  externalDatabaseUrl,
19
23
  localDSN,
20
24
  projectRootFromConfig,
25
+ resolveRuntimeProvider,
21
26
  type SupatypeProjectConfig,
22
27
  } from "./project-config.js"
23
28
 
29
+ /** Where `supatype dev` publishes a docker project's Postgres when `.env` does not say. */
30
+ export const COMPOSE_DEV_DB_PORT = 54329
31
+
32
+ /**
33
+ * A docker project's own Postgres, as reached from the host: the port `supatype dev` publishes it
34
+ * on, with the credentials and database the stack was created with, all read from `.env`.
35
+ */
36
+ export function hostComposeDbUrl(cwd: string): string {
37
+ const port = readEnvValue(cwd, "SUPATYPE_DEV_DB_PORT", String(COMPOSE_DEV_DB_PORT))
38
+ const user = readEnvValue(cwd, "POSTGRES_USER", "supatype_admin")
39
+ const db = readEnvValue(cwd, "POSTGRES_DB", "supatype")
40
+ return `postgresql://${user}:${devPostgresPassword(cwd)}@127.0.0.1:${port}/${db}?sslmode=disable`
41
+ }
42
+
43
+ /**
44
+ * The database Supatype runs for this project, when nothing names one.
45
+ *
46
+ * For docker, the published compose database. It used to be `localDSN` for every provider,
47
+ * `postgres:postgres@127.0.0.1:5432/<project name>`, which is the native layout: a docker
48
+ * project with no `.env` got a user, database and port that do not exist.
49
+ */
50
+ function derivedDsn(root: string, config: SupatypeProjectConfig): string {
51
+ return resolveRuntimeProvider(config) === "docker" ? hostComposeDbUrl(root) : localDSN(config)
52
+ }
53
+
24
54
  /** One place a connection string could have come from. */
25
55
  export interface DsnSource {
26
56
  /** How it would be described to the person running the command. */
@@ -42,7 +72,7 @@ export interface ResolvedDsn {
42
72
  export class DsnNotFound extends Error {
43
73
  constructor(readonly tried: readonly DsnSource[]) {
44
74
  super(
45
- `No database connection string for this seed run.\n${tried
75
+ `No database connection string to connect with.\n${tried
46
76
  .map((source) => ` ${source.found ? "found" : "not set"} ${source.name}: ${source.detail}`)
47
77
  .join("\n")}`,
48
78
  )
@@ -69,7 +99,7 @@ export interface ResolveOptions {
69
99
  * `.env` is loaded first but ranks below a real environment variable, which is how every
70
100
  * other dotenv reader behaves and how Compose resolves the same names.
71
101
  */
72
- export function resolveSeedDsn(
102
+ export function resolveHostDatabaseUrl(
73
103
  cwd: string,
74
104
  config: SupatypeProjectConfig,
75
105
  options: ResolveOptions = {},
@@ -122,7 +152,7 @@ export function resolveSeedDsn(
122
152
  if (fileValue !== undefined) return { dsn: fileValue, source: fileLabel, tried }
123
153
 
124
154
  if (options.allowDerived === true) {
125
- const derived = localDSN(config)
155
+ const derived = derivedDsn(root, config)
126
156
  tried.push({ name: "the project's own local database", detail: redact(derived), found: true })
127
157
  return { dsn: derived, source: "the project's own local database", tried }
128
158
  }
@@ -4,12 +4,13 @@ import { loadConfig } from "./config.js"
4
4
  import type { DiffResult } from "./engine-client.js"
5
5
  import { ensureEngine, engineRequest } from "./engine-client.js"
6
6
  import type { SchemaSourcesPayload } from "./schema-sources.js"
7
+ import { resolveHostDatabaseUrl } from "./host-database.js"
7
8
  import {
8
- connectionString,
9
9
  pgSchema,
10
10
  resolveRuntimeProvider,
11
11
  schemaPathFromProject,
12
12
  serverBaseUrl,
13
+ type SupatypeProjectConfig,
13
14
  } from "./project-config.js"
14
15
  import {
15
16
  getEnvironmentTarget,
@@ -86,6 +87,17 @@ function resolveBranchDefaults(cwd: string, configEnvDefault?: string): string |
86
87
  }
87
88
  }
88
89
 
90
+ /**
91
+ * The project's database as a host process reaches it, for a target that runs the engine here.
92
+ *
93
+ * Never `.supatype/environment.json`'s URL: that one describes the docker `db` container, right
94
+ * for a container and unresolvable from the host, which is how `supatype adopt` on a docker
95
+ * project failed (supatype#85).
96
+ */
97
+ function hostDatabaseUrl(cwd: string, config: SupatypeProjectConfig, connection: string | undefined): string {
98
+ return resolveHostDatabaseUrl(cwd, config, { connection, allowDerived: true }).dsn
99
+ }
100
+
89
101
  export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): DeployTarget {
90
102
  const config = loadConfig(cwd)
91
103
  const projectRef = config.project?.name ?? config.project?.ref ?? "project"
@@ -104,7 +116,6 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
104
116
  }
105
117
 
106
118
  if (flags.direct || flags.local) {
107
- const localEnv = loadLocalEnvironment(cwd)
108
119
  return {
109
120
  mode: "direct",
110
121
  environment: "local",
@@ -112,10 +123,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
112
123
  apiBaseUrl: (serverBaseUrl(config) ?? "").replace(/\/$/, ""),
113
124
  apiPrefix: "/platform/v1",
114
125
  link: null,
115
- databaseUrl:
116
- flags.connection ??
117
- localEnv?.databaseUrl ??
118
- connectionString(config),
126
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
119
127
  }
120
128
  }
121
129
 
@@ -132,7 +140,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
132
140
  apiPrefix: "/platform/v1",
133
141
  token: resolveLocalToken(cwd),
134
142
  link: null,
135
- databaseUrl: localEnv.databaseUrl,
143
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
136
144
  }
137
145
  }
138
146
  return {
@@ -142,7 +150,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
142
150
  apiBaseUrl: (serverBaseUrl(config) ?? "").replace(/\/$/, ""),
143
151
  apiPrefix: "/platform/v1",
144
152
  link: null,
145
- databaseUrl: flags.connection ?? connectionString(config),
153
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
146
154
  }
147
155
  }
148
156
 
@@ -269,6 +277,8 @@ export async function targetSchemaPush(
269
277
  message?: string
270
278
  status?: string
271
279
  name?: string
280
+ /** The schema's warnings, then any found once applied. See `printPushWarnings`. */
281
+ warnings?: string[]
272
282
  /**
273
283
  * What the control plane made of this schema's cache declaration. Absent from an engine push and
274
284
  * from a control plane too old to send it, which is why every reader of it has to treat absence
@@ -381,7 +391,7 @@ export async function targetListMigrations(
381
391
  export async function targetSchemaDoctor(
382
392
  target: DeployTarget,
383
393
  ast: unknown,
384
- opts?: { noCache?: boolean | undefined; schema?: string },
394
+ opts?: { schema?: string },
385
395
  ): Promise<unknown> {
386
396
  if (target.mode === "direct" || (target.mode === "local" && !target.token)) {
387
397
  await ensureEngine()
@@ -389,7 +399,6 @@ export async function targetSchemaDoctor(
389
399
  ast,
390
400
  database_url: target.databaseUrl!,
391
401
  schema: opts?.schema ?? "public",
392
- no_cache: opts?.noCache ?? false,
393
402
  })
394
403
  }
395
404
 
@@ -398,7 +407,6 @@ export async function targetSchemaDoctor(
398
407
  target.apiPrefix,
399
408
  apiFetchOpts(target, "POST", projectPath(target, "/schema/doctor"), {
400
409
  ast,
401
- no_cache: opts?.noCache ?? false,
402
410
  schema: opts?.schema ?? "public",
403
411
  }),
404
412
  )
@@ -428,7 +436,7 @@ export async function targetSchemaIntrospect(
428
436
  export async function targetSchemaAdopt(
429
437
  target: DeployTarget,
430
438
  ast: unknown,
431
- opts?: { names?: string[]; schema?: string; yes?: boolean; noCache?: boolean },
439
+ opts?: { names?: string[]; schema?: string; yes?: boolean },
432
440
  ): Promise<unknown> {
433
441
  if (target.mode === "direct" || (target.mode === "local" && !target.token)) {
434
442
  await ensureEngine()
@@ -438,7 +446,6 @@ export async function targetSchemaAdopt(
438
446
  schema: opts?.schema ?? "public",
439
447
  names: opts?.names,
440
448
  yes: opts?.yes ?? false,
441
- no_cache: opts?.noCache ?? false,
442
449
  })
443
450
  }
444
451
 
@@ -449,7 +456,6 @@ export async function targetSchemaAdopt(
449
456
  ast,
450
457
  schema: opts?.schema ?? "public",
451
458
  yes: opts?.yes ?? false,
452
- no_cache: opts?.noCache ?? false,
453
459
  ...(opts?.names !== undefined ? { names: opts.names } : {}),
454
460
  }),
455
461
  )
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `--no-cache` on `adopt` and `doctor`, which no longer read a cache at all.
3
+ *
4
+ * The engine diffed `adopt` against the snapshot the last push wrote, so a table changed outside
5
+ * Supatype since was invisible to it (supatype#86). Both commands read the database live now, so
6
+ * the flag has nothing left to bypass. It never worked from the CLI either: Commander stores
7
+ * `--no-cache` as `cache: false`, the commands read `noCache`, and the flag was always ignored.
8
+ *
9
+ * Kept, hidden, for one release so a script that passes it keeps working, and says so.
10
+ */
11
+ import { Option, type Command } from "commander"
12
+ import { warn } from "./ui/messages.js"
13
+
14
+ export function addRetiredNoCacheOption(command: Command): Command {
15
+ return command.addOption(new Option("--no-cache", "No longer needed; does nothing").hideHelp())
16
+ }
17
+
18
+ /** Commander's spelling of a passed `--no-cache`. */
19
+ export interface RetiredNoCacheOpts {
20
+ cache?: boolean
21
+ }
22
+
23
+ export function warnIfRetiredNoCache(opts: RetiredNoCacheOpts): void {
24
+ if (opts.cache === false) {
25
+ warn("--no-cache is no longer needed: the database is always read live. It will be removed.")
26
+ }
27
+ }
@@ -51,7 +51,7 @@ const SEAWEEDFS_IMAGE =
51
51
  * Not a guess and not configurable: the plugin prefixes every key it writes
52
52
  * with this and enforces it in its own `reserved_words.lua`, so it is the one
53
53
  * durable thing in a keyspace that is otherwise a cache. Verified on a live
54
- * instance — both ACME keys survived `kill -9` with only this prefix named
54
+ * instance: both ACME keys survived `kill -9` with only this prefix named
55
55
  * durable, and a response-cache key beside them did not.
56
56
  */
57
57
  const ACME_KEY_PREFIX = "kong_acme:"
@@ -62,6 +62,13 @@ const OBJECT_STORE_SECRET_KEY = "supatype-secret"
62
62
  /** Where the rendered SeaweedFS identity file sits, resolved from the project root like kong.yml. */
63
63
  const SEAWEED_CONFIG_MOUNT = ".supatype/self-host/s3.json"
64
64
 
65
+ /**
66
+ * The compose volume key Postgres keeps its data in. Docker names the volume
67
+ * `<compose project>_<key>`, and `supatype dev --reset-db` removes it by that name, so the key is
68
+ * declared once rather than spelled out in the file and again in the code that deletes it.
69
+ */
70
+ export const DB_VOLUME_KEY = "db-data"
71
+
65
72
  type DockerPinComponent = "engine" | "server" | "postgres"
66
73
 
67
74
  /** Map a config version pin to a Docker Hub image reference. */
@@ -524,7 +531,7 @@ ${seaweedPorts}`
524
531
  `
525
532
  // An external database is not ours to declare a volume for.
526
533
  const volumesBlock = `volumes:
527
- ${external ? "" : " db-data:\n"} storage-data:
534
+ ${external ? "" : ` ${DB_VOLUME_KEY}:\n`} storage-data:
528
535
  ${keyspaceInPg ? "" : " valkey-data:\n"}`
529
536
 
530
537
  // `depends_on` for the services that talk to Postgres. With an external database there is no
@@ -682,7 +689,7 @@ ${dbDependency}`
682
689
  # Read by the image's init to password the \`authenticator\` role PostgREST connects as.
683
690
  AUTHENTICATOR_PASSWORD: \${AUTHENTICATOR_PASSWORD:?AUTHENTICATOR_PASSWORD is missing from .env}
684
691
  ${keyspaceDbEnv}${dbPorts}${keyspaceExpose} volumes:
685
- - db-data:/var/lib/postgresql/data
692
+ - ${DB_VOLUME_KEY}:/var/lib/postgresql/data
686
693
  healthcheck:
687
694
  # -h 127.0.0.1 forces TCP. Without it \`pg_isready\` uses the Unix socket, which the
688
695
  # entrypoint's temporary init server is already listening on while TCP is still refused,
@@ -1308,10 +1308,7 @@ function parseAccessModeLiteral(
1308
1308
  }
1309
1309
 
1310
1310
  function parseSizeStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
1311
- if (ts.isLiteralTypeNode(typeNode) && ts.isStringLiteral(typeNode.literal)) {
1312
- return typeNode.literal.text
1313
- }
1314
- return stripQuotes(typeNode.getText(sourceFile)) || undefined
1311
+ return literalStringType(typeNode) ?? (stripQuotes(typeNode.getText(sourceFile)) || undefined)
1315
1312
  }
1316
1313
 
1317
1314
  function parseJsonStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
@@ -1344,6 +1341,9 @@ function parseMimeAcceptList(typeNode: ts.TypeNode, sourceFile: ts.SourceFile):
1344
1341
  return undefined
1345
1342
  }
1346
1343
 
1344
+ /** The operations a bucket's `access` may name, the same four a model's may. */
1345
+ const BUCKET_RULE_KEYS: ReadonlySet<string> = new Set(["read", "create", "update", "delete"])
1346
+
1347
1347
  function parsePartialBucketAccess(
1348
1348
  typeNode: ts.TypeNode,
1349
1349
  sourceFile: ts.SourceFile,
@@ -1367,7 +1367,14 @@ function parsePartialBucketAccess(
1367
1367
  for (const member of literal.members) {
1368
1368
  if (!ts.isPropertySignature(member) || !member.type) continue
1369
1369
  const key = getPropertyName(member.name)
1370
- if (key !== "read" && key !== "create" && key !== "delete") continue
1370
+ // Refused rather than skipped. Skipping is how `update` went unenforced: the author wrote an
1371
+ // overwrite rule, the bucket got none, and nothing said so.
1372
+ if (key === null || !BUCKET_RULE_KEYS.has(key)) {
1373
+ const written = key ?? member.name.getText(sourceFile)
1374
+ throw new Error(
1375
+ `Bucket "${bucketId}": \`${written}\` is not a bucket rule. Use read, create, update or delete.`,
1376
+ )
1377
+ }
1371
1378
  const bucketRule = parseAccessRule(member.type, sourceFile, resolveCtx)
1372
1379
  assertAccessRuleIsRenderable(bucketRule, bucketId, key)
1373
1380
  access[key] = bucketRule
@@ -1593,10 +1600,7 @@ function resolveBucketName(
1593
1600
  if (ts.isTypeReferenceNode(typeArg) && ts.isIdentifier(typeArg.typeName)) {
1594
1601
  return bucketAliases.get(typeArg.typeName.text) ?? typeArg.typeName.text
1595
1602
  }
1596
- if (ts.isLiteralTypeNode(typeArg) && ts.isStringLiteral(typeArg.literal)) {
1597
- return typeArg.literal.text
1598
- }
1599
- return typeArg.getText(sourceFile).replace(/^['"]|['"]$/g, "") || fallback
1603
+ return literalStringType(typeArg) ?? (typeArg.getText(sourceFile).replace(/^['"]|['"]$/g, "") || fallback)
1600
1604
  }
1601
1605
 
1602
1606
  function isBooleanLiteralType(typeNode: ts.TypeNode, value: boolean): boolean {
@@ -1670,27 +1674,23 @@ function parseVersions(typeNode: ts.TypeNode): ParsedVersions | undefined {
1670
1674
  return parsed
1671
1675
  }
1672
1676
 
1673
- function parseMetaLiteral(
1674
- metaArg: ts.TypeNode | undefined,
1675
- sourceFile: ts.SourceFile,
1676
- ): {
1677
+ interface MetaLiteral {
1677
1678
  tableName?: string
1679
+ label?: string
1680
+ labelPlural?: string
1678
1681
  singleton?: boolean
1679
1682
  timestamps?: boolean
1680
1683
  softDelete?: boolean
1681
1684
  autoLocalize?: boolean
1682
1685
  versions?: ParsedVersions
1683
1686
  searchable?: string[]
1684
- } {
1685
- const result: {
1686
- tableName?: string
1687
- singleton?: boolean
1688
- timestamps?: boolean
1689
- softDelete?: boolean
1690
- autoLocalize?: boolean
1691
- versions?: ParsedVersions
1692
- searchable?: string[]
1693
- } = {}
1687
+ }
1688
+
1689
+ function parseMetaLiteral(
1690
+ metaArg: ts.TypeNode | undefined,
1691
+ sourceFile: ts.SourceFile,
1692
+ ): MetaLiteral {
1693
+ const result: MetaLiteral = {}
1694
1694
 
1695
1695
  if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return result
1696
1696
 
@@ -1711,17 +1711,14 @@ function parseMetaLiteral(
1711
1711
  result.autoLocalize = true
1712
1712
  } else if (key === "searchable" && ts.isTupleTypeNode(member.type)) {
1713
1713
  result.searchable = member.type.elements
1714
- .map((el) => (ts.isLiteralTypeNode(el) && ts.isStringLiteral(el.literal) ? el.literal.text : null))
1714
+ .map(literalStringType)
1715
1715
  .filter((name): name is string => name !== null)
1716
1716
  } else if (key === "versions") {
1717
1717
  const versions = parseVersions(member.type)
1718
1718
  if (versions !== undefined) result.versions = versions
1719
- } else if (
1720
- key === "tableName" &&
1721
- ts.isLiteralTypeNode(member.type) &&
1722
- ts.isStringLiteral(member.type.literal)
1723
- ) {
1724
- result.tableName = member.type.literal.text
1719
+ } else if (key === "tableName" || key === "label" || key === "labelPlural") {
1720
+ const text = literalStringType(member.type)
1721
+ if (text !== null) result[key] = text
1725
1722
  }
1726
1723
  }
1727
1724
 
@@ -1780,6 +1777,8 @@ function parseModelMeta(
1780
1777
  if (softDelete) options.softDelete = true
1781
1778
  if (literal.autoLocalize === true) options.autoLocalize = true
1782
1779
  if (literal.versions !== undefined) options.versions = literal.versions
1780
+ if (literal.label !== undefined) options.label = literal.label
1781
+ if (literal.labelPlural !== undefined) options.labelPlural = literal.labelPlural
1783
1782
 
1784
1783
  const access = parseModelAccess(metaArg, sourceFile, modelName, fields, resolveCtx)
1785
1784
  if (literal.versions !== undefined) assertVersionsWithoutFieldRules(access, modelName)
@@ -1826,7 +1825,7 @@ function assertCacheIsServable(
1826
1825
  `Model "${model}": \`cache.public\` cannot be used with an \`access.read\` rule that ` +
1827
1826
  `varies by caller. A public cache entry is shared by everyone, so one caller's rows ` +
1828
1827
  `would be served to another. Use \`cache: { enabled: true }\` for per-user entries, or ` +
1829
- `make the read rule row-independent — a rule like \`Lte<"published_at", Now>\` varies by ` +
1828
+ `make the read rule row-independent: a rule like \`Lte<"published_at", Now>\` varies by ` +
1830
1829
  `row without varying by caller and is safe to share.`,
1831
1830
  )
1832
1831
  }
@@ -1837,7 +1836,7 @@ function assertCacheIsServable(
1837
1836
  if (keyed.length === 0) {
1838
1837
  throw new Error(
1839
1838
  `Model "${model}": \`cache.rows\` needs a primary key, because the row cache's key IS the ` +
1840
- `primary key — there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1839
+ `primary key, so there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1841
1840
  `response cache, which has no such requirement.`,
1842
1841
  )
1843
1842
  }
@@ -1887,7 +1886,7 @@ function resolveSearchFields(
1887
1886
  *
1888
1887
  * `cache_max_ttl` is refused outside 0–86400 by `PATCH /admin/v1/config/rest`, and a declared cap
1889
1888
  * is the same quantity. Left to the server, an out-of-range `maxTtl` reaches it as part of a
1890
- * manifest rather than a request — nothing refuses a manifest — and the ceiling it produces is
1889
+ * manifest rather than a request (nothing refuses a manifest), and the ceiling it produces is
1891
1890
  * whatever the arithmetic makes of it: a negative cap reads as "no cap declared" and permits more
1892
1891
  * than the author asked for, which is the one direction a ceiling must never move in.
1893
1892
  */
@@ -2239,8 +2238,9 @@ function parseModelIndexes(
2239
2238
  if (!ts.isPropertySignature(member) || !member.type) continue
2240
2239
  const key = getPropertyName(member.name)
2241
2240
  if (!key) continue
2242
- if (key === "name" && ts.isLiteralTypeNode(member.type) && ts.isStringLiteral(member.type.literal)) {
2243
- indexDef.name = member.type.literal.text
2241
+ if (key === "name") {
2242
+ const name = literalStringType(member.type)
2243
+ if (name !== null) indexDef.name = name
2244
2244
  } else if (key === "unique" && isBooleanLiteralType(member.type, true)) {
2245
2245
  indexDef.unique = true
2246
2246
  } else if (key === "fields" && ts.isTupleTypeNode(member.type)) {
@@ -3224,12 +3224,9 @@ function parseRelationOptions(
3224
3224
  continue
3225
3225
  }
3226
3226
 
3227
- if (
3228
- (key === "onDelete" || key === "onUpdate" || key === "through") &&
3229
- ts.isLiteralTypeNode(member.type) &&
3230
- ts.isStringLiteral(member.type.literal)
3231
- ) {
3232
- out[key] = member.type.literal.text
3227
+ if (key === "onDelete" || key === "onUpdate" || key === "through") {
3228
+ const text = literalStringType(member.type)
3229
+ if (text !== null) out[key] = text
3233
3230
  }
3234
3231
  }
3235
3232
 
@@ -3323,7 +3320,7 @@ export interface ParsedModelCache {
3323
3320
  * Shaped like `parseModelHooks`, and travelling the same way: onto the route manifest beside
3324
3321
  * `hooks`, not into `annotations.platform`. The schema engine re-serialises its own parsed AST
3325
3322
  * (`serde_json::to_value(&ast)`), and `PlatformModelAnnotations` carries only `access` and
3326
- * `search_fields` with no catch-all — so a key placed there is silently dropped on the way to the
3323
+ * `search_fields` with no catch-all, so a key placed there is silently dropped on the way to the
3327
3324
  * server rather than riding through. Verified rather than assumed; see plan §13.1.
3328
3325
  */
3329
3326
  function parseModelCache(
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import { adoptResultFrom } from "../src/dev-compose.js"
3
+
4
+ /**
5
+ * The engine prints the adopt preview as multi-line JSON. Read with stderr joined on, any warning a
6
+ * compose run prints made it unparseable, and a preview that worked was reported as a failed adopt.
7
+ */
8
+ const PREVIEW = JSON.stringify(
9
+ { status: "preview", stampStatements: ['COMMENT ON TABLE "public"."orders" IS \'...\''] },
10
+ null,
11
+ 2,
12
+ )
13
+
14
+ describe("adoptResultFrom()", () => {
15
+ it("reads the preview from stdout even when stderr printed something", () => {
16
+ const run = {
17
+ status: 0,
18
+ stdout: PREVIEW,
19
+ output: `${PREVIEW}\nWARN[0000] The "FOO" variable is not set. Defaulting to a blank string.`,
20
+ }
21
+ expect(adoptResultFrom(run)?.stampStatements).toHaveLength(1)
22
+ })
23
+
24
+ it("is null for a run that failed, whatever it printed", () => {
25
+ expect(adoptResultFrom({ status: 1, stdout: PREVIEW, output: PREVIEW })).toBeNull()
26
+ })
27
+ })
@@ -0,0 +1,129 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
2
+
3
+ /**
4
+ * What a push does when the engine refuses tables Supatype does not manage.
5
+ *
6
+ * It used to stop with a message naming `supatype adopt`, a command that could not reach a docker
7
+ * database and found nothing to stamp when it did. Now a terminal is offered adoption there and
8
+ * then, shown the SQL, and asked twice; anywhere else nothing is adopted and the command is
9
+ * printed. These pin that agreeing to a push is never agreeing to adopt.
10
+ */
11
+
12
+ const printed: string[] = []
13
+ vi.mock("../src/ui/messages.js", () => ({
14
+ warn: (line: string) => printed.push(`warn: ${line}`),
15
+ plain: (line?: string) => printed.push(line ?? ""),
16
+ }))
17
+
18
+ let interactive = true
19
+ vi.mock("../src/ui/interactive.js", () => ({ isInteractive: () => interactive }))
20
+
21
+ const answers: boolean[] = []
22
+ vi.mock("../src/ui/confirm.js", () => ({ confirm: vi.fn(async () => answers.shift() ?? false) }))
23
+
24
+ const { EngineError } = await import("../src/engine-client.js")
25
+ const { engineOutputOf, offerAdoption, pushOfferingAdoption, unmanagedTables } = await import(
26
+ "../src/adopt-walkthrough.js"
27
+ )
28
+
29
+ const REFUSAL = '{"status":"refused","reason":"unmanaged_model_tables","tables":["orders","items"]}'
30
+ const POLICY = { yes: false, retry: "supatype push" }
31
+
32
+ function adoptSteps(statements = ['COMMENT ON TABLE "public"."orders" IS ...']) {
33
+ return { preview: vi.fn(async () => statements), apply: vi.fn(async () => statements.length) }
34
+ }
35
+
36
+ beforeEach(() => {
37
+ printed.length = 0
38
+ answers.length = 0
39
+ interactive = true
40
+ })
41
+ afterEach(() => vi.clearAllMocks())
42
+
43
+ describe("unmanagedTables()", () => {
44
+ it("reads the tables from the engine's JSON refusal", () => {
45
+ expect(unmanagedTables(`some compose noise\n${REFUSAL}\nError: ...`)).toEqual(["orders", "items"])
46
+ })
47
+
48
+ it("falls back to the wording of an engine that predates the JSON", () => {
49
+ const legacy = "Your schema declares model(s) for table(s) Supatype does not manage: public.orders, public.items.\n\nNothing was applied."
50
+ expect(unmanagedTables(legacy)).toEqual(["public.orders", "public.items"])
51
+ })
52
+
53
+ it("is null for any other failure, including another JSON refusal", () => {
54
+ expect(unmanagedTables("2 destructive operation(s) detected")).toBeNull()
55
+ expect(unmanagedTables('{"status":"refused","reason":"something_else","tables":["x"]}')).toBeNull()
56
+ })
57
+
58
+ it("reads an engine error's stdout, where the refusal is printed", () => {
59
+ const err = new EngineError("Engine /push failed (exit 1): Error: ...", "/push", 1, REFUSAL)
60
+ expect(unmanagedTables(engineOutputOf(err))).toEqual(["orders", "items"])
61
+ })
62
+ })
63
+
64
+ describe("offerAdoption()", () => {
65
+ it("never adopts without a terminal, and prints the command instead", async () => {
66
+ interactive = false
67
+ // Would be yes to both, so only the missing terminal can be what stops it.
68
+ answers.push(true, true)
69
+ const steps = adoptSteps()
70
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("declined")
71
+ expect(steps.preview).not.toHaveBeenCalled()
72
+ expect(steps.apply).not.toHaveBeenCalled()
73
+ expect(printed.join("\n")).toContain("Run `supatype adopt`")
74
+ })
75
+
76
+ it("never adopts on --yes, because agreeing to a push is not agreeing to adopt", async () => {
77
+ answers.push(true, true)
78
+ const steps = adoptSteps()
79
+ expect(await offerAdoption(["orders"], steps, { ...POLICY, yes: true })).toBe("declined")
80
+ expect(steps.apply).not.toHaveBeenCalled()
81
+ })
82
+
83
+ it("says which tables, and that their access rules are not in force", async () => {
84
+ interactive = false
85
+ await offerAdoption(["orders", "items"], adoptSteps(), POLICY)
86
+ expect(printed.join("\n")).toContain("access rules your schema declares for them are not in force: orders, items")
87
+ })
88
+
89
+ it("shows the SQL before applying, and applies only on the second yes", async () => {
90
+ answers.push(true, true)
91
+ const steps = adoptSteps()
92
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("adopted")
93
+ expect(printed.join("\n")).toContain('COMMENT ON TABLE "public"."orders"')
94
+ expect(steps.apply).toHaveBeenCalledTimes(1)
95
+ })
96
+
97
+ it("applies nothing when the SQL is declined", async () => {
98
+ answers.push(true, false)
99
+ const steps = adoptSteps()
100
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("declined")
101
+ expect(steps.apply).not.toHaveBeenCalled()
102
+ })
103
+ })
104
+
105
+ describe("pushOfferingAdoption()", () => {
106
+ it("adopts and pushes once more after an unmanaged-tables refusal", async () => {
107
+ answers.push(true, true)
108
+ const push = vi
109
+ .fn<() => Promise<string>>()
110
+ .mockRejectedValueOnce(new EngineError("refused", "/push", 1, REFUSAL))
111
+ .mockResolvedValueOnce("applied")
112
+ expect(await pushOfferingAdoption(push, adoptSteps(), POLICY)).toBe("applied")
113
+ expect(push).toHaveBeenCalledTimes(2)
114
+ })
115
+
116
+ it("throws the refusal as it came when adoption is declined, so the push still fails", async () => {
117
+ const refusal = new EngineError("refused", "/push", 1, REFUSAL)
118
+ const push = vi.fn<() => Promise<string>>().mockRejectedValue(refusal)
119
+ await expect(pushOfferingAdoption(push, adoptSteps(), POLICY)).rejects.toBe(refusal)
120
+ expect(push).toHaveBeenCalledTimes(1)
121
+ })
122
+
123
+ it("does not offer anything for any other failure", async () => {
124
+ const other = new Error("2 destructive operation(s) detected")
125
+ const steps = adoptSteps()
126
+ await expect(pushOfferingAdoption(vi.fn().mockRejectedValue(other), steps, POLICY)).rejects.toBe(other)
127
+ expect(steps.preview).not.toHaveBeenCalled()
128
+ })
129
+ })