@protobase/cli 0.51.0 → 0.51.2

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 (34) hide show
  1. package/dist/cli/package.js +1 -1
  2. package/dist/db/model.d.ts +43 -0
  3. package/dist/doctor/check.js +1 -1
  4. package/dist/doctor/run.js +1 -1
  5. package/dist/infer/defaults.d.ts +3 -0
  6. package/dist/infer/proposal.d.ts +24 -0
  7. package/dist/infer/proposal.js +3 -3
  8. package/dist/infer/type-map.d.ts +3 -0
  9. package/dist/project/project-types.js +6 -2
  10. package/dist/scaffold/drift.d.ts +9 -0
  11. package/dist/scaffold/drift.js +1 -1
  12. package/dist/scaffold/existing-config.d.ts +1 -0
  13. package/dist/scaffold/plan.d.ts +17 -0
  14. package/dist/scaffold/plan.js +1 -1
  15. package/dist/scaffold/prompt.d.ts +11 -0
  16. package/dist/scaffold/prompt.js +18 -17
  17. package/dist/scaffold/protobase-tables.d.ts +8 -0
  18. package/dist/scaffold/run.d.ts +17 -0
  19. package/dist/scaffold/run.js +4 -3
  20. package/dist/scaffold/tables.d.ts +17 -0
  21. package/dist/scaffold/tables.js +47 -0
  22. package/dist/scaffold/ui-file.d.ts +3 -0
  23. package/dist/scaffold-api.d.ts +4 -0
  24. package/dist/scaffold-api.js +4 -0
  25. package/dist/serve/host-modules.js +3 -3
  26. package/dist/supabase/load-phase.js +2 -2
  27. package/package.json +9 -8
  28. package/skills/protobase/references/features/compatibility.md +1 -1
  29. package/skills/protobase/references/features/start-a-project.md +1 -0
  30. package/skills/protobase/references/getting-started.md +29 -2
  31. package/skills/protobase/references/guides/existing-database.md +2 -0
  32. package/skills/protobase/references/reference/architecture.md +2 -2
  33. package/skills/protobase/references/reference/cli.md +3 -1
  34. package/skills/protobase/references/reference/supabase-realtime.md +14 -2
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.51.0";
2
+ var version = "0.51.2";
3
3
  //#endregion
4
4
  export { version };
@@ -0,0 +1,43 @@
1
+ //#region src/db/model.d.ts
2
+ export type DbColumn = {
3
+ name: string;
4
+ position: number;
5
+ typeName: string;
6
+ formatted: string;
7
+ isEnum: boolean;
8
+ enumValues: string[];
9
+ notNull: boolean;
10
+ identity: boolean;
11
+ identityAlways: boolean;
12
+ generated: boolean;
13
+ defaultExpr?: string;
14
+ };
15
+ export type DbForeignKey = {
16
+ columns: string[];
17
+ refSchema: string;
18
+ refTable: string;
19
+ refColumns: string[];
20
+ };
21
+ export type DbIndex = {
22
+ name: string;
23
+ columns: (string | null)[];
24
+ unique: boolean;
25
+ primary: boolean;
26
+ partial: boolean;
27
+ method: string;
28
+ opclasses: string[];
29
+ };
30
+ export type DbCheck = {
31
+ columns: string[];
32
+ definition: string;
33
+ };
34
+ export type DbTable = {
35
+ schema: string;
36
+ name: string;
37
+ kind: 'table' | 'view' | 'materialized view';
38
+ columns: DbColumn[];
39
+ foreignKeys: DbForeignKey[];
40
+ indexes: DbIndex[];
41
+ checks: DbCheck[];
42
+ };
43
+ //#endregion
@@ -1,9 +1,9 @@
1
1
  import { tableKey } from "../db/model.js";
2
2
  import { isUniqueSet, keyColumns } from "../db/keys.js";
3
3
  import { checkEnumValues } from "../infer/check-values.js";
4
- import { typesCompatible } from "../infer/compat.js";
5
4
  import { columnDefault } from "../infer/defaults.js";
6
5
  import { inferKind } from "../infer/type-map.js";
6
+ import { typesCompatible } from "../infer/compat.js";
7
7
  //#region src/doctor/check.ts
8
8
  const quoteIdent = (name) => /^[a-z_][a-z0-9_]*$/.test(name) ? name : `"${name.replaceAll("\"", "\"\"")}"`;
9
9
  const sameValues = (a = [], b = []) => a.length === b.length && a.every((v) => b.includes(v));
@@ -1,6 +1,6 @@
1
- import { loadDataConfig } from "../project/load-data-config.js";
2
1
  import { connect } from "../db/connect.js";
3
2
  import { introspect } from "../db/introspect.js";
3
+ import { loadDataConfig } from "../project/load-data-config.js";
4
4
  import { readOnlyDb } from "../db/read-only-db.js";
5
5
  import { checkResource } from "./check.js";
6
6
  import { indexIssues } from "./index-issues.js";
@@ -0,0 +1,3 @@
1
+ //#region src/infer/defaults.d.ts
2
+ export type DefaultValue = string | number | boolean;
3
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import { BaseType } from "./type-map.js";
2
+ import { DefaultValue } from "./defaults.js";
3
+ //#region src/infer/proposal.d.ts
4
+ export type FieldType = BaseType | 'relation' | 'currency' | 'country';
5
+ export type Proposal = {
6
+ name: string;
7
+ column: string;
8
+ type: FieldType;
9
+ base: BaseType;
10
+ precision?: number;
11
+ scale?: number;
12
+ enumValues?: string[];
13
+ relation?: {
14
+ resource: string;
15
+ columns?: string[];
16
+ };
17
+ optional: boolean;
18
+ defaultValue?: DefaultValue;
19
+ readOnly: boolean;
20
+ dbDefault?: boolean;
21
+ filterable: boolean;
22
+ sortable: boolean;
23
+ };
24
+ //#endregion
@@ -1,10 +1,10 @@
1
1
  import { coverageIndexes } from "../db/keys.js";
2
- import { checkEnumValues } from "./check-values.js";
3
- import { columnDefault } from "./defaults.js";
4
- import { inferKind } from "./type-map.js";
5
2
  import { defaultColumn } from "./default-column.js";
6
3
  import { snakeName } from "./names.js";
7
4
  import { isTenantColumn } from "./tenant.js";
5
+ import { checkEnumValues } from "./check-values.js";
6
+ import { columnDefault } from "./defaults.js";
7
+ import { inferKind } from "./type-map.js";
8
8
  import { indexServes } from "@protobase/query";
9
9
  //#region src/infer/proposal.ts
10
10
  const columnIndexing = (table, column, type) => {
@@ -0,0 +1,3 @@
1
+ //#region src/infer/type-map.d.ts
2
+ export type BaseType = 'integer' | 'bigint' | 'decimal' | 'text' | 'boolean' | 'date' | 'timestamp' | 'uuid' | 'json' | 'enum';
3
+ //#endregion
@@ -52,7 +52,8 @@ const cliTypePaths = (ownDir = cliDir) => Object.fromEntries(typedPackages.flatM
52
52
  * Writes `.protobase/tsconfig.json` in `projectDir`, which the project's tsconfig.json extends: in a bundled project
53
53
  * its `paths` give the @protobase packages and those the serve runtime supplies the types of the CLI that builds the
54
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.
55
+ * folder ignores itself in git, since the paths are this machine's. An unchanged file is left alone: Vite reloads every
56
+ * module on any write to a tsconfig.json, so another command rewriting it would rebuild a running dev server's API.
56
57
  */
57
58
  const writeProjectTypes = async (projectDir) => {
58
59
  const folder = path.join(projectDir, protobaseFolder);
@@ -60,7 +61,10 @@ const writeProjectTypes = async (projectDir) => {
60
61
  const ignore = path.join(folder, ".gitignore");
61
62
  if (!existsSync(ignore)) await writeFile(ignore, "*\n");
62
63
  const compilerOptions = projectPackages(projectDir).mode === "bundled" ? { paths: cliTypePaths() } : {};
63
- await writeFile(path.join(projectDir, typesFile), `${JSON.stringify({ compilerOptions }, null, 2)}\n`);
64
+ const file = path.join(projectDir, typesFile);
65
+ const content = `${JSON.stringify({ compilerOptions }, null, 2)}\n`;
66
+ if (existsSync(file) && readFileSync(file, "utf8") === content) return;
67
+ await writeFile(file, content);
64
68
  };
65
69
  //#endregion
66
70
  export { cliTypePaths, typesFile, writeProjectTypes };
@@ -0,0 +1,9 @@
1
+ import "./existing-config.js";
2
+ //#region src/scaffold/drift.d.ts
3
+ export type Drift = {
4
+ resource: string;
5
+ field: string;
6
+ problem: string;
7
+ suggestion: string;
8
+ };
9
+ //#endregion
@@ -1,6 +1,6 @@
1
- import { typesCompatible } from "../infer/compat.js";
2
1
  import { proposeField } from "../infer/proposal.js";
3
2
  import { renderField } from "../infer/render-field.js";
3
+ import { typesCompatible } from "../infer/compat.js";
4
4
  //#region src/scaffold/drift.ts
5
5
  const sameValues = (a = [], b = []) => a.length === b.length && a.every((v) => b.includes(v));
6
6
  const detectDrift = (existing, table, context) => existing.fields.filter((field) => !field.ignored).flatMap((field) => {
@@ -0,0 +1 @@
1
+ import "ts-morph";
@@ -0,0 +1,17 @@
1
+ import "./existing-config.js";
2
+ import { Drift } from "./drift.js";
3
+ import { ProtobaseSchema } from "./protobase-tables.js";
4
+ //#region src/scaffold/plan.d.ts
5
+ export type FileChange = {
6
+ path: string;
7
+ before?: string;
8
+ after: string;
9
+ };
10
+ export type ScaffoldPlan = {
11
+ changes: FileChange[];
12
+ drift: Drift[];
13
+ warnings: string[];
14
+ skipped: ProtobaseSchema[];
15
+ live: string[];
16
+ };
17
+ //#endregion
@@ -1,5 +1,6 @@
1
1
  import { tableKey } from "../db/model.js";
2
2
  import { keyColumns } from "../db/keys.js";
3
+ import { protobaseSchemas } from "./protobase-tables.js";
3
4
  import { camelCase } from "../infer/names.js";
4
5
  import { findField } from "./existing-config.js";
5
6
  import { proposeField } from "../infer/proposal.js";
@@ -8,7 +9,6 @@ import { detectDrift } from "./drift.js";
8
9
  import { ensureExports } from "./index-file.js";
9
10
  import { assignNames } from "./resource-names.js";
10
11
  import { planResource } from "./resource-plan.js";
11
- import { protobaseSchemas } from "./protobase-tables.js";
12
12
  import { dependencyOrder } from "./table-order.js";
13
13
  import { isExcluded, matchesTarget } from "./targets.js";
14
14
  import { uiFields } from "./ui-fields.js";
@@ -0,0 +1,11 @@
1
+ import { Proposal } from "../infer/proposal.js";
2
+ //#region src/scaffold/prompt.d.ts
3
+ export type DecideContext = {
4
+ table: string;
5
+ required: boolean;
6
+ };
7
+ export type Decide = (proposal: Proposal, context: DecideContext) => Promise<Proposal | null>;
8
+ type Ask = (question: string) => Promise<string>;
9
+ type Write = (text: string) => void;
10
+ export declare const asking: (ask: Ask, write: Write) => Decide;
11
+ //#endregion
@@ -17,12 +17,12 @@ const types = [
17
17
  "currency",
18
18
  "country"
19
19
  ];
20
- const retype = async (proposal, ask) => {
20
+ const retype = async (proposal, ask, write) => {
21
21
  const answer = (await ask(` type (${types.join(", ")}) [${proposal.type}]: `)).trim();
22
22
  if (!answer || answer === proposal.type) return proposal;
23
23
  const type = types.find((t) => t === answer);
24
24
  if (!type) {
25
- process.stdout.write(` unknown type "${answer}", keeping ${proposal.type}\n`);
25
+ write(` unknown type "${answer}", keeping ${proposal.type}\n`);
26
26
  return proposal;
27
27
  }
28
28
  const { enumValues, relation, precision, scale, defaultValue, ...rest } = proposal;
@@ -38,40 +38,41 @@ const retype = async (proposal, ask) => {
38
38
  }
39
39
  return next;
40
40
  };
41
- const edit = async (proposal, ask) => {
41
+ const edit = async (proposal, ask, write) => {
42
42
  const name = (await ask(` field name [${proposal.name}]: `)).trim() || proposal.name;
43
43
  return retype({
44
44
  ...proposal,
45
45
  name
46
- }, ask);
46
+ }, ask, write);
47
47
  };
48
- const interactive = (input = process.stdin, output = process.stdout) => {
49
- const rl = createInterface({
50
- input,
51
- output
52
- });
48
+ const asking = (ask, write) => {
53
49
  let acceptRest = false;
54
- const decide = async (initial, { table, required }) => {
50
+ return async (initial, { table, required }) => {
55
51
  if (acceptRest) return initial;
56
52
  let proposal = initial;
57
53
  for (;;) {
58
- output.write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
59
- const options = required ? "[a]ccept, accept a[l]l, [e]dit" : "[a]ccept, accept a[l]l, [e]dit, [i]gnore";
60
- const answer = (await rl.question(` ${options} (a): `)).trim().toLowerCase() || "a";
54
+ write(`\n${table}.${proposal.column}\n ${proposal.name}: ${renderField(proposal)}\n`);
55
+ const answer = (await ask(` ${required ? "[a]ccept, accept a[l]l, [e]dit" : "[a]ccept, accept a[l]l, [e]dit, [i]gnore"} (a): `)).trim().toLowerCase() || "a";
61
56
  if (answer === "a") return proposal;
62
57
  if (answer === "l") {
63
58
  acceptRest = true;
64
- output.write(" accepting this and every remaining proposal\n");
59
+ write(" accepting this and every remaining proposal\n");
65
60
  return proposal;
66
61
  }
67
- if (answer === "e") proposal = await edit(proposal, (q) => rl.question(q));
62
+ if (answer === "e") proposal = await edit(proposal, ask, write);
68
63
  if (answer === "i" && !required) return null;
69
64
  }
70
65
  };
66
+ };
67
+ const interactive = (input = process.stdin, output = process.stdout) => {
68
+ const rl = createInterface({
69
+ input,
70
+ output
71
+ });
71
72
  return {
72
- decide,
73
+ decide: asking((q) => rl.question(q), (text) => output.write(text)),
73
74
  close: () => rl.close()
74
75
  };
75
76
  };
76
77
  //#endregion
77
- export { acceptAll, interactive };
78
+ export { acceptAll, asking, interactive };
@@ -0,0 +1,8 @@
1
+ import { DbTable } from "../db/model.js";
2
+ //#region src/scaffold/protobase-tables.d.ts
3
+ export type ProtobaseSchema = {
4
+ schema: string;
5
+ what: 'auth store' | 'job queue';
6
+ tables: DbTable[];
7
+ };
8
+ //#endregion
@@ -0,0 +1,17 @@
1
+ import { Decide } from "./prompt.js";
2
+ import { UiSection } from "./ui-file.js";
3
+ import { ScaffoldPlan } from "./plan.js";
4
+ //#region src/scaffold/run.d.ts
5
+ export type ScaffoldOptions = {
6
+ url: string;
7
+ target?: string;
8
+ configDir: string;
9
+ yes: boolean;
10
+ dryRun: boolean;
11
+ ui: UiSection[];
12
+ excludes: string[];
13
+ live?: string[];
14
+ decide?: Decide;
15
+ };
16
+ export declare const runScaffold: (options: ScaffoldOptions, out: (text: string) => void) => Promise<ScaffoldPlan>;
17
+ //#endregion
@@ -18,9 +18,10 @@ const write = async ({ path: file, after }) => {
18
18
  await writeFile(file, after);
19
19
  };
20
20
  const runScaffold = async (options, out) => {
21
- if (!options.yes && !process.stdin.isTTY) throw new Error("Interactive scaffolding needs a terminal; pass --yes to accept all proposals");
21
+ const asks = !options.yes && !options.decide;
22
+ if (asks && !process.stdin.isTTY) throw new Error("Interactive scaffolding needs a terminal; pass --yes to accept all proposals");
22
23
  const sql = connect(options.url);
23
- const prompter = options.yes ? void 0 : interactive();
24
+ const prompter = asks ? interactive() : void 0;
24
25
  const plan = await (async () => {
25
26
  try {
26
27
  return await planScaffold({
@@ -30,7 +31,7 @@ const runScaffold = async (options, out) => {
30
31
  target: parseTarget(options.target),
31
32
  excludes: options.excludes,
32
33
  live: options.live,
33
- decide: prompter?.decide ?? acceptAll,
34
+ decide: options.decide ?? prompter?.decide ?? acceptAll,
34
35
  ui: options.ui,
35
36
  readText
36
37
  });
@@ -0,0 +1,17 @@
1
+ //#region src/scaffold/tables.d.ts
2
+ /**
3
+ * A table scaffold writes a resource over, with its number of columns and the tables among them its foreign keys point
4
+ * to, as schema.table, whose resources its relations name.
5
+ */
6
+ export type ScaffoldTable = {
7
+ schema: string;
8
+ name: string;
9
+ columns: number;
10
+ references: string[];
11
+ };
12
+ /** `scaffoldTables` of the database at `url`, read in one read-only session. */
13
+ export declare const listTables: (url: string) => Promise<{
14
+ tables: ScaffoldTable[];
15
+ skipped: string[];
16
+ }>;
17
+ //#endregion
@@ -0,0 +1,47 @@
1
+ import { connect } from "../db/connect.js";
2
+ import { tableKey } from "../db/model.js";
3
+ import { introspect } from "../db/introspect.js";
4
+ import { keyColumns } from "../db/keys.js";
5
+ import { protobaseSchemas } from "./protobase-tables.js";
6
+ //#region src/scaffold/tables.ts
7
+ /**
8
+ * The tables of a database without a config yet that scaffold, run on all of them, writes resources over, and what it
9
+ * leaves out, each with why: views, tables without a key, and Protobase's own tables, as one line per schema.
10
+ */
11
+ const scaffoldTables = (relations) => {
12
+ const tables = relations.filter((relation) => relation.kind === "table");
13
+ const protobase = protobaseSchemas(tables, {});
14
+ const isProtobase = (relation) => protobase.some(({ schema, tables }) => tables.includes(relation) || schema !== "public" && schema === relation.schema);
15
+ const own = relations.filter((relation) => !isProtobase(relation));
16
+ const skipped = [
17
+ ...own.filter((relation) => relation.kind !== "table").map((view) => `${tableKey(view)}: a ${view.kind}`),
18
+ ...own.filter((table) => table.kind === "table" && !keyColumns(table)).map((table) => `${tableKey(table)}: no primary key or unique NOT NULL index`),
19
+ ...protobase.map(({ schema, what }) => `schema ${schema}: Protobase's ${what}`)
20
+ ];
21
+ const importable = own.filter((table) => table.kind === "table" && keyColumns(table));
22
+ const keys = new Set(importable.map(tableKey));
23
+ const referencesOf = (table) => [...new Set(table.foreignKeys.map((key) => tableKey({
24
+ schema: key.refSchema,
25
+ name: key.refTable
26
+ })).filter((key) => keys.has(key)))];
27
+ return {
28
+ tables: importable.map((table) => ({
29
+ schema: table.schema,
30
+ name: table.name,
31
+ columns: table.columns.length,
32
+ references: referencesOf(table)
33
+ })).sort((a, b) => tableKey(a).localeCompare(tableKey(b))),
34
+ skipped
35
+ };
36
+ };
37
+ /** `scaffoldTables` of the database at `url`, read in one read-only session. */
38
+ const listTables = async (url) => {
39
+ const sql = connect(url);
40
+ try {
41
+ return scaffoldTables(await introspect(sql, { views: true }));
42
+ } finally {
43
+ await sql.end();
44
+ }
45
+ };
46
+ //#endregion
47
+ export { listTables, scaffoldTables };
@@ -0,0 +1,3 @@
1
+ //#region src/scaffold/ui-file.d.ts
2
+ export type UiSection = 'names' | 'list';
3
+ //#endregion
@@ -0,0 +1,4 @@
1
+ import { ScaffoldTable, listTables } from "./scaffold/tables.js";
2
+ import { asking } from "./scaffold/prompt.js";
3
+ import { ScaffoldOptions, runScaffold } from "./scaffold/run.js";
4
+ export { type ScaffoldOptions, type ScaffoldTable, asking, listTables, runScaffold };
@@ -0,0 +1,4 @@
1
+ import { listTables } from "./scaffold/tables.js";
2
+ import { asking } from "./scaffold/prompt.js";
3
+ import { runScaffold } from "./scaffold/run.js";
4
+ export { asking, listTables, runScaffold };
@@ -2,6 +2,9 @@ import * as pg$1 from "pg";
2
2
  import * as server from "@protobase/server";
3
3
  import * as layout from "@protobase/layout";
4
4
  import * as kysely from "kysely";
5
+ import * as postgres$1 from "postgres";
6
+ import * as schema from "@protobase/schema";
7
+ import * as query from "@protobase/query";
5
8
  import * as nodeServer from "@hono/node-server";
6
9
  import * as hono from "hono";
7
10
  import * as reactEmailRender from "@react-email/render";
@@ -13,13 +16,10 @@ import * as honoHttpException from "hono/http-exception";
13
16
  import * as honoValidator from "hono/validator";
14
17
  import * as jose from "jose";
15
18
  import * as kyselyPostgres from "kysely/helpers/postgres";
16
- import * as postgres$1 from "postgres";
17
19
  import * as react from "react";
18
20
  import * as reactJsxRuntime from "react/jsx-runtime";
19
21
  import * as zod from "zod";
20
22
  import * as protobaseConfig from "@protobase/config";
21
- import * as query from "@protobase/query";
22
- import * as schema from "@protobase/schema";
23
23
  //#region src/serve/host-modules.ts
24
24
  const hostModules = {
25
25
  "@protobase/config": protobaseConfig,
@@ -1,8 +1,8 @@
1
1
  import { loadProjectAuth } from "../users/load-auth.js";
2
- import { writeAuthMigration } from "../auth/write-migration.js";
3
2
  import { connect } from "../db/connect.js";
4
- import { runDoctor } from "../doctor/run.js";
5
3
  import { runScaffold } from "../scaffold/run.js";
4
+ import { writeAuthMigration } from "../auth/write-migration.js";
5
+ import { runDoctor } from "../doctor/run.js";
6
6
  import { convertedCronJobs } from "./cron-plan.js";
7
7
  import { importState } from "./import-state.js";
8
8
  import { writeMigration } from "./migration-files.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.51.0",
3
+ "version": "0.51.2",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -21,7 +21,8 @@
21
21
  },
22
22
  "exports": {
23
23
  "./auth": "./dist/project-auth.js",
24
- "./runner": "./dist/runner.js"
24
+ "./runner": "./dist/runner.js",
25
+ "./scaffold": "./dist/scaffold-api.js"
25
26
  },
26
27
  "bin": {
27
28
  "protobase": "./bin/protobase.mjs"
@@ -41,12 +42,12 @@
41
42
  "dependencies": {
42
43
  "@better-auth/core": "^1.7.12",
43
44
  "@hono/node-server": "^2.1.3",
44
- "@protobase/config": "0.51.0",
45
- "@protobase/layout": "0.51.0",
46
- "@protobase/query": "0.51.0",
47
- "@protobase/schema": "0.51.0",
48
- "@protobase/server": "0.51.0",
49
- "@protobase/ui": "0.51.0",
45
+ "@protobase/config": "0.51.2",
46
+ "@protobase/layout": "0.51.2",
47
+ "@protobase/query": "0.51.2",
48
+ "@protobase/schema": "0.51.2",
49
+ "@protobase/server": "0.51.2",
50
+ "@protobase/ui": "0.51.2",
50
51
  "@react-email/render": "^2.1.0",
51
52
  "@scalar/hono-api-reference": "^0.12.10",
52
53
  "@tailwindcss/vite": "^4.3.3",
@@ -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, private ones authorized by the policies on `realtime.messages`.
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`, and broadcasts sent from a server without joining a channel.
14
14
  - [Edge Functions](../guides/api-functions.md#functions-moved-from-supabase): Functions moved from Supabase answer at their old addresses.
@@ -5,6 +5,7 @@
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
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
+ - [Start on an existing database](../getting-started.md#on-an-existing-database): `npm create protobase <database-url>` makes a project on a Postgres database you already have and asks which of its tables become resources, only reading the database.
8
9
  - [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
10
  - [One config](../reference/config.md): The whole app is one object of data in `protobase.config.ts`, typed with `defineConfig`, with a sensible default for every key.
10
11
  - [Code found by path](../reference/config.md#where-the-code-is): The config names jobs, hooks and providers, and Protobase finds their code by its path, such as `jobs/<name>.ts`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Getting started
4
4
 
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.
5
+ Start an app with npm create protobase, on a new database or one you have, install the repository, run the ERP, real estate and property portal examples and learn the development commands.
6
6
 
7
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
 
@@ -41,9 +41,36 @@ bun run protobase doctor
41
41
 
42
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
43
 
44
+ ### On an existing database
45
+
46
+ Given the URL of a Postgres database you already have, `npm create protobase` makes the project on that database:
47
+
48
+ ```sh
49
+ npm create protobase 'postgres://user:password@localhost:5432/shop'
50
+ bun create protobase 'postgres://user:password@localhost:5432/shop'
51
+ pnpm create protobase 'postgres://user:password@localhost:5432/shop'
52
+ ```
53
+
54
+ It connects read-only and names the database and its Postgres version, then asks for the folder, the database's name by default (`npm create protobase my-app <url>` names it). It writes the scratch preset there, with the URL in `.env`, the URL without its password in `.env.example`, and no `docker-compose.yml`, and installs its packages with Bun, or with npm without Bun. It then lists the tables the project's [`scaffold`](reference/cli.md#scaffold) writes resources over, and what it leaves out, with why: views, tables without a primary key or a unique index on columns that are never null, and Protobase's own tables. It asks:
55
+
56
+ - which tables become resources: numbers, ranges such as `2-4` or names, separated by commas, all of them by default. The tables those point to through foreign keys come too, since a relation needs the resource of its table, and it names them;
57
+ - whether each gets a `ui.ts` with its names and list, yes by default;
58
+ - whether to review the field proposed for each column, as `scaffold` asks it, no by default.
59
+
60
+ Then it runs that `scaffold` in the project and prints the next steps. Without a terminal it asks nothing: the folder is the database's name, and every table gets a resource and a `ui.ts`. Quote the URL, as a shell reads `?` and `&` in it. `--preset` is refused with a URL: the project starts from scratch.
61
+
62
+ It never writes to the database. The first of the next steps does: `bun run db:migrate` adds the `auth` schema that sign-in keeps its users in, and `public.schema_migrations`, where the script records the migrations it applied.
63
+
64
+ ```sh
65
+ cd shop
66
+ bun run db:migrate # the first write to the database
67
+ bun run protobase users create you@example.com --generate-password
68
+ bun run dev # http://localhost:5173
69
+ ```
70
+
44
71
  ## Admin over an existing database
45
72
 
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`.
73
+ For a Postgres database you already have, `npm create protobase <database-url>` makes the project, as [above](#on-an-existing-database). [Admin over an existing database](guides/existing-database.md) does it by hand, in a folder of your own: 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`.
47
74
 
48
75
  ## Docs as Markdown
49
76
 
@@ -6,6 +6,8 @@ Put an admin on a Postgres database you already have, in six steps, from install
6
6
 
7
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
8
 
9
+ `npm create protobase <database-url>` does steps 1, 2 and 4 in one go, in a new project, and writes the migration of step 5 for its `bun run db:migrate` to apply: see [On an existing database](../getting-started.md#on-an-existing-database). This guide takes each step by hand, in a folder of your own.
10
+
9
11
  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
12
 
11
13
  ## 1. Install
@@ -17,9 +17,9 @@ A Bun workspace of npm packages under the `@protobase` scope, in `packages/<name
17
17
  | `@protobase/ui` | `packages/ui` | `@protobase/ui`, `@protobase/ui/theme.css`, `@protobase/ui/styles.css`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
18
  | `@protobase/server` | `packages/server` | `@protobase/server`, `@protobase/server/auth-store`, `@protobase/server/config-exports`, `@protobase/server/email`, `@protobase/server/vapid`; `@protobase/server/internal` for the other packages only | server | `schema`, `layout`, `query` |
19
19
  | `@protobase/config` | `packages/config` | `@protobase/config`, `@protobase/config/schema.json` | anywhere | types of `server` only: it runs nothing besides `defineConfig` |
20
- | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
20
+ | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner`, `@protobase/cli/scaffold` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
21
21
  | `@protobase/mobile` | `packages/mobile` | none: the Capacitor packages and native plugins `protobase mobile` installs on first use | the app's iOS and Android projects | none |
22
- | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | none |
22
+ | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | no other `@protobase` package: `postgres` checks a database URL's connection, and `@protobase/cli/scaffold` is loaded from the project it installed |
23
23
  | `@protobase/presets` | `packages/presets` | none: private, `bun run presets:write` writes a project per preset | Bun | none; each preset depends on the `@protobase` packages of the major it is written at, locked at that version |
24
24
  | `tests/apps/*` | | none | any | `@protobase/*` entry points only |
25
25
 
@@ -25,7 +25,7 @@ In this repository nothing needs a build: the packages' `exports` point at `src`
25
25
 
26
26
  ### In another process
27
27
 
28
- 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 for that; `@protobase/cli/auth` exports the other one a script may call, `loadProjectAuth`, which builds the project's sign-in as the `users` commands do (see [Auth](auth.md#first-run)). Nothing else of the CLI is exported:
28
+ 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 for that; `@protobase/cli/auth` exports the other one a script may call, `loadProjectAuth`, which builds the project's sign-in as the `users` commands do (see [Auth](auth.md#first-run)). `@protobase/cli/scaffold` is [`scaffold`](#scaffold) as functions, for `npm create protobase <database-url>`, which loads it from the project it installed: `listTables`, `runScaffold` and `asking`, its column prompt on a question function of the caller's. Nothing else of the CLI is exported:
29
29
 
30
30
  ```ts
31
31
  import { runCommand } from '@protobase/cli/runner'
@@ -63,6 +63,8 @@ Protobase's own tables are left out, since they hold password hashes, OAuth toke
63
63
  | `--ui-list`, `--ui-section <names\|list>` | write only those `ui.ts` sections |
64
64
  | `--exclude <schema[.table]>` | skip tables, repeatable |
65
65
 
66
+ `npm create protobase <database-url>` runs it in the project it makes, on the tables you pick there (see [On an existing database](../getting-started.md#on-an-existing-database)).
67
+
66
68
  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).
67
69
 
68
70
  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.
@@ -28,7 +28,7 @@ A channel may listen to the tables of the resources with [`.live()`](live.md), b
28
28
 
29
29
  ## Broadcast and presence
30
30
 
31
- Channels on the same topic exchange broadcasts and see each other's presence, as on Supabase:
31
+ Channels on the same topic exchange broadcasts and see each other's presence, as on Supabase, private channels among themselves and public ones among themselves:
32
32
 
33
33
  ```ts
34
34
  const room = supabase.channel('room', { config: { broadcast: { self: false, ack: true }, presence: { key: 'alice' } } })
@@ -46,7 +46,19 @@ A broadcast reaches the topic's other channels, and the sender's own with `self`
46
46
 
47
47
  Limits, near Supabase's Free plan, apply per socket and per topic. A socket sends at most 100 broadcast and presence messages a second, joins at most 100 times a second and holds at most 100 channels; on each channel it sends at most 5 presence updates in 30 seconds, also counted across a rejoin. A topic takes 100 broadcasts a second, whoever sends them, so one busy sender can use up a topic's budget. A topic is at most 255 bytes, and a tracked presence at most 10 000 bytes of JSON. A message over a limit gets an error reply and goes to no one, where Supabase would close the channel. A frame over 256 KiB closes the socket with 1009. It closes with 1008 when the client leaves more than 4 MiB unread, or sends more than 300 messages or 4 MiB while earlier ones wait, such as behind a token check.
48
48
 
49
- Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap> <gap>Sending without a joined channel, which supabase-js does over `POST /api/sb/realtime/v1/api/broadcast`, is not supported.</gap>
49
+ Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap>
50
+
51
+ ### Broadcast without a channel
52
+
53
+ A backend or an edge function broadcasts without joining a channel, as on Supabase: supabase-js's `httpSend()`, and `send()` on a channel that has not joined, send it over `POST /api/sb/realtime/v1/api/broadcast`. The request carries the app's key in `apikey` and, for a user, their token in its bearer, as the socket does, and is answered `202`; one without a key of the app is refused with `401`.
54
+
55
+ ```ts
56
+ const room = supabase.channel('room')
57
+ await room.httpSend('cursor', { x: 1, y: 2 })
58
+ await supabase.removeChannel(room)
59
+ ```
60
+
61
+ `POST /api/sb/realtime/v1/api/broadcast` takes Supabase's batch, `{ "messages": [{ "topic": "room", "event": "cursor", "payload": { "x": 1 }, "private": false }] }`, of at most 100 messages, each with an object payload. `httpSend()` sends one message to `POST /api/sb/realtime/v1/api/broadcast/<topic>/events/<event>`, `?private=true` for a private one, with a JSON object or, as `application/octet-stream`, binary bytes. A message reaches the channels joined on its topic in this process, under a broadcast's limits: a body is at most 256 KiB, a topic and an event at most 255 bytes each, and a request that would take a topic over its 100 broadcasts a second is refused with `429` and reaches no one. A public message reaches the topic's public channels; a private one reaches only its private channels that may receive broadcasts, and only when the caller may send broadcasts there by the [policies on `realtime.messages`](#private-channels): a batch drops one it may not send, as Supabase does, and `httpSend()` is refused with `403`. <gap>A policy cannot read a broadcast request's headers in `request.headers` because passing them to the checks is not implemented.</gap>
50
62
 
51
63
  ## Private channels
52
64