@protobase/cli 0.46.12 → 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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.46.12";
2
+ var version = "0.46.13";
3
3
  //#endregion
4
4
  export { version };
@@ -6,16 +6,5 @@ const connect = (url, options = {}) => postgres(url, {
6
6
  onnotice: () => {},
7
7
  connection: { default_transaction_read_only: true }
8
8
  });
9
- /** Whether a command's first argument is a connection string rather than a target. */
10
- const isConnectionString = (value) => /^postgres(ql)?:\/\//.test(value);
11
- const defaultConnectionEnv = "DATABASE_URL";
12
- const resolveConnectionUrl = (arg, envName) => {
13
- if (arg && envName) throw new Error("Pass either a connection string or --env, not both");
14
- if (arg) return arg;
15
- const value = process.env[envName ?? "DATABASE_URL"];
16
- if (value) return value;
17
- if (envName) throw new Error(`Environment variable ${envName} is not set`);
18
- throw new Error(`Pass a connection string or --env <VARIABLE>, or set ${defaultConnectionEnv} in .env`);
19
- };
20
9
  //#endregion
21
- export { connect, defaultConnectionEnv, isConnectionString, resolveConnectionUrl };
10
+ export { connect };
@@ -0,0 +1,14 @@
1
+ //#region src/db/connection-url.ts
2
+ /** Whether a command's first argument is a connection string rather than a target. */
3
+ const isConnectionString = (value) => /^postgres(ql)?:\/\//.test(value);
4
+ const defaultConnectionEnv = "DATABASE_URL";
5
+ const resolveConnectionUrl = (arg, envName) => {
6
+ if (arg && envName) throw new Error("Pass either a connection string or --env, not both");
7
+ if (arg) return arg;
8
+ const value = process.env[envName ?? "DATABASE_URL"];
9
+ if (value) return value;
10
+ if (envName) throw new Error(`Environment variable ${envName} is not set`);
11
+ throw new Error(`Pass a connection string or --env <VARIABLE>, or set ${defaultConnectionEnv} in .env`);
12
+ };
13
+ //#endregion
14
+ export { defaultConnectionEnv, isConnectionString, resolveConnectionUrl };
@@ -1,5 +1,5 @@
1
- import { connect } from "../db/connect.js";
2
1
  import { loadDataConfig } from "../project/load-data-config.js";
2
+ import { connect } from "../db/connect.js";
3
3
  import { introspect } from "../db/introspect.js";
4
4
  import { readOnlyDb } from "../db/read-only-db.js";
5
5
  import { checkResource } from "./check.js";
@@ -0,0 +1,10 @@
1
+ //#region src/exit-signal.ts
2
+ var ExitSignal = class extends Error {
3
+ code;
4
+ constructor(code) {
5
+ super(`The command exited with code ${code}`);
6
+ this.code = code;
7
+ }
8
+ };
9
+ //#endregion
10
+ export { ExitSignal };
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { registerAuth } from "./auth/register.js";
2
- import { isConnectionString, resolveConnectionUrl } from "./db/connect.js";
2
+ import { isConnectionString, resolveConnectionUrl } from "./db/connection-url.js";
3
3
  import { parseHosts } from "./dev/hosts.js";
4
4
  import { loadNearestEnvFile } from "./dev/env.js";
5
5
  import { resolveExtensions } from "./project/extensions.js";
@@ -14,6 +14,7 @@ import { protobaseVersion } from "./version/version.js";
14
14
  import { registerSkill } from "./skill/register.js";
15
15
  import { registerImport } from "./supabase/register.js";
16
16
  import { registerToken, registerUsers } from "./users/register.js";
17
+ import { ExitSignal } from "./exit-signal.js";
17
18
  import { errorMessage } from "./error-message.js";
18
19
  import { statSync } from "node:fs";
19
20
  import path from "node:path";
@@ -149,6 +150,10 @@ registerImport(program);
149
150
  registerMobile(program);
150
151
  registerNotifications(program);
151
152
  const run = (argv) => program.parseAsync(argv).catch((error) => {
153
+ if (error instanceof ExitSignal) {
154
+ process.exitCode = error.code;
155
+ return;
156
+ }
152
157
  process.stderr.write(`error: ${errorMessage(error)}\n`);
153
158
  process.exitCode = 1;
154
159
  });
@@ -1,21 +1,31 @@
1
- import { runnerImport } from "vite";
1
+ import path from "node:path";
2
2
  //#region src/project/import-project-file.ts
3
- const importProjectFile = async (file, plugins = []) => {
4
- const { module } = await runnerImport(file, {
3
+ const runnerImport = async (file, plugins = []) => {
4
+ const { module } = await (await import("vite")).runnerImport(file, {
5
5
  configFile: false,
6
6
  logLevel: "error",
7
7
  plugins
8
8
  });
9
9
  return module;
10
10
  };
11
+ const importProjectFile = async (file) => process.versions.bun ? import(file) : runnerImport(file);
11
12
  /**
12
- * Imports `code` as if it were the project's file `file`, which need not exist: its imports resolve from there, and
13
- * the modules it imports are loaded once, however many of them import each other.
13
+ * Imports several of the project's files in order, so that the modules they share are loaded once. Bun's module cache
14
+ * does that itself; Vite's runner gets them as the imports of one module, which need not exist, beside the first file.
14
15
  */
15
- const importProjectCode = (file, code) => importProjectFile(file, [{
16
- name: "protobase-project-code",
17
- resolveId: (id) => id === file ? `\0${file}` : void 0,
18
- load: (id) => id === `\0${file}` ? code : void 0
19
- }]);
16
+ const importProjectFiles = async (files) => {
17
+ if (process.versions.bun) {
18
+ const modules = [];
19
+ for (const file of files) modules.push(await importProjectFile(file));
20
+ return modules;
21
+ }
22
+ const id = path.join(path.dirname(files[0]), "protobase-project-files.js");
23
+ const code = [...files.map((file, i) => `import * as m${i} from ${JSON.stringify(file)}`), `export const modules = [${files.map((_, i) => `m${i}`).join(", ")}]`].join("\n");
24
+ return (await runnerImport(id, [{
25
+ name: "protobase-project-files",
26
+ resolveId: (source) => source === id ? `\0${id}` : void 0,
27
+ load: (source) => source === `\0${id}` ? code : void 0
28
+ }])).modules;
29
+ };
20
30
  //#endregion
21
- export { importProjectCode, importProjectFile };
31
+ export { importProjectFile, importProjectFiles };
@@ -1,6 +1,6 @@
1
1
  import { conventionConfig } from "./convention.js";
2
2
  import { uiDirs } from "./convention-files.js";
3
- import { importProjectCode } from "./import-project-file.js";
3
+ import { importProjectFiles } from "./import-project-file.js";
4
4
  import path from "node:path";
5
5
  import { configExports } from "@protobase/server";
6
6
  //#region src/project/load-data-config.ts
@@ -10,15 +10,8 @@ import { configExports } from "@protobase/server";
10
10
  */
11
11
  const loadDataConfig = async (configDir) => {
12
12
  const dirs = uiDirs(configDir);
13
- const code = [
14
- `import * as index from ${JSON.stringify(path.join(configDir, "index.ts"))}`,
15
- ...dirs.map((dir, i) => `import * as ui${i} from ${JSON.stringify(path.join(configDir, dir, "ui.ts"))}`),
16
- "export { index }",
17
- `export const ui = [${dirs.map((dir, i) => `[${JSON.stringify(dir)}, ui${i}]`).join(", ")}]`,
18
- ""
19
- ].join("\n");
20
- const loaded = await importProjectCode(path.join(configDir, "protobase-data-config.js"), code);
21
- const config = conventionConfig(loaded.index, loaded.ui);
13
+ const [index, ...ui] = await importProjectFiles([path.join(configDir, "index.ts"), ...dirs.map((dir) => path.join(configDir, dir, "ui.ts"))]);
14
+ const config = conventionConfig(index, dirs.map((dir, i) => [dir, ui[i]]));
22
15
  const { resources, views, pages } = configExports(config);
23
16
  return {
24
17
  models: resources.map((resource) => resource.toModel()),
@@ -0,0 +1,20 @@
1
+ //#region src/runner.d.ts
2
+ export type CommandOptions = {
3
+ /** The folder the command runs in; default: the current one. */
4
+ cwd?: string;
5
+ /** The command's whole environment, as a child process gets it; default: a copy of the current one. */
6
+ env?: Record<string, string | undefined>;
7
+ /** What the command reads from stdin; default: nothing. */
8
+ stdin?: string;
9
+ };
10
+ export type CommandResult = {
11
+ exitCode: number;
12
+ stdout: string;
13
+ stderr: string;
14
+ };
15
+ /**
16
+ * Runs one protobase command in this process, as `protobase <args>` would run in a process of its own, and returns its
17
+ * exit code and output. The CLI stays loaded between commands, so only the first pays for starting it.
18
+ */
19
+ export declare const runCommand: (args: string[], options?: CommandOptions) => Promise<CommandResult>;
20
+ //#endregion
package/dist/runner.js ADDED
@@ -0,0 +1,94 @@
1
+ import { ExitSignal } from "./exit-signal.js";
2
+ import { run } from "./main.js";
3
+ import { createRequire } from "node:module";
4
+ import { realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { Readable } from "node:stream";
7
+ //#region src/runner.ts
8
+ const longRunning = /* @__PURE__ */ new Set([
9
+ "dev",
10
+ "serve",
11
+ "worker",
12
+ "mobile"
13
+ ]);
14
+ const enter = (options, output) => {
15
+ const cwd = process.cwd();
16
+ const env = { ...process.env };
17
+ const exitCode = process.exitCode;
18
+ const { exit } = process;
19
+ const stdin = Object.getOwnPropertyDescriptor(process, "stdin");
20
+ const writeOut = process.stdout.write;
21
+ const writeErr = process.stderr.write;
22
+ const replaceEnv = (next) => {
23
+ for (const name of Object.keys(process.env)) delete process.env[name];
24
+ for (const [name, value] of Object.entries(next)) if (value !== void 0) process.env[name] = value;
25
+ };
26
+ const capture = (stream) => ((chunk) => {
27
+ output[stream] += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
28
+ return true;
29
+ });
30
+ if (options.cwd) process.chdir(options.cwd);
31
+ replaceEnv(options.env ?? env);
32
+ process.exitCode = void 0;
33
+ process.exit = ((code) => {
34
+ throw new ExitSignal(Number(code ?? process.exitCode ?? 0));
35
+ });
36
+ Object.defineProperty(process, "stdin", {
37
+ value: Object.assign(Readable.from(options.stdin ? [options.stdin] : []), { isTTY: false }),
38
+ configurable: true
39
+ });
40
+ process.stdout.write = capture("stdout");
41
+ process.stderr.write = capture("stderr");
42
+ return () => {
43
+ process.stdout.write = writeOut;
44
+ process.stderr.write = writeErr;
45
+ if (stdin) Object.defineProperty(process, "stdin", stdin);
46
+ process.exit = exit;
47
+ process.exitCode = exitCode ?? 0;
48
+ replaceEnv(env);
49
+ process.chdir(cwd);
50
+ };
51
+ };
52
+ const modules = createRequire(import.meta.url).cache;
53
+ const forgetProjectFiles = (projectDir, loadedBefore) => {
54
+ const prefix = realpathSync(projectDir) + path.sep;
55
+ for (const file of Object.keys(modules)) {
56
+ if (loadedBefore.has(file) || !file.startsWith(prefix) || file.includes(`${path.sep}node_modules${path.sep}`)) continue;
57
+ delete modules[file];
58
+ }
59
+ };
60
+ const runOne = async (args, options) => {
61
+ if (longRunning.has(args[0] ?? "")) throw new Error(`protobase ${args[0]} runs until a signal; start it as a process`);
62
+ const output = {
63
+ stdout: "",
64
+ stderr: ""
65
+ };
66
+ const loadedBefore = new Set(Object.keys(modules));
67
+ const leave = enter(options, output);
68
+ try {
69
+ await run([
70
+ "protobase",
71
+ "protobase",
72
+ ...args
73
+ ]);
74
+ return {
75
+ exitCode: Number(process.exitCode ?? 0),
76
+ ...output
77
+ };
78
+ } finally {
79
+ forgetProjectFiles(process.cwd(), loadedBefore);
80
+ leave();
81
+ }
82
+ };
83
+ let queue = Promise.resolve();
84
+ /**
85
+ * Runs one protobase command in this process, as `protobase <args>` would run in a process of its own, and returns its
86
+ * exit code and output. The CLI stays loaded between commands, so only the first pays for starting it.
87
+ */
88
+ const runCommand = (args, options = {}) => {
89
+ const result = queue.then(() => runOne(args, options));
90
+ queue = result.then(() => void 0, () => void 0);
91
+ return result;
92
+ };
93
+ //#endregion
94
+ export { runCommand };
@@ -1,4 +1,3 @@
1
- import * as postgres$1 from "postgres";
2
1
  import * as nodeServer from "@hono/node-server";
3
2
  import * as hono from "hono";
4
3
  import * as server from "@protobase/server";
@@ -13,6 +12,7 @@ import * as honoHttpException from "hono/http-exception";
13
12
  import * as honoValidator from "hono/validator";
14
13
  import * as jose from "jose";
15
14
  import * as kyselyPostgres from "kysely/helpers/postgres";
15
+ import * as postgres$1 from "postgres";
16
16
  import * as react from "react";
17
17
  import * as reactJsxRuntime from "react/jsx-runtime";
18
18
  import * as zod from "zod";
@@ -17,9 +17,9 @@ 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 postgres from "postgres";
21
20
  import { mkdir, readFile, rm } from "node:fs/promises";
22
21
  import { isSchedule } from "@protobase/server";
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. */
25
25
  const checkSupabase = async (sql) => {
@@ -1,5 +1,5 @@
1
- import { connect } from "../db/connect.js";
2
1
  import { writeAuthMigration } from "../auth/write-migration.js";
2
+ import { connect } from "../db/connect.js";
3
3
  import { runDoctor } from "../doctor/run.js";
4
4
  import { runScaffold } from "../scaffold/run.js";
5
5
  import { convertedCronJobs } from "./cron-plan.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.46.12",
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.12",
40
- "@protobase/query": "0.46.12",
41
- "@protobase/schema": "0.46.12",
42
- "@protobase/server": "0.46.12",
43
- "@protobase/ui": "0.46.12",
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",
@@ -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,24 @@ 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
+
20
31
  ## Admin over an existing database
21
32
 
22
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`.
@@ -16,10 +16,26 @@ Any package manager installs the packages, and the command runs on Node or on Bu
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.