@protobase/cli 0.127.3 → 0.127.5

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.127.3";
2
+ var version = "0.127.5";
3
3
  //#endregion
4
4
  export { version };
@@ -1,5 +1,5 @@
1
1
  import { relayAppEntry } from "../relay/app-entry.js";
2
- import { relayBinary } from "./relay-binary.js";
2
+ import { realtimeBinary } from "./realtime-binary.js";
3
3
  import { freePort, relayUrl, startRelay } from "./relay-process.js";
4
4
  import { randomBytes } from "node:crypto";
5
5
  import { checkRelayOptions, defaultRelayChannels } from "@protobase/server";
@@ -22,11 +22,11 @@ const relayEnded = (code) => {
22
22
  };
23
23
  /**
24
24
  * The config with a relay of its own when `realtime.relay` names none: without a `url`, protobase dev runs the relay
25
- * from its npm package for the app at `devUrl`, with keys it makes unless the config sets them, the presence key too, and gives the app its
25
+ * from the pinned Protobase Realtime release (`realtimeBinary`) for the app at `devUrl`, with keys it makes unless the config sets them, the presence key too, and gives the app its
26
26
  * address and keys; its apps file declares the events of `views`' typing conversation pages too, and its channels default to those of the conversation pages with members (`defaultRelayChannels`). It starts on the first load whose config has `realtime.relay`, and again when an edit changes the
27
27
  * app's entry in its apps file; a config without `realtime.relay`, or one with a `url`, stops it.
28
28
  */
29
- const withDevRelay = async (config, projectDir, devUrl, { views, models }) => {
29
+ const withDevRelay = async (config, devUrl, { views, models }) => {
30
30
  const relay = config.realtime?.relay;
31
31
  if (!relay || relay.url) {
32
32
  await stopDevRelay();
@@ -60,7 +60,7 @@ const withDevRelay = async (config, projectDir, devUrl, { views, models }) => {
60
60
  store.__protobaseDevRelay = {
61
61
  entry,
62
62
  url: relayUrl(port),
63
- relay: await startRelay(await relayBinary(projectDir), port, JSON.parse(entry), relayEnded)
63
+ relay: await startRelay(await realtimeBinary(), port, JSON.parse(entry), relayEnded)
64
64
  };
65
65
  }
66
66
  return {
package/dist/dev/entry.js CHANGED
@@ -21,7 +21,7 @@ const relayApp = {
21
21
  views: relayExports?.views.map((view) => view.toModel()) ?? [],
22
22
  models: relayExports?.resources.map((resource) => resource.toModel()) ?? []
23
23
  };
24
- const config = await withDevRelay(loaded, projectDir, process.env.PROTOBASE_DEV_URL, relayApp);
24
+ const config = await withDevRelay(loaded, process.env.PROTOBASE_DEV_URL, relayApp);
25
25
  const database = devDatabase(projectDir);
26
26
  const { db } = database;
27
27
  const project = await buildProject(config, database);
@@ -0,0 +1,60 @@
1
+ import { realtimeAsset, realtimeRelease } from "./realtime-release2.js";
2
+ import { userCacheDir } from "./user-cache-dir.js";
3
+ import path from "node:path";
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ //#region src/dev/realtime-binary.ts
7
+ const realtimeBinaryVariable = "PROTOBASE_REALTIME_BINARY";
8
+ const realtimeDownloadVariable = "PROTOBASE_REALTIME_DOWNLOAD_URL";
9
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
10
+ const readCached = async (file) => {
11
+ try {
12
+ return await readFile(file);
13
+ } catch (error) {
14
+ if (error.code === "ENOENT") return;
15
+ throw error;
16
+ }
17
+ };
18
+ const download = async (url) => {
19
+ const failed = (reason) => /* @__PURE__ */ new Error(`protobase dev could not download Protobase Realtime from ${url} (${reason}): check the connection, or set ${realtimeBinaryVariable} to a binary of your own`);
20
+ let response;
21
+ try {
22
+ response = await fetch(url);
23
+ } catch (error) {
24
+ if (error instanceof TypeError) throw failed("no connection");
25
+ throw error;
26
+ }
27
+ if (!response.ok) throw failed(`HTTP ${response.status}`);
28
+ return new Uint8Array(await response.arrayBuffer());
29
+ };
30
+ /**
31
+ * The path of the Protobase Realtime binary protobase dev runs: `PROTOBASE_REALTIME_BINARY` when it is set, unchecked;
32
+ * otherwise the pinned release's asset for this machine from the cache, its sha256 checked on every call, downloaded
33
+ * from the release's tag on first use or when the cached file no longer matches. A download is written to a file of
34
+ * its own, checked, made executable and only then renamed into place, so runs side by side or one cut off never leave
35
+ * a partial binary in the cache.
36
+ */
37
+ const realtimeBinary = async ({ env = process.env, release = realtimeRelease, cacheDir, platform = process.platform, arch = process.arch } = {}) => {
38
+ const own = env[realtimeBinaryVariable];
39
+ if (own) return path.resolve(own);
40
+ const asset = realtimeAsset(platform, arch);
41
+ const expected = asset && release.sha256[asset];
42
+ if (!asset || !expected) throw new Error(`Protobase Realtime ${release.version} has no build for ${platform}-${arch}: set ${realtimeBinaryVariable} to a binary of your own, or set realtime.relay.url to a running relay`);
43
+ const versionDir = path.join(cacheDir ?? path.join(userCacheDir(env, platform), "protobase", "realtime"), release.version);
44
+ const file = path.join(versionDir, asset);
45
+ const cached = await readCached(file);
46
+ if (cached && sha256(cached) === expected) return file;
47
+ if (cached) await rm(file, { force: true });
48
+ const url = `${env["PROTOBASE_REALTIME_DOWNLOAD_URL"] || "https://github.com/PrototeamHQ/protobase-realtime/releases/download"}/v${release.version}/${asset}`;
49
+ const bytes = await download(url);
50
+ const actual = sha256(bytes);
51
+ if (actual !== expected) throw new Error(`Protobase Realtime from ${url} has sha256 ${actual}, not the pinned ${expected}, so protobase dev does not run it`);
52
+ await mkdir(versionDir, { recursive: true });
53
+ const partial = `${file}.${randomBytes(6).toString("hex")}.partial`;
54
+ await writeFile(partial, bytes);
55
+ await chmod(partial, 493);
56
+ await rename(partial, file);
57
+ return file;
58
+ };
59
+ //#endregion
60
+ export { realtimeBinary, realtimeBinaryVariable, realtimeDownloadVariable };
@@ -0,0 +1,13 @@
1
+ //#region src/dev/realtime-release.json
2
+ var realtime_release_default = {
3
+ version: "0.1.0",
4
+ sha256: {
5
+ "protobase-realtime-linux-amd64": "9222d79cf9b1ad222a7580b4cb40fcd9b47ba8bdd4c6dc6b301eee5c57c73a1f",
6
+ "protobase-realtime-linux-arm64": "417801feaffd70849122fa2de59726f02afb78ce75af71bb21856b8dedca9c83",
7
+ "protobase-realtime-darwin-amd64": "811aed0f1f17623a4b900c5cdc2948e4f23343161f770e13836a2800f48ee793",
8
+ "protobase-realtime-darwin-arm64": "70bacaef85cd6b554556a29e7ca0710ced96036083c7b00da9b064ae94198ae0",
9
+ "protobase-realtime-windows-amd64.exe": "93ecd3fc44ca00b19cd5abf86a0d48da2f76436acf844e86c82f76f05b112cfc"
10
+ }
11
+ };
12
+ //#endregion
13
+ export { realtime_release_default as default };
@@ -0,0 +1,32 @@
1
+ import realtime_release_default from "./realtime-release.js";
2
+ //#region src/dev/realtime-release.ts
3
+ const realtimeRelease = realtime_release_default;
4
+ /** Where the releases' assets are, `<base>/v<version>/<asset>`; `PROTOBASE_REALTIME_DOWNLOAD_URL` replaces it, such as with a mirror. */
5
+ const realtimeDownloadBase = "https://github.com/PrototeamHQ/protobase-realtime/releases/download";
6
+ const goos = {
7
+ linux: "linux",
8
+ darwin: "darwin",
9
+ win32: "windows"
10
+ };
11
+ const goarch = {
12
+ x64: "amd64",
13
+ arm64: "arm64"
14
+ };
15
+ /** The asset of every machine the release must have a build for. */
16
+ const realtimeAssets = [
17
+ "protobase-realtime-linux-amd64",
18
+ "protobase-realtime-linux-arm64",
19
+ "protobase-realtime-darwin-amd64",
20
+ "protobase-realtime-darwin-arm64",
21
+ "protobase-realtime-windows-amd64.exe"
22
+ ];
23
+ /** The asset for `platform` and `arch`, such as `protobase-realtime-linux-amd64`; undefined for a machine the release has no build for. */
24
+ const realtimeAsset = (platform, arch) => {
25
+ const os = goos[platform];
26
+ const cpu = goarch[arch];
27
+ if (!os || !cpu) return;
28
+ const asset = `protobase-realtime-${os}-${cpu}${os === "windows" ? ".exe" : ""}`;
29
+ return realtimeAssets.includes(asset) ? asset : void 0;
30
+ };
31
+ //#endregion
32
+ export { realtimeAsset, realtimeAssets, realtimeDownloadBase, realtimeRelease };
@@ -2,9 +2,9 @@ import { devHost } from "./loopback.js";
2
2
  import path from "node:path";
3
3
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
4
  import { createServer } from "node:net";
5
+ import { tmpdir } from "node:os";
5
6
  import { spawn } from "node:child_process";
6
7
  import { once } from "node:events";
7
- import { tmpdir } from "node:os";
8
8
  //#region src/dev/relay-process.ts
9
9
  /** The address of a relay on the loopback's `port`. */
10
10
  const relayUrl = (port) => `http://${devHost}:${port}`;
@@ -29,8 +29,8 @@ const startRelay = async (binary, port, entry, onExit) => {
29
29
  await writeFile(appsFile, JSON.stringify({ apps: [entry] }), { mode: 384 });
30
30
  const child = spawn(binary, [], {
31
31
  env: {
32
- RELAY_APPS_FILE: appsFile,
33
- RELAY_ADDR: `${devHost}:${port}`
32
+ PROTOBASE_REALTIME_APPS_FILE: appsFile,
33
+ PROTOBASE_REALTIME_ADDR: `${devHost}:${port}`
34
34
  },
35
35
  stdio: [
36
36
  "ignore",
@@ -0,0 +1,11 @@
1
+ import path from "node:path";
2
+ import { homedir } from "node:os";
3
+ //#region src/dev/user-cache-dir.ts
4
+ /** The user's cache folder by the platform's convention: XDG_CACHE_HOME or ~/.cache on Linux, ~/Library/Caches on macOS, LOCALAPPDATA on Windows. */
5
+ const userCacheDir = (env = process.env, platform = process.platform, home = homedir()) => {
6
+ if (platform === "darwin") return path.join(home, "Library", "Caches");
7
+ if (platform === "win32") return env.LOCALAPPDATA || path.join(home, "AppData", "Local");
8
+ return env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(home, ".cache");
9
+ };
10
+ //#endregion
11
+ export { userCacheDir };
@@ -31,4 +31,4 @@ const applyMigrations = async (sql, dir, out) => {
31
31
  return applied;
32
32
  };
33
33
  //#endregion
34
- export { applyMigrations };
34
+ export { applyMigrations, executeFile, lockKey };
@@ -1,15 +1,6 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { projectJobs, projectNotifications, projectResources, projectWebhooks } from "../config/project-parts.js";
3
- import { mailFeedbackOn } from "../config/mail-feedback-config.js";
4
- import { unsubscribeOn } from "../config/unsubscribe-config.js";
5
- import { userTablesOn } from "../config/user-tables-config.js";
6
- import { projectAuth } from "../config/build-project.js";
7
2
  import { loadSourceConfig } from "../config/source-config.js";
8
3
  import { withDevUrl } from "../config/tool-url.js";
9
- import { openAppDatabase } from "../project/pg-db.js";
10
- import pg from "pg";
11
- import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
12
- import { checkStatusOptions } from "@protobase/server/internal";
13
4
  //#region src/migration/load-project.ts
14
5
  /**
15
6
  * The config of the project in `dir` as `protobase dev` merges it: protobase.config.ts, with the convention's resources
@@ -23,46 +14,5 @@ const loadMigrationConfig = async (dir, extensions = []) => {
23
14
  extensions
24
15
  }), dir);
25
16
  };
26
- /**
27
- * A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, and the
28
- * features that write migrations. `close` ends the pool.
29
- */
30
- const migrationProject = async (config, url) => {
31
- if (!url) throw new Error("No database: set DATABASE_URL");
32
- const database = openAppDatabase(pg, url);
33
- const [resources, jobs, webhooks, notifications, auth] = await Promise.all([
34
- projectResources(config),
35
- projectJobs(config),
36
- projectWebhooks(config),
37
- projectNotifications(config),
38
- projectAuth(config, database)
39
- ]);
40
- const exported = configExports(resources);
41
- return {
42
- models: exported.resources.map((source) => source.toModel()),
43
- views: exported.views.map((source) => source.toModel()),
44
- db: database.db,
45
- ...auth && { auth },
46
- ...config.events && { events: config.events },
47
- ...webhooks && { webhooks },
48
- ...config.workflows && { workflows: config.workflows },
49
- ...config.realtime && { realtime: config.realtime },
50
- ...config.calls && { calls: config.calls },
51
- ...notifications && { notifications },
52
- ...config.status && { status: checkStatusOptions(config.status) },
53
- jobs,
54
- userTables: userTablesOn(config),
55
- unsubscribe: unsubscribeOn(config),
56
- mailFeedback: mailFeedbackOn(config),
57
- readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
58
- authTables: auth ? authStoreTables(auth) : {
59
- tables: [],
60
- schemas: []
61
- },
62
- close: async () => {
63
- await database.db.destroy();
64
- }
65
- };
66
- };
67
17
  //#endregion
68
- export { loadMigrationConfig, migrationProject };
18
+ export { loadMigrationConfig };
@@ -0,0 +1,53 @@
1
+ import { projectJobs, projectNotifications, projectResources, projectWebhooks } from "../config/project-parts.js";
2
+ import { mailFeedbackOn } from "../config/mail-feedback-config.js";
3
+ import { unsubscribeOn } from "../config/unsubscribe-config.js";
4
+ import { userTablesOn } from "../config/user-tables-config.js";
5
+ import { projectAuth } from "../config/build-project.js";
6
+ import { openAppDatabase } from "../project/pg-db.js";
7
+ import pg from "pg";
8
+ import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
9
+ import { checkStatusOptions } from "@protobase/server/internal";
10
+ //#region src/migration/migration-project.ts
11
+ /**
12
+ * A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, and the
13
+ * features that write migrations. `close` ends the pool.
14
+ */
15
+ const migrationProject = async (config, url) => {
16
+ if (!url) throw new Error("No database: set DATABASE_URL");
17
+ const database = openAppDatabase(pg, url);
18
+ const [resources, jobs, webhooks, notifications, auth] = await Promise.all([
19
+ projectResources(config),
20
+ projectJobs(config),
21
+ projectWebhooks(config),
22
+ projectNotifications(config),
23
+ projectAuth(config, database)
24
+ ]);
25
+ const exported = configExports(resources);
26
+ return {
27
+ models: exported.resources.map((source) => source.toModel()),
28
+ views: exported.views.map((source) => source.toModel()),
29
+ db: database.db,
30
+ ...auth && { auth },
31
+ ...config.events && { events: config.events },
32
+ ...webhooks && { webhooks },
33
+ ...config.workflows && { workflows: config.workflows },
34
+ ...config.realtime && { realtime: config.realtime },
35
+ ...config.calls && { calls: config.calls },
36
+ ...notifications && { notifications },
37
+ ...config.status && { status: checkStatusOptions(config.status) },
38
+ jobs,
39
+ userTables: userTablesOn(config),
40
+ unsubscribe: unsubscribeOn(config),
41
+ mailFeedback: mailFeedbackOn(config),
42
+ readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
43
+ authTables: auth ? authStoreTables(auth) : {
44
+ tables: [],
45
+ schemas: []
46
+ },
47
+ close: async () => {
48
+ await database.db.destroy();
49
+ }
50
+ };
51
+ };
52
+ //#endregion
53
+ export { migrationProject };
@@ -9,17 +9,23 @@ const appliedNames = async (tx) => {
9
9
  if (record.earlier) return (await tx`select name from public.schema_migrations`).map((row) => row.name);
10
10
  return [];
11
11
  };
12
+ /** The `*.sql` files of `dir` the database has not recorded as applied, in their order, read in the transaction `tx`. */
13
+ const pendingIn = async (tx, dir) => {
14
+ const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
15
+ const done = new Set(await appliedNames(tx));
16
+ return files.filter((file) => !done.has(file));
17
+ };
18
+ /** `pendingIn`, from a read-only transaction of its own. */
19
+ const pendingMigrations = (sql, dir) => sql.begin("read only", (tx) => pendingIn(tx, dir));
12
20
  /**
13
21
  * `protobase migrate --plan`: prints each `*.sql` file of `dir` that `migrate` would apply, in its order, under its
14
- * name, with its SQL, from a read-only transaction: it applies and records nothing. Returns the names.
22
+ * name, with its SQL: it applies and records nothing. Returns the names.
15
23
  */
16
24
  const planMigrations = async (sql, dir, out) => {
17
- const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
18
- const done = new Set(await sql.begin("read only", (tx) => appliedNames(tx)));
19
- const pending = files.filter((file) => !done.has(file));
25
+ const pending = await pendingMigrations(sql, dir);
20
26
  for (const file of pending) out(`-- ${file}\n${(await readFile(path.join(dir, file), "utf8")).trimEnd()}\n\n`);
21
27
  out(pending.length > 0 ? `${pending.length} migrations to apply; nothing was applied\n` : "the database is up to date\n");
22
28
  return pending;
23
29
  };
24
30
  //#endregion
25
- export { planMigrations };
31
+ export { pendingIn, pendingMigrations, planMigrations };
@@ -44,7 +44,7 @@ const registerMigration = (program) => {
44
44
  return;
45
45
  }
46
46
  const [{ migrationProject }, { migrationParts }, { runMigration }, { migrationSummary }] = await Promise.all([
47
- import("./load-project.js"),
47
+ import("./migration-project.js"),
48
48
  import("./parts.js"),
49
49
  import("./snapshot/run-migration.js"),
50
50
  import("./summary.js")
@@ -0,0 +1,34 @@
1
+ import { executeFile, lockKey } from "../apply-migrations.js";
2
+ //#region src/migration/release/apply-release-steps.ts
3
+ /**
4
+ * Applies the steps `find` gives in one transaction, behind the lock `migrate` takes, each as `migrate` runs a file, so
5
+ * none commits early: when one fails, such as a check that refuses the rows already there, none is applied. `find` runs
6
+ * once the lock is held, so a run that waited on another finds the steps from what that one committed.
7
+ */
8
+ const applyReleaseSteps = async (sql, find, out) => {
9
+ const applied = await sql.begin(async (tx) => {
10
+ await tx`select pg_advisory_xact_lock(${lockKey})`;
11
+ const steps = await find(tx);
12
+ for (const step of steps) {
13
+ out(`applying ${step.name}\n`);
14
+ await tx`select set_config('migrations.file', ${step.sql}, true)`;
15
+ await tx.unsafe(executeFile);
16
+ }
17
+ return steps;
18
+ });
19
+ out(applied.length > 0 ? `applied ${applied.length} steps\n` : "the database is up to date\n");
20
+ };
21
+ /** The steps `find` gives from a read-only transaction, printed as `releaseStepsPlan`: nothing is applied. */
22
+ const planReleaseSteps = async (sql, find, out) => {
23
+ out(releaseStepsPlan(await sql.begin("read only", (tx) => find(tx))));
24
+ };
25
+ /**
26
+ * The steps as one SQL script, each under its title, ending with a comment that says how many there are: what a caller
27
+ * runs in a transaction of its own, which its rollback undoes. It records the auth store's versions itself.
28
+ */
29
+ const releaseStepsPlan = (steps) => {
30
+ if (steps.length === 0) return "-- the database is up to date\n";
31
+ return `${steps.map(({ name, title, sql }) => `-- ${name}: ${title}.\n${sql.trimEnd()}\n`).join("\n")}\n-- ${steps.length} steps to apply; nothing was applied\n`;
32
+ };
33
+ //#endregion
34
+ export { applyReleaseSteps, planReleaseSteps, releaseStepsPlan };
@@ -0,0 +1,28 @@
1
+ import { authMigrationTitle } from "../../auth/migration-file.js";
2
+ import { migrationParts } from "../parts.js";
3
+ import { authSchemaMigration } from "@protobase/server";
4
+ //#region src/migration/release/release-steps.ts
5
+ /**
6
+ * What this release of Protobase still needs of the project's database for every feature its config turns on, compared
7
+ * with the database itself: the auth store by its `auth_migrations` record, the other parts by their schemas, as
8
+ * `protobase migration` compares them. In the order they apply; none when the database is current.
9
+ */
10
+ const releaseSteps = async (project) => {
11
+ const auth = project.auth && await authSchemaMigration(project.auth);
12
+ const steps = auth ? [{
13
+ name: "auth",
14
+ title: authMigrationTitle,
15
+ sql: auth
16
+ }] : [];
17
+ for (const part of migrationParts(project)) {
18
+ const sql = await part.sql({ authWritten: Boolean(auth) });
19
+ if (sql !== void 0) steps.push({
20
+ name: part.name,
21
+ title: part.title,
22
+ sql
23
+ });
24
+ }
25
+ return steps;
26
+ };
27
+ //#endregion
28
+ export { releaseSteps };
@@ -1,6 +1,7 @@
1
1
  import { createAdminInBundle } from "./create-admin.js";
2
2
  import { provideHostModules } from "./host-modules.js";
3
3
  import { migrateBundle } from "./migrate-bundle.js";
4
+ import { migrateRelease } from "./migrate-release.js";
4
5
  import { runtimeProgram } from "./runtime-program.js";
5
6
  import { serveBundlePath } from "./serve-bundle-path.js";
6
7
  //#region src/serve/main.ts
@@ -9,15 +10,20 @@ const fail = (message) => {
9
10
  process.exit(1);
10
11
  };
11
12
  const out = (text) => process.stdout.write(text);
13
+ const exitWhenWritten = () => process.stdout.write("", () => process.exit(0));
12
14
  provideHostModules();
13
15
  await runtimeProgram({
14
16
  serve: async (bundle) => {
15
17
  await serveBundlePath(bundle, process.env, out);
16
18
  },
17
19
  migrate: (bundle) => migrateBundle(bundle, process.env, out),
20
+ migrateRelease: async (bundle, { plan }) => {
21
+ await migrateRelease(bundle, process.env, out, plan);
22
+ exitWhenWritten();
23
+ },
18
24
  createAdmin: async (bundle, email, options) => {
19
25
  await createAdminInBundle(bundle, email, options, out);
20
- process.exit(0);
26
+ exitWhenWritten();
21
27
  }
22
28
  }).parseAsync(process.argv).catch((error) => fail(error.message));
23
29
  //#endregion
@@ -0,0 +1,39 @@
1
+ import { readManifest } from "../bundle/manifest.js";
2
+ import { checkBundleManifest } from "./bundle-manifest.js";
3
+ import { loadBundle } from "./load-bundle.js";
4
+ import { bundleConfigFile } from "../worker/start-worker.js";
5
+ import { migrationProject } from "../migration/migration-project.js";
6
+ import { pendingIn } from "../migration/plan-migrations.js";
7
+ import { applyReleaseSteps, planReleaseSteps } from "../migration/release/apply-release-steps.js";
8
+ import { releaseSteps } from "../migration/release/release-steps.js";
9
+ import path from "node:path";
10
+ import postgres from "postgres";
11
+ //#region src/serve/migrate-release.ts
12
+ /**
13
+ * The runtime's `migrate-release`: brings DATABASE_URL to this release's own schema steps for every feature the
14
+ * bundle's config turns on (see releaseSteps), applied in one transaction, or with `plan` printed as SQL and applied
15
+ * not at all. It writes no file: the steps come from the database and this release. The bundle's own migrations go
16
+ * first, since the steps are compared with the database they made. On a failure the error ends the process.
17
+ */
18
+ const migrateRelease = async (bundle, env, out, plan) => {
19
+ const file = await bundleConfigFile(bundle);
20
+ checkBundleManifest(file);
21
+ const dir = path.dirname(file);
22
+ if (!env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
23
+ const sql = postgres(env.DATABASE_URL, {
24
+ max: 1,
25
+ onnotice: () => {}
26
+ });
27
+ const { migrations } = await readManifest(dir);
28
+ const project = await migrationProject(await loadBundle(file), env.DATABASE_URL);
29
+ const find = async (tx) => {
30
+ const pending = migrations ? await pendingIn(tx, path.join(dir, migrations)) : [];
31
+ if (pending.length > 0) throw new Error(`The database lacks the bundle's migrations ${pending.join(", ")}: apply them first with \`protobase-serve migrate\``);
32
+ return releaseSteps(project);
33
+ };
34
+ await (plan ? planReleaseSteps(sql, find, out) : applyReleaseSteps(sql, find, out));
35
+ await project.close();
36
+ await sql.end();
37
+ };
38
+ //#endregion
39
+ export { migrateRelease };
@@ -9,6 +9,7 @@ const runtimeProgram = (actions) => {
9
9
  const program = new Command("protobase-serve").description("Protobase's serve runtime for a bundle from `protobase build`");
10
10
  program.command("serve", { isDefault: true }).description("Serve a bundle: its folder serves the app and the API, its config module the API alone").argument("<bundle>").action((bundle) => actions.serve(bundle));
11
11
  program.command("migrate").description("Apply the bundle's pending migrations in one transaction, before a new version serves (DATABASE_URL)").argument("<bundle>").action((bundle) => actions.migrate(bundle));
12
+ program.command("migrate-release").description("Apply this release's own schema steps for the features the bundle's config turns on, in one transaction, writing no file (DATABASE_URL)").argument("<bundle>").option("--plan", "print the steps as SQL, and apply nothing", false).action((bundle, opts) => actions.migrateRelease(bundle, { plan: opts.plan }));
12
13
  program.command("create-admin").description("Create an admin user of the bundle's app").argument("<bundle>").argument("<email>").option("--name <name>", "display name").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).addOption(new Option("--password <value>").hideHelp()).action((bundle, email, opts) => {
13
14
  rejectPasswordArgument(opts.password);
14
15
  return actions.createAdmin(bundle, email, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.127.3",
3
+ "version": "0.127.5",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.127.3",
47
- "@protobase/layout": "0.127.3",
48
- "@protobase/query": "0.127.3",
49
- "@protobase/schema": "0.127.3",
50
- "@protobase/server": "0.127.3",
51
- "@protobase/ui": "0.127.3",
52
- "@protobase/workflows": "0.127.3",
46
+ "@protobase/config": "0.127.5",
47
+ "@protobase/layout": "0.127.5",
48
+ "@protobase/query": "0.127.5",
49
+ "@protobase/schema": "0.127.5",
50
+ "@protobase/server": "0.127.5",
51
+ "@protobase/ui": "0.127.5",
52
+ "@protobase/workflows": "0.127.5",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -22,6 +22,7 @@ Develop, build and run an app, on servers, in containers and on phones.
22
22
  - [Serve runtime](../reference/cli.md#serve): Runs a bundle, set by environment variables, with a health check, startup checks, jobs and a clean shutdown. `PROTOBASE_HOST=127.0.0.1` keeps it to this computer.
23
23
  - [Host module list](../reference/cli.md#the-config-module): Each release of `@protobase/cli` carries the modules its runtime supplies to a bundle as `@protobase/cli/host-modules.json`, for a host to check a bundle's imports against the version that serves it.
24
24
  - [Migrations at update time](../guides/deploy.md#migrations): The bundle carries the project's migrations, and the runtime applies them in one transaction before the new version serves.
25
+ - [Release steps](../reference/cli.md#release-steps): `protobase-serve migrate-release` brings a database up to a release's own built-in schema steps straight from a built bundle, with a dry-run plan, without writing files into the project.
25
26
  - [Single-file runtime](../reference/cli.md#build-serve): The runtime as one file, so a host needs only Bun and that file.
26
27
  - [Separate worker](../reference/cli.md#worker): Jobs and event delivery in their own process.
27
28
  - [Container images](../guides/deploy.md#images): A runtime image for each release, for amd64 and arm64.
@@ -17,7 +17,7 @@ The changes of each record, comments on it, and pages that refresh as records ch
17
17
  - [Change stream](../reference/live.md#the-stream): Apps follow record changes over a stream that catches up after a reconnect.
18
18
  - [Polling, then a socket](../reference/live.md#polling-then-a-socket): Apps and Node scripts poll for changes first and switch to a WebSocket after 30 seconds, or at once, falling back to polling while the socket is down.
19
19
  - [Presence](../reference/channels.md#presence) (beta): Apps see who else has a record open and what each of them tracks, such as online or away, for whoever may read the record.
20
- - [Realtime relay](../reference/realtime-relay.md) (in development): Apps hand their realtime connections to a relay, so they and their database can sleep while people stay connected: the app issues connect tickets for signed-in people and visitors, keeps the relay's channel members in step with its members records, tells each channel's members of every change, and closes a session's sockets when it signs out or expires. `protobase dev` runs a relay for the app by itself. An app on a platform that runs the relay, Protobase Realtime, picks up its address and keys from PROTOBASE_REALTIME_URL, PROTOBASE_REALTIME_APP, PROTOBASE_REALTIME_API_KEY, PROTOBASE_REALTIME_TICKET_KEY and PROTOBASE_REALTIME_PRESENCE_KEY; a value in the config wins. `protobase build` writes the app's events and presence for the relay's apps file into the bundle's manifest, and the platform's PROTOBASE_REALTIME_ENABLED switch, true or false, says when it moves the app, an app without realtime.relay too: its conversation pages with members become its channels, whose members Protobase keeps in an indexed table of its own.
20
+ - [Realtime relay](../reference/realtime-relay.md) (in development): Apps hand their realtime connections to a relay, so they and their database can sleep while people stay connected: the app issues connect tickets for signed-in people and visitors, keeps the relay's channel members in step with its members records, tells each channel's members of every change, and closes a session's sockets when it signs out or expires. `protobase dev` runs a relay for the app by itself, downloading Protobase Realtime from its GitHub release on first use. An app on a platform that runs the relay, Protobase Realtime, picks up its address and keys from PROTOBASE_REALTIME_URL, PROTOBASE_REALTIME_APP, PROTOBASE_REALTIME_API_KEY, PROTOBASE_REALTIME_TICKET_KEY and PROTOBASE_REALTIME_PRESENCE_KEY; a value in the config wins. `protobase build` writes the app's events and presence for the relay's apps file into the bundle's manifest, and the platform's PROTOBASE_REALTIME_ENABLED switch, true or false, says when it moves the app, an app without realtime.relay too: its conversation pages with members become its channels, whose members Protobase keeps in an indexed table of its own.
21
21
  - [Relay presence](../reference/realtime-relay.md#presence) (in development): The relay reports who comes online, goes away and goes offline; the app keeps it in a resource of its own, raises that resource's events, so workflows can act when someone goes offline, and tells the people who share a conversation with them, whose sidebar and members page show them online, away or offline.
22
22
  - [Relay in pages](../reference/realtime-relay.md#pages) (in development): Pages follow the relay on one socket: open views stay current from its notices and read again once after a reconnect, conversations show who types, sidebar groups say "typing…" and count unread messages without reading per message, also of a conversation the person was just added to, all by configuration; `client.relay` gives the same from code.
23
23
  - [Relay client events](../reference/realtime-relay.md#client-events) (in development): Each channel resource declares in the config the events its clients may send each other, such as typing, with a schema, a size and a rate.
@@ -32,7 +32,7 @@ The host serves `public/` itself and sends only the manifest's `api` paths to th
32
32
 
33
33
  ## Migrations
34
34
 
35
- Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `migrations.applied` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A database an earlier version migrated keeps its record in `public.schema_migrations`, which `migrate` copies over the first time; a `public.schema_migrations` of another migration tool, without Protobase's `name` and `applied_at` columns, is never read or written. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth store has not applied every auth migration of the new version, which it reads from the store's `auth_migrations` table without comparing its tables (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
35
+ Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `migrations.applied` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A database an earlier version migrated keeps its record in `public.schema_migrations`, which `migrate` copies over the first time; a `public.schema_migrations` of another migration tool, without Protobase's `name` and `applied_at` columns, is never read or written. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth store has not applied every auth migration of the new version, which it reads from the store's `auth_migrations` table without comparing its tables (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts. A host that serves a bundle on a newer release's runtime brings the database to that release's own schema steps with the runtime's [`migrate-release <bundle>`](../reference/cli.md#release-steps), after `migrate` and before the bundle serves there.
36
36
 
37
37
  ## Images
38
38
 
@@ -202,7 +202,7 @@ One port, two processes: Vite serves the admin app from `@protobase/ui`'s `src/a
202
202
  - **Login:** real sign-in only, with the config's `auth`, on by default, or its `authenticate` for tokens of an auth server elsewhere (see [protobase.config.ts](config.md) and [Login with Better Auth](auth.md)). A project with sign-in off and no authenticator fails at startup with a message pointing there, as does one with sign-in on and no `PROTOBASE_SECRET`, one whose auth store has not applied every migration of this version, naming them (see [`auth migration`](#auth-migration)), one with a resource over a table of the auth store, and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there. A `warning` line follows for each way the auth store's tables differ from what the app's sign-in needs, such as a column dropped by hand: the one place Protobase compares them, since `serve` reads the store's record of [migrations](auth.md#migrations) alone.
203
203
  - **Mobile releases:** see [below](#mobile-releases).
204
204
  - **Jobs:** with [jobs](jobs.md) in the config it runs them in the API's process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on. `--no-jobs` runs none of them and delivers none of the app's [events](events.md), webhooks or pushes, for a dev server on the database of a hosted app that already runs them; jobs are still enqueued, for that app to run, and the startup message says `jobs off`.
205
- - **Realtime relay:** with [`realtime.relay`](realtime-relay.md) and no `url`, it runs the relay from `@protobase/realtime`, the project's install or else the CLI's, for the app, gives the app its address and keys, and stops it with the dev server (see [Local development](realtime-relay.md#local-development)).
205
+ - **Realtime relay:** with [`realtime.relay`](realtime-relay.md) and no `url`, it runs the relay for the app, Protobase Realtime downloaded from its GitHub release on first use, its sha256 checked and cached in the user's cache folder (`PROTOBASE_REALTIME_BINARY` runs a build of your own), gives the app its address and keys, and stops it with the dev server (see [Local development](realtime-relay.md#local-development)).
206
206
  - **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). The API's WebSockets, such as an [API function](../guides/api-functions.md#websockets)'s, pass the same check: an upgrade with another Host header is refused with `403`. Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
207
207
  - **Project discovery**, by convention: `config/index.ts` exports the resources (and views), and every `config/*/ui.ts` export that is not already exported by the index is added as a view. Each `functions/<name>.ts` (or `functions/<name>/index.ts`) is an [API function](../guides/api-functions.md) at `/api/functions/<name>`. `protobase.config.ts` (or `protobase.config.json`) in the project root describes the rest as data, and the jobs, hooks and other code it names are found by their paths; see [protobase.config.ts](config.md). Without it, the app runs on the defaults.
208
208
  - **Project UI:** the app imports `protobase.ui.tsx` from the project root, with hot reload, when it exists (see [Custom components](custom-components.md)): the same contract as the plugin `protobase build` makes of it, built into the dev page instead. Layout files are checked as they load, as `protobase build` checks them.
@@ -444,10 +444,27 @@ Bundles the serve runtime (`@protobase/cli`'s `src/serve/main.ts`) and all its d
444
444
  ```sh
445
445
  bun --no-install protobase-serve.js [serve] <bundle> # the folder: the app and the API; the config module: the API
446
446
  bun --no-install protobase-serve.js migrate <bundle> # apply the bundle's migrations to DATABASE_URL
447
+ bun --no-install protobase-serve.js migrate-release <bundle> # [--plan] apply this release's own schema steps to DATABASE_URL
447
448
  bun --no-install protobase-serve.js create-admin <bundle> <email> # [--name <name>] [--generate-password | --password-stdin]
448
449
  ```
449
450
 
450
- `migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind; without `--generate-password` or `--password-stdin` it asks for the password at a hidden prompt. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image) puts the three in a self-hosted image.
451
+ `migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind; without `--generate-password` or `--password-stdin` it asks for the password at a hidden prompt. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image) puts `serve`, `migrate` and `create-admin` in a self-hosted image.
452
+
453
+ ### Release steps
454
+
455
+ A bundle built on one release can be served on the runtime of a newer one, whose built-in schemas may have moved on: new steps of the [sign-in tables](auth.md#migrations), a newer jobs or workflows schema. `migrate-release` brings the database to them straight from the bundle, with no checkout of the project, and writes no file into it:
456
+
457
+ ```sh
458
+ bun --no-install protobase-serve.js migrate <bundle> # the bundle's own migrations first
459
+ bun --no-install protobase-serve.js migrate-release <bundle> --plan # print what this release still needs, as SQL
460
+ bun --no-install protobase-serve.js migrate-release <bundle> # apply it
461
+ ```
462
+
463
+ It loads the bundle's config with the app's settings, as `create-admin` does, and compares every feature the config turns on with the database itself, as [`migration`](#migration) does with `DATABASE_URL` set: the sign-in tables by the versions their `auth_migrations` table records, the jobs, change capture, workflows, notifications and the other built-in schemas by what the database has. It applies what differs in one transaction, behind the lock `migrate` takes, prints each part it applies, such as `applying auth`, or that the database is up to date, so a second run applies nothing. A step whose check refuses the rows already there, such as two From addresses one person entered with different case, stops it with the step's message and exit code 1, and nothing is applied. It refuses a database that lacks any of the bundle's own migrations, since the steps are compared with what they made.
464
+
465
+ `--plan` applies nothing and prints the same statements as one SQL script, each part under a comment, ending with `-- N steps to apply; nothing was applied`. The script records the sign-in versions it applies itself, so a host can run it in a transaction of its own, such as one it rolls back to try it first, or one it commits while nothing else writes.
466
+
467
+ A project that gets the same steps later from its own [`migration`](#migration) applies them without doing any twice: each sign-in step in its files runs only while `auth_migrations` lacks its version, and the other parts are compared with its database.
451
468
 
452
469
  ## `serve`
453
470
 
@@ -489,6 +506,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
489
506
  | `PROTOBASE_SENTRY_DSN` | the DSN of a Sentry-compatible error tracker the app's server and admin app send their errors to, after the config's `errorReporting` ([Error reporting](api.md#error-reporting)); without it nothing is sent |
490
507
  | `PROTOBASE_REALTIME_URL`, `PROTOBASE_REALTIME_APP`, `PROTOBASE_REALTIME_API_KEY`, `PROTOBASE_REALTIME_TICKET_KEY`, `PROTOBASE_REALTIME_PRESENCE_KEY` | the address, the app's id, its API and ticket keys and its presence key of [Protobase Realtime](realtime-relay.md#from-the-platform), the WebSocket relay, each where the config's `realtime.relay` leaves it out; without `realtime.relay` or `PROTOBASE_REALTIME_ENABLED` the relay stays off |
491
508
  | `PROTOBASE_REALTIME_ENABLED` | `true` when the platform moves the app to [Realtime](realtime-relay.md#from-the-platform), with the channels of `realtime.relay` or else of its live resources whose conversation page has `members`; `true` for an app with neither stops the server. Unset or empty is `false`; any other value stops the server |
509
+ | `PROTOBASE_REALTIME_BINARY`, `PROTOBASE_REALTIME_DOWNLOAD_URL` | `protobase dev` only: the path of a [Realtime](realtime-relay.md#local-development) build of your own to run, unchecked, in place of the pinned release it downloads, and the address it downloads that release from, default its GitHub releases |
492
510
  | `PROTOBASE_MAP_STYLE_URL` | the URL of the MapLibre style the record page's [maps](ui-config.md#maps) are drawn with, after the config's `maps`; without it there are no maps |
493
511
  | `PROTOBASE_SOURCES` | other Protobase APIs whose resources the app draws as its own, a JSON list of `{ "url", "label", "resources", "roles"? }` after the config's `remoteResources` ([Remote resources](remote-resources.md#declaring-a-source)) |
494
512
  | `PROTOBASE_FILES_<NAME>`, `PROTOBASE_FILES_RETENTION`, `PROTOBASE_FILES_SECRET` | [file providers](files.md#providers) and their settings, over `files` in the config; a bucket's credentials in `PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` |
@@ -652,7 +670,7 @@ protobase migration up
652
670
 
653
671
  Writes what the config and this version of Protobase need beyond the project's `protobase.snapshot.json` as the project's next migration in `--dir`: one numbered file each run, named after what it holds, such as `004_auth.sql` or `005_changes_webhooks.sql`, after the folder's highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: `-- protobase:id`, a random id of its own, then the version that wrote it, each sign-in module's last step, and the hash of the snapshot's model once it is applied. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
654
672
 
655
- The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization; and `physical`, every schema, table, column and index name the store has. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each version followed by its row in `auth_migrations`, which the server's startup check reads. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. <gap>`protobase migration` cannot write the sign-in store of a project with auth migrations from before `protobase.snapshot.json` because `protobase migration baseline`, which reads the database once to start the snapshot, is not implemented.</gap>
673
+ The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization; and `physical`, every schema, table, column and index name the store has. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each version followed by its row in `auth_migrations`, which the server's startup check reads. Each runs only while `auth_migrations` lacks its version, so a database that has it already, such as one [`migrate-release`](#release-steps) brought to a newer release, skips it. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. <gap>`protobase migration` cannot write the sign-in store of a project with auth migrations from before `protobase.snapshot.json` because `protobase migration baseline`, which reads the database once to start the snapshot, is not implemented.</gap>
656
674
 
657
675
  The rest of the file is what the other features the config enables still need of the database, compared with it, each under its own comment and named in the file name as in brackets: the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`jobs`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`changes`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`computed`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`query`), the [comments table](comments.md#the-table) (`comments`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`workflows`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notifications`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`realtime_relay`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`channel_sends`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets and `realtime.members` with the triggers that keep it from channel records that list their members, also for an app with sign-in and a live resource whose conversation page has `members` (`relay`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`user_tables`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). Those are compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. <gap>`protobase migration` cannot write the jobs, change capture, rollup and other feature schemas from the snapshot because recording their models in it is not implemented.</gap> It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
658
676
 
@@ -75,13 +75,9 @@ export default defineConfig({
75
75
 
76
76
  ## Local development
77
77
 
78
- [`protobase dev`](cli.md#dev) runs a relay of its own when `realtime.relay` has no `url`, such as with `RELAY_URL` unset in `.env`, so local realtime needs no second command. Add the relay's npm package to the project once:
78
+ [`protobase dev`](cli.md#dev) runs a relay of its own when `realtime.relay` has no `url`, such as with `RELAY_URL` unset in `.env`, so local realtime needs nothing installed and no second command. On first use it downloads the Protobase Realtime build for this machine from the GitHub release the CLI pins, checks it against the sha256 the CLI pins for it, and caches it in `protobase/realtime/<version>/` of the user's cache folder (`XDG_CACHE_HOME` or `~/.cache` on Linux, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows); each start checks the cached file again and downloads it anew when it no longer matches. An app without `realtime.relay`, or with a `url`, downloads nothing. `PROTOBASE_REALTIME_BINARY` runs a build of your own instead, unchecked, such as on a machine without a release build or without the network, and `PROTOBASE_REALTIME_DOWNLOAD_URL` downloads the release from a mirror that keeps its `v<version>/<asset>` paths.
79
79
 
80
- ```sh
81
- npm install --save-dev @protobase/realtime
82
- ```
83
-
84
- <gap>`protobase dev` cannot run the relay without the project installing `@protobase/realtime` because the CLI does not depend on it until the package is published.</gap>
80
+ <gap>`protobase dev` cannot download Realtime on Windows on Arm because a release build for it is not implemented.</gap>
85
81
 
86
82
  It starts the relay on the first load of a config with `realtime.relay`, an edit that adds it included, on a free port of `127.0.0.1`, serving this one app with the dev server's origin, and gives the app its address. The keys, the presence key included, are the config's when it sets them, and otherwise made anew for each `protobase dev`. An edit that changes the app's id or keys starts it again, one that removes `realtime.relay` or sets a `url` stops it, and it stops with `dev`. Its own messages, such as an apps file it refuses, show in the terminal. With a `url`, the app uses that relay and `dev` starts none. `dev` reads [the platform's variables](#from-the-platform) for neither: the app's id comes from the config.
87
83
 
@@ -1,30 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import path from "node:path";
3
- import { fileURLToPath, pathToFileURL } from "node:url";
4
- //#region src/dev/relay-binary.ts
5
- const relayPackage = "@protobase/realtime";
6
- const cliDir = fileURLToPath(new URL("../..", import.meta.url));
7
- const resolveFrom = (dir) => {
8
- try {
9
- return createRequire(path.join(dir, "package.json")).resolve(relayPackage);
10
- } catch (error) {
11
- if (error.code === "MODULE_NOT_FOUND") return;
12
- throw error;
13
- }
14
- };
15
- /** The entry of the relay's npm package: the project's own install first, then the CLI's. */
16
- const relayPackageEntry = (projectDir, ownDir = cliDir) => {
17
- const entry = resolveFrom(projectDir) ?? resolveFrom(ownDir);
18
- if (!entry) throw new Error(`realtime.relay has no url, so protobase dev runs a relay of its own from ${relayPackage}, which is not installed: add it to the project's devDependencies, or set realtime.relay.url to a running relay`);
19
- return entry;
20
- };
21
- /** The path of the relay binary for this machine, as the package's `binaryPath()` finds it. */
22
- const relayBinary = async (projectDir, ownDir = cliDir) => {
23
- const { binaryPath } = await import(
24
- /* @vite-ignore */
25
- pathToFileURL(relayPackageEntry(projectDir, ownDir)).href
26
- );
27
- return binaryPath();
28
- };
29
- //#endregion
30
- export { relayBinary, relayPackage, relayPackageEntry };