@protobase/cli 0.49.2 → 0.50.1

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 (72) hide show
  1. package/bin/protobase.mjs +3 -2
  2. package/dist/build/config-bundle.js +1 -1
  3. package/dist/build/deploy-bundle.js +3 -4
  4. package/dist/build/plugin-build.js +16 -8
  5. package/dist/build/plugin-fields.js +5 -2
  6. package/dist/build/ui-check.js +5 -0
  7. package/dist/build/view-check.js +1 -1
  8. package/dist/cli/package.js +1 -1
  9. package/dist/config/project-files.js +4 -1
  10. package/dist/config/source-config.js +1 -1
  11. package/dist/dev/api-process.js +1 -1
  12. package/dist/dev/app-server.js +43 -35
  13. package/dist/dev/create-db.js +2 -2
  14. package/dist/dev/project.js +3 -2
  15. package/dist/dev/server-package.js +9 -21
  16. package/dist/doctor/run.js +1 -1
  17. package/dist/hand-over.d.ts +15 -0
  18. package/dist/hand-over.js +32 -0
  19. package/dist/main.js +22 -5
  20. package/dist/project/bundled-imports.js +41 -0
  21. package/dist/project/import-project-file.js +28 -8
  22. package/dist/project/load-data-config.js +4 -3
  23. package/dist/project/project-types.js +66 -0
  24. package/dist/run/preload.d.ts +1 -0
  25. package/dist/run/preload.js +20 -0
  26. package/dist/run/run-script.js +36 -0
  27. package/dist/supabase/dump-phase.js +9 -4
  28. package/dist/supabase/load-phase.js +5 -4
  29. package/dist/supabase/realtime-policies.js +60 -0
  30. package/dist/version/project-packages.js +39 -0
  31. package/dist/version/project-version.js +33 -12
  32. package/package.json +9 -8
  33. package/skills/protobase/SKILL.md +1 -1
  34. package/skills/protobase/references/features/build-and-run.md +3 -0
  35. package/skills/protobase/references/features/compatibility.md +1 -1
  36. package/skills/protobase/references/features/releases.md +2 -1
  37. package/skills/protobase/references/getting-started.md +18 -5
  38. package/skills/protobase/references/guides/api-functions.md +1 -1
  39. package/skills/protobase/references/guides/billing-page.md +4 -4
  40. package/skills/protobase/references/guides/create-page.md +2 -2
  41. package/skills/protobase/references/guides/deploy.md +24 -8
  42. package/skills/protobase/references/guides/field-type.md +1 -1
  43. package/skills/protobase/references/guides/first-plugin.md +1 -1
  44. package/skills/protobase/references/guides/plugin-build.md +1 -1
  45. package/skills/protobase/references/guides/remote-resources.md +1 -1
  46. package/skills/protobase/references/guides/table-to-admin.md +8 -8
  47. package/skills/protobase/references/reference/ai.md +1 -1
  48. package/skills/protobase/references/reference/api.md +4 -4
  49. package/skills/protobase/references/reference/architecture.md +11 -6
  50. package/skills/protobase/references/reference/assistant.md +1 -1
  51. package/skills/protobase/references/reference/auth.md +17 -4
  52. package/skills/protobase/references/reference/blocks.md +1 -1
  53. package/skills/protobase/references/reference/bottom-bar.md +2 -2
  54. package/skills/protobase/references/reference/cli.md +51 -22
  55. package/skills/protobase/references/reference/client.md +3 -1
  56. package/skills/protobase/references/reference/config/api.md +2 -2
  57. package/skills/protobase/references/reference/config/app.md +2 -2
  58. package/skills/protobase/references/reference/config/sign-in.md +2 -3
  59. package/skills/protobase/references/reference/config.md +11 -9
  60. package/skills/protobase/references/reference/custom-components.md +3 -2
  61. package/skills/protobase/references/reference/email.md +4 -4
  62. package/skills/protobase/references/reference/events.md +1 -1
  63. package/skills/protobase/references/reference/jobs.md +6 -5
  64. package/skills/protobase/references/reference/layouts.md +2 -2
  65. package/skills/protobase/references/reference/mcp.md +9 -8
  66. package/skills/protobase/references/reference/notifications.md +10 -8
  67. package/skills/protobase/references/reference/plugins.md +3 -3
  68. package/skills/protobase/references/reference/supabase-realtime.md +36 -2
  69. package/skills/protobase/references/reference/ui-config.md +1 -1
  70. package/skills/protobase/references/reference/user-menu.md +3 -3
  71. package/skills/protobase/references/reference/versioning.md +21 -4
  72. package/skills/protobase/references/reference/webhooks.md +5 -5
@@ -6,11 +6,12 @@ import { configExports } from "@protobase/server/config-exports";
6
6
  //#region src/project/load-data-config.ts
7
7
  /**
8
8
  * The resources, views and pages of a config folder, as the config module has them by convention: config/index.ts and
9
- * every config/<dir>/ui.ts. Only those files and what they import run, not protobase.config.ts, which may need secrets.
9
+ * every config/<dir>/ui.ts, of the project in `projectDir`. Only those files and what they import run, not
10
+ * protobase.config.ts, which may need secrets.
10
11
  */
11
- const loadDataConfig = async (configDir) => {
12
+ const loadDataConfig = async (configDir, projectDir) => {
12
13
  const dirs = uiDirs(configDir);
13
- const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))]);
14
+ const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))], projectDir);
14
15
  const config = conventionConfig(index, dirs.map((dir, i) => [dir, ui[i]]));
15
16
  const { resources, views, pages } = configExports(config);
16
17
  return {
@@ -0,0 +1,66 @@
1
+ import { findPackageDirSync, packageName } from "../build/packages/package-dir.js";
2
+ import { projectPackages } from "../version/project-packages.js";
3
+ import { hostModuleIds } from "../serve/host-module-ids.js";
4
+ import { uiPackageDir } from "./admin-app.js";
5
+ import { protobaseFolder } from "./protobase-folder.js";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { mkdir, writeFile } from "node:fs/promises";
10
+ //#region src/project/project-types.ts
11
+ /** The tsconfig a project's own extends, relative to the project. */
12
+ const typesFile = path.join(protobaseFolder, "tsconfig.json");
13
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
14
+ const typedPackages = [.../* @__PURE__ */ new Set([
15
+ "@protobase/cli",
16
+ "@protobase/client",
17
+ "@protobase/ui",
18
+ ...hostModuleIds.map((id) => packageName(id))
19
+ ])];
20
+ const declarationOf = (dir, target) => {
21
+ if (target === null) return void 0;
22
+ if (typeof target !== "string") {
23
+ const chosen = target.types ?? target.import ?? target.default ?? target.require;
24
+ return chosen === void 0 ? void 0 : declarationOf(dir, chosen);
25
+ }
26
+ const file = path.join(dir, target);
27
+ if (/\.(d\.[mc]?ts|tsx?)$/.test(file)) return existsSync(file) ? file : void 0;
28
+ if (!/\.[mc]?js$/.test(file)) return void 0;
29
+ return [
30
+ ".d.ts",
31
+ ".d.mts",
32
+ ".d.cts"
33
+ ].map((extension) => file.replace(/\.[mc]?js$/, extension)).find((candidate) => existsSync(candidate));
34
+ };
35
+ const packagePaths = (name, dir) => {
36
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
37
+ const exported = manifest.exports;
38
+ return (exported === void 0 || exported === null ? [[".", manifest.types ?? manifest.typings ?? manifest.main ?? "index.js"]] : typeof exported === "string" || !Object.keys(exported).every((key) => key.startsWith(".")) ? [[".", exported]] : Object.entries(exported).filter(([key]) => !key.includes("*"))).flatMap(([sub, target]) => {
39
+ const file = declarationOf(dir, target);
40
+ return file ? [[`${name}${sub.slice(1)}`, file]] : [];
41
+ });
42
+ };
43
+ /**
44
+ * The `paths` that point TypeScript at the CLI's own copies of the packages a bundled project gets from it, each import
45
+ * by name, never `*`, so a package the project lacks still fails as missing.
46
+ */
47
+ const cliTypePaths = (ownDir = cliDir) => Object.fromEntries(typedPackages.flatMap((name) => {
48
+ const dir = findPackageDirSync(name, ownDir) ?? findPackageDirSync(name, uiPackageDir);
49
+ return dir ? packagePaths(name, dir).map(([id, file]) => [id, [file]]) : [];
50
+ }));
51
+ /**
52
+ * Writes `.protobase/tsconfig.json` in `projectDir`, which the project's tsconfig.json extends: in a bundled project
53
+ * its `paths` give the @protobase packages and those the serve runtime supplies the types of the CLI that builds the
54
+ * app, with nothing installed; a locked project's installed packages type themselves, so it holds no paths. The
55
+ * folder ignores itself in git, since the paths are this machine's.
56
+ */
57
+ const writeProjectTypes = async (projectDir) => {
58
+ const folder = path.join(projectDir, protobaseFolder);
59
+ await mkdir(folder, { recursive: true });
60
+ const ignore = path.join(folder, ".gitignore");
61
+ if (!existsSync(ignore)) await writeFile(ignore, "*\n");
62
+ const compilerOptions = projectPackages(projectDir).mode === "bundled" ? { paths: cliTypePaths() } : {};
63
+ await writeFile(path.join(projectDir, typesFile), `${JSON.stringify({ compilerOptions }, null, 2)}\n`);
64
+ };
65
+ //#endregion
66
+ export { cliTypePaths, typesFile, writeProjectTypes };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,20 @@
1
+ import { hostModuleIds } from "../serve/host-module-ids.js";
2
+ import { provideHostModules } from "../serve/host-modules.js";
3
+ import { cliTypePaths } from "../project/project-types.js";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/run/preload.ts
6
+ const bun = globalThis.Bun;
7
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
8
+ provideHostModules();
9
+ const others = Object.keys(cliTypePaths()).filter((id) => id.startsWith("@protobase/") && !hostModuleIds.includes(id));
10
+ bun.plugin({
11
+ name: "protobase-cli-modules",
12
+ setup: (build) => {
13
+ for (const id of others) build.module(id, async () => ({
14
+ exports: await import(bun.resolveSync(id, cliDir)),
15
+ loader: "object"
16
+ }));
17
+ }
18
+ });
19
+ //#endregion
20
+ export {};
@@ -0,0 +1,36 @@
1
+ import { projectPackages } from "../version/project-packages.js";
2
+ import { moduleFile } from "../module-file.js";
3
+ import { spawn } from "node:child_process";
4
+ //#region src/run/run-script.ts
5
+ const preload = moduleFile("./preload", import.meta.url);
6
+ /**
7
+ * The Bun command line that runs `file` with `args` for the project in `projectDir`: never installing a missing package,
8
+ * and in a bundled project with the CLI's own copies of the @protobase packages and those the serve runtime supplies
9
+ * (see preload.ts). A locked project's script imports its installed packages.
10
+ */
11
+ const scriptCommand = (projectDir, file, args) => [
12
+ "--no-install",
13
+ ...projectPackages(projectDir).mode === "bundled" ? ["--preload", preload] : [],
14
+ file,
15
+ ...args
16
+ ];
17
+ /**
18
+ * Runs a project script, such as a seed or a migration, under Bun in a process of its own, in `projectDir`, and
19
+ * resolves with its exit code. Its output goes to this process's, so a host that captures that captures it too.
20
+ */
21
+ const runScript = (projectDir, file, args) => new Promise((resolve, reject) => {
22
+ const child = spawn("bun", scriptCommand(projectDir, file, args), {
23
+ cwd: projectDir,
24
+ stdio: [
25
+ "inherit",
26
+ "pipe",
27
+ "pipe"
28
+ ]
29
+ });
30
+ child.stdout.on("data", (chunk) => process.stdout.write(chunk));
31
+ child.stderr.on("data", (chunk) => process.stderr.write(chunk));
32
+ child.once("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error("protobase run needs Bun: install it from https://bun.sh") : error));
33
+ child.once("close", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
34
+ });
35
+ //#endregion
36
+ export { runScript, scriptCommand };
@@ -8,6 +8,7 @@ import { importPlan, probedExtensions } from "./import-plan.js";
8
8
  import { importState } from "./import-state.js";
9
9
  import { writeMigration } from "./migration-files.js";
10
10
  import { runPgTool } from "./pg-tools.js";
11
+ import { realtimeMigration, realtimePolicies } from "./realtime-policies.js";
11
12
  import { replayScript } from "./replay.js";
12
13
  import { schemaMigration } from "./schema-migration.js";
13
14
  import { refuseSsoUsers, ssoUserCount } from "./sso-users.js";
@@ -88,6 +89,7 @@ const readSource = async (sql, targetUrl) => {
88
89
  routinesLeftOut: await routinesIn(sql, schemas, plan.missing.languages)
89
90
  },
90
91
  plan,
92
+ realtimePolicies: await realtimePolicies((text, params) => sql.unsafe(text, params)),
91
93
  replay: replayScript({
92
94
  secrets: secrets ?? [],
93
95
  queues: replayed,
@@ -120,8 +122,9 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
120
122
  /**
121
123
  * The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
122
124
  * the project's next migration, with the extensions the project's database can create, and the columns Better Auth
123
- * needs on auth.users as the one after, points the app's Better Auth setup at auth.users in place of the user table
124
- * the project's auth migrations make, removing them, and keeps the data dump, the replay of Vault's secrets, pgmq's
125
+ * needs on auth.users as the one after, then `realtime.messages` with its policies, which authorize private Realtime
126
+ * channels, when the source has any, points the app's Better Auth setup at auth.users in place of the user table the
127
+ * project's auth migrations make, removing them, and keeps the data dump, the replay of Vault's secrets, pgmq's
125
128
  * queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads it, once the
126
129
  * project's migrations are applied.
127
130
  */
@@ -140,8 +143,8 @@ const runDumpPhase = async (options, out) => {
140
143
  const [exported] = await reserved`select pg_export_snapshot() as snapshot`;
141
144
  const snapshot = exported.snapshot;
142
145
  refuseSsoUsers(await ssoUserCount((text) => reserved.unsafe(text)));
143
- const { manifest: source, plan, replay } = await readSource(reserved, options.targetUrl);
144
- const created = await checkTarget(options.targetUrl, source.schemas, source.tables);
146
+ const { manifest: source, plan, realtimePolicies: policies, replay } = await readSource(reserved, options.targetUrl);
147
+ const created = await checkTarget(options.targetUrl, policies.length > 0 ? [...source.schemas, "realtime"] : source.schemas, source.tables);
145
148
  if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
146
149
  await state.prepare();
147
150
  const schemaFile = path.join(state.dir, "schema.sql");
@@ -172,6 +175,7 @@ const runDumpPhase = async (options, out) => {
172
175
  await mkdir(options.migrationsDir, { recursive: true });
173
176
  const file = await writeMigration(options.migrationsDir, "supabase_schema", migration.text);
174
177
  const usersFile = await writeMigration(options.migrationsDir, "supabase_users", usersColumnsMigration());
178
+ const realtimeFile = policies.length > 0 ? await writeMigration(options.migrationsDir, "supabase_realtime", realtimeMigration(policies)) : void 0;
175
179
  await authConfig.write();
176
180
  for (const store of storeMigrations) await rm(path.join(options.migrationsDir, store));
177
181
  const packages = await writeFunctions(options.projectDir, functions);
@@ -189,6 +193,7 @@ const runDumpPhase = async (options, out) => {
189
193
  const relative = (to) => path.relative(options.projectDir, to);
190
194
  out(`wrote ${relative(path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
191
195
  out(`wrote ${relative(path.join(options.migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
196
+ if (realtimeFile) out(`wrote ${relative(path.join(options.migrationsDir, realtimeFile))}, realtime.messages with its ${policies.length} policies, which authorize private Realtime channels\n`);
192
197
  for (const store of storeMigrations) out(`removed ${relative(path.join(options.migrationsDir, store))}: auth.users replaces Protobase's own user table it made\n`);
193
198
  if (functions.functions.length > 0) out(`converted ${functions.functions.length} Edge Functions into functions/${packages.length > 0 ? `, adding ${packages.length} packages to package.json: install them` : ""}\n`);
194
199
  out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
@@ -37,13 +37,14 @@ const checkReady = async (url, projectDir, manifest) => {
37
37
  await sql.end();
38
38
  }
39
39
  };
40
- /** `protobase doctor`'s output on the config at `configDir`, or `undefined` when there is none. */
41
- const doctorOutput = async (url, configDir) => {
40
+ /** `protobase doctor`'s output on the config at `configDir` of the project in `projectDir`, or `undefined` when there is none. */
41
+ const doctorOutput = async (url, configDir, projectDir) => {
42
42
  if (!existsSync(path.join(configDir, "index.ts"))) return void 0;
43
43
  let text = "";
44
44
  await runDoctor({
45
45
  url,
46
- configDir
46
+ configDir,
47
+ projectDir
47
48
  }, (line) => text += line);
48
49
  return text;
49
50
  };
@@ -106,7 +107,7 @@ const runLoadPhase = async (options, out) => {
106
107
  out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, accountsFile))}, the users' accounts with their Supabase passwords and social providers\n`);
107
108
  const target = connect(options.targetUrl);
108
109
  const providers = await providerCounts(target).finally(() => target.end());
109
- await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir), jobsWired, live, providers), { mode: 384 });
110
+ await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir, options.projectDir), jobsWired, live, providers), { mode: 384 });
110
111
  out(`wrote ${path.relative(options.projectDir, state.report)}: what the import could not carry over\n`);
111
112
  out("next: apply the migrations with the project's migrations; Supabase's users then sign in with their own passwords\n");
112
113
  };
@@ -0,0 +1,60 @@
1
+ import { isSupabaseRole } from "./rewrite.js";
2
+ //#region src/supabase/realtime-policies.ts
3
+ /**
4
+ * The source's row security policies on `realtime.messages`, which authorize private Realtime channels, their
5
+ * expressions read with an empty search_path so that every name in them is schema-qualified; it is put back after, for
6
+ * the reads that follow in the same transaction.
7
+ */
8
+ const realtimePolicies = async (query) => {
9
+ const [setting] = await query("select current_setting('search_path') as path");
10
+ await query("select set_config('search_path', '', true)");
11
+ const policies = await query(`select policyname as name, permissive = 'PERMISSIVE' as permissive, roles::text[] as roles, cmd as command, qual as "using", with_check as "withCheck"
12
+ from pg_policies where schemaname = 'realtime' and tablename = 'messages' order by policyname`);
13
+ await query("select set_config('search_path', $1, true)", [setting.path]);
14
+ return policies;
15
+ };
16
+ const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
17
+ const schema = `create schema realtime;
18
+
19
+ create table realtime.messages (
20
+ topic text not null,
21
+ extension text not null,
22
+ payload jsonb,
23
+ event text,
24
+ private boolean,
25
+ updated_at timestamp without time zone not null default now(),
26
+ inserted_at timestamp without time zone not null default now(),
27
+ id uuid not null default gen_random_uuid() primary key
28
+ );
29
+
30
+ create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
31
+
32
+ alter table realtime.messages enable row level security;
33
+ grant usage on schema realtime to anon, authenticated, service_role;
34
+ grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
35
+ `;
36
+ const policySql = (policy) => {
37
+ const roles = policy.roles.filter((role) => !isSupabaseRole(role));
38
+ if (roles.length === 0) return `-- Left out by protobase import supabase: the policy ${JSON.stringify(policy.name)} names only Supabase's own roles.\n`;
39
+ return [
40
+ `create policy ${quoted(policy.name)} on realtime.messages as ${policy.permissive ? "permissive" : "restrictive"} for ${policy.command}`,
41
+ ` to ${roles.map((role) => role === "public" ? "public" : quoted(role)).join(", ")}`,
42
+ policy.using === null ? "" : ` using (${policy.using})`,
43
+ policy.withCheck === null ? "" : ` with check (${policy.withCheck})`,
44
+ ";\n"
45
+ ].join("");
46
+ };
47
+ /**
48
+ * The migration that makes Supabase's `realtime.messages` and `realtime.topic()` with the source's policies on it, which
49
+ * decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The role that applies it owns the
50
+ * table; the server's probes need the app's database role to own it or to bypass row security.
51
+ */
52
+ const realtimeMigration = (policies) => [
53
+ "-- realtime.messages of a Supabase database with its row security policies, which authorize private Realtime\n",
54
+ "-- channels, written by `protobase import supabase`.\n\n",
55
+ schema,
56
+ "\n",
57
+ ...policies.map(policySql)
58
+ ].join("");
59
+ //#endregion
60
+ export { realtimeMigration, realtimePolicies };
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/version/project-packages.ts
4
+ const fields = [
5
+ "dependencies",
6
+ "devDependencies",
7
+ "optionalDependencies",
8
+ "peerDependencies"
9
+ ];
10
+ /** The @protobase packages the package.json in `projectDir` lists, each with its field and specifier; none without one. */
11
+ const listedPackages = (projectDir) => {
12
+ const file = path.join(projectDir, "package.json");
13
+ if (!existsSync(file)) return [];
14
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
15
+ return fields.flatMap((field) => Object.entries(manifest[field] ?? {}).flatMap(([name, specifier]) => name.startsWith("@protobase/") ? [{
16
+ field,
17
+ name,
18
+ specifier
19
+ }] : []));
20
+ };
21
+ /** Locked when any @protobase package is listed in dependencies, otherwise bundled. */
22
+ const modeOf = (listed) => listed.some((entry) => entry.field === "dependencies") ? "locked" : "bundled";
23
+ /**
24
+ * The project's mode and Protobase version specifier, from the package.json in `projectDir`. Every @protobase package
25
+ * it lists must carry the same specifier: they are released together and pass values to each other.
26
+ */
27
+ const projectPackages = (projectDir) => {
28
+ const listed = listedPackages(projectDir);
29
+ const [first] = listed;
30
+ if (!first) return { mode: "bundled" };
31
+ const other = listed.find((entry) => entry.specifier !== first.specifier);
32
+ if (other) throw new Error(`${path.join(projectDir, "package.json")} lists ${first.name} at ${first.specifier} and ${other.name} at ${other.specifier}; list every @protobase package at the same version`);
33
+ return {
34
+ mode: modeOf(listed),
35
+ specifier: first.specifier
36
+ };
37
+ };
38
+ //#endregion
39
+ export { listedPackages, modeOf, projectPackages };
@@ -1,35 +1,56 @@
1
1
  import { protobaseVersion } from "./version.js";
2
2
  import { findPackageDirSync } from "../build/packages/package-dir.js";
3
+ import { projectPackages } from "./project-packages.js";
3
4
  import { readFileSync } from "node:fs";
4
5
  import path from "node:path";
5
6
  import semver from "semver";
6
7
  //#region src/version/project-version.ts
7
- const projectPackages = [
8
+ const installedPackages = [
8
9
  "@protobase/cli",
9
10
  "@protobase/server",
10
11
  "@protobase/ui"
11
12
  ];
12
13
  /**
13
- * The Protobase version the project in `projectDir` is pinned to: the version its lockfile installed, read from the
14
+ * The Protobase version installed for the project in `projectDir`: the version its lockfile installed, read from the
14
15
  * @protobase package Node's resolution finds from there. Undefined outside a project, or before its install.
15
16
  */
16
17
  const projectProtobaseVersion = (projectDir) => {
17
- for (const name of projectPackages) {
18
+ for (const name of installedPackages) {
18
19
  const dir = findPackageDirSync(name, projectDir);
19
20
  if (dir) return JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).version;
20
21
  }
21
22
  };
22
23
  /**
23
- * Refuses a project whose Protobase version this CLI is not compatible with, the one version check the CLI makes: the
24
- * CLI's version must be in the caret range of the project's, so from 1.0 on the same major and below 1.0, where a minor
25
- * may break, the same minor, and never older. Outside a project, or before its install, there is nothing to check.
24
+ * The Protobase version a bundle of the project in `projectDir` runs on, its manifest's `protobase`: the version of the
25
+ * copies the build uses, the CLI's own in a bundled project and the installed ones in a locked project, which fails
26
+ * before its install.
26
27
  */
27
- const checkProjectVersion = (projectDir, cliVersion = protobaseVersion) => {
28
- const project = projectProtobaseVersion(projectDir);
29
- if (project === void 0) return;
30
- const range = `^${project}`;
28
+ const bundleProtobaseVersion = (projectDir, cliVersion = protobaseVersion) => {
29
+ if (projectPackages(projectDir).mode === "bundled") return cliVersion;
30
+ const installed = projectProtobaseVersion(projectDir);
31
+ if (installed === void 0) throw new Error(`${projectDir} lists its @protobase packages in dependencies and has none installed; install the project's dependencies first`);
32
+ return installed;
33
+ };
34
+ const checkInstalled = (projectDir, cliVersion) => {
35
+ const installed = projectProtobaseVersion(projectDir);
36
+ if (installed === void 0) return;
37
+ const range = `^${installed}`;
31
38
  if (semver.satisfies(cliVersion, range)) return;
32
- throw new Error(`This project is on Protobase ${project}, and this CLI is Protobase ${cliVersion}: run it with a Protobase ${range} CLI`);
39
+ throw new Error(`This project has Protobase ${installed} installed, and this CLI is Protobase ${cliVersion}: run it with a Protobase ${range} CLI`);
40
+ };
41
+ /**
42
+ * Refuses a project whose Protobase version this CLI does not satisfy, the one version check the CLI makes: the
43
+ * specifier its package.json lists the @protobase packages at must hold the CLI's version, by semver, and in a locked
44
+ * project, whose installed copies run, those must be ones the CLI runs. A specifier that is no semver range, such as
45
+ * `workspace:*`, says no version, so the installed copies are checked instead. Outside a project, or one that lists no
46
+ * @protobase package, there is nothing to check.
47
+ */
48
+ const checkProjectVersion = (projectDir, cliVersion = protobaseVersion) => {
49
+ const { mode, specifier } = projectPackages(projectDir);
50
+ if (specifier === void 0) return;
51
+ const range = semver.validRange(specifier) !== null;
52
+ if (range && !semver.satisfies(cliVersion, specifier)) throw new Error(`This project asks for Protobase ${specifier}, and this CLI is Protobase ${cliVersion}: run it with a CLI whose version ${specifier} holds`);
53
+ if (mode === "locked" || !range) checkInstalled(projectDir, cliVersion);
33
54
  };
34
55
  //#endregion
35
- export { checkProjectVersion, projectProtobaseVersion };
56
+ export { bundleProtobaseVersion, checkProjectVersion, projectProtobaseVersion };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.49.2",
3
+ "version": "0.50.1",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -13,7 +13,8 @@
13
13
  "sideEffects": [
14
14
  "./dist/dev/entry.js",
15
15
  "./dist/dev/api-process.js",
16
- "./dist/serve/main.js"
16
+ "./dist/serve/main.js",
17
+ "./dist/run/preload.js"
17
18
  ],
18
19
  "engines": {
19
20
  "node": ">=22.12.0"
@@ -40,12 +41,12 @@
40
41
  "dependencies": {
41
42
  "@better-auth/core": "^1.7.12",
42
43
  "@hono/node-server": "^2.1.3",
43
- "@protobase/config": "0.49.2",
44
- "@protobase/layout": "0.49.2",
45
- "@protobase/query": "0.49.2",
46
- "@protobase/schema": "0.49.2",
47
- "@protobase/server": "0.49.2",
48
- "@protobase/ui": "0.49.2",
44
+ "@protobase/config": "0.50.1",
45
+ "@protobase/layout": "0.50.1",
46
+ "@protobase/query": "0.50.1",
47
+ "@protobase/schema": "0.50.1",
48
+ "@protobase/server": "0.50.1",
49
+ "@protobase/ui": "0.50.1",
49
50
  "@react-email/render": "^2.1.0",
50
51
  "@scalar/hono-api-reference": "^0.12.10",
51
52
  "@tailwindcss/vite": "^4.3.3",
@@ -11,7 +11,7 @@ Run the CLI as the project does: `npx protobase <command>`, or `bun run protobas
11
11
 
12
12
  ## Everyday workflow
13
13
 
14
- 1. Run `protobase dev`: one process and one port, the admin app and the API; changes to config, layouts and functions show without a restart.
14
+ 1. Run `protobase dev`: one port for the admin app and the API, which runs in a process of its own; changes to config, layouts and functions show without a restart.
15
15
  2. Change the config (`data.ts`, `ui.ts`, layouts) or the app's code.
16
16
  3. Database changes go through the project's migrations, never through startup: `protobase migration` writes the migrations a config feature needs, the project applies them with its own migrate script. See [references/reference/cli.md](references/reference/cli.md#migration).
17
17
 
@@ -6,6 +6,8 @@ Develop, build and run an app, on servers, in containers and on phones.
6
6
 
7
7
  - [Node and Bun](../reference/cli.md#how-it-runs): The `protobase` command runs on Node 22.12 or later or on Bun, and a bundle runs on both unless it is built for Bun only.
8
8
  - [Dev server](../reference/cli.md#dev): The admin app and the API on one port, with changes shown without a restart.
9
+ - [Editor types](../reference/cli.md#types): `protobase types` gives the editor and `tsc` the types of the CLI that builds the app, with nothing installed.
10
+ - [Project scripts](../reference/cli.md#run): `protobase run` runs a seed or a migration script on the CLI's packages.
9
11
  - [Migrations from config](../reference/cli.md#migration): Writes the SQL migrations for what the config turns on, as files of the project.
10
12
  - [User and organization commands](../reference/cli.md#users): Create users, set roles and manage organizations from the terminal.
11
13
  - [Encryption commands](../reference/cli.md#encryption-status): Report and fix plaintext or old-key values of encrypted fields.
@@ -19,4 +21,5 @@ Develop, build and run an app, on servers, in containers and on phones.
19
21
  - [Separate worker](../reference/cli.md#worker): Jobs and event delivery in their own process.
20
22
  - [Container images](../guides/deploy.md#images): A runtime image for each release, for amd64 and arm64.
21
23
  - [Self-hosted image](../guides/deploy.md#a-self-hosted-image): One image with the app inside that serves, migrates and creates the first admin.
24
+ - [Protobase Cloud deploys](../guides/deploy.md#protobase-cloud): A push to the app's GitHub branch builds it, migrates and checks its database in one transaction, and switches to the new version once it answers its health check.
22
25
  - [Mobile apps](../guides/mobile-app.md) (beta): Runs an app on iOS and Android, also on your own iPhone, with sign-in, and builds signed store releases from a section in its config.
@@ -10,5 +10,5 @@ Apps written for other systems that keep working on Protobase, and moving their
10
10
  - [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
11
11
  - [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
12
12
  - [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
13
- - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels.
13
+ - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`.
14
14
  - [Edge Functions](../guides/api-functions.md#functions-moved-from-supabase): Functions moved from Supabase answer at their old addresses.
@@ -6,7 +6,8 @@ How Protobase is released and versioned, and what a release keeps working.
6
6
 
7
7
  - [Releases](../reference/versioning.md#releases): Every fix and feature is released when it lands, as npm packages, published with provenance, and images of one version.
8
8
  - [Version rules](../reference/versioning.md#versions-below-10): Semantic versioning. Below 1.0 a minor version may break.
9
- - [Bundles and runtimes](../reference/versioning.md#bundles-and-runtimes): The CLI runs every project of its major, and a bundle names the version its project is pinned to, for the host to serve it on.
9
+ - [Bundled and locked projects](../reference/versioning.md#bundled-and-locked-projects): A project that lists the `@protobase` packages as dev dependencies, or not at all, runs on the CLI's own and updates with a newer CLI, with nothing of Protobase installed. Listed as dependencies, they lock it to one version.
10
+ - [Bundles and runtimes](../reference/versioning.md#bundles-and-runtimes): The CLI runs every project whose version specifier holds its own version, and a bundle names the version it was built with, for the host to serve it on.
10
11
  - [Plugins keep working](../reference/versioning.md#plugins): Plugins target a plugin API that releases keep.
11
12
  - [Runtime updates](../reference/versioning.md#runtime-updates): Admins see whether the runtime has an update and start it from the app, when the host offers one.
12
13
  - [New version notice](../reference/versioning.md#a-new-version-under-an-open-page): An open page keeps working when the server moves to a new Protobase version, and offers a reload.
@@ -4,13 +4,13 @@
4
4
 
5
5
  Start an app with npm create protobase, install the repository, run the ERP, real estate and property portal examples and learn the development commands.
6
6
 
7
- Protobase is a config-driven admin panel framework for existing Postgres databases. Data config lives in `data.ts`, UI config in `ui.ts`; a Hono server serves the API and a React app renders the admin. Coding agents get the guides and reference of the installed version with [`protobase skill install`](reference/cli.md#skill).
7
+ Protobase is a config-driven admin panel framework for existing Postgres databases. Each resource's data config lives in `config/<resource>/data.ts` and its UI config in `ui.ts`, all exported from `config/index.ts`; the rest of the app, its sign-in, jobs, files and API settings, is one object of data in [`protobase.config.ts`](reference/config.md). A Hono server serves the API and a React app renders the admin. Coding agents get the guides and reference of the installed version with [`protobase skill install`](reference/cli.md#skill).
8
8
 
9
9
  An app's own React code, its components, field types and actions, is a [plugin](reference/plugins.md): built on its own against a plugin API that Protobase's releases keep, and loaded by the admin app when it starts. Protobase maintains the admin app, the API and the server, and a plugin keeps working as the app moves to newer releases, with their fixes and features, without changes of its own. Below 1.0 a new minor version may still change the config, and the bundle is built again for it; the plugins' code stays as it is (see [Who maintains what](reference/plugins.md#who-maintains-what)).
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. 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.
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 `devDependencies` at the caret range of the latest release, so it is [bundled](reference/versioning.md#bundled-and-locked-projects): dev, the build and its scripts run the CLI's own copies, and a newer CLI in that range updates it with no change to its files. It 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
@@ -28,6 +28,19 @@ bun run protobase users create you@example.com --generate-password
28
28
  bun run dev # http://localhost:5173
29
29
  ```
30
30
 
31
+ ### The first table
32
+
33
+ A scratch app starts without resources, so `protobase doctor` refuses it until it has one. A table comes in through a migration, the next file in `db/migrations/`, and `scaffold` writes its resource from the database:
34
+
35
+ ```sh
36
+ # db/migrations/007_customers.sql: create table customers (id bigint generated always as identity primary key, name text not null);
37
+ bun run db:migrate
38
+ bun run protobase scaffold --ui --yes --exclude public.schema_migrations
39
+ bun run protobase doctor
40
+ ```
41
+
42
+ `scaffold` writes `config/customers/data.ts` and `ui.ts` and exports them from `config/index.ts`, where Protobase finds every resource, view and page; `--exclude public.schema_migrations` leaves out the table the migrate script records its migrations in. `bun run dev` shows the new list at once. The [Data config](reference/data-config.md) and [UI config](reference/ui-config.md) say what else a resource can be.
43
+
31
44
  ## Admin over an existing database
32
45
 
33
46
  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`.
@@ -88,14 +101,14 @@ bun run --cwd tests/apps/property-portal dev # http://localhost:517
88
101
  | `bun run test:watch` | `bun run test` in watch mode |
89
102
  | `bun run test:integration` | the database, subprocess and build tests (projects `integration*`), against the Postgres container, among them the real-Postgres tests (`*.postgres.test.ts`) |
90
103
  | `bun run test:smoke` / `node --run test:smoke` | the CLI on Bun or on Node builds the ERP and serves its bundle, whose `€` must come back intact; part of `test:integration` on Bun |
91
- | `bun run presets:write <version> <dir>` | writes each preset to `<dir>/<name>`: a standalone copy of its example with the `@protobase` packages in the caret range of `<version>` (`^x.y.z`, which below 1.0 covers only that minor) and its own `bun.lock` at exactly `<version>`, which must be on npm |
104
+ | `bun run presets:write <version> <dir>` | writes each preset to `<dir>/<name>`: a standalone copy of its example with the `@protobase` packages in `devDependencies`, bundled, in the caret range of `<version>` (`^x.y.z`, which below 1.0 covers only that minor) and its own `bun.lock` at exactly `<version>`, which must be on npm |
92
105
  | `bun run images:context` | the build contexts of the `protobase` and `protobase-dev` images in `dist/images`, at the version in `package.json` (see [Deploy](guides/deploy.md#images)) |
93
106
  | `bun run test:presets` | writes each preset as `bun run presets:write` does it and installs it with Bun from npm (so at a published version), then migrates, seeds, checks, tests and builds it on a database of its own, as a role without superuser rights; needs the Postgres container |
94
107
  | `bun run test:postgres` | the Postgres suite in `tests/postgres/` (Vitest project `postgres`): the ERP's medium seed and the planner's statistics on it, and the jobs and event delivery through PgBouncer; needs the Postgres and PgBouncer containers and `bun run test:db postgres` |
95
108
  | `bun run test:db` | builds the template databases the database tests clone for each run (`protobase_test_template`, `real_estate_test_template`, `property_portal_test_template`, all at small scale, and the empty, auth and jobs `snapshot_*_test_template` the real-Postgres and end-to-end tests clone), when missing or older than what they are built from; without them those tests skip. `bun run test:db postgres` builds the Postgres suite's (`protobase_medium_test_template`, the ERP at medium scale), `bun run test:db snapshots` the ones `test:record` records on (`snapshot_*_test_template`). Tests never use the `protobase`, `real_estate` or `property_portal` databases |
96
109
  | `bun run typecheck` | `tsc --noEmit` |
97
110
  | `bun run check:boundaries` | dependency-cruiser package rules |
98
- | `bun run check` | typecheck + test + test:integration + check:boundaries |
111
+ | `bun run check` | typecheck, the unit, snapshot, integration and end-to-end tests a change affects (all of them without `CHECK_BASE`), and check:boundaries |
99
112
  | `bun run storybook` | Storybook on port 6006 |
100
113
  | `bun run build-storybook` | static Storybook build; its toolbar switches every story between light and dark |
101
114
  | `bun run screenshots` / `bun run screenshots:dark` | screenshots of the stories tagged `website`, in light into `screenshots/`, in dark into `screenshots/dark/` |
@@ -105,4 +118,4 @@ bun run --cwd tests/apps/property-portal dev # http://localhost:517
105
118
  | `bun run release --dry-run` | the next version and its changelog, from the commits since the last release (see [Versioning](reference/versioning.md)) |
106
119
  | `bun run docs:check` | opens every page of the built site in Chromium and fails on console errors and failed requests; `BASE=https://docs.protobase.net` checks the live site |
107
120
 
108
- Each public import is a package in `packages/` (`@protobase/schema`, `layout`, `query`, `client`, `ui`, `server`, and `cli` for the `protobase` command); `packages/presets` writes the projects a new app starts from and is not published; `packages/create-protobase` is `npm create protobase`, with every preset. See [Architecture](reference/architecture.md) for the layout and import rules.
121
+ Each public import is a package in `packages/` (`@protobase/schema`, `layout`, `query`, `client`, `ui`, `server`, `config` for `protobase.config.ts`, `mobile` for `protobase mobile`, and `cli` for the `protobase` command); `packages/presets` writes the projects a new app starts from and is not published; `packages/create-protobase` is `npm create protobase`, with every preset. See [Architecture](reference/architecture.md) for the layout and import rules.
@@ -402,7 +402,7 @@ export default defineFunction({ longQueries: true }, async (request, { db }) =>
402
402
  ```
403
403
 
404
404
  - **Up to 30 seconds** per query, the most any query of an app may run. Work longer than that belongs in steps, such as a [job](../reference/jobs.md) per batch, which takes `longQueries` too.
405
- - **One connection kept for it.** Under `protobase dev` and `serve`, those queries run on a connection of their own, which asks for the longer timeout when it logs in, so long work never takes the connections pages need; a second long call waits for it. A PgBouncer of your own in front of the database must list `statement_timeout` in `track_extra_parameters` to pass that on; Protobase Cloud's does. With a `db` the project exports itself, the option changes nothing.
405
+ - **One connection kept for it.** Under `protobase dev` and `serve`, those queries run on a connection of their own, which asks for the longer timeout when it logs in, so long work never takes the connections pages need; a second long call waits for it. A PgBouncer of your own in front of the database must list `statement_timeout` in `track_extra_parameters` to pass that on; Protobase Cloud's does.
406
406
  - **`records` keep the API's limit,** [`statementTimeoutMs`](../reference/api.md#safety).
407
407
  - **A query past its limit** is stopped, and the call answers `504 statement-timeout` naming the call, its limit and the way out, such as `POST /api/functions/import ran a query longer than the database's statement timeout, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or give it longQueries: true, whose queries may run up to 30 s.` It goes to the app's error hook, `hooks/error.ts`, and the [error tracker](../reference/api.md#error-reporting).
408
408
 
@@ -40,7 +40,7 @@ The card shows the active subscription. `plan.name` and `plan.price` reach throu
40
40
 
41
41
  The two header buttons are named actions of the subscriptions view, each with its own kind of behaviour. The views of the billing schema declare every action this page uses:
42
42
 
43
- ```ts title="config/billing/views.ts"
43
+ ```ts title="config/billing/ui.ts"
44
44
  import { view } from '@protobase/schema'
45
45
  import type { billingProfiles, invoices, paymentMethods, plans, subscriptions } from './billing-config'
46
46
 
@@ -73,7 +73,7 @@ export const invoicesView = view<typeof invoices>('invoices')
73
73
  .actions((a) => [a.action('download', { label: 'Download PDF' })])
74
74
  ```
75
75
 
76
- `a.update('cancel', ...)` sets `status` after its `confirm` question. `a.link` opens its `href`, with `{plan}` filled in from the record: a path in the app (`/plans`) stays in the app, anything else (`https:`, `mailto:`) leaves it. Cancel the plan in the story and the card says there is no active plan, because its `filter` no longer matches.
76
+ `a.update('cancel', ...)` sets `status` after its `confirm` question. `a.link` opens its `href`, with `{plan}` filled in from the record: an `href` leaves the app (`https:`, `mailto:`), while a place in the app is a `to`, such as `{ kind: 'record', resource: 'plans', key: '{plan}' }`; a path in the app as an `href` is refused. Cancel the plan in the story and the card says there is no active plan, because its `filter` no longer matches.
77
77
 
78
78
  ## 2. Who we bill
79
79
 
@@ -260,7 +260,7 @@ export const billing = page(
260
260
 
261
261
  Two things here are not built-in blocks.
262
262
 
263
- `SeatHistory` is a **custom component**. `component('SeatHistory')` declares it for the layout, with its props typed, and the element stays data: `{ type: 'SeatHistory', props: { months: 6 }, custom: true }`. The React code lives in the app, exported under the same name from `protobase.ui.tsx` at the project root, which the admin bundles with itself. Inside a RecordCard, `useLayoutRecord()` gives it the record.
263
+ `SeatHistory` is a **custom component**. `component('SeatHistory')` declares it for the layout, with its props typed, and the element stays data: `{ type: 'SeatHistory', props: { months: 6 }, custom: true }`. The React code lives in the app, exported under the same name from `protobase.ui.tsx` at the project root, which `protobase build` builds into a [plugin](../reference/plugins.md) the admin app loads. Inside a RecordCard, `useLayoutRecord()` gives it the record.
264
264
 
265
265
  "Download PDF" is a named action without built-in behaviour (`a.action('download', ...)`), so it runs the handler registered under its name, with the record, the API client and the router. The ERP example has one of each, its component in a file of its own:
266
266
 
@@ -281,7 +281,7 @@ const send = async ({ record, recordKey, etag, client }: ActionContext) => {
281
281
  export default defineUi({ actions: { send } })
282
282
  ```
283
283
 
284
- The rest is familiar: a paged `Table` of invoices spanning two of the three columns, a count of open invoices, and a `Link` inside the text of a card.
284
+ The rest is familiar: a `Table` of the latest invoices, with a link to all of them, spanning two of the three columns, a count of open invoices, and a `Link` inside the text of a card.
285
285
 
286
286
  If the app has no component registered under a name, the page says so where the component would be, and an action without a handler is disabled:
287
287