@protobase/cli 0.46.10 → 0.46.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/auth/register.js +1 -2
  2. package/dist/auth/write-migration.js +1 -1
  3. package/dist/build/app-icons.js +1 -1
  4. package/dist/build/config-bundle.js +1 -1
  5. package/dist/build/deploy-bundle.js +2 -2
  6. package/dist/build/entry-code.js +1 -1
  7. package/dist/build/plugin-build.js +3 -3
  8. package/dist/build/plugin-fields.js +1 -1
  9. package/dist/build/service-worker-code.js +1 -1
  10. package/dist/build/shell.js +2 -2
  11. package/dist/build/ui-check.js +2 -2
  12. package/dist/build/vite-bundle.js +1 -1
  13. package/dist/bundle/manifest.js +1 -1
  14. package/dist/cli/package.js +1 -1
  15. package/dist/db/connect.js +8 -5
  16. package/dist/dev/check-database.js +5 -3
  17. package/dist/dev/entry.d.ts +2 -0
  18. package/dist/dev/entry.js +6 -10
  19. package/dist/dev/login-line.js +21 -0
  20. package/dist/dev/loopback.js +42 -0
  21. package/dist/dev/project.js +2 -2
  22. package/dist/dev/run.js +19 -11
  23. package/dist/dev/startup-logger.js +24 -0
  24. package/dist/doctor/run.js +4 -1
  25. package/dist/encryption/register.js +1 -2
  26. package/dist/error-message.js +15 -0
  27. package/dist/files/register.js +1 -2
  28. package/dist/infer/proposal.js +1 -1
  29. package/dist/main.js +34 -26
  30. package/dist/migration/load-project.js +1 -1
  31. package/dist/migration/register.js +7 -4
  32. package/dist/migration/summary.js +15 -0
  33. package/dist/mobile/local-spec.js +1 -1
  34. package/dist/mobile/run.js +1 -1
  35. package/dist/mobile/web-part.js +2 -2
  36. package/dist/mobile/workspace.js +1 -1
  37. package/dist/notifications/register.js +1 -2
  38. package/dist/organizations/api.js +15 -0
  39. package/dist/organizations/register.js +5 -15
  40. package/dist/project/favicon-link.js +1 -1
  41. package/dist/project/load-bundle-project.js +2 -2
  42. package/dist/project/load-data-config.js +2 -2
  43. package/dist/project/placeholder-secret.js +9 -0
  44. package/dist/scaffold/existing-config.js +4 -1
  45. package/dist/scaffold/plan.js +17 -5
  46. package/dist/scaffold/project.js +2 -1
  47. package/dist/scaffold/prompt.js +12 -5
  48. package/dist/scaffold/protobase-tables.js +44 -0
  49. package/dist/scaffold/run.js +3 -1
  50. package/dist/scaffold/ui-fields.js +3 -0
  51. package/dist/scaffold/ui-file.js +42 -5
  52. package/dist/serve/app.js +1 -1
  53. package/dist/serve/bundle-version.js +1 -1
  54. package/dist/serve/create-admin.js +3 -3
  55. package/dist/serve/host-modules.js +5 -5
  56. package/dist/serve/lifecycle.js +3 -3
  57. package/dist/serve/mobile-release.js +1 -1
  58. package/dist/serve/serve-bundle-path.js +1 -1
  59. package/dist/serve/serve-bundle.js +3 -3
  60. package/dist/serve/serve-dir.js +2 -2
  61. package/dist/supabase/dump-phase.js +2 -2
  62. package/dist/supabase/load-phase.js +2 -2
  63. package/dist/supabase/register.js +1 -1
  64. package/dist/supabase/storage-phase.js +1 -1
  65. package/dist/users/commands.js +7 -1
  66. package/dist/users/register.js +17 -11
  67. package/dist/users/users-api.js +2 -1
  68. package/dist/worker/start-worker.js +2 -2
  69. package/package.json +6 -6
  70. package/skills/protobase/SKILL.md +1 -0
  71. package/skills/protobase/references/getting-started.md +5 -1
  72. package/skills/protobase/references/guides/existing-database.md +112 -0
  73. package/skills/protobase/references/reference/auth.md +6 -6
  74. package/skills/protobase/references/reference/cli.md +19 -11
@@ -1,10 +1,9 @@
1
- import { loadProjectAuth } from "../users/load-auth.js";
2
- import { writeAuthMigration } from "./write-migration.js";
3
1
  import path from "node:path";
4
2
  //#region src/auth/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
4
  const registerAuth = (program) => {
7
5
  program.command("auth").description("The auth schema of the project in the current directory").command("migration").description("Write the auth schema changes this Protobase version needs as the project's next SQL migration, compared with its database").option("--dir <dir>", "migrations folder", "db/migrations").option("--name <name>", "file name after the number", "auth").action(async (opts) => {
6
+ const [{ loadProjectAuth }, { writeAuthMigration }] = await Promise.all([import("../users/load-auth.js"), import("./write-migration.js")]);
8
7
  const file = await writeAuthMigration({
9
8
  auth: await loadProjectAuth(process.cwd()),
10
9
  dir: path.resolve(opts.dir),
@@ -1,7 +1,7 @@
1
1
  import { migrationText, nextMigrationName } from "./migration-file.js";
2
2
  import path from "node:path";
3
- import { authSchemaMigration } from "@protobase/server";
4
3
  import { mkdir, readdir, writeFile } from "node:fs/promises";
4
+ import { authSchemaMigration } from "@protobase/server";
5
5
  //#region src/auth/write-migration.ts
6
6
  /**
7
7
  * Writes the auth schema changes the database still needs as the next migration in `dir`, and returns its path;
@@ -1,8 +1,8 @@
1
1
  import { buildFavicon, faviconFile } from "./favicon.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { pngIcons } from "@protobase/server";
5
4
  import { copyFile, readFile } from "node:fs/promises";
5
+ import { pngIcons } from "@protobase/server";
6
6
  //#region src/build/app-icons.ts
7
7
  const pngSignature = Buffer.from([
8
8
  137,
@@ -1,5 +1,5 @@
1
- import { findPackageDir, packageName } from "./packages/package-dir.js";
2
1
  import { extensionImports } from "../project/extensions.js";
2
+ import { findPackageDir, packageName } from "./packages/package-dir.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { hostModuleIds } from "../serve/host-module-ids.js";
5
5
  import { collectComponents } from "./component-names.js";
@@ -1,12 +1,12 @@
1
+ import { protobaseVersion } from "../version/version.js";
2
+ import { buildIcons } from "./app-icons.js";
1
3
  import { bundleLayout, bundleMigrations, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
2
4
  import { buildBundlePlugins } from "./bundle-plugins.js";
3
5
  import { copyMigrations } from "./bundle-migrations.js";
4
6
  import { buildConfigBundle } from "./config-bundle.js";
5
- import { protobaseVersion } from "../version/version.js";
6
7
  import { copyPackages } from "./packages/copy-packages.js";
7
8
  import { buildTheme } from "./theme.js";
8
9
  import { shellForBuild, shellManifestFile } from "./shell.js";
9
- import { buildIcons } from "./app-icons.js";
10
10
  import { checkUi } from "./ui-check.js";
11
11
  import { checkViews } from "./view-check.js";
12
12
  import { protobaseFolder } from "../project/protobase-folder.js";
@@ -1,7 +1,7 @@
1
+ import { functionFiles } from "../project/functions-folder.js";
1
2
  import { moduleFile } from "../module-file.js";
2
3
  import { exportOrder } from "./export-order.js";
3
4
  import { uiDirs } from "../project/convention-files.js";
4
- import { functionFiles } from "../project/functions-folder.js";
5
5
  import { existsSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  //#region src/build/entry-code.ts
@@ -1,17 +1,17 @@
1
- import { findPackageDirSync, readPackageJson } from "./packages/package-dir.js";
2
1
  import { uiPackageDir } from "../project/admin-app.js";
3
2
  import { extensionImports } from "../project/extensions.js";
3
+ import { findPackageDirSync, readPackageJson } from "./packages/package-dir.js";
4
4
  import { sharedModules } from "../project/shared-modules.js";
5
5
  import { pluginFieldTypes } from "./plugin-fields.js";
6
6
  import { layerPluginUtilities } from "./plugin-styles.js";
7
7
  import { createRequire } from "node:module";
8
8
  import { existsSync } from "node:fs";
9
9
  import path from "node:path";
10
- import { build } from "vite";
11
10
  import { writeFile } from "node:fs/promises";
11
+ import { inRange } from "@protobase/schema/internal";
12
12
  import tailwindcss from "@tailwindcss/vite";
13
13
  import react from "@vitejs/plugin-react";
14
- import { inRange } from "@protobase/schema/internal";
14
+ import { build } from "vite";
15
15
  //#region src/build/plugin-build.ts
16
16
  /** The module a plugin's components and action handlers are exported from, as a project's are. */
17
17
  const pluginEntryFile = "protobase.ui.tsx";
@@ -3,9 +3,9 @@ import { sharedModules } from "../project/shared-modules.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
6
7
  import { mkdtemp, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
- import { pathToFileURL } from "node:url";
9
9
  //#region src/build/plugin-fields.ts
10
10
  const fieldsCode = (entry) => [
11
11
  `import * as ui from ${JSON.stringify(entry)}`,
@@ -1,6 +1,6 @@
1
1
  import { faviconFile } from "./favicon.js";
2
- import { themeFile } from "./theme.js";
3
2
  import { pushHandlersCode } from "./service-worker-push-code.js";
3
+ import { themeFile } from "./theme.js";
4
4
  import { serviceWorkerFile as serviceWorkerFile$1 } from "@protobase/schema/internal";
5
5
  //#region src/build/service-worker-code.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
+ import { adminAppDir, uiEntry, uiPackageDir } from "../project/admin-app.js";
1
2
  import { projectUiPlugin } from "../project/project-ui.js";
2
3
  import { readPackageJson } from "./packages/package-dir.js";
3
- import { adminAppDir, uiEntry, uiPackageDir } from "../project/admin-app.js";
4
4
  import { sharedModulesPlugin } from "../project/shared-modules.js";
5
5
  import { faviconLink } from "../project/favicon-link.js";
6
6
  import { themeLink } from "../project/theme-link.js";
@@ -10,10 +10,10 @@ import { moveSourceMaps } from "./source-maps.js";
10
10
  import { shellCodeSplitting } from "./shell-chunks.js";
11
11
  import { existsSync } from "node:fs";
12
12
  import path from "node:path";
13
- import { build } from "vite";
14
13
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
15
14
  import tailwindcss from "@tailwindcss/vite";
16
15
  import react from "@vitejs/plugin-react";
16
+ import { build } from "vite";
17
17
  import { tmpdir } from "node:os";
18
18
  //#region src/build/shell.ts
19
19
  /** What a shell folder holds beside its files: the `BundleShell` a bundle's manifest copies. */
@@ -1,11 +1,11 @@
1
- import { projectUiFile, projectUiId, projectUiPlugin } from "../project/project-ui.js";
2
1
  import { extensionImports } from "../project/extensions.js";
2
+ import { projectUiFile, projectUiId, projectUiPlugin } from "../project/project-ui.js";
3
3
  import { viteBundle } from "./vite-bundle.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
6
7
  import { mkdtemp, rm } from "node:fs/promises";
7
8
  import { tmpdir } from "node:os";
8
- import { pathToFileURL } from "node:url";
9
9
  //#region src/build/ui-check.ts
10
10
  const checkFile = (projectDir) => path.join(projectDir, "protobase-ui-check.js");
11
11
  const checkCode = [
@@ -1,7 +1,7 @@
1
1
  import { bunBuild } from "./bun-build.js";
2
2
  import path from "node:path";
3
- import { build } from "vite";
4
3
  import { mkdtemp, rm } from "node:fs/promises";
4
+ import { build } from "vite";
5
5
  import { tmpdir } from "node:os";
6
6
  //#region src/build/vite-bundle.ts
7
7
  const viteBuild = async ({ root, entry, outFile, plugins, logLevel = "warn" }) => {
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
- import { oauthWellKnownPaths, pngIcons } from "@protobase/server";
3
2
  import { readFile } from "node:fs/promises";
3
+ import { oauthWellKnownPaths, pngIcons } from "@protobase/server";
4
4
  //#region src/bundle/manifest.ts
5
5
  const manifestFile = "protobase.bundle.json";
6
6
  const isApiPath = (api, pathname) => api.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.46.10";
2
+ var version = "0.46.12";
3
3
  //#endregion
4
4
  export { version };
@@ -6,13 +6,16 @@ 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";
9
12
  const resolveConnectionUrl = (arg, envName) => {
10
13
  if (arg && envName) throw new Error("Pass either a connection string or --env, not both");
11
14
  if (arg) return arg;
12
- if (!envName) throw new Error("Pass a connection string or --env <VARIABLE>");
13
- const value = process.env[envName];
14
- if (!value) throw new Error(`Environment variable ${envName} is not set`);
15
- return value;
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`);
16
19
  };
17
20
  //#endregion
18
- export { connect, resolveConnectionUrl };
21
+ export { connect, defaultConnectionEnv, isConnectionString, resolveConnectionUrl };
@@ -27,12 +27,14 @@ const reasons = {
27
27
  };
28
28
  const checkDatabase = async (url, projectDir) => {
29
29
  const sql = connect(url, { connectTimeout: 3 });
30
- const failure = await sql`select 1`.then(() => void 0, (error) => {
30
+ const code = await sql`select 1`.then(() => void 0, (error) => {
31
31
  if (!error.code || !(error.code in reasons)) throw error;
32
- return reasons[error.code];
32
+ return error.code;
33
33
  });
34
34
  await sql.end();
35
- if (failure) throw new Error(`Cannot reach the database at ${describeTarget(url)}: ${failure}.${await startHint(projectDir)}`);
35
+ if (!code) return;
36
+ const hint = code === "ECONNREFUSED" ? await startHint(projectDir) : "";
37
+ throw new Error(`Cannot reach the database at ${describeTarget(url)}: ${reasons[code]}.${hint}`);
36
38
  };
37
39
  //#endregion
38
40
  export { checkDatabase };
@@ -1,4 +1,6 @@
1
1
  //#region src/dev/entry.d.ts
2
2
  declare const _default: import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema | import("hono/types").MergeSchemaPath<import("hono/types").BlankSchema, "/">, "/", "/">;
3
+ /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
4
+ export declare const anyUsers: () => Promise<boolean> | Promise<undefined>;
3
5
  //#endregion
4
6
  export { _default as default };
package/dist/dev/entry.js CHANGED
@@ -1,19 +1,19 @@
1
1
  import { projectIcons } from "../build/app-icons.js";
2
- import { devJobs } from "./dev-jobs.js";
3
2
  import { projectErrorReporter } from "../project/error-reporter.js";
4
3
  import { projectAdmin } from "../project/project-admin.js";
4
+ import { devJobs } from "./dev-jobs.js";
5
5
  import { loadProject, projectDb } from "./project.js";
6
6
  import { withDevServiceWorker } from "./service-worker-route.js";
7
7
  import { setMissing, supabaseEnv } from "./supabase-env.js";
8
- import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
9
8
  import { upgradeWebSocket } from "@hono/node-server";
10
9
  import { Hono } from "hono";
10
+ import { apiKeySettings, assistantSettings, authStoreTables, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
11
11
  //#region src/dev/entry.ts
12
12
  const projectDir = process.env.PROTOBASE_PROJECT;
13
13
  const project = await loadProject(projectDir, JSON.parse(process.env.PROTOBASE_EXTENSIONS ?? "[]"));
14
14
  const db = projectDb(project, projectDir);
15
15
  const { resources, views } = configExports(project.exports);
16
- if (!project.authenticate) throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/reference/auth/");
16
+ if (!project.authenticate) throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/guides/existing-database/#4-add-sign-in");
17
17
  const store = globalThis;
18
18
  if (project.auth && !store.__protobaseAuthSchemaChecked) {
19
19
  await checkAuthSchema(project.auth);
@@ -49,11 +49,7 @@ const { admin, jobs } = projectAdmin({
49
49
  }, project.exports, db, ui, reporter, upgradeWebSocket);
50
50
  await devJobs(db, jobs);
51
51
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
52
- if (project.auth && !store.__protobaseNoUsersShown) {
53
- store.__protobaseNoUsersShown = true;
54
- hasUsers(project.auth).then((any) => {
55
- if (!any) console.log("No users yet. Create the first admin with: protobase users create you@example.com");
56
- }, (error) => console.error(`Could not check for users, is the auth schema migrated? ${error.message}`));
57
- }
52
+ /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
53
+ const anyUsers = () => project.auth ? hasUsers(project.auth) : Promise.resolve(void 0);
58
54
  //#endregion
59
- export { entry_default as default };
55
+ export { anyUsers, entry_default as default };
@@ -0,0 +1,21 @@
1
+ //#region src/dev/login-line.ts
2
+ const runners = {
3
+ bun: "bun run protobase",
4
+ pnpm: "pnpm protobase",
5
+ yarn: "yarn protobase",
6
+ npm: "npx protobase"
7
+ };
8
+ const protobaseCommand = (userAgent) => runners[userAgent?.split("/")[0] ?? ""] ?? "npx protobase";
9
+ /**
10
+ * The banner's sign-in line: with an empty auth store, the exact command that creates the first admin, since nobody can
11
+ * sign in until it runs. `anyUsers` is undefined when the project has no auth store the users commands manage.
12
+ */
13
+ const loginLine = (anyUsers, userAgent) => {
14
+ if (anyUsers === void 0) return "";
15
+ const protobase = protobaseCommand(userAgent);
16
+ const create = `${protobase} users create you@example.com --generate-password`;
17
+ if (!anyUsers) return ` login no users yet; create the first admin with:\n ${create}\n`;
18
+ return ` login sign in as one of its users (\`${protobase} users list\`), or add one: ${create}\n`;
19
+ };
20
+ //#endregion
21
+ export { loginLine, protobaseCommand };
@@ -0,0 +1,42 @@
1
+ import { createServer } from "node:net";
2
+ //#region src/dev/loopback.ts
3
+ const devHost = "127.0.0.1";
4
+ const loopbacks = [devHost, "::1"];
5
+ const missingFamily = ["EADDRNOTAVAIL", "EAFNOSUPPORT"];
6
+ const listen = (server, port, host) => new Promise((resolve, reject) => {
7
+ server.once("error", reject);
8
+ server.listen(port, host, () => {
9
+ server.off("error", reject);
10
+ resolve();
11
+ });
12
+ });
13
+ const hold = async (server, port, host) => {
14
+ try {
15
+ await listen(server, port, host);
16
+ return true;
17
+ } catch (error) {
18
+ const { code } = error;
19
+ if (code === "EADDRINUSE") throw new Error(`Port ${port} is in use by another server on ${host}, which would answer http://localhost:${port} instead. Stop it, or run on a free port with --port`);
20
+ if (code && missingFamily.includes(code)) return false;
21
+ throw error;
22
+ }
23
+ };
24
+ /** Fails when another process holds `port` on either loopback address, before the dev server starts. */
25
+ const checkPortFree = async (port) => {
26
+ for (const host of loopbacks) {
27
+ const probe = createServer();
28
+ if (await hold(probe, port, host)) await new Promise((resolve) => probe.close(resolve));
29
+ }
30
+ };
31
+ /**
32
+ * Hands each connection to `port` on ::1 to `httpServer`, listening on 127.0.0.1, WebSocket upgrades included, until it
33
+ * closes. Returns the server listening on ::1, undefined when the machine has no IPv6 loopback.
34
+ */
35
+ const alsoOnIpv6 = async (httpServer, port) => {
36
+ const forwarder = createServer((socket) => httpServer.emit("connection", socket));
37
+ if (!await hold(forwarder, port, "::1")) return void 0;
38
+ httpServer.once("close", () => forwarder.close());
39
+ return forwarder;
40
+ };
41
+ //#endregion
42
+ export { alsoOnIpv6, checkPortFree, devHost };
@@ -1,10 +1,10 @@
1
- import { functionFiles } from "../project/functions-folder.js";
2
1
  import { conventionConfig } from "../project/convention.js";
2
+ import { functionFiles } from "../project/functions-folder.js";
3
3
  import { sharedDb } from "./create-db.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { mergeConfig } from "@protobase/server";
7
6
  import { readdir } from "node:fs/promises";
7
+ import { mergeConfig } from "@protobase/server";
8
8
  //#region src/dev/project.ts
9
9
  const load = (file) => import(
10
10
  /* @vite-ignore */
package/dist/dev/run.js CHANGED
@@ -1,22 +1,25 @@
1
1
  import { loadNearestEnvFile } from "./env.js";
2
- import { projectUiPlugin } from "../project/project-ui.js";
3
2
  import { adminAppDir, adminAppMain, uiPackageDir } from "../project/admin-app.js";
4
3
  import { extensionImports, extensionStyles } from "../project/extensions.js";
4
+ import { stopDevJobs } from "./dev-jobs.js";
5
+ import { frameHeaders } from "../serve/static-site.js";
6
+ import { projectUiPlugin } from "../project/project-ui.js";
5
7
  import { sharedModulesPlugin } from "../project/shared-modules.js";
6
8
  import { moduleFile } from "../module-file.js";
7
9
  import { layoutCheck } from "../build/layout-check.js";
8
10
  import { faviconLink } from "../project/favicon-link.js";
9
11
  import { themeLink } from "../project/theme-link.js";
10
12
  import { checkDatabase } from "./check-database.js";
11
- import { stopDevJobs } from "./dev-jobs.js";
13
+ import { alsoOnIpv6, checkPortFree, devHost } from "./loopback.js";
14
+ import { loginLine } from "./login-line.js";
15
+ import { startupLogger } from "./startup-logger.js";
12
16
  import { isProjectFile } from "./project-files.js";
13
17
  import { apiWebSockets } from "./api-websockets.js";
14
- import { frameHeaders } from "../serve/static-site.js";
15
18
  import { existsSync } from "node:fs";
16
19
  import path from "node:path";
17
- import { createServer, searchForWorkspaceRoot } from "vite";
18
20
  import tailwindcss from "@tailwindcss/vite";
19
21
  import react from "@vitejs/plugin-react";
22
+ import { createServer, searchForWorkspaceRoot } from "vite";
20
23
  import devServer from "@hono/vite-dev-server";
21
24
  //#region src/dev/run.ts
22
25
  const entry = moduleFile("./entry", import.meta.url);
@@ -58,14 +61,17 @@ const runDev = async (options, out) => {
58
61
  const appDir = options.appDir ?? adminAppDir;
59
62
  requireAppFiles(appDir);
60
63
  await checkDatabase(url, options.projectDir);
64
+ if (options.port !== 0) await checkPortFree(options.port);
61
65
  const extensions = options.extensions ?? [];
62
66
  const projectDirs = [options.projectDir, ...extensions.map((extension) => extension.dir)];
63
67
  process.env.PROTOBASE_PROJECT = options.projectDir;
64
68
  process.env.PROTOBASE_EXTENSIONS = JSON.stringify(extensions);
65
69
  process.env.PROTOBASE_DATABASE_URL = url;
70
+ const logging = startupLogger();
66
71
  const server = await createServer({
67
72
  root: appDir,
68
73
  configFile: false,
74
+ customLogger: logging.logger,
69
75
  ...options.cacheDir && { cacheDir: options.cacheDir },
70
76
  optimizeDeps: {
71
77
  include: appDependencies,
@@ -73,6 +79,7 @@ const runDev = async (options, out) => {
73
79
  },
74
80
  server: {
75
81
  headers: frameHeaders,
82
+ host: devHost,
76
83
  port: options.port,
77
84
  strictPort: true,
78
85
  ...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
@@ -103,17 +110,18 @@ const runDev = async (options, out) => {
103
110
  })
104
111
  ]
105
112
  });
113
+ const closeAndThrow = async (error) => {
114
+ await server.close();
115
+ throw error;
116
+ };
106
117
  await server.listen();
107
118
  const address = server.httpServer?.address();
108
119
  const port = typeof address === "object" && address ? address.port : options.port;
120
+ if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
109
121
  process.env.PROTOBASE_DEV_URL = `http://localhost:${port}`;
110
- await server.ssrLoadModule(entry).catch(async (error) => {
111
- await server.close();
112
- throw error;
113
- });
114
- out(`protobase dev ready at http://localhost:${port}\n`);
115
- out(` project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n`);
116
- out(" login sign in with a user created by `protobase users create`\n");
122
+ const anyUsers = await (await server.ssrLoadModule(entry).catch(closeAndThrow)).anyUsers().catch(closeAndThrow);
123
+ logging.started();
124
+ out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent));
117
125
  return server;
118
126
  };
119
127
  //#endregion
@@ -0,0 +1,24 @@
1
+ import { createLogger } from "vite";
2
+ //#region src/dev/startup-logger.ts
3
+ /**
4
+ * Vite's logger for `protobase dev`. Vite logs a module that fails to evaluate, with its stack, before
5
+ * `ssrLoadModule` throws the error. The first load is the startup check, whose error the CLI prints as one line, so
6
+ * Vite's copy is left out until `started`; a module that fails while the server runs still shows Vite's stack.
7
+ */
8
+ const startupLogger = () => {
9
+ const logger = createLogger();
10
+ const error = logger.error;
11
+ let starting = true;
12
+ logger.error = (message, options) => {
13
+ if (starting && message.includes("Error when evaluating SSR module")) return;
14
+ error(message, options);
15
+ };
16
+ return {
17
+ logger,
18
+ started: () => {
19
+ starting = false;
20
+ }
21
+ };
22
+ };
23
+ //#endregion
24
+ export { startupLogger };
@@ -1,14 +1,17 @@
1
- import { loadDataConfig } from "../project/load-data-config.js";
2
1
  import { connect } from "../db/connect.js";
2
+ import { loadDataConfig } from "../project/load-data-config.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";
6
6
  import { indexIssues } from "./index-issues.js";
7
7
  import { readShapes } from "./read-shapes.js";
8
+ import { existsSync } from "node:fs";
9
+ import path from "node:path";
8
10
  import { tableIndexes } from "@protobase/query";
9
11
  //#region src/doctor/run.ts
10
12
  const format = (issue) => ` ${issue.severity.padEnd(7)} ${issue.resource}: ${issue.message}${issue.suggestion ? `\n fix: ${issue.suggestion}` : ""}\n`;
11
13
  const runDoctor = async (options, out) => {
14
+ if (!existsSync(path.join(options.configDir, "index.ts"))) throw new Error(`No config in ${options.configDir}: write it with \`protobase scaffold\`, or pass --config <dir>`);
12
15
  const config = await loadDataConfig(options.configDir);
13
16
  const { models } = config;
14
17
  if (models.length === 0) throw new Error(`No resources exported from ${options.configDir}/index.ts`);
@@ -1,12 +1,11 @@
1
- import { loadBundleProject } from "../project/load-bundle-project.js";
2
1
  import { printStatus } from "./print-status.js";
3
2
  import { printApply } from "./print-apply.js";
4
3
  import { rebindOption } from "./rebind-option.js";
5
- import { createEncryptionTools } from "@protobase/server";
6
4
  //#region src/encryption/register.ts
7
5
  const out = (text) => void process.stdout.write(text);
8
6
  const bundleArgument = ["[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory"];
9
7
  const withTools = async (bundle, work) => {
8
+ const [{ createEncryptionTools }, { loadBundleProject }] = await Promise.all([import("@protobase/server"), import("../project/load-bundle-project.js")]);
10
9
  const project = await loadBundleProject(bundle, process.cwd());
11
10
  try {
12
11
  const tools = createEncryptionTools({
@@ -0,0 +1,15 @@
1
+ //#region src/error-message.ts
2
+ const target = ({ address, port }) => address?.includes(":") ? `[${address}]:${port}` : `${address}:${port}`;
3
+ /**
4
+ * The line the central error handler prints for an error. A connection to a host with several addresses, such as
5
+ * localhost's ::1 and 127.0.0.1, fails with an AggregateError of one error per address and no message of its own.
6
+ */
7
+ const errorMessage = (error) => {
8
+ if (error.message) return error.message;
9
+ if (!(error instanceof AggregateError) || error.errors.length === 0) return error.name;
10
+ const errors = error.errors;
11
+ if (errors.every((inner) => inner.code === "ECONNREFUSED" && inner.address)) return `Cannot connect to ${errors.map(target).join(" or ")}: the connection was refused, so nothing is listening there. Is the database running?`;
12
+ return errors.map(errorMessage).join("; ");
13
+ };
14
+ //#endregion
15
+ export { errorMessage };
@@ -1,10 +1,9 @@
1
1
  import { cleanupCommand } from "./cleanup-command.js";
2
- import { loadBundleProject } from "../project/load-bundle-project.js";
3
- import { createFileCleanup } from "@protobase/server";
4
2
  //#region src/files/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
4
  const registerFiles = (program) => {
7
5
  program.command("files").description("Manage the stored files of the project in the current directory").command("cleanup").description("Delete the files whose scheduled delete is due and that no row references, such as replaced files and unused uploads").argument("[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory").action(async (bundle) => {
6
+ const [{ createFileCleanup }, { loadBundleProject }] = await Promise.all([import("@protobase/server"), import("../project/load-bundle-project.js")]);
8
7
  const project = await loadBundleProject(bundle, process.cwd());
9
8
  try {
10
9
  const cleanup = createFileCleanup(project);
@@ -27,7 +27,7 @@ const relationOf = (table, column, context) => {
27
27
  columns: fk.columns
28
28
  };
29
29
  };
30
- const auditColumn = /^(created|inserted|updated|modified)_at$/;
30
+ const auditColumn = /^(created|inserted|updated|modified)(_at|At)$/;
31
31
  const isServerManaged = (table, column) => column.identity || auditColumn.test(column.name) || table.indexes.some((index) => index.primary && index.columns.includes(column.name));
32
32
  const defaultsOf = (table, column, kind) => {
33
33
  const fallback = columnDefault(column, kind);