@protobase/cli 0.46.11 → 0.46.13

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 (74) hide show
  1. package/dist/auth/register.js +1 -2
  2. package/dist/auth/write-migration.js +1 -1
  3. package/dist/build/app-icons.js +1 -1
  4. package/dist/build/config-bundle.js +1 -1
  5. package/dist/build/deploy-bundle.js +2 -2
  6. package/dist/build/entry-code.js +1 -1
  7. package/dist/build/plugin-build.js +3 -3
  8. package/dist/build/plugin-fields.js +1 -1
  9. package/dist/build/service-worker-code.js +1 -1
  10. package/dist/build/shell.js +2 -2
  11. package/dist/build/ui-check.js +2 -2
  12. package/dist/build/vite-bundle.js +1 -1
  13. package/dist/bundle/manifest.js +1 -1
  14. package/dist/cli/package.js +1 -1
  15. package/dist/db/connect.js +1 -9
  16. package/dist/db/connection-url.js +14 -0
  17. package/dist/dev/entry.js +3 -3
  18. package/dist/dev/project.js +2 -2
  19. package/dist/dev/run.js +8 -4
  20. package/dist/dev/startup-logger.js +24 -0
  21. package/dist/doctor/run.js +3 -0
  22. package/dist/encryption/register.js +1 -2
  23. package/dist/error-message.js +15 -0
  24. package/dist/exit-signal.js +10 -0
  25. package/dist/files/register.js +1 -2
  26. package/dist/infer/proposal.js +1 -1
  27. package/dist/main.js +39 -26
  28. package/dist/migration/load-project.js +1 -1
  29. package/dist/migration/register.js +7 -4
  30. package/dist/migration/summary.js +15 -0
  31. package/dist/mobile/local-spec.js +1 -1
  32. package/dist/mobile/run.js +1 -1
  33. package/dist/mobile/web-part.js +2 -2
  34. package/dist/mobile/workspace.js +1 -1
  35. package/dist/notifications/register.js +1 -2
  36. package/dist/organizations/api.js +15 -0
  37. package/dist/organizations/register.js +5 -15
  38. package/dist/project/favicon-link.js +1 -1
  39. package/dist/project/import-project-file.js +21 -11
  40. package/dist/project/load-bundle-project.js +2 -2
  41. package/dist/project/load-data-config.js +4 -11
  42. package/dist/project/placeholder-secret.js +9 -0
  43. package/dist/runner.d.ts +20 -0
  44. package/dist/runner.js +94 -0
  45. package/dist/scaffold/existing-config.js +4 -1
  46. package/dist/scaffold/plan.js +11 -7
  47. package/dist/scaffold/project.js +2 -1
  48. package/dist/scaffold/prompt.js +12 -5
  49. package/dist/scaffold/run.js +1 -1
  50. package/dist/scaffold/ui-fields.js +3 -0
  51. package/dist/scaffold/ui-file.js +26 -4
  52. package/dist/serve/app.js +1 -1
  53. package/dist/serve/bundle-version.js +1 -1
  54. package/dist/serve/create-admin.js +3 -3
  55. package/dist/serve/host-modules.js +6 -6
  56. package/dist/serve/lifecycle.js +3 -3
  57. package/dist/serve/mobile-release.js +1 -1
  58. package/dist/serve/serve-bundle-path.js +1 -1
  59. package/dist/serve/serve-bundle.js +3 -3
  60. package/dist/serve/serve-dir.js +2 -2
  61. package/dist/supabase/dump-phase.js +1 -1
  62. package/dist/supabase/load-phase.js +1 -1
  63. package/dist/supabase/register.js +1 -1
  64. package/dist/supabase/storage-phase.js +1 -1
  65. package/dist/users/commands.js +7 -1
  66. package/dist/users/register.js +17 -11
  67. package/dist/users/users-api.js +2 -1
  68. package/dist/worker/start-worker.js +2 -2
  69. package/package.json +9 -6
  70. package/skills/protobase/SKILL.md +1 -0
  71. package/skills/protobase/references/features/start-a-project.md +1 -1
  72. package/skills/protobase/references/getting-started.md +16 -1
  73. package/skills/protobase/references/guides/existing-database.md +112 -0
  74. package/skills/protobase/references/reference/cli.md +29 -8
@@ -1,8 +1,8 @@
1
1
  import { readManifest } from "../bundle/manifest.js";
2
+ import { bundleSite } from "./bundle-site.js";
3
+ import { serveBundle } from "./serve-bundle.js";
2
4
  import { installedShellDir } from "../build/shell.js";
3
5
  import { pinnedNative } from "../mobile/pinned-packages.js";
4
- import { serveBundle } from "./serve-bundle.js";
5
- import { bundleSite } from "./bundle-site.js";
6
6
  import { servedShell, shellVariable } from "./served-shell.js";
7
7
  import path from "node:path";
8
8
  //#region src/serve/serve-dir.ts
@@ -17,8 +17,8 @@ import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks
17
17
  import { creatableExtensions } from "./target-extensions.js";
18
18
  import { usersColumnsMigration } from "./users-migrations.js";
19
19
  import path from "node:path";
20
- import { isSchedule } from "@protobase/server";
21
20
  import { mkdir, readFile, rm } from "node:fs/promises";
21
+ import { isSchedule } from "@protobase/server";
22
22
  import postgres from "postgres";
23
23
  //#region src/supabase/dump-phase.ts
24
24
  /** Fails unless the database at `sql` is Supabase's: its auth and storage schemas, and its own admin role. */
@@ -1,4 +1,3 @@
1
- import { loadProjectAuth } from "../users/load-auth.js";
2
1
  import { writeAuthMigration } from "../auth/write-migration.js";
3
2
  import { connect } from "../db/connect.js";
4
3
  import { runDoctor } from "../doctor/run.js";
@@ -11,6 +10,7 @@ import { loadScript, qualified } from "./load-script.js";
11
10
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
12
11
  import { providerCounts } from "./identity-providers.js";
13
12
  import { accountsMigration } from "./users-migrations.js";
13
+ import { loadProjectAuth } from "../users/load-auth.js";
14
14
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
15
  import { importReport } from "./report.js";
16
16
  import { existsSync } from "node:fs";
@@ -1,5 +1,4 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { runSupabaseImport } from "./run.js";
3
2
  import path from "node:path";
4
3
  //#region src/supabase/register.ts
5
4
  const out = (text) => process.stdout.write(text);
@@ -19,6 +18,7 @@ const registerImport = (program) => {
19
18
  if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
20
19
  const projectDir = process.cwd();
21
20
  loadNearestEnvFile(projectDir);
21
+ const { runSupabaseImport } = await import("./run.js");
22
22
  await runSupabaseImport({
23
23
  sourceUrl: source ?? (opts.sourceEnv ? variable(opts.sourceEnv) : void 0),
24
24
  targetUrl: variable(opts.env),
@@ -9,8 +9,8 @@ import { storageObjects } from "./storage-objects.js";
9
9
  import { bucketLines, megabytes, objectCount, overQuota, totalBytes } from "./storage-sizes.js";
10
10
  import { storageReport } from "./storage-report.js";
11
11
  import path from "node:path";
12
- import { objectKey, storageProvider, storeUsage } from "@protobase/server";
13
12
  import { writeFile } from "node:fs/promises";
13
+ import { objectKey, storageProvider, storeUsage } from "@protobase/server";
14
14
  //#region src/supabase/storage-phase.ts
15
15
  /** Objects copied at once: enough to keep a connection busy, few enough for any host. */
16
16
  const parallel = 4;
@@ -1,6 +1,11 @@
1
1
  import { resolvePassword } from "./password.js";
2
2
  //#region src/users/commands.ts
3
3
  const githubId = /^[1-9][0-9]*$/;
4
+ const shownAs = (role, labels) => {
5
+ const names = role.split(",");
6
+ const shown = names.map((name) => labels[name] ?? name);
7
+ return shown.some((label, index) => label.toLowerCase() !== names[index].toLowerCase()) ? `, shown in the app as ${shown.join(", ")}` : "";
8
+ };
4
9
  const createUserCommand = async (api, options, deps, out) => {
5
10
  if (!options.email.includes("@")) throw new Error(`"${options.email}" is not an email address`);
6
11
  if (options.githubId !== void 0 && !githubId.test(options.githubId)) throw new Error(`"${options.githubId}" is not a GitHub user id, a number such as 583231`);
@@ -16,7 +21,8 @@ const createUserCommand = async (api, options, deps, out) => {
16
21
  accountId: options.githubId
17
22
  }] }
18
23
  });
19
- out(`Created ${user.role} ${user.email}${options.githubId ? `, linked to GitHub user ${options.githubId}` : ""}\n`);
24
+ const { labels } = await api.roles();
25
+ out(`Created ${user.role} ${user.email}${shownAs(user.role, labels)}${options.githubId ? `, linked to GitHub user ${options.githubId}` : ""}\n`);
20
26
  if (generated) out(`Password (shown once): ${password}\n`);
21
27
  };
22
28
  const listUsersCommand = async (api, out) => {
@@ -1,18 +1,15 @@
1
- import { loadProjectAuth } from "./load-auth.js";
2
1
  import { addMemberCommand } from "../organizations/commands.js";
3
- import { organizationsApi } from "../organizations/register.js";
4
- import { readHidden, rejectPasswordArgument } from "./password.js";
5
- import { createUserCommand, listRolesCommand, listUsersCommand } from "./commands.js";
6
2
  import { deleteUserCommand, setRoleCommand } from "./manage.js";
7
- import { usersApi } from "./users-api.js";
8
- import { setDisabledInProject } from "./set-disabled.js";
9
3
  import { parseTtl } from "./ttl.js";
10
4
  import { Option } from "commander";
11
- import { issueToken } from "@protobase/server";
12
5
  import { createInterface } from "node:readline/promises";
13
6
  //#region src/users/register.ts
14
7
  const out = (text) => process.stdout.write(text);
15
- const projectApi = async () => usersApi(await loadProjectAuth(process.cwd()));
8
+ const loadAuth = async () => (await import("./load-auth.js")).loadProjectAuth(process.cwd());
9
+ const projectApi = async () => {
10
+ const [{ usersApi }, auth] = await Promise.all([import("./users-api.js"), loadAuth()]);
11
+ return usersApi(auth);
12
+ };
16
13
  const ask = async (question) => {
17
14
  if (!process.stdin.isTTY) throw new Error("Confirmation needs a terminal; pass --yes to skip it");
18
15
  const rl = createInterface({
@@ -27,8 +24,14 @@ const finish = (code) => process.exit(code);
27
24
  const registerUsers = (program) => {
28
25
  const users = program.command("users").description("Manage the admin users of the project in the current directory");
29
26
  users.command("create").description("Create a user; the first user is always an admin").argument("<email>").option("--name <name>", "display name").option("--role <role>", "role for users after the first (default: the project's default role; see `users roles`)").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).option("--no-password", "no password: the user signs in by emailed code, passkey or a sign-in provider").option("--github-id <id>", "link the user to this GitHub user id, so signing in with GitHub finds them whatever their address").option("--organization <organization>", "with organizations: add the user to this one (its slug or id)").option("--org-role <role>", "with --organization: owner, admin or member (default member)").option("--app-roles <roles>", "with --organization: app roles there, comma separated").addOption(new Option("--password <value>").hideHelp()).action(async (email, opts) => {
27
+ const { readHidden, rejectPasswordArgument } = await import("./password.js");
30
28
  rejectPasswordArgument(opts.password);
31
- const auth = await loadProjectAuth(process.cwd());
29
+ const [{ createUserCommand }, { usersApi }, { organizationsApi }, auth] = await Promise.all([
30
+ import("./commands.js"),
31
+ import("./users-api.js"),
32
+ import("../organizations/api.js"),
33
+ loadAuth()
34
+ ]);
32
35
  await createUserCommand(usersApi(auth), {
33
36
  email,
34
37
  name: opts.name,
@@ -64,17 +67,20 @@ const registerUsers = (program) => {
64
67
  finish(0);
65
68
  });
66
69
  for (const disabled of [true, false]) users.command(disabled ? "disable" : "enable").description(disabled ? "Ban a user and revoke their sessions" : "Lift a ban").argument("<email>").action(async (email) => {
67
- await setDisabledInProject(await loadProjectAuth(process.cwd()), {
70
+ const { setDisabledInProject } = await import("./set-disabled.js");
71
+ await setDisabledInProject(await loadAuth(), {
68
72
  email,
69
73
  disabled
70
74
  }, out);
71
75
  finish(0);
72
76
  });
73
77
  users.command("roles").description("List the roles of the project (the first is admin)").action(async () => {
78
+ const { listRolesCommand } = await import("./commands.js");
74
79
  await listRolesCommand(await projectApi(), out);
75
80
  finish(0);
76
81
  });
77
82
  users.command("list").description("List users: email, role, creation date").action(async () => {
83
+ const { listUsersCommand } = await import("./commands.js");
78
84
  await listUsersCommand(await projectApi(), out);
79
85
  finish(0);
80
86
  });
@@ -82,7 +88,7 @@ const registerUsers = (program) => {
82
88
  const registerToken = (program) => {
83
89
  program.command("token").description("Print a bearer token (JWT) for an existing user").argument("<email>").option("--ttl <duration>", "lifetime: 30s, 15m, up to 24h", "15m").action(async (email, opts) => {
84
90
  const ttlSeconds = parseTtl(opts.ttl);
85
- const auth = await loadProjectAuth(process.cwd());
91
+ const [{ issueToken }, auth] = await Promise.all([import("@protobase/server"), loadAuth()]);
86
92
  const { token } = await issueToken(auth, {
87
93
  email,
88
94
  ttlSeconds
@@ -4,7 +4,8 @@ const usersApi = (auth) => ({
4
4
  hasUsers: () => hasUsers(auth),
5
5
  roles: async () => ({
6
6
  roles: roleChoices(auth),
7
- defaultRole: auth.defaultRole
7
+ defaultRole: auth.defaultRole,
8
+ labels: auth.roleDefinitions.labels
8
9
  }),
9
10
  createUser: (input) => createUser(auth, input),
10
11
  listUsers: () => listUsers(auth),
@@ -1,7 +1,7 @@
1
- import { readManifest } from "../bundle/manifest.js";
2
- import { checkBundleVersion } from "../serve/bundle-version.js";
3
1
  import { projectAdmin } from "../project/project-admin.js";
4
2
  import { createPgDb } from "../project/pg-db.js";
3
+ import { readManifest } from "../bundle/manifest.js";
4
+ import { checkBundleVersion } from "../serve/bundle-version.js";
5
5
  import { loadBundle } from "../serve/load-bundle.js";
6
6
  import { statSync } from "node:fs";
7
7
  import path from "node:path";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.46.11",
3
+ "version": "0.46.13",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -17,6 +17,9 @@
17
17
  "engines": {
18
18
  "node": ">=22.12.0"
19
19
  },
20
+ "exports": {
21
+ "./runner": "./dist/runner.js"
22
+ },
20
23
  "bin": {
21
24
  "protobase": "./bin/protobase.mjs"
22
25
  },
@@ -36,11 +39,11 @@
36
39
  "@better-auth/core": "^1.7.12",
37
40
  "@hono/node-server": "^2.1.3",
38
41
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.46.11",
40
- "@protobase/query": "0.46.11",
41
- "@protobase/schema": "0.46.11",
42
- "@protobase/server": "0.46.11",
43
- "@protobase/ui": "0.46.11",
42
+ "@protobase/layout": "0.46.13",
43
+ "@protobase/query": "0.46.13",
44
+ "@protobase/schema": "0.46.13",
45
+ "@protobase/server": "0.46.13",
46
+ "@protobase/ui": "0.46.13",
44
47
  "@react-email/render": "^2.1.0",
45
48
  "@scalar/hono-api-reference": "^0.12.10",
46
49
  "@tailwindcss/vite": "^4.3.3",
@@ -43,6 +43,7 @@ Guides:
43
43
  - When setting up or running a project for the first time → read [Getting started](references/getting-started.md)
44
44
  - When you need to know whether Protobase has a feature, what it is called or how stable it is → read [Features](references/features.md), which links a page per area
45
45
  - When shipping a project as a bundle and running it with the serve runtime → read [Deploy](references/guides/deploy.md)
46
+ - When putting an admin on a Postgres database that already exists, from install to the first sign-in → read [Admin over an existing database](references/guides/existing-database.md)
46
47
  - When turning a table into an admin with fields, views and filters → read [From a table to an admin](references/guides/table-to-admin.md)
47
48
  - When building a page from layouts and blocks → read [Your first composed page](references/guides/first-composed-page.md)
48
49
  - When giving customers a page for their plan, cards and invoices → read [A billing page](references/guides/billing-page.md)
@@ -4,7 +4,7 @@
4
4
 
5
5
  Start a new app, or an admin over an existing Postgres database, and keep the config in step with it.
6
6
 
7
- - [Project starter](../getting-started.md#start-an-app): `npm create protobase` starts a new app from the scratch, ERP or real estate preset and prints the next steps. Each preset has an `AGENTS.md` with rules for coding agents.
7
+ - [Project starter](../getting-started.md#start-an-app): `npm create protobase` (also `bun create` and `pnpm create`) starts a new app from the scratch, ERP or real estate preset, with its own Postgres in Docker for development, and prints the next steps. Each preset has an `AGENTS.md` with rules for coding agents.
8
8
  - [Example apps](../getting-started.md#run-the-erp-example): Seeded example apps on Postgres: an ERP, real estate property management and a public property portal.
9
9
  - [Scaffold from a database](../reference/cli.md#scaffold): Reads your Postgres tables and writes the data config for them, with field types, keys, relations, enums, soft delete, tenants and search filled in, and with `--ui` a first view of each.
10
10
  - [Safe re-scaffolding](../reference/cli.md#re-running): Running scaffold again adds only the columns that are not declared yet and leaves your own config code as it is.
@@ -10,13 +10,28 @@ An app's own React code, its components, field types and actions, is a [plugin](
10
10
 
11
11
  ## Start an app
12
12
 
13
- `npm create protobase my-app` asks which preset to start from, scratch (the default), the ERP or real estate, writes the project into `my-app`, with the `@protobase` packages in the range of the latest release's major, and prints the next steps: install it with Bun, point `.env` at a Postgres database, migrate it, load the preset's base data, if it has any, create a user and run `bun run dev`. `--preset <name>` picks one without asking; without a terminal it takes scratch. It needs Node 22.12 or later. Each preset has an `AGENTS.md` with the rules for a coding agent that changes the app, such as a new migration file for every schema change.
13
+ `npm create protobase my-app` asks which preset to start from, scratch (the default), the ERP or real estate, writes the project into `my-app`, with the `@protobase` packages in the range of the latest release's major, and prints the next steps. Without a folder it asks for one too. `--preset <name>` picks the preset without asking; without a terminal it takes scratch. `bun create protobase` and `pnpm create protobase` do the same, and take `--preset` without the `--` that npm needs. It needs Node 22.12 or later. Each preset has an `AGENTS.md` with the rules for a coding agent that changes the app, such as a new migration file for every schema change.
14
14
 
15
15
  ```sh
16
16
  npm create protobase my-app
17
17
  npm create protobase my-app -- --preset real-estate
18
18
  ```
19
19
 
20
+ The project comes with its own Postgres for development: a `docker-compose.yml` with Postgres 18, started by `bun run db:up` and stopped by `bun run db:down`, on port 55432 or, when something listens there already, the next free one. Its `.env` points at that database and has a `BETTER_AUTH_SECRET` of its own. Without Docker, set `DATABASE_URL` in `.env` to a Postgres database of yours. The next steps install it with Bun, which runs the project's scripts, start the database, migrate it, load the preset's base data, if it has any, create a user and run `bun run dev`. For scratch:
21
+
22
+ ```sh
23
+ cd my-app
24
+ bun install
25
+ bun run db:up
26
+ bun run db:migrate
27
+ bun run protobase users create you@example.com --generate-password
28
+ bun run dev # http://localhost:5173
29
+ ```
30
+
31
+ ## Admin over an existing database
32
+
33
+ For a Postgres database you already have, [Admin over an existing database](guides/existing-database.md) goes from an empty folder to signing in: install the packages, scaffold the config from the tables, check it with `doctor`, add sign-in and its tables, create the first admin and run `protobase dev`.
34
+
20
35
  ## Docs as Markdown
21
36
 
22
37
  Every page of these docs is also Markdown at its address plus `.md`: `https://docs.protobase.net/reference/cli/` is also `https://docs.protobase.net/reference/cli.md`. The code a page shows from example files is written out in it, and its live demos are left out, so a coding agent or a chat assistant reads the page whole. In a project, [`protobase skill install`](reference/cli.md#skill) gives coding agents the docs of the installed version.
@@ -0,0 +1,112 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/existing-database.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Admin over an existing database
4
+
5
+ Put an admin on a Postgres database you already have, in six steps, from install to signing in, with every file sign-in needs.
6
+
7
+ You have a Postgres database and want an admin over its tables, without moving the data. This guide goes from an empty folder to signing in to that admin. It takes about fifteen minutes and needs Node 22.12 or later.
8
+
9
+ Protobase never changes your tables. Sign-in is the one thing it adds to the database: an `auth` schema with its own tables for users, sessions and signing keys. `protobase migration` writes them as a SQL file you apply yourself, like any other migration, and the app never changes the schema while it runs.
10
+
11
+ ## 1. Install
12
+
13
+ In a new folder, next to the database's own code or anywhere else:
14
+
15
+ ```sh
16
+ npm install @protobase/cli @protobase/schema @protobase/layout @protobase/server @protobase/ui pg kysely
17
+ ```
18
+
19
+ Then a `.env` beside it, which every `protobase` command reads:
20
+
21
+ ```sh
22
+ DATABASE_URL=postgres://user:password@localhost:5432/shop
23
+ # Signs session cookies: generate your own with openssl rand -base64 32
24
+ BETTER_AUTH_SECRET=
25
+ BETTER_AUTH_URL=http://localhost:5173
26
+ ```
27
+
28
+ Keep `.env` out of version control.
29
+
30
+ ## 2. Scaffold the config
31
+
32
+ ```sh
33
+ npx protobase scaffold --ui
34
+ ```
35
+
36
+ It reads the tables, read-only, and writes `config/<resource>/data.ts` and `ui.ts` for each one, and `config/index.ts`. In a terminal it asks about each column: press Enter to accept one, `l` to accept it and every one after it. `--yes` accepts them all without asking, and `--dry-run` shows the files without writing them. A table without a primary key, or a unique index on columns that are never null, is skipped with a warning, and so is a view. What it infers is in the [CLI reference](../reference/cli.md#scaffold).
37
+
38
+ ## 3. Check it
39
+
40
+ ```sh
41
+ npx protobase doctor
42
+ ```
43
+
44
+ It checks the config against the database: each table and column exists, each type fits, and an index serves every filter and sort the admin makes. Each error names the index to add, such as `create index on "public"."orders" ("total");`. Add those with your own migrations, or drop the `.filterable()` or `.sortable()` that needs it.
45
+
46
+ ## 4. Add sign-in
47
+
48
+ Two files. `protobase.config.ts` is the project:
49
+
50
+ ```ts
51
+ import * as config from './config'
52
+ import { auth, authenticate } from './auth/auth'
53
+
54
+ export default { config, auth, authenticate }
55
+ ```
56
+
57
+ `auth/auth.ts` sets up sign-in with [Better Auth](../reference/auth.md), with its tables in the `auth` schema:
58
+
59
+ ```ts
60
+ import { PostgresDialect } from 'kysely'
61
+ import pg from 'pg'
62
+ import { appPool, betterAuthAuthenticator, createAuth } from '@protobase/server'
63
+
64
+ const secret = process.env.BETTER_AUTH_SECRET
65
+ if (!secret) throw new Error('BETTER_AUTH_SECRET is not set: put the output of `openssl rand -base64 32` in .env')
66
+
67
+ // The app's one pool on DATABASE_URL, which `protobase dev` and `serve` share.
68
+ const pool = appPool(pg, process.env.DATABASE_URL!)
69
+
70
+ export const auth = createAuth({
71
+ // Users, sessions and signing keys live in a schema of their own, next to your tables.
72
+ database: { dialect: new PostgresDialect({ pool }), type: 'postgres', schemaName: 'auth', transaction: true },
73
+ baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:5173',
74
+ secret,
75
+ })
76
+
77
+ export const authenticate = betterAuthAuthenticator({ auth, tenant: 1 })
78
+ ```
79
+
80
+ The [auth reference](../reference/auth.md) has the rest: emailed codes, passkeys, two-factor, roles, and a users table the database already has.
81
+
82
+ ## 5. Write and apply the auth tables
83
+
84
+ ```sh
85
+ npx protobase migration
86
+ ```
87
+
88
+ It compares the database with what sign-in needs and writes `db/migrations/001_auth.sql`: the `auth` schema and its tables. It only adds; it never drops or changes your tables. Read it, then apply it with your migration tool, or with `psql`:
89
+
90
+ ```sh
91
+ psql "$DATABASE_URL" -1 -f db/migrations/001_auth.sql
92
+ ```
93
+
94
+ After a Protobase upgrade, run `npx protobase migration` again: it writes only what the new version adds, as the next file.
95
+
96
+ ## 6. Create the first admin and sign in
97
+
98
+ ```sh
99
+ npx protobase users create you@example.com --generate-password
100
+ npx protobase dev
101
+ ```
102
+
103
+ The first user is always an admin. The password is printed once. `protobase dev` serves the admin and its API at `http://localhost:5173` (`--port` picks another port); sign in there with that email and password.
104
+
105
+ ## Running scaffold again
106
+
107
+ When the database gets a new table or column, run `npx protobase scaffold --ui` again. It adds only what is new, and leaves your edits as they are. It leaves out the `auth` schema of step 5 on its own, and says so, as the sign-in tables are no admin pages. It also reports drift: a declared field whose column has gone, or whose type no longer fits.
108
+
109
+ ## Next
110
+
111
+ - [From a table to an admin](table-to-admin.md): names, columns, filters and record pages for the resources you scaffolded.
112
+ - [Deploy](deploy.md): build the app and run it on your own server.
@@ -12,14 +12,30 @@ bun run protobase <command> # from the project, config folde
12
12
  bun run --cwd examples/erp protobase <command> # in this repository, for an example
13
13
  ```
14
14
 
15
- Any package manager installs the packages, and the command runs on Node or on Bun: `npm install` and `npx protobase <command>` work the same. The bin starts with `#!/usr/bin/env node`, so where Node is installed `bun run protobase` starts it on Node, unless the project's `bunfig.toml` sets `[run] bun = true`, as the presets' does.
15
+ Any package manager installs the packages, and the command runs on Node or on Bun: `npm install` and `npx protobase <command>` work the same. The bin starts with `#!/usr/bin/env node`, so where Node is installed `bun run protobase` starts it on Node, unless the project's `bunfig.toml` sets `[run] bun = true`, as the presets' does. `protobase --version` (or `-v`) prints the Protobase version.
16
16
 
17
17
  ## How it runs
18
18
 
19
- The published `@protobase` packages are JavaScript: each is built with [tsdown](https://tsdown.dev) to ES modules and type declarations in `dist`, one file per source module, and packing them points their `exports`, `types` and `bin` at it (`publishConfig`). The installed `protobase` command (`bin/protobase.mjs`) runs `dist` on Node 22.12 or later, or on Bun. The project's own TypeScript is loaded with Vite on both: `users` and `doctor` import it through Vite's module runner, `dev` serves it and `build` bundles it.
19
+ The published `@protobase` packages are JavaScript: each is built with [tsdown](https://tsdown.dev) to ES modules and type declarations in `dist`, one file per source module, and packing them points their `exports`, `types` and `bin` at it (`publishConfig`). The installed `protobase` command (`bin/protobase.mjs`) runs `dist` on Node 22.12 or later, or on Bun. The commands that read the project's own TypeScript, such as `users` and `doctor`, import it directly on Bun and through Vite's module runner on Node, which cannot resolve its extensionless imports; `dev` serves it with Vite and `build` bundles it.
20
20
 
21
21
  In this repository nothing needs a build: the packages' `exports` point at `src`, and the workspace's `protobase` is `bin/protobase-source.mjs`, which imports `src/index.ts`: Bun loads it itself, Node through [tsx](https://tsx.is). `bun run build` builds every package to `dist`.
22
22
 
23
+ ### In another process
24
+
25
+ A process that runs many commands, such as a deploy, can run them without starting the CLI each time. `@protobase/cli/runner` exports one function, and nothing else of the CLI:
26
+
27
+ ```ts
28
+ import { runCommand } from '@protobase/cli/runner'
29
+
30
+ const { exitCode, stdout, stderr } = await runCommand(['doctor', '--env', 'DATABASE_URL'], { cwd: '/srv/app', env: { DATABASE_URL: url } })
31
+ ```
32
+
33
+ - `cwd` is the folder the command runs in, and `env` its whole environment, as a child process gets them. Both default to the current process's. `stdin` is what the command reads from stdin, by default nothing.
34
+ - Commands run one at a time, since they share the process's working folder, environment and output. Each puts them back when it ends.
35
+ - The CLI and its packages stay loaded, so only the first command pays for loading them. On Bun the project's own files are loaded again for each command, so a command sees them as they are when it starts.
36
+ - `dev`, `serve`, `worker` and `mobile` run until a signal, so the runner refuses them; start them as a process.
37
+ - A command that ends with an exit code returns it rather than ending the process. Database pools the project's config opens close once idle.
38
+
23
39
  The serve runtime is bundled by `protobase build-serve` into one JavaScript file for Bun, so production needs neither `node_modules` nor the CLI (see [serve](#serve)).
24
40
 
25
41
  The CLI reads the database with `default_transaction_read_only = on`, so it can never write.
@@ -27,10 +43,10 @@ The CLI reads the database with `default_transaction_read_only = on`, so it can
27
43
  ## `scaffold`
28
44
 
29
45
  ```sh
30
- protobase scaffold <connection string | --env DATABASE_URL> [target] [options]
46
+ protobase scaffold [connection string | --env VAR] [target] [options]
31
47
  ```
32
48
 
33
- `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
49
+ Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
34
50
 
35
51
  Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the `auth` schema, another schema holding Better Auth's `user`, `session`, `account` and `verification` tables (in `public`, only the auth store's tables), and pg-boss's `jobs` schema. A line names each one skipped; a target naming the schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it.
36
52
 
@@ -43,7 +59,9 @@ Protobase's own tables are left out, since they hold password hashes, OAuth toke
43
59
  | `--ui-list`, `--ui-section <names\|list>` | write only those `ui.ts` sections |
44
60
  | `--exclude <schema[.table]>` | skip tables, repeatable |
45
61
 
46
- Interactively, each new column shows its proposal: accept, edit (name, type) or ignore (writes `field: null`; key columns cannot be ignored).
62
+ Interactively, each new column shows its proposal: accept, accept all (this one and every one after it, without asking), edit (name, type) or ignore (writes `field: null`; key columns cannot be ignored).
63
+
64
+ The list `--ui` writes shows five columns at most: the key unless it is a uuid, up to two relations, then the other fields but long text, json and audit timestamps. It sorts newest first by a sortable `created_at` (or `inserted_at`, `createdAt`, ...), else by another sortable date or timestamp, else not at all.
47
65
 
48
66
  ### Inference
49
67
 
@@ -58,10 +76,10 @@ Interactively, each new column shows its proposal: accept, edit (name, type) or
58
76
  | anything else (`ltree`, arrays, ...) | `f.text().readOnly()` |
59
77
 
60
78
  - `NOT NULL` absent: `.optional()`. Literal default: `.default(v)`.
61
- - Computed defaults (function, sequence, expression, `GENERATED BY DEFAULT` identity): `.dbDefault()`. It also gets `.readOnly()` when the column is an identity column, a primary-key column, or an audit timestamp (`created_at`, `inserted_at`, `updated_at`, `modified_at`); other computed defaults, such as `order_date DEFAULT current_date`, stay editable. `GENERATED ALWAYS` identity and generated columns are only `.readOnly()`.
79
+ - Computed defaults (function, sequence, expression, `GENERATED BY DEFAULT` identity): `.dbDefault()`. It also gets `.readOnly()` when the column is an identity column, a primary-key column, or an audit timestamp (`created_at`, `inserted_at`, `updated_at`, `modified_at`, or the same in camelCase, such as `createdAt`); other computed defaults, such as `order_date DEFAULT current_date`, stay editable. `GENERATED ALWAYS` identity and generated columns are only `.readOnly()`.
62
80
  - Leading column of a non-partial index: `.filterable()`; of a btree: also `.sortable()`. Not applied to json.
63
81
  - The text field that names a record (`name`, `title`, `number`, `sku`, `email`, `code` or `description`, else the first text field) becomes the resource's `.search(...)` when a non-partial pg_trgm index (`gin_trgm_ops` or `gist_trgm_ops`) serves it, so the [global search](client.md#global-search) finds its records by name. Without one the API would refuse the search, so it is left out; add the index and run `protobase scaffold` on a new resource, or add `.search` by hand.
64
- - Key: primary key (composite supported), else the first unique index with only `NOT NULL` columns, else the table is skipped with a warning.
82
+ - Key: primary key (composite supported), else the first unique index with only `NOT NULL` columns, else the table is skipped with a warning. A view or materialized view is skipped with a warning too, as Postgres knows no key for it: declare a resource over one by hand.
65
83
  - `deleted_at`, `removed_at`, `archived_at` (nullable timestamp/date) become `.softDelete`; `organization_id` and `tenant_id` become `.tenant`.
66
84
  - Unique indexes are listed in the doc comment above the resource.
67
85
  - Field names are the column names in snake_case; `.column()` is written only when the schema builder's default mapping would not give the column back (always for `hr."EMP_MASTER"`).
@@ -78,9 +96,11 @@ After each run, declared fields are compared with the database: a column that no
78
96
  ## `doctor`
79
97
 
80
98
  ```sh
81
- protobase doctor <connection string | --env VAR> [--config <dir>]
99
+ protobase doctor [connection string | --env VAR] [--config <dir>]
82
100
  ```
83
101
 
102
+ The URL comes as for [`scaffold`](#scaffold): the connection string, the variable `--env` names, or `DATABASE_URL`, each also read from the nearest `.env`.
103
+
84
104
  Imports `config/index.ts` and the views of `config/*/ui.ts`, as the config module has them by convention, and checks every exported resource against the database:
85
105
 
86
106
  - error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index
@@ -105,6 +125,7 @@ protobase dev [--port 5173] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-
105
125
 
106
126
  One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`, supabase-js's `/api/sb` included. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
107
127
 
128
+ - **Secret:** a `BETTER_AUTH_SECRET` still set to the placeholder of `.env.example` (`change-me-...`) prints a warning once the server is ready, as `serve` does at start: anyone who knows it can sign session cookies.
108
129
  - **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
109
130
  - **Port:** the app listens on `--port` at both `127.0.0.1` and `::1`, since `localhost` is either one depending on the runtime and the browser. When another process holds the port on either address the command stops before it starts and names that address; stop the other server or pass another `--port`.
110
131
  - **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).