@protobase/cli 0.26.9 → 0.28.0

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 (45) hide show
  1. package/dist/build/app-icons.js +51 -0
  2. package/dist/build/deploy-bundle.js +6 -4
  3. package/dist/bundle/manifest.js +5 -1
  4. package/dist/{package.js → cli/package.js} +1 -1
  5. package/dist/dev/entry.js +7 -1
  6. package/dist/main.js +2 -0
  7. package/dist/mobile/api-origin.js +34 -0
  8. package/dist/mobile/arguments.js +16 -0
  9. package/dist/mobile/cap-run-args.js +22 -0
  10. package/dist/mobile/capacitor-config.js +25 -0
  11. package/dist/mobile/capacitor.js +17 -0
  12. package/dist/mobile/child-env.js +26 -0
  13. package/dist/mobile/child-process.js +17 -0
  14. package/dist/mobile/fingerprint.js +12 -0
  15. package/dist/mobile/generate.js +20 -0
  16. package/dist/mobile/info-plist.js +11 -0
  17. package/dist/mobile/installed-package.js +20 -0
  18. package/dist/mobile/load-project.js +25 -0
  19. package/dist/mobile/mobile-config.js +26 -0
  20. package/dist/mobile/package.js +13 -0
  21. package/dist/mobile/pinned-packages.js +27 -0
  22. package/dist/mobile/platform.js +4 -0
  23. package/dist/mobile/register.js +33 -0
  24. package/dist/mobile/run.js +84 -0
  25. package/dist/mobile/web-part.js +54 -0
  26. package/dist/mobile/workspace.js +42 -0
  27. package/dist/project/favicon-link.js +24 -2
  28. package/dist/project/project-admin.js +5 -2
  29. package/dist/project/protobase-folder.js +5 -0
  30. package/dist/project/service-worker.js +1 -1
  31. package/dist/serve/bundle-ui.js +2 -1
  32. package/dist/version/version.js +1 -1
  33. package/package.json +6 -6
  34. package/skills/protobase/SKILL.md +2 -0
  35. package/skills/protobase/references/guides/deploy.md +2 -1
  36. package/skills/protobase/references/guides/mobile-app.md +64 -0
  37. package/skills/protobase/references/guides/plugin-build.md +2 -1
  38. package/skills/protobase/references/reference/api.md +1 -1
  39. package/skills/protobase/references/reference/app-identity.md +54 -0
  40. package/skills/protobase/references/reference/auth.md +8 -3
  41. package/skills/protobase/references/reference/cli.md +19 -3
  42. package/skills/protobase/references/reference/custom-components.md +1 -1
  43. package/skills/protobase/references/reference/email.md +1 -1
  44. package/skills/protobase/references/reference/installable-app.md +11 -2
  45. package/skills/protobase/references/reference/theme.md +2 -2
@@ -0,0 +1,51 @@
1
+ import { buildFavicon, faviconFile } from "./favicon.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { copyFile, readFile } from "node:fs/promises";
5
+ import { pngIcons } from "@protobase/server";
6
+ //#region src/build/app-icons.ts
7
+ const pngSignature = Buffer.from([
8
+ 137,
9
+ 80,
10
+ 78,
11
+ 71,
12
+ 13,
13
+ 10,
14
+ 26,
15
+ 10
16
+ ]);
17
+ /** The width and height of a PNG, from its signature and IHDR chunk; `undefined` for a file that is no PNG. */
18
+ const pngSize = (head) => {
19
+ if (head.length < 24 || !head.subarray(0, 8).equals(pngSignature) || head.toString("latin1", 12, 16) !== "IHDR") return void 0;
20
+ return {
21
+ width: head.readUInt32BE(16),
22
+ height: head.readUInt32BE(20)
23
+ };
24
+ };
25
+ const checkPng = async (projectDir, icon) => {
26
+ const { file, size } = pngIcons[icon];
27
+ const found = pngSize(await readFile(path.join(projectDir, file)));
28
+ if (!found) throw new Error(`${file} is no PNG`);
29
+ if (found.width !== size || found.height !== size) throw new Error(`${file} is ${found.width}x${found.height} pixels; it must be ${size}x${size}`);
30
+ };
31
+ /** The icons the project in `projectDir` has of its own: its protobase.favicon.svg and the PNGs beside it (see `pngIcons`). */
32
+ const projectIcons = (projectDir) => ({
33
+ favicon: existsSync(path.join(projectDir, faviconFile)),
34
+ png: Object.keys(pngIcons).filter((icon) => existsSync(path.join(projectDir, pngIcons[icon].file)))
35
+ });
36
+ /**
37
+ * Writes the app's icons into `publicDir`: the favicon, the project's or Protobase's (see `buildFavicon`), and the PNGs
38
+ * the project has, each checked to be its size. Says which are the project's own, which the server's manifest names.
39
+ */
40
+ const buildIcons = async ({ projectDir, publicDir }) => {
41
+ const icons = projectIcons(projectDir);
42
+ for (const icon of icons.png) await checkPng(projectDir, icon);
43
+ await buildFavicon({
44
+ projectDir,
45
+ outFile: path.join(publicDir, faviconFile)
46
+ });
47
+ await Promise.all(icons.png.map((icon) => copyFile(path.join(projectDir, pngIcons[icon].file), path.join(publicDir, pngIcons[icon].file))));
48
+ return icons;
49
+ };
50
+ //#endregion
51
+ export { buildIcons, pngSize, projectIcons };
@@ -3,11 +3,12 @@ import { buildBundlePlugins } from "./bundle-plugins.js";
3
3
  import { buildConfigBundle } from "./config-bundle.js";
4
4
  import { protobaseVersion } from "../version/version.js";
5
5
  import { copyPackages } from "./packages/copy-packages.js";
6
- import { buildFavicon, faviconFile } from "./favicon.js";
7
6
  import { buildTheme } from "./theme.js";
8
7
  import { shellForBuild, shellManifestFile } from "./shell.js";
8
+ import { buildIcons } from "./app-icons.js";
9
9
  import { checkUi } from "./ui-check.js";
10
10
  import { checkViews } from "./view-check.js";
11
+ import { protobaseFolder } from "../project/protobase-folder.js";
11
12
  import { existsSync } from "node:fs";
12
13
  import path from "node:path";
13
14
  import { cp, readFile, rm, writeFile } from "node:fs/promises";
@@ -60,15 +61,15 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], onW
60
61
  projectDir,
61
62
  publicDir,
62
63
  extensions,
63
- ignore: [outDir]
64
+ ignore: [outDir, path.join(projectDir, protobaseFolder)]
64
65
  });
65
66
  for (const warning of await buildTheme({
66
67
  projectDir,
67
68
  outFile: path.join(publicDir, bundleLayout.theme)
68
69
  })) onWarning?.(warning);
69
- await buildFavicon({
70
+ const icons = await buildIcons({
70
71
  projectDir,
71
- outFile: path.join(publicDir, faviconFile)
72
+ publicDir
72
73
  });
73
74
  const manifest = {
74
75
  version: 3,
@@ -77,6 +78,7 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], onW
77
78
  api: [...bundleLayout.api],
78
79
  plugins,
79
80
  shell,
81
+ icons,
80
82
  ...packages.length > 0 ? { nodeModules: bundleNodeModules } : {}
81
83
  };
82
84
  await writeFile(path.join(outDir, manifestFile), `${JSON.stringify(manifest, null, 2)}\n`);
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { readFile } from "node:fs/promises";
3
+ import { pngIcons } from "@protobase/server";
3
4
  //#region src/bundle/manifest.ts
4
5
  const manifestFile = "protobase.bundle.json";
5
6
  const isApiPath = (api, pathname) => api.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
@@ -17,13 +18,15 @@ const isObject = (value) => typeof value === "object" && value !== null && !Arra
17
18
  const isFieldTypes = (value) => isObject(value) && Object.values(value).every(isStringList);
18
19
  const isPlugin = (value) => isObject(value) && typeof value.name === "string" && typeof value.path === "string" && Number.isInteger(value.api) && typeof value.protobase === "string" && (value.fields === void 0 || isFieldTypes(value.fields));
19
20
  const isShell = (value) => isObject(value) && typeof value.protobase === "string" && Number.isInteger(value.pluginApi) && isStringList(value.paths);
21
+ const isIcons = (value) => isObject(value) && typeof value.favicon === "boolean" && isStringList(value.png) && value.png.every((icon) => icon in pngIcons);
20
22
  const parseManifest = (value, file) => {
21
23
  const manifest = value;
22
24
  if (manifest?.version !== 3) throw new Error(`${file} is not a version 3 bundle manifest; rebuild it with \`protobase build\``);
23
- const { server, public: publicDir, api, spa, plugins, theme, shell, nodeModules } = manifest;
25
+ const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules } = manifest;
24
26
  if (typeof server !== "string" || typeof publicDir !== "string" || typeof spa !== "string" || typeof theme !== "string" || !isStringList(api)) throw new Error(`${file} needs server, public, spa and theme paths and an api list`);
25
27
  if (!Array.isArray(plugins) || !plugins.every(isPlugin)) throw new Error(`${file} needs a plugins list, each with a name, path, api and protobase`);
26
28
  if (!isShell(shell)) throw new Error(`${file} needs a shell with its protobase version, pluginApi and paths`);
29
+ if (icons !== void 0 && !isIcons(icons)) throw new Error(`${file} has icons that are not a favicon flag and a list of PNG icons`);
27
30
  if (nodeModules !== void 0 && typeof nodeModules !== "string") throw new Error(`${file} has a nodeModules that is no path`);
28
31
  return {
29
32
  version: 3,
@@ -34,6 +37,7 @@ const parseManifest = (value, file) => {
34
37
  plugins,
35
38
  theme,
36
39
  shell,
40
+ ...icons && { icons },
37
41
  ...nodeModules === void 0 ? {} : { nodeModules }
38
42
  };
39
43
  };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.26.9";
2
+ var version = "0.28.0";
3
3
  //#endregion
4
4
  export { version };
package/dist/dev/entry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { projectIcons } from "../build/app-icons.js";
1
2
  import { devJobs } from "./dev-jobs.js";
2
3
  import { projectErrorReporter } from "../project/error-reporter.js";
3
4
  import { projectAdmin } from "../project/project-admin.js";
@@ -27,10 +28,15 @@ checkAi({
27
28
  });
28
29
  if (project.webhooks) await checkWebhooksSchema(db, project.webhooks);
29
30
  const reporter = await projectErrorReporter(project, process.env);
31
+ const ui = {
32
+ plugins: [],
33
+ fieldTypes: {},
34
+ icons: projectIcons(projectDir)
35
+ };
30
36
  const { admin, jobs } = projectAdmin({
31
37
  ...project,
32
38
  authenticate: project.authenticate
33
- }, project.exports, db, void 0, reporter, upgradeWebSocket);
39
+ }, project.exports, db, ui, reporter, upgradeWebSocket);
34
40
  await devJobs(db, jobs);
35
41
  var entry_default = new Hono().route("/", admin);
36
42
  if (project.auth && !store.__protobaseNoUsersShown) {
package/dist/main.js CHANGED
@@ -20,6 +20,7 @@ import { loadWorkerBundle, startWorker } from "./worker/start-worker.js";
20
20
  import { registerOrganizations } from "./organizations/register.js";
21
21
  import { registerFiles } from "./files/register.js";
22
22
  import { registerMigration } from "./migration/register.js";
23
+ import { registerMobile } from "./mobile/register.js";
23
24
  import { registerSkill } from "./skill/register.js";
24
25
  import { registerImport } from "./supabase/register.js";
25
26
  import { registerToken, registerUsers } from "./users/register.js";
@@ -132,6 +133,7 @@ registerMigration(program);
132
133
  registerFiles(program);
133
134
  registerSkill(program);
134
135
  registerImport(program);
136
+ registerMobile(program);
135
137
  const run = (argv) => program.parseAsync(argv).catch((error) => {
136
138
  process.stderr.write(`error: ${error.message}\n`);
137
139
  process.exitCode = 1;
@@ -0,0 +1,34 @@
1
+ //#region src/mobile/api-origin.ts
2
+ const loopback = ["localhost", "127.0.0.1"];
3
+ const httpHosts = {
4
+ ios: [...loopback, "[::1]"],
5
+ android: [...loopback, "10.0.2.2"]
6
+ };
7
+ /**
8
+ * The server the app calls: `--api` when given, else the auth issuer (`baseURL`). It must be an http or https origin
9
+ * with nothing after it; plain http only to this machine, or the Android emulator's host, since anyone on the network
10
+ * between could read or change what it sends.
11
+ */
12
+ const apiUrl = (given, issuer, platform) => {
13
+ const value = given ?? issuer;
14
+ const what = given === void 0 ? `The auth issuer (baseURL) "${value}"` : `--api ${given}`;
15
+ if (value === void 0) throw new Error("This project has no auth issuer (baseURL) for the app to call: pass --api https://…");
16
+ if (!URL.canParse(value)) throw new Error(`${what} is not a URL such as https://shop.example.com`);
17
+ const url = new URL(value);
18
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${what} must be an http or https URL`);
19
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || value.endsWith("?") || value.endsWith("#")) throw new Error(`${what} must be an origin such as https://shop.example.com, without a user, path, query or fragment`);
20
+ if (url.protocol === "http:" && !httpHosts[platform].includes(url.hostname)) throw new Error(`${what} uses plain http to ${url.hostname}: plain http is only for a server on this machine (${httpHosts[platform].join(", ")}); any other server needs https`);
21
+ return url;
22
+ };
23
+ /** What the app must allow to reach `url`: plain http, and on Android mixed content for a host that is not loopback. */
24
+ const httpAllowances = (url) => ({
25
+ cleartext: url.protocol === "http:",
26
+ mixedContent: url.hostname === "10.0.2.2"
27
+ });
28
+ /** The port `adb reverse` forwards for an Android app calling `url` on this machine, `undefined` for any other. */
29
+ const forwardedPort = (url, platform) => {
30
+ if (platform !== "android" || !loopback.includes(url.hostname)) return void 0;
31
+ return Number(url.port || (url.protocol === "https:" ? 443 : 80));
32
+ };
33
+ //#endregion
34
+ export { apiUrl, forwardedPort, httpAllowances };
@@ -0,0 +1,16 @@
1
+ import { platforms } from "./platform.js";
2
+ import { InvalidArgumentError } from "commander";
3
+ //#region src/mobile/arguments.ts
4
+ /** The `<platform>` argument: ios or android. */
5
+ const parsePlatform = (value) => {
6
+ if (platforms.includes(value)) return value;
7
+ throw new InvalidArgumentError("expected ios or android");
8
+ };
9
+ /** A `--port` option: digits only, from 1 to 65535, as a number, so no other text reaches a URL or Capacitor. */
10
+ const parsePort = (value) => {
11
+ const number = /^\d{1,5}$/.test(value) ? Number(value) : 0;
12
+ if (number < 1 || number > 65535) throw new InvalidArgumentError("expected a port from 1 to 65535");
13
+ return number;
14
+ };
15
+ //#endregion
16
+ export { parsePlatform, parsePort };
@@ -0,0 +1,22 @@
1
+ import { forwardedPort } from "./api-origin.js";
2
+ //#region src/mobile/cap-run-args.ts
3
+ /** The arguments of `cap run`, after the native project was generated and synced. */
4
+ const capRunArgs = ({ platform, target, url, live }) => {
5
+ const port = forwardedPort(url, platform);
6
+ return [
7
+ "run",
8
+ platform,
9
+ "--no-sync",
10
+ ...target ? ["--target", target] : [],
11
+ ...port === void 0 ? [] : ["--forwardPorts", `${port}:${port}`],
12
+ ...live === void 0 ? [] : [
13
+ "--live-reload",
14
+ "--host",
15
+ "localhost",
16
+ "--port",
17
+ String(live)
18
+ ]
19
+ ];
20
+ };
21
+ //#endregion
22
+ export { capRunArgs };
@@ -0,0 +1,25 @@
1
+ import path from "node:path";
2
+ import { rm, writeFile } from "node:fs/promises";
3
+ //#region src/mobile/capacitor-config.ts
4
+ /**
5
+ * The app's `capacitor.config.json`, every key it sets named here. It never sets `server.url`, the hostname or the
6
+ * schemes (the API's CORS list names Capacitor's default origins), `plugins` (so CapacitorHttp and CapacitorCookies
7
+ * stay off) or WebView debugging (on in debug builds only). The fingerprint goes in the user agent, which a live
8
+ * update cannot change.
9
+ */
10
+ const capacitorConfig = ({ appId, appName, fingerprint, plugins, allowances }) => ({
11
+ appId,
12
+ appName,
13
+ webDir: "web",
14
+ appendUserAgent: `ProtobaseNative/${fingerprint}`,
15
+ includePlugins: plugins,
16
+ ...allowances.cleartext && { server: { cleartext: true } },
17
+ ...allowances.mixedContent && { android: { allowMixedContent: true } }
18
+ });
19
+ /** Writes the config into the workspace `dir`, removing the `.ts` and `.js` configs Capacitor would read instead. */
20
+ const writeCapacitorConfig = async (dir, config) => {
21
+ await Promise.all(["capacitor.config.ts", "capacitor.config.js"].map((name) => rm(path.join(dir, name), { force: true })));
22
+ await writeFile(path.join(dir, "capacitor.config.json"), `${JSON.stringify(config, null, 2)}\n`);
23
+ };
24
+ //#endregion
25
+ export { capacitorConfig, writeCapacitorConfig };
@@ -0,0 +1,17 @@
1
+ import { installedPackage } from "./installed-package.js";
2
+ import path from "node:path";
3
+ //#region src/mobile/capacitor.ts
4
+ /**
5
+ * Runs the workspace's own Capacitor CLI, read from `<ws>/node_modules/@capacitor/cli` by path, so never one of the
6
+ * project's or another found further up, with Node and the given environment.
7
+ */
8
+ const capacitorRunner = (ws, env, run) => async (args) => {
9
+ const { name, bin } = installedPackage(ws, "@capacitor/cli");
10
+ if (name !== "@capacitor/cli" || !bin?.cap) throw new Error(`${path.join(ws, "node_modules", "@capacitor/cli")} is ${name}, not Capacitor's CLI`);
11
+ await run("node", [path.join(ws, "node_modules", "@capacitor", "cli", bin.cap), ...args], {
12
+ cwd: ws,
13
+ env
14
+ });
15
+ };
16
+ //#endregion
17
+ export { capacitorRunner };
@@ -0,0 +1,26 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseEnv } from "node:util";
4
+ //#region src/mobile/child-env.ts
5
+ const isFile = (file) => {
6
+ try {
7
+ return statSync(file).isFile();
8
+ } catch (error) {
9
+ if (error.code === "ENOENT") return false;
10
+ throw error;
11
+ }
12
+ };
13
+ /** The files in `dir` Bun may have loaded env from: every `.env*`, in any letter case, that is a file once links are followed. */
14
+ const projectEnvFiles = (dir) => readdirSync(dir).filter((name) => name.toLowerCase().startsWith(".env")).map((name) => path.join(dir, name)).filter(isFile);
15
+ /** The keys `files` set, without a leading byte order mark, which Bun strips and `parseEnv` keeps. */
16
+ const envFileKeys = (files) => new Set(files.flatMap((file) => Object.keys(parseEnv(readFileSync(file, "utf8").replace(/^/, "")))));
17
+ /**
18
+ * The environment for npm and Capacitor: `env` without `keys`, even where the shell set one of them, and with `CI`,
19
+ * without which Capacitor opts the user into its telemetry from an interactive terminal and sends the app id.
20
+ */
21
+ const childEnv = (env, keys) => ({
22
+ ...Object.fromEntries(Object.entries(env).filter(([key, value]) => value !== void 0 && !keys.has(key))),
23
+ CI: "true"
24
+ });
25
+ //#endregion
26
+ export { childEnv, envFileKeys, projectEnvFiles };
@@ -0,0 +1,17 @@
1
+ import { spawn } from "node:child_process";
2
+ //#region src/mobile/child-process.ts
3
+ /**
4
+ * Runs `command` with `args` as given, never through a shell, in `cwd` with exactly `env`: without it the child would
5
+ * get the CLI's whole environment, with the project's secrets.
6
+ */
7
+ const runChild = (command, args, { cwd, env }, spawn$1 = spawn) => new Promise((resolve, reject) => {
8
+ const child = spawn$1(command, args, {
9
+ cwd,
10
+ env,
11
+ stdio: "inherit"
12
+ });
13
+ child.on("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error(`${command} is not installed, or not on PATH`) : error));
14
+ child.on("close", (status) => status === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`\`${command} ${args.join(" ")}\` exited with status ${status}`)));
15
+ });
16
+ //#endregion
17
+ export { runChild };
@@ -0,0 +1,12 @@
1
+ import { createHash } from "node:crypto";
2
+ //#region src/mobile/fingerprint.ts
3
+ /** Names the app's native code: the same for two builds only when they compile in the same native packages. */
4
+ const nativeFingerprint = ({ mobile, plugins }) => {
5
+ const sorted = [...plugins].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
6
+ return createHash("sha256").update(JSON.stringify({
7
+ mobile,
8
+ plugins: sorted
9
+ })).digest("hex").slice(0, 16);
10
+ };
11
+ //#endregion
12
+ export { nativeFingerprint };
@@ -0,0 +1,20 @@
1
+ import { withLocalNetworking } from "./info-plist.js";
2
+ import path from "node:path";
3
+ import { readFile, rm, writeFile } from "node:fs/promises";
4
+ //#region src/mobile/generate.ts
5
+ const infoPlist = (ws) => path.join(ws, "ios", "App", "App", "Info.plist");
6
+ /**
7
+ * Generates the platform's native project in the workspace from its capacitor.config.json and app files, replacing
8
+ * the last one: it is never edited by hand. An iOS app calling the API over plain http may reach local addresses.
9
+ */
10
+ const generatePlatform = async (ws, platform, { cleartext }, cap) => {
11
+ await rm(path.join(ws, platform), {
12
+ recursive: true,
13
+ force: true
14
+ });
15
+ await cap(["add", platform]);
16
+ if (platform !== "ios" || !cleartext) return;
17
+ await writeFile(infoPlist(ws), withLocalNetworking(await readFile(infoPlist(ws), "utf8")));
18
+ };
19
+ //#endregion
20
+ export { generatePlatform };
@@ -0,0 +1,11 @@
1
+ //#region src/mobile/info-plist.ts
2
+ const end = "</dict>\n</plist>";
3
+ /** The app's Info.plist allowing plain http to local addresses only (`NSAllowsLocalNetworking`), never to the internet. */
4
+ const withLocalNetworking = (plist) => {
5
+ if (plist.includes("<key>NSAppTransportSecurity</key>")) throw new Error("Info.plist already has NSAppTransportSecurity");
6
+ const at = plist.lastIndexOf(end);
7
+ if (at < 0) throw new Error("Info.plist does not end with </dict></plist>");
8
+ return `${plist.slice(0, at)}\t<key>NSAppTransportSecurity</key>\n\t<dict>\n\t\t<key>NSAllowsLocalNetworking</key>\n\t\t<true/>\n\t</dict>\n${plist.slice(at)}`;
9
+ };
10
+ //#endregion
11
+ export { withLocalNetworking };
@@ -0,0 +1,20 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/mobile/installed-package.ts
4
+ /**
5
+ * The name and version of the package installed as `name` in the workspace `dir`, read from
6
+ * `<dir>/node_modules/<name>/package.json` by path, never by Node's lookup, which would go on into the project's own
7
+ * node_modules. Its `name` is the package's own, which differs from `name` for an npm alias.
8
+ */
9
+ const installedPackage = (dir, name) => {
10
+ const file = path.join(dir, "node_modules", name, "package.json");
11
+ if (!existsSync(file)) throw new Error(`${name} is not installed in ${dir}: run the command again to install it`);
12
+ const { name: own, version, bin } = JSON.parse(readFileSync(file, "utf8"));
13
+ return {
14
+ name: own,
15
+ version,
16
+ ...bin && { bin }
17
+ };
18
+ };
19
+ //#endregion
20
+ export { installedPackage };
@@ -0,0 +1,25 @@
1
+ import { loadNearestEnvFile } from "../dev/env.js";
2
+ import { importProjectFile } from "../project/import-project-file.js";
3
+ import { noMobileSection } from "./mobile-config.js";
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { mergeConfig } from "@protobase/server";
7
+ //#region src/mobile/load-project.ts
8
+ const configOf = async (file) => (await importProjectFile(file)).default ?? {};
9
+ /**
10
+ * What a mobile build needs of the project in `dir`, merged as `protobase dev` merges it after the configs of
11
+ * `extensions`: its mobile section, unchecked, and its auth. The project's .env is loaded first, as other commands do.
12
+ */
13
+ const loadMobileProject = async (dir, extensions) => {
14
+ loadNearestEnvFile(dir);
15
+ const file = path.join(dir, "protobase.config.ts");
16
+ if (!existsSync(file)) throw new Error(noMobileSection);
17
+ const extended = await Promise.all(extensions.flatMap((extension) => extension.config ? [configOf(extension.config)] : []));
18
+ const { mobile, auth } = mergeConfig(...extended, await configOf(file));
19
+ return {
20
+ mobile,
21
+ auth
22
+ };
23
+ };
24
+ //#endregion
25
+ export { loadMobileProject };
@@ -0,0 +1,26 @@
1
+ import { pinnedProblem } from "./pinned-packages.js";
2
+ //#region src/mobile/mobile-config.ts
3
+ const noMobileSection = "This project has no mobile section: add `mobile: { appId: 'com.example.app' }` to the default export of protobase.config.ts";
4
+ const appIdPattern = /^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)+$/;
5
+ const unauthenticated = /^(?:http:|git:|git\+http:)/i;
6
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
+ /** The project's `mobile` section, checked: an error says what to add or fix. */
8
+ const checkMobileConfig = (value) => {
9
+ if (value === void 0) throw new Error(noMobileSection);
10
+ if (!isRecord(value)) throw new Error("mobile in protobase.config.ts must be an object such as { appId: 'com.example.app' }");
11
+ const { appId, plugins } = value;
12
+ if (typeof appId !== "string" || !appIdPattern.test(appId.toLowerCase())) throw new Error(`mobile.appId must be a reverse-DNS id such as com.example.app: at least two parts separated by dots, each starting with a letter and holding only letters, digits and underscores, not ${JSON.stringify(appId)}`);
13
+ if (plugins === void 0) return { appId };
14
+ if (!isRecord(plugins) || Object.values(plugins).some((spec) => typeof spec !== "string")) throw new Error("mobile.plugins must map each plugin's npm name to a version range, such as { '@capacitor/camera': '^8.0.0' }");
15
+ for (const [name, spec] of Object.entries(plugins)) {
16
+ const problem = pinnedProblem(name);
17
+ if (problem) throw new Error(problem);
18
+ if (unauthenticated.test(spec)) throw new Error(`mobile.plugins installs ${name} from ${spec}, over a connection that is not secure: use a version range, https or git+https`);
19
+ }
20
+ return {
21
+ appId,
22
+ plugins
23
+ };
24
+ };
25
+ //#endregion
26
+ export { checkMobileConfig, noMobileSection };
@@ -0,0 +1,13 @@
1
+ //#region ../mobile/package.json
2
+ var name = "@protobase/mobile";
3
+ var dependencies = {
4
+ "@capacitor/android": "8.5.3",
5
+ "@capacitor/app": "8.1.2",
6
+ "@capacitor/cli": "8.5.3",
7
+ "@capacitor/core": "8.5.3",
8
+ "@capacitor/ios": "8.5.3",
9
+ "@capacitor/splash-screen": "8.0.2",
10
+ "@capawesome/capacitor-live-update": "8.7.1"
11
+ };
12
+ //#endregion
13
+ export { dependencies, name };
@@ -0,0 +1,27 @@
1
+ import { installedPackage } from "./installed-package.js";
2
+ import { dependencies, name } from "./package.js";
3
+ //#region src/mobile/pinned-packages.ts
4
+ /**
5
+ * The packages @protobase/mobile pins, itself included, which `mobile.plugins` may neither pin again nor compile into
6
+ * the app. Read from its package.json and inlined into the CLI's build, so the CLI carries the list of the
7
+ * @protobase/mobile of its own version, the one it installs.
8
+ */
9
+ const pinnedPackages = /* @__PURE__ */ new Set([name, ...Object.keys(dependencies)]);
10
+ const liveUpdate = "@capawesome/capacitor-live-update";
11
+ /** Why the plugin `key`, a package that is or names `name`, may not be listed; `undefined` when it may. */
12
+ const pinnedProblem = (key, name = key) => {
13
+ if (name === liveUpdate) return `mobile.plugins lists ${key}, ${liveUpdate}: live updates come with Protobase's updater, which does not enable the plugin yet; remove it from mobile.plugins`;
14
+ if (pinnedPackages.has(name)) return `mobile.plugins lists ${key}, which ${name === key ? "comes" : `installs ${name}, which comes`} with Protobase at a fixed version: remove it from mobile.plugins`;
15
+ };
16
+ /**
17
+ * Checks the installed packages of the configured plugins `keys` in the workspace `dir`: one that is a pinned package
18
+ * under another name, such as an npm alias or a `file:` spec, is refused before Capacitor compiles it in.
19
+ */
20
+ const checkInstalledPlugins = (dir, keys) => {
21
+ for (const key of keys) {
22
+ const problem = pinnedProblem(key, installedPackage(dir, key).name);
23
+ if (problem) throw new Error(problem);
24
+ }
25
+ };
26
+ //#endregion
27
+ export { checkInstalledPlugins, pinnedPackages, pinnedProblem };
@@ -0,0 +1,4 @@
1
+ //#region src/mobile/platform.ts
2
+ const platforms = ["ios", "android"];
3
+ //#endregion
4
+ export { platforms };
@@ -0,0 +1,33 @@
1
+ import { resolveExtensions } from "../project/extensions.js";
2
+ import { parsePlatform, parsePort } from "./arguments.js";
3
+ //#region src/mobile/register.ts
4
+ const out = (text) => process.stdout.write(text);
5
+ const collect = (value, previous) => [...previous, value];
6
+ const registerMobile = (program) => {
7
+ const mobile = program.command("mobile").description("Build the project in the current directory as an iOS or Android app, from the mobile section of its protobase.config.ts");
8
+ const api = "--api <url>";
9
+ const apiHelp = "the server the app calls (default: the auth issuer, the project's baseURL)";
10
+ const extend = "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable";
11
+ mobile.command("run").description("Generate the native project and run the app in a simulator, an emulator or on a device").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--target <id>", "the device or simulator to run on (default: Capacitor asks)").option("--live", "open the running protobase dev instead of the app's own files, reloading as you save", false).option("--port <port>", "the port of protobase dev, for --live", parsePort, 5173).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
12
+ const { mobileRun } = await import("./run.js");
13
+ await mobileRun({
14
+ projectDir: process.cwd(),
15
+ platform: chosen,
16
+ extensions: resolveExtensions(opts.extend),
17
+ ...opts.api !== void 0 && { api: opts.api },
18
+ ...opts.target && { target: opts.target },
19
+ ...opts.live && { live: opts.port }
20
+ }, out);
21
+ });
22
+ mobile.command("open").description("Generate the native project and open it in Xcode or Android Studio").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
23
+ const { mobileOpen } = await import("./run.js");
24
+ await mobileOpen({
25
+ projectDir: process.cwd(),
26
+ platform: chosen,
27
+ extensions: resolveExtensions(opts.extend),
28
+ ...opts.api !== void 0 && { api: opts.api }
29
+ }, out);
30
+ });
31
+ };
32
+ //#endregion
33
+ export { registerMobile };
@@ -0,0 +1,84 @@
1
+ import { apiUrl, httpAllowances } from "./api-origin.js";
2
+ import { capRunArgs } from "./cap-run-args.js";
3
+ import { installedPackage } from "./installed-package.js";
4
+ import { capacitorRunner } from "./capacitor.js";
5
+ import { buildWebPart, placeholderWebPart } from "./web-part.js";
6
+ import { capacitorConfig, writeCapacitorConfig } from "./capacitor-config.js";
7
+ import { childEnv, envFileKeys, projectEnvFiles } from "./child-env.js";
8
+ import { runChild } from "./child-process.js";
9
+ import { nativeFingerprint } from "./fingerprint.js";
10
+ import { generatePlatform } from "./generate.js";
11
+ import { checkInstalledPlugins } from "./pinned-packages.js";
12
+ import { checkMobileConfig } from "./mobile-config.js";
13
+ import { loadMobileProject } from "./load-project.js";
14
+ import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from "./workspace.js";
15
+ import path from "node:path";
16
+ import { defaultAppName } from "@protobase/server";
17
+ //#region src/mobile/run.ts
18
+ const prepare = async ({ projectDir, platform, api, extensions, live }, { run = runChild, build }) => {
19
+ const env = childEnv({ ...process.env }, envFileKeys(projectEnvFiles(projectDir)));
20
+ if (live !== void 0 && api !== void 0) throw new Error("--live opens protobase dev, which serves the API itself: leave out --api");
21
+ const project = await loadMobileProject(projectDir, extensions);
22
+ const mobile = checkMobileConfig(project.mobile);
23
+ const url = live === void 0 ? apiUrl(api, project.auth?.issuer, platform) : new URL(`http://localhost:${live}`);
24
+ const allowances = httpAllowances(url);
25
+ const ws = workspaceDir(projectDir);
26
+ const plugins = Object.keys(mobile.plugins ?? {});
27
+ await prepareWorkspace(ws, workspacePackageJson({
28
+ mobileSpec: mobileSpec(),
29
+ ...mobile.plugins && { plugins: mobile.plugins }
30
+ }), (command, args) => run(command, args, {
31
+ cwd: ws,
32
+ env
33
+ }));
34
+ checkInstalledPlugins(ws, plugins);
35
+ if (live === void 0) await buildWebPart({
36
+ projectDir,
37
+ ws,
38
+ extensions,
39
+ apiOrigin: url.origin,
40
+ ...build && { build },
41
+ onWarning: (message) => process.stderr.write(`warning: ${message}\n`)
42
+ });
43
+ else await placeholderWebPart(ws);
44
+ const fingerprint = nativeFingerprint({
45
+ mobile: installedPackage(ws, "@protobase/mobile").version,
46
+ plugins: plugins.map((key) => [key, installedPackage(ws, key).version])
47
+ });
48
+ const appName = project.auth?.appName ?? defaultAppName;
49
+ await writeCapacitorConfig(ws, capacitorConfig({
50
+ appId: mobile.appId,
51
+ appName,
52
+ fingerprint,
53
+ plugins,
54
+ allowances
55
+ }));
56
+ const cap = capacitorRunner(ws, env, run);
57
+ await generatePlatform(ws, platform, allowances, cap);
58
+ return {
59
+ ws,
60
+ url,
61
+ fingerprint,
62
+ cap
63
+ };
64
+ };
65
+ const summary = (projectDir, { ws, url, fingerprint }) => `workspace ${path.relative(projectDir, ws)}, api ${url.origin}, native fingerprint ${fingerprint}\n`;
66
+ /** `protobase mobile run`: generates the native project and runs the app on a simulator, emulator or device. */
67
+ const mobileRun = async (input, out, deps = {}) => {
68
+ const prepared = await prepare(input, deps);
69
+ out(summary(input.projectDir, prepared));
70
+ await prepared.cap(capRunArgs({
71
+ platform: input.platform,
72
+ url: prepared.url,
73
+ ...input.target && { target: input.target },
74
+ ...input.live !== void 0 && { live: input.live }
75
+ }));
76
+ };
77
+ /** `protobase mobile open`: generates the native project and opens it in Xcode or Android Studio. */
78
+ const mobileOpen = async (input, out, deps = {}) => {
79
+ const prepared = await prepare(input, deps);
80
+ out(summary(input.projectDir, prepared));
81
+ await prepared.cap(["open", input.platform]);
82
+ };
83
+ //#endregion
84
+ export { mobileOpen, mobileRun };