@rebasepro/cli 0.26.0 → 0.27.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.
- package/dist/{apps-CnLDV5b6.js → apps-CdrFm7Y3.js} +2 -2
- package/dist/{apps-CnLDV5b6.js.map → apps-CdrFm7Y3.js.map} +1 -1
- package/dist/{build-Cza7ZQrp.js → build-D-t5FSg0.js} +10 -10
- package/dist/build-D-t5FSg0.js.map +1 -0
- package/dist/{bundle-C6yEtMJ-.js → bundle-CrAWbpbG.js} +120 -19
- package/dist/bundle-CrAWbpbG.js.map +1 -0
- package/dist/bundle.d.ts +25 -11
- package/dist/{cloud-BdnmqQaZ.js → cloud-B2_oJmK7.js} +369 -41
- package/dist/cloud-B2_oJmK7.js.map +1 -0
- package/dist/commands/cloud/auth.d.ts +13 -0
- package/dist/commands/cloud/bundle-deploy.d.ts +8 -15
- package/dist/commands/cloud/guests.d.ts +11 -0
- package/dist/commands/cloud/index.d.ts +1 -0
- package/dist/commands/cloud/projects.d.ts +4 -0
- package/dist/commands/cloud/resources.d.ts +22 -0
- package/dist/{fold-static-BnAK-anQ.js → fold-static-BGlpi22F.js} +2 -2
- package/dist/{fold-static-BnAK-anQ.js.map → fold-static-BGlpi22F.js.map} +1 -1
- package/dist/index.es.js +10 -10
- package/dist/{normalize-imports-D0zXlM6g.js → normalize-imports-CK_Mpcej.js} +2 -2
- package/dist/{normalize-imports-D0zXlM6g.js.map → normalize-imports-CK_Mpcej.js.map} +1 -1
- package/dist/{start-mVb6upwY.js → start-CflvYL60.js} +2 -2
- package/dist/{start-mVb6upwY.js.map → start-CflvYL60.js.map} +1 -1
- package/dist/utils/bundle-lock.d.ts +9 -0
- package/package.json +8 -8
- package/templates/overlays/baas/README.md +2 -2
- package/templates/overlays/baas/ai-instructions.md +3 -2
- package/templates/overlays/baas/package.json +1 -0
- package/templates/overlays/baas/pnpm-workspace.yaml +4 -0
- package/templates/template/.env.example +1 -1
- package/templates/template/ai-instructions.md +4 -3
- package/templates/template/pnpm-workspace.yaml +4 -1
- package/dist/build-Cza7ZQrp.js.map +0 -1
- package/dist/bundle-C6yEtMJ-.js.map +0 -1
- package/dist/cloud-BdnmqQaZ.js.map +0 -1
|
@@ -40,3 +40,16 @@ export declare function passwordOnTheCommandLine(args: {
|
|
|
40
40
|
export declare function loginCommand(rawArgs: string[]): Promise<void>;
|
|
41
41
|
export declare function logoutCommand(rawArgs: string[]): Promise<void>;
|
|
42
42
|
export declare function whoamiCommand(rawArgs: string[]): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* `rebase cloud access-token` — the bearer this CLI would send right now.
|
|
45
|
+
*
|
|
46
|
+
* For tools that reach the control plane on a person's behalf without a second
|
|
47
|
+
* login: the MCP server reads a project's data through the console's Studio
|
|
48
|
+
* proxy with it, so whoever is signed in to Rebase Cloud reaches every project
|
|
49
|
+
* their organizations hold, and no service key leaves the control plane. It is
|
|
50
|
+
* the same credential `requireClient` resolves — `REBASE_TOKEN`, the token
|
|
51
|
+
* `init --claim` stored for a linked project, or the login, refreshed first when
|
|
52
|
+
* it is close to expiry — so the control plane checks it exactly as it checks
|
|
53
|
+
* this CLI. The token is printed bare, so `$(rebase cloud access-token)` works.
|
|
54
|
+
*/
|
|
55
|
+
export declare function accessTokenCommand(rawArgs: string[]): Promise<void>;
|
|
@@ -18,23 +18,16 @@ export declare function packBundle(bundleDir: string, outPath: string, options?:
|
|
|
18
18
|
withModules?: boolean;
|
|
19
19
|
}): Promise<void>;
|
|
20
20
|
/**
|
|
21
|
-
* Pack a bundle for upload
|
|
21
|
+
* Pack a bundle for upload, with the dependency tree the build vendored for it.
|
|
22
22
|
*
|
|
23
|
-
* Vendoring
|
|
24
|
-
* every start in `npm install`,
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* into memory on every pod start, and a runtime rollout restarts every tenant's
|
|
28
|
-
* pods at once. Bundles it was sized against are a few hundred kB; a vendored
|
|
29
|
-
* one is tens of MB, up to the 100 MB cap — N pods starting together would hold
|
|
30
|
-
* N of them. A slower cold start per pod is the status quo every deploy has
|
|
31
|
-
* shipped with; a control plane out of memory is every tenant's outage. The
|
|
32
|
-
* platform's own rebuilds build with `--no-vendor` for the same shape of
|
|
33
|
-
* reason. When the control plane streams bundles, this is the one switch to
|
|
34
|
-
* flip, and `rebase cloud deploy` builds with `vendor: false` until then.
|
|
23
|
+
* Vendoring is what lets a pod untar and boot rather than spending 35-55s of
|
|
24
|
+
* every start in `npm install`, which is the bulk of a new instance's time to
|
|
25
|
+
* ready. The control plane streams an archive in both directions, so its size
|
|
26
|
+
* costs that process nothing.
|
|
35
27
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
28
|
+
* A vendored tree that takes the archive over the cap is left out rather than
|
|
29
|
+
* failing the deploy: a bundle without its dependencies still boots, only more
|
|
30
|
+
* slowly. `modulesLeftOut` says that happened.
|
|
38
31
|
*/
|
|
39
32
|
export declare function packBundleForUpload(bundleDir: string, outPath: string, manifest: RebaseBundleManifest, maxBytes?: number): Promise<{
|
|
40
33
|
bytes: number;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const GUESTS_FLAGS: {
|
|
2
|
+
readonly "--limit": StringConstructor;
|
|
3
|
+
readonly "--older-than": StringConstructor;
|
|
4
|
+
};
|
|
5
|
+
export declare const GUESTS_ACTIONS: readonly ["delete", "prune"];
|
|
6
|
+
/**
|
|
7
|
+
* `30d` as milliseconds, or undefined. A unit is required and the age cannot be
|
|
8
|
+
* zero: `--older-than 30` is a typo for something, and `0d` would be everyone.
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseAge(value: string): number | undefined;
|
|
11
|
+
export declare function guestsCommand(rawArgs: string[]): Promise<void>;
|
|
@@ -58,6 +58,7 @@ export declare const CLOUD_VALUE_FLAGS: {
|
|
|
58
58
|
readonly "--message": StringConstructor;
|
|
59
59
|
readonly "--month": StringConstructor;
|
|
60
60
|
readonly "--name": StringConstructor;
|
|
61
|
+
readonly "--older-than": StringConstructor;
|
|
61
62
|
readonly "--org": StringConstructor;
|
|
62
63
|
readonly "--output": StringConstructor;
|
|
63
64
|
readonly "--password": StringConstructor;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { type DeployTarget, type CloudClient } from "./context.js";
|
|
2
|
+
/** Documented in `action-help.ts`, and paired with it by `action-help.test.ts`. */
|
|
3
|
+
export declare const LIST_PROJECTS_FLAGS: {
|
|
4
|
+
readonly "--all-orgs": BooleanConstructor;
|
|
5
|
+
};
|
|
2
6
|
export declare function listProjects(rawArgs: string[]): Promise<void>;
|
|
3
7
|
/**
|
|
4
8
|
* Where this project says it runs.
|
|
@@ -92,6 +92,28 @@ export declare function describeRuntime(project: {
|
|
|
92
92
|
runtimeVersionPin?: string | null;
|
|
93
93
|
}): string;
|
|
94
94
|
export declare function statusCommand(rawArgs: string[]): Promise<void>;
|
|
95
|
+
/** What `/api/functions/metrics/:projectId/realtime` returns. Mirrors saas metrics.ts. */
|
|
96
|
+
interface TenantRealtime {
|
|
97
|
+
/** `null` when the instances could not be listed. */
|
|
98
|
+
instances?: {
|
|
99
|
+
name?: string;
|
|
100
|
+
/** `null` when this instance could not be asked, or its runtime does not report these. */
|
|
101
|
+
realtime?: {
|
|
102
|
+
sockets?: number;
|
|
103
|
+
channels?: number;
|
|
104
|
+
busFramesPublished?: number;
|
|
105
|
+
busFramesSkipped?: number;
|
|
106
|
+
} | null;
|
|
107
|
+
}[] | null;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* One row per instance, under a header, for `cloud metrics`.
|
|
111
|
+
*
|
|
112
|
+
* Per instance because that is the question: where the sockets landed. A group
|
|
113
|
+
* that stays on one instance shows as `skipped` climbing while `to bus` stays
|
|
114
|
+
* flat, and both count from when that instance started.
|
|
115
|
+
*/
|
|
116
|
+
export declare function realtimeTable(instances: NonNullable<TenantRealtime["instances"]>): string[];
|
|
95
117
|
export declare function metricsCommand(rawArgs: string[]): Promise<void>;
|
|
96
118
|
/**
|
|
97
119
|
* `rebase cloud webhooks` is retired, and says where to go instead.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { u as compareMountOrder, v as staticAppAddress } from "./manifest-BtzDy7KQ.js";
|
|
2
|
-
import {
|
|
2
|
+
import { C as toolStdio, y as foldStaticIntoBundle } from "./bundle-CrAWbpbG.js";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
@@ -198,4 +198,4 @@ async function foldFrontendIntoBundle(options) {
|
|
|
198
198
|
//#endregion
|
|
199
199
|
export { staticBuildEnv as i, foldFrontendIntoBundle as n, foldableApps as r, assertBuiltForPath as t };
|
|
200
200
|
|
|
201
|
-
//# sourceMappingURL=fold-static-
|
|
201
|
+
//# sourceMappingURL=fold-static-BGlpi22F.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fold-static-BnAK-anQ.js","names":[],"sources":["../src/fold-static.ts"],"sourcesContent":["/**\n * Folding a project's static apps into its backend bundle.\n *\n * Shared by `rebase build` and `rebase cloud deploy` deliberately. It lived in\n * the build *command* first, and `deploy` rebuilds the bundle itself — so a\n * deploy silently produced a bundle without the frontend, packed 164 KB where\n * 39 MB was expected, and the site 404'd on the managed runtime exactly as if\n * folding had never been written. Two callers building the same artefact must\n * share the step that completes it.\n *\n * Why fold at all: `bootFromBundle` serves static apps from `entry.static`\n * behind `REBASE_SERVE_STATIC` (default on). A managed tenant runs one pod, so\n * putting the built assets in the bundle gives it the shape a custom container\n * already had — site at `/`, admin at `/admin`, API at `/api` — which is the\n * only honest baseline for calling the managed runtime a drop-in replacement.\n *\n * **Every** static app is folded, each at its declared path. Folding used to\n * pick exactly one and refuse when it found two, which meant a project with a\n * site and an admin panel deployed with neither.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { foldStaticIntoBundle } from \"./bundle\";\nimport { compareMountOrder, staticAppAddress } from \"./manifest\";\nimport { toolStdio } from \"./utils/tool-stdio\";\n\n/** The apps section of a project manifest, as much of it as folding needs. */\nexport interface FoldableManifest {\n apps?: Record<string, {\n type?: string;\n build?: string;\n output?: string;\n path?: string;\n spa?: boolean;\n cms?: string;\n }>;\n}\n\nexport interface FoldOptions {\n projectRoot: string;\n manifest: FoldableManifest;\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Skip running each app's own build command; fold what is already built. */\n skipBuild?: boolean;\n /**\n * The static apps already built in this run, shared with `buildAssetApp`.\n * An app named here is not built again; an app built here is added. One\n * `rebase build` used to run the admin's `vite build && tsc` twice — once\n * to fold it, once for its own static bundle — with the same command, the\n * same environment and the same output directory.\n */\n builtApps?: Set<string>;\n log?: (message: string) => void;\n /** Send each app's build output to stderr: the caller's stdout carries a result. See `toolStdio`. */\n quietStdout?: boolean;\n}\n\nexport interface FoldOutcome {\n appName: string;\n fileCount: number;\n /** Public base path this app was folded in at. */\n path: string;\n /** The one hostname it answers on, when its `path` names one. */\n host?: string;\n}\n\n/** A static app as folding sees it, with the manifest's defaults applied. */\nexport interface FoldableApp {\n name: string;\n build?: string;\n output?: string;\n /**\n * Public base path, defaulted to `/`. Always a path: when the manifest's\n * `path` is a URL, this is the part after the hostname, which is what the\n * app is built for and mounted at.\n */\n path: string;\n /** The one hostname this app answers on, when its `path` is a URL. */\n host?: string;\n /** SPA fallback, defaulted to `true`. */\n spa: boolean;\n /** Where this app mounts the Rebase CMS, if it does. */\n cms?: string;\n}\n\n/**\n * Every static app in the manifest, in mount order.\n *\n * Longest path first, so the `/`-rooted app is registered last — its catch-all\n * would otherwise claim its siblings' URLs — and, at an equal path, the app with\n * a hostname before the one without (see `compareMountOrder`). Pure, so the\n * ordering is testable without a filesystem.\n */\nexport function foldableApps(manifest: FoldableManifest): {\n apps: FoldableApp[];\n /** Apps that cannot be folded, and why. */\n skipped: { name: string; reason: string }[];\n} {\n const apps: FoldableApp[] = [];\n const skipped: { name: string; reason: string }[] = [];\n\n for (const [name, app] of Object.entries(manifest.apps ?? {})) {\n if (app?.type !== \"static\") continue;\n if (!app.output) {\n skipped.push({ name,\nreason: `\"${name}\" declares no output directory — not folded in.` });\n continue;\n }\n const { host, path: appPath } = staticAppAddress(name, app);\n apps.push({\n name,\n build: app.build,\n output: app.output,\n path: appPath,\n ...(host ? { host } : {}),\n spa: app.spa ?? true,\n cms: app.cms\n });\n }\n\n apps.sort(compareMountOrder);\n return { apps,\nskipped };\n}\n\n/**\n * Assert a built app's assets are actually rooted at the path it is served from.\n *\n * An app mounted at `/admin` but built with Vite's default `base: \"/\"` emits\n * `<script src=\"/assets/index-a1b2.js\">`. The server serves `index.html` fine\n * and 404s every asset: a blank page, no server error, nothing in the logs. It\n * is the single most expensive silent failure in this design, so it is a build\n * error rather than a runtime surprise.\n *\n * Only `<script src>` and `<link href>` are inspected — those are what a bundler\n * rewrites through `base`. Author-written anchors and canonical URLs are not\n * evidence of a misbuild.\n */\nexport function assertBuiltForPath(\n indexHtml: string,\n basePath: string,\n appName: string\n): void {\n if (basePath === \"/\") return;\n\n const offenders: string[] = [];\n const pattern = /<(?:script|link)\\b[^>]*?\\b(?:src|href)\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n for (const match of indexHtml.matchAll(pattern)) {\n const ref = match[1];\n if (!ref.startsWith(\"/\")) continue;\n if (ref === `${basePath}` || ref.startsWith(`${basePath}/`)) continue;\n offenders.push(ref);\n }\n\n if (offenders.length === 0) return;\n\n throw new Error(\n `\"${appName}\" is declared at ${basePath} but its build emitted assets rooted at /.\\n` +\n ` index.html references: ${offenders.slice(0, 3).join(\", \")}\\n` +\n \" The app would load a blank page. Set `base` from REBASE_APP_BASE in its\\n\" +\n \" build config — see docs/apps-and-runtimes.md §4.2.\"\n );\n}\n\n/**\n * The environment every static app is built with, wherever that build is driven from.\n *\n * Shared because there are two drivers — `foldFrontendIntoBundle` here, and\n * `buildAssetApp` in `build.ts` for a standalone `type: \"static\"` app — and they\n * had already drifted: the path variables were duplicated into both, so a fix\n * applied to one shipped a bundle built the old way from the other. One function\n * makes that impossible rather than merely unlikely.\n *\n * ## REBASE_APP_*\n *\n * The declared path is a build-time input, not only a serving concern: Vite\n * reads `base` from REBASE_APP_BASE, and the trailing slash is that field's\n * convention. See `assertBuiltForPath`.\n *\n * For an app declared at a URL these carry the path part only — `/` for\n * `https://admin.example.com`. The hostname is where the platform routes the\n * app, not something its assets should name: an absolute `base` would pin\n * every script to production, so `vite preview` and any other hostname the app\n * is opened on would load it from somewhere else.\n *\n * ## NODE_ENV\n *\n * A built app is a production artifact by construction, so build it as one. Not\n * a formality: the scaffold's `.env` carries `NODE_ENV=development` for the dev\n * backend, and Vite's `loadEnv` promotes a `NODE_ENV` found in an env file into\n * the build unless the environment already sets one. So `rebase build` and\n * `rebase cloud deploy` shipped a *development* bundle — `import.meta.env.DEV\n * === true`, development React, dev-only branches live — from commands whose\n * whole purpose is to produce something deployable. Setting it here is what\n * closes it: Vite consults the env file's NODE_ENV only when `process.env`\n * has none.\n *\n * ## VITE_API_URL\n *\n * An app served by the backend it talks to has its API on its own origin by\n * construction, so a baked-in absolute URL can only be wrong. It was: that same\n * `.env` carries `VITE_API_URL=http://localhost:3001` and\n * `frontend/vite.config.ts` reads the project root via `envDir: \"..\"`, so a\n * stock deploy shipped a site whose every request went to whoever ran the build\n * — passing every server-side health check on the way out. Blanking it here\n * fixes the bundle even for a project whose `.env` predates the `init` fix, or\n * was written by hand. Empty is the right value rather than a missing one: the\n * client falls back to `window.location.origin`, which keeps working when a\n * custom domain is added.\n *\n * Vite prioritises `process.env.VITE_*` over `.env` files, so an explicit\n * `VITE_API_URL=https://api.example.com rebase cloud deploy` still wins — the\n * cross-origin escape hatch stays open, it just has to be deliberate. Nothing on\n * this path loads the project `.env` into `process.env`, so a value inherited\n * here really was set by the caller.\n */\nexport function staticBuildEnv(appPath: string, appName: string): Record<string, string> {\n return {\n REBASE_APP_PATH: appPath,\n REBASE_APP_BASE: appPath === \"/\" ? \"/\" : `${appPath}/`,\n REBASE_APP_NAME: appName,\n NODE_ENV: \"production\",\n VITE_API_URL: process.env.VITE_API_URL ?? \"\"\n };\n}\n\n/**\n * Build the project's static apps and fold them into the backend bundle.\n *\n * Throws rather than exiting, so the caller decides whether a missing frontend\n * should fail its command — a `build` may reasonably want to stop, and so should\n * a deploy, but that is not this function's call to make.\n */\nexport async function foldFrontendIntoBundle(options: FoldOptions): Promise<FoldOutcome[]> {\n const { projectRoot, manifest, bundleDir, skipBuild } = options;\n const log = options.log ?? ((m: string) => console.log(m));\n\n const { apps, skipped } = foldableApps(manifest);\n for (const { reason } of skipped) log(chalk.yellow(` ⚠ ${reason}`));\n if (apps.length === 0) return [];\n\n const outcomes: FoldOutcome[] = [];\n\n for (const app of apps) {\n if (app.build && !skipBuild && !options.builtApps?.has(app.name)) {\n await execa(app.build, {\n cwd: projectRoot,\n stdio: toolStdio(options.quietStdout),\n shell: true,\n env: staticBuildEnv(app.path, app.name)\n });\n options.builtApps?.add(app.name);\n }\n\n const assetsDir = path.join(projectRoot, app.output as string);\n if (!fs.existsSync(assetsDir)) {\n // Exited 0 and produced nothing where the manifest says it should.\n // Folding that ships an empty site, which from the outside is\n // indistinguishable from a broken deploy.\n throw new Error(\n `\"${app.name}\" declared output \"${app.output}\" does not exist after building — ` +\n \"the bundle would ship without a frontend.\"\n );\n }\n\n const indexHtml = path.join(assetsDir, \"index.html\");\n if (fs.existsSync(indexHtml)) {\n assertBuiltForPath(fs.readFileSync(indexHtml, \"utf8\"), app.path, app.name);\n }\n\n const { fileCount } = foldStaticIntoBundle({\n bundleDir,\n assetsDir,\n appName: app.name,\n path: app.path,\n host: app.host,\n spa: app.spa,\n cms: app.cms\n });\n outcomes.push({ appName: app.name,\nfileCount,\npath: app.path,\n...(app.host ? { host: app.host } : {}) });\n }\n\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,aAAa,UAI3B;CACE,MAAM,OAAsB,CAAC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1
|
+
{"version":3,"file":"fold-static-BGlpi22F.js","names":[],"sources":["../src/fold-static.ts"],"sourcesContent":["/**\n * Folding a project's static apps into its backend bundle.\n *\n * Shared by `rebase build` and `rebase cloud deploy` deliberately. It lived in\n * the build *command* first, and `deploy` rebuilds the bundle itself — so a\n * deploy silently produced a bundle without the frontend, packed 164 KB where\n * 39 MB was expected, and the site 404'd on the managed runtime exactly as if\n * folding had never been written. Two callers building the same artefact must\n * share the step that completes it.\n *\n * Why fold at all: `bootFromBundle` serves static apps from `entry.static`\n * behind `REBASE_SERVE_STATIC` (default on). A managed tenant runs one pod, so\n * putting the built assets in the bundle gives it the shape a custom container\n * already had — site at `/`, admin at `/admin`, API at `/api` — which is the\n * only honest baseline for calling the managed runtime a drop-in replacement.\n *\n * **Every** static app is folded, each at its declared path. Folding used to\n * pick exactly one and refuse when it found two, which meant a project with a\n * site and an admin panel deployed with neither.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport chalk from \"chalk\";\nimport { foldStaticIntoBundle } from \"./bundle\";\nimport { compareMountOrder, staticAppAddress } from \"./manifest\";\nimport { toolStdio } from \"./utils/tool-stdio\";\n\n/** The apps section of a project manifest, as much of it as folding needs. */\nexport interface FoldableManifest {\n apps?: Record<string, {\n type?: string;\n build?: string;\n output?: string;\n path?: string;\n spa?: boolean;\n cms?: string;\n }>;\n}\n\nexport interface FoldOptions {\n projectRoot: string;\n manifest: FoldableManifest;\n /** The backend bundle directory, already written. */\n bundleDir: string;\n /** Skip running each app's own build command; fold what is already built. */\n skipBuild?: boolean;\n /**\n * The static apps already built in this run, shared with `buildAssetApp`.\n * An app named here is not built again; an app built here is added. One\n * `rebase build` used to run the admin's `vite build && tsc` twice — once\n * to fold it, once for its own static bundle — with the same command, the\n * same environment and the same output directory.\n */\n builtApps?: Set<string>;\n log?: (message: string) => void;\n /** Send each app's build output to stderr: the caller's stdout carries a result. See `toolStdio`. */\n quietStdout?: boolean;\n}\n\nexport interface FoldOutcome {\n appName: string;\n fileCount: number;\n /** Public base path this app was folded in at. */\n path: string;\n /** The one hostname it answers on, when its `path` names one. */\n host?: string;\n}\n\n/** A static app as folding sees it, with the manifest's defaults applied. */\nexport interface FoldableApp {\n name: string;\n build?: string;\n output?: string;\n /**\n * Public base path, defaulted to `/`. Always a path: when the manifest's\n * `path` is a URL, this is the part after the hostname, which is what the\n * app is built for and mounted at.\n */\n path: string;\n /** The one hostname this app answers on, when its `path` is a URL. */\n host?: string;\n /** SPA fallback, defaulted to `true`. */\n spa: boolean;\n /** Where this app mounts the Rebase CMS, if it does. */\n cms?: string;\n}\n\n/**\n * Every static app in the manifest, in mount order.\n *\n * Longest path first, so the `/`-rooted app is registered last — its catch-all\n * would otherwise claim its siblings' URLs — and, at an equal path, the app with\n * a hostname before the one without (see `compareMountOrder`). Pure, so the\n * ordering is testable without a filesystem.\n */\nexport function foldableApps(manifest: FoldableManifest): {\n apps: FoldableApp[];\n /** Apps that cannot be folded, and why. */\n skipped: { name: string; reason: string }[];\n} {\n const apps: FoldableApp[] = [];\n const skipped: { name: string; reason: string }[] = [];\n\n for (const [name, app] of Object.entries(manifest.apps ?? {})) {\n if (app?.type !== \"static\") continue;\n if (!app.output) {\n skipped.push({ name,\nreason: `\"${name}\" declares no output directory — not folded in.` });\n continue;\n }\n const { host, path: appPath } = staticAppAddress(name, app);\n apps.push({\n name,\n build: app.build,\n output: app.output,\n path: appPath,\n ...(host ? { host } : {}),\n spa: app.spa ?? true,\n cms: app.cms\n });\n }\n\n apps.sort(compareMountOrder);\n return { apps,\nskipped };\n}\n\n/**\n * Assert a built app's assets are actually rooted at the path it is served from.\n *\n * An app mounted at `/admin` but built with Vite's default `base: \"/\"` emits\n * `<script src=\"/assets/index-a1b2.js\">`. The server serves `index.html` fine\n * and 404s every asset: a blank page, no server error, nothing in the logs. It\n * is the single most expensive silent failure in this design, so it is a build\n * error rather than a runtime surprise.\n *\n * Only `<script src>` and `<link href>` are inspected — those are what a bundler\n * rewrites through `base`. Author-written anchors and canonical URLs are not\n * evidence of a misbuild.\n */\nexport function assertBuiltForPath(\n indexHtml: string,\n basePath: string,\n appName: string\n): void {\n if (basePath === \"/\") return;\n\n const offenders: string[] = [];\n const pattern = /<(?:script|link)\\b[^>]*?\\b(?:src|href)\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n for (const match of indexHtml.matchAll(pattern)) {\n const ref = match[1];\n if (!ref.startsWith(\"/\")) continue;\n if (ref === `${basePath}` || ref.startsWith(`${basePath}/`)) continue;\n offenders.push(ref);\n }\n\n if (offenders.length === 0) return;\n\n throw new Error(\n `\"${appName}\" is declared at ${basePath} but its build emitted assets rooted at /.\\n` +\n ` index.html references: ${offenders.slice(0, 3).join(\", \")}\\n` +\n \" The app would load a blank page. Set `base` from REBASE_APP_BASE in its\\n\" +\n \" build config — see docs/apps-and-runtimes.md §4.2.\"\n );\n}\n\n/**\n * The environment every static app is built with, wherever that build is driven from.\n *\n * Shared because there are two drivers — `foldFrontendIntoBundle` here, and\n * `buildAssetApp` in `build.ts` for a standalone `type: \"static\"` app — and they\n * had already drifted: the path variables were duplicated into both, so a fix\n * applied to one shipped a bundle built the old way from the other. One function\n * makes that impossible rather than merely unlikely.\n *\n * ## REBASE_APP_*\n *\n * The declared path is a build-time input, not only a serving concern: Vite\n * reads `base` from REBASE_APP_BASE, and the trailing slash is that field's\n * convention. See `assertBuiltForPath`.\n *\n * For an app declared at a URL these carry the path part only — `/` for\n * `https://admin.example.com`. The hostname is where the platform routes the\n * app, not something its assets should name: an absolute `base` would pin\n * every script to production, so `vite preview` and any other hostname the app\n * is opened on would load it from somewhere else.\n *\n * ## NODE_ENV\n *\n * A built app is a production artifact by construction, so build it as one. Not\n * a formality: the scaffold's `.env` carries `NODE_ENV=development` for the dev\n * backend, and Vite's `loadEnv` promotes a `NODE_ENV` found in an env file into\n * the build unless the environment already sets one. So `rebase build` and\n * `rebase cloud deploy` shipped a *development* bundle — `import.meta.env.DEV\n * === true`, development React, dev-only branches live — from commands whose\n * whole purpose is to produce something deployable. Setting it here is what\n * closes it: Vite consults the env file's NODE_ENV only when `process.env`\n * has none.\n *\n * ## VITE_API_URL\n *\n * An app served by the backend it talks to has its API on its own origin by\n * construction, so a baked-in absolute URL can only be wrong. It was: that same\n * `.env` carries `VITE_API_URL=http://localhost:3001` and\n * `frontend/vite.config.ts` reads the project root via `envDir: \"..\"`, so a\n * stock deploy shipped a site whose every request went to whoever ran the build\n * — passing every server-side health check on the way out. Blanking it here\n * fixes the bundle even for a project whose `.env` predates the `init` fix, or\n * was written by hand. Empty is the right value rather than a missing one: the\n * client falls back to `window.location.origin`, which keeps working when a\n * custom domain is added.\n *\n * Vite prioritises `process.env.VITE_*` over `.env` files, so an explicit\n * `VITE_API_URL=https://api.example.com rebase cloud deploy` still wins — the\n * cross-origin escape hatch stays open, it just has to be deliberate. Nothing on\n * this path loads the project `.env` into `process.env`, so a value inherited\n * here really was set by the caller.\n */\nexport function staticBuildEnv(appPath: string, appName: string): Record<string, string> {\n return {\n REBASE_APP_PATH: appPath,\n REBASE_APP_BASE: appPath === \"/\" ? \"/\" : `${appPath}/`,\n REBASE_APP_NAME: appName,\n NODE_ENV: \"production\",\n VITE_API_URL: process.env.VITE_API_URL ?? \"\"\n };\n}\n\n/**\n * Build the project's static apps and fold them into the backend bundle.\n *\n * Throws rather than exiting, so the caller decides whether a missing frontend\n * should fail its command — a `build` may reasonably want to stop, and so should\n * a deploy, but that is not this function's call to make.\n */\nexport async function foldFrontendIntoBundle(options: FoldOptions): Promise<FoldOutcome[]> {\n const { projectRoot, manifest, bundleDir, skipBuild } = options;\n const log = options.log ?? ((m: string) => console.log(m));\n\n const { apps, skipped } = foldableApps(manifest);\n for (const { reason } of skipped) log(chalk.yellow(` ⚠ ${reason}`));\n if (apps.length === 0) return [];\n\n const outcomes: FoldOutcome[] = [];\n\n for (const app of apps) {\n if (app.build && !skipBuild && !options.builtApps?.has(app.name)) {\n await execa(app.build, {\n cwd: projectRoot,\n stdio: toolStdio(options.quietStdout),\n shell: true,\n env: staticBuildEnv(app.path, app.name)\n });\n options.builtApps?.add(app.name);\n }\n\n const assetsDir = path.join(projectRoot, app.output as string);\n if (!fs.existsSync(assetsDir)) {\n // Exited 0 and produced nothing where the manifest says it should.\n // Folding that ships an empty site, which from the outside is\n // indistinguishable from a broken deploy.\n throw new Error(\n `\"${app.name}\" declared output \"${app.output}\" does not exist after building — ` +\n \"the bundle would ship without a frontend.\"\n );\n }\n\n const indexHtml = path.join(assetsDir, \"index.html\");\n if (fs.existsSync(indexHtml)) {\n assertBuiltForPath(fs.readFileSync(indexHtml, \"utf8\"), app.path, app.name);\n }\n\n const { fileCount } = foldStaticIntoBundle({\n bundleDir,\n assetsDir,\n appName: app.name,\n path: app.path,\n host: app.host,\n spa: app.spa,\n cms: app.cms\n });\n outcomes.push({ appName: app.name,\nfileCount,\npath: app.path,\n...(app.host ? { host: app.host } : {}) });\n }\n\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,aAAa,UAI3B;CACE,MAAM,OAAsB,CAAC;CAC7B,MAAM,UAA8C,CAAC;CAErD,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,SAAS,QAAQ,CAAC,CAAC,GAAG;EAC3D,IAAI,KAAK,SAAS,UAAU;EAC5B,IAAI,CAAC,IAAI,QAAQ;GACb,QAAQ,KAAK;IAAE;IAC3B,QAAQ,IAAI,KAAK;GAAiD,CAAC;GACvD;EACJ;EACA,MAAM,EAAE,MAAM,MAAM,YAAY,iBAAiB,MAAM,GAAG;EAC1D,KAAK,KAAK;GACN;GACA,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,MAAM;GACN,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;GACvB,KAAK,IAAI,OAAO;GAChB,KAAK,IAAI;EACb,CAAC;CACL;CAEA,KAAK,KAAK,iBAAiB;CAC3B,OAAO;EAAE;EACb;CAAQ;AACR;;;;;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,KAAK,eAAe,IAAI,MAAM,IAAI,IAAI;GAC1C,CAAC;GACD,QAAQ,WAAW,IAAI,IAAI,IAAI;EACnC;EAEA,MAAM,YAAY,KAAK,KAAK,aAAa,IAAI,MAAgB;EAC7D,IAAI,CAAC,GAAG,WAAW,SAAS,GAIxB,MAAM,IAAI,MACN,IAAI,IAAI,KAAK,qBAAqB,IAAI,OAAO,4EAEjD;EAGJ,MAAM,YAAY,KAAK,KAAK,WAAW,YAAY;EACnD,IAAI,GAAG,WAAW,SAAS,GACvB,mBAAmB,GAAG,aAAa,WAAW,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI;EAG7E,MAAM,EAAE,cAAc,qBAAqB;GACvC;GACA;GACA,SAAS,IAAI;GACb,MAAM,IAAI;GACV,MAAM,IAAI;GACV,KAAK,IAAI;GACT,KAAK,IAAI;EACb,CAAC;EACD,SAAS,KAAK;GAAE,SAAS,IAAI;GACrC;GACA,MAAM,IAAI;GACV,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;EAAG,CAAC;CACrC;CAEA,OAAO;AACX"}
|
package/dist/index.es.js
CHANGED
|
@@ -2,7 +2,7 @@ import { i as recordEvent, n as isEnabled, u as errorClass } from "./telemetry-C
|
|
|
2
2
|
import { E as unknownCommand, b as UsageError, i as failAsJson, p as requireProjectRoot, x as parseCommandArgs, y as wantsJsonOutput } from "./project-CasK56vN.js";
|
|
3
3
|
import { n as cliVersion } from "./version-Buyyo1ut.js";
|
|
4
4
|
import { _ as selectDeployApp, a as DEFAULT_SCHEMA_FILE, b as validateManifest, c as buildableApps, d as findBackendApp, f as formatAppAddress, g as resolveBackendPaths, h as manifestPath, i as DEFAULT_FUNCTIONS_DIR, l as cmsMountOf, m as manifestExists, n as DEFAULT_CONFIG_DIR, o as ManifestError, p as loadManifest, r as DEFAULT_CRONS_DIR, s as assessManagedCompatibility, t as CURRENT_RUNTIME_RANGE, u as compareMountOrder, v as staticAppAddress, x as writeManifest, y as synthesizeManifest } from "./manifest-BtzDy7KQ.js";
|
|
5
|
-
import { _ as
|
|
5
|
+
import { S as vendorDependencies, _ as detectStorageAuthorize, a as VENDOR_TARGET_CPU, b as normalizeEsmSpecifiers, c as buildStaticBundle, d as commentSpans, f as composeBundleManifest, g as detectNativeDependencies, h as detectFrameworkDepDrift, i as VENDOR_SIZE_WARN_BYTES, l as bundledNpmrc, m as detectDeclaredDepConflicts, n as UNVENDORED_COST, o as VENDOR_TARGET_OS, p as describeDepConflicts, r as VENDOR_SIZE_MAX_BYTES, s as buildBundle, t as DEFAULT_BUNDLE_DIR, u as collectDeclaredDependencies, v as findUnusedServerEntry, x as unvendoredReason, y as foldStaticIntoBundle } from "./bundle-CrAWbpbG.js";
|
|
6
6
|
import chalk from "chalk";
|
|
7
7
|
import arg from "arg";
|
|
8
8
|
import path from "path";
|
|
@@ -114,7 +114,7 @@ async function commandVocabulary(command) {
|
|
|
114
114
|
aliases: {}
|
|
115
115
|
};
|
|
116
116
|
case "apps": return {
|
|
117
|
-
subcommands: (await import("./apps-
|
|
117
|
+
subcommands: (await import("./apps-CdrFm7Y3.js")).APPS_SUBCOMMANDS,
|
|
118
118
|
aliases: {}
|
|
119
119
|
};
|
|
120
120
|
case "telemetry": return {
|
|
@@ -126,7 +126,7 @@ async function commandVocabulary(command) {
|
|
|
126
126
|
aliases: {}
|
|
127
127
|
};
|
|
128
128
|
case "cloud": {
|
|
129
|
-
const cloud = await import("./cloud-
|
|
129
|
+
const cloud = await import("./cloud-B2_oJmK7.js");
|
|
130
130
|
return {
|
|
131
131
|
subcommands: cloud.CLOUD_GROUP_NAMES,
|
|
132
132
|
aliases: cloud.GROUP_ALIASES
|
|
@@ -311,17 +311,17 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
311
311
|
break;
|
|
312
312
|
}
|
|
313
313
|
case "normalize-imports": {
|
|
314
|
-
const { normalizeImportsCommand } = await import("./normalize-imports-
|
|
314
|
+
const { normalizeImportsCommand } = await import("./normalize-imports-CK_Mpcej.js");
|
|
315
315
|
await normalizeImportsCommand(args);
|
|
316
316
|
break;
|
|
317
317
|
}
|
|
318
318
|
case "build": {
|
|
319
|
-
const { buildCommand } = await import("./build-
|
|
319
|
+
const { buildCommand } = await import("./build-D-t5FSg0.js").then((n) => n.n);
|
|
320
320
|
await buildCommand(args);
|
|
321
321
|
break;
|
|
322
322
|
}
|
|
323
323
|
case "start": {
|
|
324
|
-
const { startCommand } = await import("./start-
|
|
324
|
+
const { startCommand } = await import("./start-CflvYL60.js");
|
|
325
325
|
await startCommand(args);
|
|
326
326
|
break;
|
|
327
327
|
}
|
|
@@ -331,7 +331,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
331
331
|
break;
|
|
332
332
|
}
|
|
333
333
|
case "apps": {
|
|
334
|
-
const { appsCommand } = await import("./apps-
|
|
334
|
+
const { appsCommand } = await import("./apps-CdrFm7Y3.js");
|
|
335
335
|
await appsCommand(effectiveSubcommand, args);
|
|
336
336
|
break;
|
|
337
337
|
}
|
|
@@ -386,7 +386,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
386
386
|
break;
|
|
387
387
|
}
|
|
388
388
|
case "cloud": {
|
|
389
|
-
const { cloudCommand } = await import("./cloud-
|
|
389
|
+
const { cloudCommand } = await import("./cloud-B2_oJmK7.js");
|
|
390
390
|
await cloudCommand(effectiveSubcommand, args);
|
|
391
391
|
break;
|
|
392
392
|
}
|
|
@@ -395,7 +395,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
395
395
|
await telemetryCommand(args);
|
|
396
396
|
break;
|
|
397
397
|
}
|
|
398
|
-
default: unknownCommand(command, namespacedCommands, "", { cloud: (await import("./cloud-
|
|
398
|
+
default: unknownCommand(command, namespacedCommands, "", { cloud: (await import("./cloud-B2_oJmK7.js")).CLOUD_GROUP_NAMES });
|
|
399
399
|
}
|
|
400
400
|
}
|
|
401
401
|
/** The global help. Exported so its Options block can be held against {@link ROOT_FLAGS}. */
|
|
@@ -501,6 +501,6 @@ function telemetryNotice() {
|
|
|
501
501
|
return chalk.gray(`Usage sharing: ${sharing ? "on" : "off"} — ${chalk.cyan("rebase telemetry")} to inspect or change\n`);
|
|
502
502
|
}
|
|
503
503
|
//#endregion
|
|
504
|
-
export { CURRENT_RUNTIME_RANGE, DEFAULT_BUNDLE_DIR, DEFAULT_CONFIG_DIR, DEFAULT_CRONS_DIR, DEFAULT_FUNCTIONS_DIR, DEFAULT_SCHEMA_FILE, ManifestError, VENDOR_SIZE_MAX_BYTES, VENDOR_SIZE_WARN_BYTES, VENDOR_TARGET_CPU, VENDOR_TARGET_OS, assessManagedCompatibility, buildBundle, buildStaticBundle, buildableApps, bundledNpmrc, cmsMountOf, collectDeclaredDependencies, commentSpans, compareMountOrder, composeBundleManifest, describeDepConflicts, detectDeclaredDepConflicts, detectFrameworkDepDrift, detectNativeDependencies, detectStorageAuthorize, entry, findBackendApp, findUnusedServerEntry, foldStaticIntoBundle, formatAppAddress, loadManifest, manifestExists, manifestPath, normalizeEsmSpecifiers, resolveBackendPaths, selectDeployApp, staticAppAddress, synthesizeManifest, validateManifest, vendorDependencies, writeManifest };
|
|
504
|
+
export { CURRENT_RUNTIME_RANGE, DEFAULT_BUNDLE_DIR, DEFAULT_CONFIG_DIR, DEFAULT_CRONS_DIR, DEFAULT_FUNCTIONS_DIR, DEFAULT_SCHEMA_FILE, ManifestError, UNVENDORED_COST, VENDOR_SIZE_MAX_BYTES, VENDOR_SIZE_WARN_BYTES, VENDOR_TARGET_CPU, VENDOR_TARGET_OS, assessManagedCompatibility, buildBundle, buildStaticBundle, buildableApps, bundledNpmrc, cmsMountOf, collectDeclaredDependencies, commentSpans, compareMountOrder, composeBundleManifest, describeDepConflicts, detectDeclaredDepConflicts, detectFrameworkDepDrift, detectNativeDependencies, detectStorageAuthorize, entry, findBackendApp, findUnusedServerEntry, foldStaticIntoBundle, formatAppAddress, loadManifest, manifestExists, manifestPath, normalizeEsmSpecifiers, resolveBackendPaths, selectDeployApp, staticAppAddress, synthesizeManifest, unvendoredReason, validateManifest, vendorDependencies, writeManifest };
|
|
505
505
|
|
|
506
506
|
//# sourceMappingURL=index.es.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { x as parseCommandArgs } from "./project-CasK56vN.js";
|
|
2
|
-
import {
|
|
2
|
+
import { b as normalizeEsmSpecifiers } from "./bundle-CrAWbpbG.js";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
@@ -104,4 +104,4 @@ async function normalizeImportsCommand(rawArgs) {
|
|
|
104
104
|
//#endregion
|
|
105
105
|
export { normalizeImportsCommand };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=normalize-imports-
|
|
107
|
+
//# sourceMappingURL=normalize-imports-CK_Mpcej.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-imports-
|
|
1
|
+
{"version":3,"file":"normalize-imports-CK_Mpcej.js","names":[],"sources":["../src/commands/normalize-imports.ts"],"sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\n\nimport chalk from \"chalk\";\n\nimport { normalizeEsmSpecifiers } from \"../bundle\";\nimport { parseCommandArgs } from \"../utils/args\";\n\n/**\n * Give compiled output the relative-import extensions Node's ESM loader needs.\n *\n * ## Why a project needs this at all\n *\n * TypeScript does not rewrite module specifiers, deliberately and by long-stated\n * policy: what you write is what it emits. Node's ESM loader, equally\n * deliberately, resolves no extensions — `./authors` is not a module, only\n * `./authors.js` is. Between those two positions sits every project that writes\n * extensionless relative imports, which is most of them, and which\n * `moduleResolution: \"bundler\"` — what this scaffold ships — is designed for.\n *\n * The usual escape is to write the *output* extension in the *source*:\n * `import x from \"./authors.js\"` in a file called `authors.ts`. It works, and it\n * is a tax on every import in the project to satisfy a step the toolchain could\n * take itself. This is that step.\n *\n * ## Why it is a command\n *\n * `rebase build` has always done this to its own bundle — the specifiers in\n * `dist-bundle` are complete because {@link normalizeEsmSpecifiers} completes\n * them. Nothing did it for the plain `tsc` output that `rebase eject` runs\n * (`node dist/backend/src/index.js`) or that a self-hoster runs after\n * `pnpm build`. So the templates wrote `.js` in source, which is the tax, and\n * removing it silently broke eject at `pnpm start` while `check:eject` — which\n * typechecks with `noEmit` — stayed green.\n *\n * One implementation, on both paths, callable from a package.json script.\n *\n * Mechanical and verifiable: only relative specifiers are touched, and only when\n * the target resolves to a file that exists. Idempotent, so a build that runs it\n * twice is a build that runs it once.\n */\nexport const NORMALIZE_IMPORTS_FLAGS = {\n /** Report what would change without writing anything. */\n \"--check\": Boolean\n} as const;\n\nconst HELP = `\n${chalk.bold(\"rebase normalize-imports\")} — complete the relative imports in compiled output\n\n${chalk.green.bold(\"Usage\")}\n rebase normalize-imports ${chalk.blue(\"<dir>\")} [--check]\n\n${chalk.green.bold(\"What it does\")}\n TypeScript emits your module specifiers verbatim, and Node's ESM loader does\n not guess extensions — so \\`./authors\\` compiles fine and fails at run time.\n This rewrites each relative specifier in the emitted JavaScript to the file it\n actually resolves to, so your source can stay extensionless.\n\n Only relative specifiers, only when the target exists on disk, and idempotent.\n\n${chalk.green.bold(\"Arguments\")}\n ${chalk.blue(\"<dir>\")} The directory tsc emitted into, e.g. ${chalk.cyan(\"dist\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--check\")} Report what would change and exit 1 if anything would\n ${chalk.gray(\"(for CI — the build itself should just run the rewrite)\")}\n\n${chalk.green.bold(\"Where it runs\")}\n The scaffold's ${chalk.cyan(\"config\")} and ${chalk.cyan(\"backend\")} build scripts, after ${chalk.cyan(\"tsc\")}.\n ${chalk.cyan(\"rebase build\")} already does the same to the bundle it writes.\n`;\n\nexport async function normalizeImportsCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals, help } = parseCommandArgs({\n spec: NORMALIZE_IMPORTS_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"normalize-imports\",\n maxPositionals: 1\n });\n\n if (help) {\n console.log(HELP);\n return;\n }\n\n const target = positionals[0] ?? \"dist\";\n const outDir = path.resolve(process.cwd(), target);\n\n // A missing directory is the common shape of \"tsc did not run\", and saying\n // so beats a rewrite that reports zero changes and looks like success.\n if (!fs.existsSync(outDir)) {\n throw new Error(\n `${target} does not exist — run your build first. `\n + \"This step rewrites what the compiler emitted; it does not compile.\"\n );\n }\n\n // `--check` reports and writes nothing: it is what a CI job runs to ask\n // whether the build did this step, and a check that repaired the output\n // would answer \"no\" once and \"yes\" for ever after.\n const check = flags[\"--check\"] === true;\n const { rewritten, unresolved } = normalizeEsmSpecifiers(outDir, { write: !check });\n // A failed check is a verdict, on stderr with exit 1 — not a thrown error,\n // whose handler adds a stack-trace hint to an answer that has no stack.\n const say = check ? console.error : console.log;\n\n if (unresolved.length > 0) {\n say(chalk.yellow(` ⚠ ${unresolved.length} relative import(s) resolve to no file:`));\n for (const specifier of unresolved.slice(0, 10)) {\n say(chalk.dim(` ${specifier}`));\n }\n if (unresolved.length > 10) {\n say(chalk.dim(` …and ${unresolved.length - 10} more`));\n }\n say(chalk.dim(\" These will throw ERR_MODULE_NOT_FOUND at run time. This command cannot complete them:\"));\n say(chalk.dim(\" there is no file to point them at — fix the import, or the build that should emit it.\"));\n }\n\n if (check) {\n if (rewritten > 0) {\n console.error(chalk.red(\n `✗ ${rewritten} relative import(s) in ${target} are incomplete for Node ESM. `\n + `Run \\`rebase normalize-imports ${target}\\` as part of the build.`\n ));\n }\n if (rewritten > 0 || unresolved.length > 0) {\n process.exitCode = 1;\n return;\n }\n console.log(chalk.green(`✓ every relative import in ${target} is complete`));\n return;\n }\n\n console.log(\n rewritten > 0\n ? chalk.dim(` completed ${rewritten} relative import(s) in ${target}/ for Node ESM`)\n : chalk.dim(` ${target}/ — every relative import was already complete`)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,0BAA0B;;AAEnC,WAAW,QACf;AAE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IAAI,WAAW,SAAS,IACpB,IAAI,MAAM,IAAI,cAAc,WAAW,SAAS,GAAG,MAAM,CAAC;EAE9D,IAAI,MAAM,IAAI,2FAA2F,CAAC;EAC1G,IAAI,MAAM,IAAI,2FAA2F,CAAC;CAC9G;CAEA,IAAI,OAAO;EACP,IAAI,YAAY,GACZ,QAAQ,MAAM,MAAM,IAChB,KAAK,UAAU,yBAAyB,OAAO,+DACX,OAAO,yBAC/C,CAAC;EAEL,IAAI,YAAY,KAAK,WAAW,SAAS,GAAG;GACxC,QAAQ,WAAW;GACnB;EACJ;EACA,QAAQ,IAAI,MAAM,MAAM,8BAA8B,OAAO,aAAa,CAAC;EAC3E;CACJ;CAEA,QAAQ,IACJ,YAAY,IACN,MAAM,IAAI,eAAe,UAAU,yBAAyB,OAAO,eAAe,IAClF,MAAM,IAAI,KAAK,OAAO,+CAA+C,CAC/E;AACJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
|
|
2
2
|
import { c as findProjectRoot, d as readEnvFile, o as findEnvFile, p as requireProjectRoot, w as wantsHelp, x as parseCommandArgs } from "./project-CasK56vN.js";
|
|
3
|
-
import { t as DEFAULT_BUNDLE_DIR } from "./bundle-
|
|
3
|
+
import { t as DEFAULT_BUNDLE_DIR } from "./bundle-CrAWbpbG.js";
|
|
4
4
|
import { t as invokedRebaseCommand } from "./invoked-command-CG_rIa_o.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
import fs from "fs";
|
|
@@ -316,4 +316,4 @@ async function startWorkspaceBackend(projectRoot, env) {
|
|
|
316
316
|
//#endregion
|
|
317
317
|
export { startCommand };
|
|
318
318
|
|
|
319
|
-
//# sourceMappingURL=start-
|
|
319
|
+
//# sourceMappingURL=start-CflvYL60.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-mVb6upwY.js","names":[],"sources":["../src/commands/start.ts"],"sourcesContent":["/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile, findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { invokedRebaseCommand } from \"../utils/invoked-command\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { detectPackageManager, getPMCommands, type PMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport type { RebaseBundleStatic } from \"@rebasepro/types\";\nimport type { DevDatabase } from \"../dev-db/resolve\";\nimport type { DaemonState } from \"../dev-db/state\";\nimport { MANAGED_POOL_MAX } from \"../dev-db/constraints\";\n\n/**\n * The help's line that runs `start` on the database `rebase dev` uses, spelled\n * as the reader can type it.\n *\n * In a project, the project's package manager: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so a bare `rebase` is \"command not found\" —\n * `pnpm exec rebase …`, as `missingDatabaseUrl` and the CLI's other hints say\n * it. Outside one, the way this CLI was started (`invokedRebaseCommand`).\n */\nexport function startHelpRunLine(projectRoot: string | null = findProjectRoot()): string {\n const rebase = (args: string[]): string => (projectRoot\n ? getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", args)\n : [...invokedRebaseCommand(), ...args]).join(\" \");\n return `DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`;\n}\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --workspace Run the backend workspace's own start script\n -h, --help Show this help\n\nRuns the bundle the way a deployment does, reading PORT and the rest of .env,\nin whatever NODE_ENV the shell or .env sets. A scaffolded .env says\ndevelopment, which keeps development behaviour on — the first account to\nregister becomes the admin. For a production server, run it with\nNODE_ENV=production; it says so at start when it is not one.\n\nIt needs a DATABASE_URL, and starts no database of its own. To run it on the\ndatabase ${chalk.cyan(\"rebase dev\")} uses: ${chalk.cyan(startHelpRunLine())}\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\n/** The NODE_ENV the runtime will see, and where it comes from. */\nexport interface StartNodeEnv {\n value: string | undefined;\n source: \"shell\" | \".env\" | \"unset\";\n}\n\n/**\n * What NODE_ENV the server will boot in. The shell wins — dotenv never\n * overrides a variable that is already set — then `.env`.\n */\nexport function startNodeEnv(projectRoot: string): StartNodeEnv {\n if (process.env.NODE_ENV !== undefined) return { value: process.env.NODE_ENV, source: \"shell\" };\n const fromFile = readEnvFile(projectRoot).NODE_ENV;\n return fromFile !== undefined ? { value: fromFile, source: \".env\" } : { value: undefined, source: \"unset\" };\n}\n\n/**\n * The banner for a `rebase start` that is not a production server, or `null`.\n *\n * Not forced to production: the scaffold's `.env` points at a loopback\n * database, which a production boot refuses, so forcing it would break the\n * documented local run. What must not happen is the silence — a command the\n * help called \"(production)\" booting with the first-registration window open.\n */\nexport function nonProductionWarning(nodeEnv: StartNodeEnv): string[] | null {\n if (nodeEnv.value === \"production\") return null;\n const what = nodeEnv.value === undefined\n ? \"NODE_ENV is not set\"\n : `NODE_ENV=${nodeEnv.value}${nodeEnv.source === \".env\" ? \" (from .env)\" : \"\"}`;\n return [\n chalk.yellow.bold(`⚠ ${what} — this is not a production server.`),\n chalk.yellow(\" Development behaviour is on: the first account to register becomes the admin\"),\n chalk.yellow(\" (REBASE_ADMIN_EMAIL is ignored), and with no SMTP configured, sign-in and\"),\n chalk.yellow(\" password-reset links are printed to this log instead of sent.\"),\n chalk.gray(\" For a production server, run it with NODE_ENV=production (in the shell or .env).\")\n ];\n}\n\n/**\n * What to say about the apps a bundle serves only on their own hostname.\n *\n * The runtime prints \"Server running at http://localhost:<port>\", and an app\n * whose `path` names a hostname answers only requests carrying that `Host` —\n * so opening the printed URL showed a 404 for an app that was running fine,\n * and nothing said why. One line per such app, with a command that reaches it.\n */\nexport function hostRoutedNotice(staticApps: readonly RebaseBundleStatic[], port: string | undefined): string[] {\n const routed = staticApps.filter(app => app.host);\n if (routed.length === 0) return [];\n const origin = `http://localhost:${port || \"<port>\"}`;\n return [\n ...routed.map(app => {\n const name = app.name ?? path.posix.basename(app.dir);\n return chalk.yellow(`⚠ ${name} answers only on ${app.host}, so ${origin}${app.path} will not show it here. Reach it with:`)\n + `\\n ${chalk.cyan(`curl -H \"Host: ${app.host}\" ${origin}${app.path}`)}`;\n }),\n chalk.gray(` (or point ${routed.map(app => app.host).join(\", \")} at 127.0.0.1 in /etc/hosts)`),\n \"\"\n ];\n}\n\n/**\n * What to say when there is no DATABASE_URL for the runtime, or `null`.\n *\n * The runtime requires one, and its refusal — `DATABASE_URL: is required`, and\n * a link to the self-hosting docs — is right for a deployment and says nothing\n * to the reader most likely to see it: someone running the scaffold's own\n * `.env`, which leaves DATABASE_URL commented out because `rebase dev` brings a\n * database of its own. That database is one command away, so this names it.\n *\n * `kind` is what `rebase dev` runs this project on, so the line can say which\n * database `rebase db url` will print. A blank value is unset, as the runtime\n * reads it. `pm` spells the command: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so it is `pnpm exec rebase …` or\n * `npx rebase …`, as in the CLI's other hints.\n */\nexport function missingDatabaseUrl(\n env: Record<string, string | undefined>,\n kind: DevDatabase[\"kind\"] | null,\n pm: PMCommands\n): string[] | null {\n if (env.DATABASE_URL?.trim()) return null;\n\n const rebase = (args: string[]): string => pm.exec(\"rebase\", args).join(\" \");\n\n const which = kind === \"docker\"\n ? \"the Docker database `rebase dev --docker` uses\"\n : kind === \"managed\"\n ? \"the managed development database (PGlite) `rebase dev` uses\"\n : \"this project's development database\";\n return [\n chalk.red(\"✗ DATABASE_URL is not set, so the runtime has no database to start against.\"),\n chalk.gray(\" `rebase start` runs the bundle the way a deployment does, against the database you name;\"),\n chalk.gray(\" `rebase dev` is the command that brings one of its own.\"),\n \"\",\n ` To run it on ${which}:`,\n ` ${chalk.cyan(`DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`)}`,\n \"\",\n chalk.gray(\" For a deployment, set DATABASE_URL in the environment or in .env.\"),\n chalk.gray(\" See https://rebase.pro/docs/deployment/self-hosting/ for the variables a deployment needs.\")\n ];\n}\n\n/**\n * What the runtime needs when DATABASE_URL is this project's managed\n * development database, or nothing.\n *\n * The connection ceiling `rebase dev` sets for it (`MANAGED_POOL_MAX`). PGlite\n * is one session behind a socket server that accepts only a few connections,\n * and a running `rebase dev` holds some. With an ordinary pool, the boot's\n * concurrent probes opened more than were left, the ones over were refused,\n * and a probe that could not connect read as a table that was not there:\n * `❌ rebase.cron_claims is unavailable`, beside tables that existed.\n *\n * Recognised by the running daemon's ports, which is what `rebase db url`\n * prints from. A ceiling set by hand is kept.\n */\nexport function managedDatabaseRuntimeEnv(\n databaseUrl: string | undefined,\n daemon: DaemonState | null,\n env: Record<string, string | undefined>\n): Record<string, string> {\n if (!databaseUrl || !daemon || env.REBASE_DB_POOL_MAX !== undefined) return {};\n let url: URL;\n try {\n url = new URL(databaseUrl);\n } catch {\n return {};\n }\n if (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname)) return {};\n const ports = [daemon.port, ...Object.values(daemon.databases ?? {}).map(database => database.port)];\n if (!ports.includes(Number(url.port))) return {};\n return { REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX) };\n}\n\nfunction readBundleStatic(bundleDir: string): RebaseBundleStatic[] {\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(bundleDir, \"manifest.json\"), \"utf8\")) as { entry?: { static?: RebaseBundleStatic[] } };\n return manifest.entry?.static ?? [];\n } catch {\n return [];\n }\n}\n\nfunction printNonProductionWarning(projectRoot: string): void {\n const warning = nonProductionWarning(startNodeEnv(projectRoot));\n if (!warning) return;\n console.log(warning.join(\"\\n\") + \"\\n\");\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n const { flags: args } = parseCommandArgs({\n spec: {\n \"--bundle\": String,\n \"--workspace\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"start\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n // Before either path, and before the runtime's own boot logs bury it.\n printNonProductionWarning(projectRoot);\n\n if (args[\"--workspace\"] || !hasBundle) {\n if (!args[\"--workspace\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile, quiet: true });\n }\n\n // Before the runtime, which would refuse with a message written for a\n // deployment. See `missingDatabaseUrl`.\n if (!process.env.DATABASE_URL?.trim()) {\n const { devDatabaseKind } = await import(\"../dev-db/prepare\");\n const missing = missingDatabaseUrl(process.env, devDatabaseKind(projectRoot), getPMCommands(detectPackageManager(projectRoot)));\n if (missing) {\n for (const line of missing) console.error(line);\n process.exit(1);\n }\n }\n\n // See `managedDatabaseRuntimeEnv`.\n const { findRunningDaemon } = await import(\"../dev-db/daemon\");\n const managedEnv = managedDatabaseRuntimeEnv(process.env.DATABASE_URL, await findRunningDaemon(projectRoot), process.env);\n if (managedEnv.REBASE_DB_POOL_MAX) {\n Object.assign(process.env, managedEnv);\n console.log(chalk.dim(\n \"DATABASE_URL is this project's managed development database: the runtime uses one connection,\\n\" +\n \"as `rebase dev` does, so requests are served one at a time.\\n\"\n ));\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n for (const line of hostRoutedNotice(readBundleStatic(bundleDir), process.env.PORT)) console.log(line);\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,iBAAiB,cAA6B,gBAAgB,GAAW;CACrF,MAAM,UAAU,UAA4B,cACtC,cAAc,qBAAqB,WAAW,CAAC,CAAC,CAAC,KAAK,UAAU,IAAI,IACpE,CAAC,GAAG,qBAAqB,GAAG,GAAG,IAAI,EAAA,CAAG,KAAK,GAAG;CACpD,OAAO,mB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EpE,IAAI;EACA,MAAM,MAAM,SAAS,IAAI,SAAS,MAAM,CAAC,GAAG;GACxC,KAAK;GACL,OAAO;GACP;EACJ,CAAC;CACL,QAAQ;EACJ,QAAQ,MAAM,MAAM,IAAI,6BAA6B,CAAC;EACtD,QAAQ,KAAK,CAAC;CAClB;AACJ"}
|
|
1
|
+
{"version":3,"file":"start-CflvYL60.js","names":[],"sources":["../src/commands/start.ts"],"sourcesContent":["/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile, findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { invokedRebaseCommand } from \"../utils/invoked-command\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { detectPackageManager, getPMCommands, type PMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport type { RebaseBundleStatic } from \"@rebasepro/types\";\nimport type { DevDatabase } from \"../dev-db/resolve\";\nimport type { DaemonState } from \"../dev-db/state\";\nimport { MANAGED_POOL_MAX } from \"../dev-db/constraints\";\n\n/**\n * The help's line that runs `start` on the database `rebase dev` uses, spelled\n * as the reader can type it.\n *\n * In a project, the project's package manager: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so a bare `rebase` is \"command not found\" —\n * `pnpm exec rebase …`, as `missingDatabaseUrl` and the CLI's other hints say\n * it. Outside one, the way this CLI was started (`invokedRebaseCommand`).\n */\nexport function startHelpRunLine(projectRoot: string | null = findProjectRoot()): string {\n const rebase = (args: string[]): string => (projectRoot\n ? getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", args)\n : [...invokedRebaseCommand(), ...args]).join(\" \");\n return `DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`;\n}\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --workspace Run the backend workspace's own start script\n -h, --help Show this help\n\nRuns the bundle the way a deployment does, reading PORT and the rest of .env,\nin whatever NODE_ENV the shell or .env sets. A scaffolded .env says\ndevelopment, which keeps development behaviour on — the first account to\nregister becomes the admin. For a production server, run it with\nNODE_ENV=production; it says so at start when it is not one.\n\nIt needs a DATABASE_URL, and starts no database of its own. To run it on the\ndatabase ${chalk.cyan(\"rebase dev\")} uses: ${chalk.cyan(startHelpRunLine())}\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\n/** The NODE_ENV the runtime will see, and where it comes from. */\nexport interface StartNodeEnv {\n value: string | undefined;\n source: \"shell\" | \".env\" | \"unset\";\n}\n\n/**\n * What NODE_ENV the server will boot in. The shell wins — dotenv never\n * overrides a variable that is already set — then `.env`.\n */\nexport function startNodeEnv(projectRoot: string): StartNodeEnv {\n if (process.env.NODE_ENV !== undefined) return { value: process.env.NODE_ENV, source: \"shell\" };\n const fromFile = readEnvFile(projectRoot).NODE_ENV;\n return fromFile !== undefined ? { value: fromFile, source: \".env\" } : { value: undefined, source: \"unset\" };\n}\n\n/**\n * The banner for a `rebase start` that is not a production server, or `null`.\n *\n * Not forced to production: the scaffold's `.env` points at a loopback\n * database, which a production boot refuses, so forcing it would break the\n * documented local run. What must not happen is the silence — a command the\n * help called \"(production)\" booting with the first-registration window open.\n */\nexport function nonProductionWarning(nodeEnv: StartNodeEnv): string[] | null {\n if (nodeEnv.value === \"production\") return null;\n const what = nodeEnv.value === undefined\n ? \"NODE_ENV is not set\"\n : `NODE_ENV=${nodeEnv.value}${nodeEnv.source === \".env\" ? \" (from .env)\" : \"\"}`;\n return [\n chalk.yellow.bold(`⚠ ${what} — this is not a production server.`),\n chalk.yellow(\" Development behaviour is on: the first account to register becomes the admin\"),\n chalk.yellow(\" (REBASE_ADMIN_EMAIL is ignored), and with no SMTP configured, sign-in and\"),\n chalk.yellow(\" password-reset links are printed to this log instead of sent.\"),\n chalk.gray(\" For a production server, run it with NODE_ENV=production (in the shell or .env).\")\n ];\n}\n\n/**\n * What to say about the apps a bundle serves only on their own hostname.\n *\n * The runtime prints \"Server running at http://localhost:<port>\", and an app\n * whose `path` names a hostname answers only requests carrying that `Host` —\n * so opening the printed URL showed a 404 for an app that was running fine,\n * and nothing said why. One line per such app, with a command that reaches it.\n */\nexport function hostRoutedNotice(staticApps: readonly RebaseBundleStatic[], port: string | undefined): string[] {\n const routed = staticApps.filter(app => app.host);\n if (routed.length === 0) return [];\n const origin = `http://localhost:${port || \"<port>\"}`;\n return [\n ...routed.map(app => {\n const name = app.name ?? path.posix.basename(app.dir);\n return chalk.yellow(`⚠ ${name} answers only on ${app.host}, so ${origin}${app.path} will not show it here. Reach it with:`)\n + `\\n ${chalk.cyan(`curl -H \"Host: ${app.host}\" ${origin}${app.path}`)}`;\n }),\n chalk.gray(` (or point ${routed.map(app => app.host).join(\", \")} at 127.0.0.1 in /etc/hosts)`),\n \"\"\n ];\n}\n\n/**\n * What to say when there is no DATABASE_URL for the runtime, or `null`.\n *\n * The runtime requires one, and its refusal — `DATABASE_URL: is required`, and\n * a link to the self-hosting docs — is right for a deployment and says nothing\n * to the reader most likely to see it: someone running the scaffold's own\n * `.env`, which leaves DATABASE_URL commented out because `rebase dev` brings a\n * database of its own. That database is one command away, so this names it.\n *\n * `kind` is what `rebase dev` runs this project on, so the line can say which\n * database `rebase db url` will print. A blank value is unset, as the runtime\n * reads it. `pm` spells the command: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so it is `pnpm exec rebase …` or\n * `npx rebase …`, as in the CLI's other hints.\n */\nexport function missingDatabaseUrl(\n env: Record<string, string | undefined>,\n kind: DevDatabase[\"kind\"] | null,\n pm: PMCommands\n): string[] | null {\n if (env.DATABASE_URL?.trim()) return null;\n\n const rebase = (args: string[]): string => pm.exec(\"rebase\", args).join(\" \");\n\n const which = kind === \"docker\"\n ? \"the Docker database `rebase dev --docker` uses\"\n : kind === \"managed\"\n ? \"the managed development database (PGlite) `rebase dev` uses\"\n : \"this project's development database\";\n return [\n chalk.red(\"✗ DATABASE_URL is not set, so the runtime has no database to start against.\"),\n chalk.gray(\" `rebase start` runs the bundle the way a deployment does, against the database you name;\"),\n chalk.gray(\" `rebase dev` is the command that brings one of its own.\"),\n \"\",\n ` To run it on ${which}:`,\n ` ${chalk.cyan(`DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`)}`,\n \"\",\n chalk.gray(\" For a deployment, set DATABASE_URL in the environment or in .env.\"),\n chalk.gray(\" See https://rebase.pro/docs/deployment/self-hosting/ for the variables a deployment needs.\")\n ];\n}\n\n/**\n * What the runtime needs when DATABASE_URL is this project's managed\n * development database, or nothing.\n *\n * The connection ceiling `rebase dev` sets for it (`MANAGED_POOL_MAX`). PGlite\n * is one session behind a socket server that accepts only a few connections,\n * and a running `rebase dev` holds some. With an ordinary pool, the boot's\n * concurrent probes opened more than were left, the ones over were refused,\n * and a probe that could not connect read as a table that was not there:\n * `❌ rebase.cron_claims is unavailable`, beside tables that existed.\n *\n * Recognised by the running daemon's ports, which is what `rebase db url`\n * prints from. A ceiling set by hand is kept.\n */\nexport function managedDatabaseRuntimeEnv(\n databaseUrl: string | undefined,\n daemon: DaemonState | null,\n env: Record<string, string | undefined>\n): Record<string, string> {\n if (!databaseUrl || !daemon || env.REBASE_DB_POOL_MAX !== undefined) return {};\n let url: URL;\n try {\n url = new URL(databaseUrl);\n } catch {\n return {};\n }\n if (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname)) return {};\n const ports = [daemon.port, ...Object.values(daemon.databases ?? {}).map(database => database.port)];\n if (!ports.includes(Number(url.port))) return {};\n return { REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX) };\n}\n\nfunction readBundleStatic(bundleDir: string): RebaseBundleStatic[] {\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(bundleDir, \"manifest.json\"), \"utf8\")) as { entry?: { static?: RebaseBundleStatic[] } };\n return manifest.entry?.static ?? [];\n } catch {\n return [];\n }\n}\n\nfunction printNonProductionWarning(projectRoot: string): void {\n const warning = nonProductionWarning(startNodeEnv(projectRoot));\n if (!warning) return;\n console.log(warning.join(\"\\n\") + \"\\n\");\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n const { flags: args } = parseCommandArgs({\n spec: {\n \"--bundle\": String,\n \"--workspace\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"start\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n // Before either path, and before the runtime's own boot logs bury it.\n printNonProductionWarning(projectRoot);\n\n if (args[\"--workspace\"] || !hasBundle) {\n if (!args[\"--workspace\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile, quiet: true });\n }\n\n // Before the runtime, which would refuse with a message written for a\n // deployment. See `missingDatabaseUrl`.\n if (!process.env.DATABASE_URL?.trim()) {\n const { devDatabaseKind } = await import(\"../dev-db/prepare\");\n const missing = missingDatabaseUrl(process.env, devDatabaseKind(projectRoot), getPMCommands(detectPackageManager(projectRoot)));\n if (missing) {\n for (const line of missing) console.error(line);\n process.exit(1);\n }\n }\n\n // See `managedDatabaseRuntimeEnv`.\n const { findRunningDaemon } = await import(\"../dev-db/daemon\");\n const managedEnv = managedDatabaseRuntimeEnv(process.env.DATABASE_URL, await findRunningDaemon(projectRoot), process.env);\n if (managedEnv.REBASE_DB_POOL_MAX) {\n Object.assign(process.env, managedEnv);\n console.log(chalk.dim(\n \"DATABASE_URL is this project's managed development database: the runtime uses one connection,\\n\" +\n \"as `rebase dev` does, so requests are served one at a time.\\n\"\n ));\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n for (const line of hostRoutedNotice(readBundleStatic(bundleDir), process.env.PORT)) console.log(line);\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.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AU,SAAS,SAAS,QAAQ,MAAM;CAErD,IAAI,SAAS,GACT,QAAQ,IAAI,MAAM,IACd,YAAY,OAAO;CAEvB,CAAC;AAET;AAEA,eAAe,sBAAsB,aAAqB,KAA4C;CAGlG,MAAM,WADO,cADF,qBAAqB,WACL,CACV,CAAA,CAAK,aAAa,WAAW,OAAO;CAErD,QAAQ,IAAI,GAAG,MAAM,KAAK,QAAQ,EAAE,gCAAgC;CAEpE,IAAI;EACA,MAAM,MAAM,SAAS,IAAI,SAAS,MAAM,CAAC,GAAG;GACxC,KAAK;GACL,OAAO;GACP;EACJ,CAAC;CACL,QAAQ;EACJ,QAAQ,MAAM,MAAM,IAAI,6BAA6B,CAAC;EACtD,QAAQ,KAAK,CAAC;CAClB;AACJ"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Take the project's build lock, or throw naming the process that holds it.
|
|
3
|
+
*
|
|
4
|
+
* Returns the release, which may be called more than once. The lock also goes
|
|
5
|
+
* with the process, and a process is never refused by itself: `fail()` ends a
|
|
6
|
+
* run on the spot with no `finally` behind it, and a build that threw leaves the
|
|
7
|
+
* lock with a caller that may build again.
|
|
8
|
+
*/
|
|
9
|
+
export declare function lockBundleBuild(projectRoot: string): () => void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"description": "Developer tools for Rebase projects",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -44,13 +44,13 @@
|
|
|
44
44
|
"inquirer": "14.0.2",
|
|
45
45
|
"jiti": "^2.7.0",
|
|
46
46
|
"pg": "^8.22.0",
|
|
47
|
-
"@rebasepro/
|
|
48
|
-
"@rebasepro/
|
|
49
|
-
"@rebasepro/
|
|
50
|
-
"@rebasepro/
|
|
51
|
-
"@rebasepro/server-postgres": "0.
|
|
52
|
-
"@rebasepro/
|
|
53
|
-
"@rebasepro/
|
|
47
|
+
"@rebasepro/client": "0.27.0",
|
|
48
|
+
"@rebasepro/codegen": "0.27.0",
|
|
49
|
+
"@rebasepro/agent-skills": "0.27.0",
|
|
50
|
+
"@rebasepro/rls-check": "0.27.0",
|
|
51
|
+
"@rebasepro/server-postgres": "0.27.0",
|
|
52
|
+
"@rebasepro/types": "0.27.0",
|
|
53
|
+
"@rebasepro/server": "0.27.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@types/node": "^26.1.2",
|
|
@@ -4,8 +4,8 @@ A headless Rebase backend: a REST API, auth, storage, realtime and backups over
|
|
|
4
4
|
your PostgreSQL database.
|
|
5
5
|
|
|
6
6
|
There are no collection files. The server reads your database schema at boot and
|
|
7
|
-
serves your tables, so the API follows your migrations — change the schema
|
|
8
|
-
the endpoints change with it.
|
|
7
|
+
serves your tables, so the API follows your migrations — change the schema,
|
|
8
|
+
restart the backend, and the endpoints change with it.
|
|
9
9
|
|
|
10
10
|
## Serving a table
|
|
11
11
|
|
|
@@ -15,7 +15,7 @@ This is a **headless** Rebase project: a REST API, auth, storage and realtime ov
|
|
|
15
15
|
| `pnpm generate:sdk` | Regenerate the typed client from `config/collections/` — so in a headless project it has nothing to read until you introspect. Once there are collections, `pnpm dev` does this on start and on every save; the script is for CI and for when `pnpm dev` is not running |
|
|
16
16
|
| `pnpm build` then `pnpm start` | Build the deployable bundle, then run it |
|
|
17
17
|
| `pnpm skills:install` | Install the Rebase skills for your assistant |
|
|
18
|
-
| `pnpm example` | Run `scripts/example.ts` against the running backend
|
|
18
|
+
| `pnpm example` | Run `scripts/example.ts` against the running backend: a health check, and an SDK call to uncomment |
|
|
19
19
|
| `rebase doctor` | Checks the environment and the database connection — run this before guessing |
|
|
20
20
|
| `rebase resources --write` | After declaring a database, bucket or topic in `config/resources.ts`: regenerate `rebase.resources.json` and commit it (`pnpm build` does this too) |
|
|
21
21
|
| `pnpm deploy` | Deploys this project. Never run it; see below |
|
|
@@ -38,6 +38,7 @@ This is a **headless** Rebase project: a REST API, auth, storage and realtime ov
|
|
|
38
38
|
6. **In `backend/functions/`, always import from `@rebasepro/server/functions`** — never from `@rebasepro/server`. Both work today; the subpath is the portable one, and it also gives you the typed context accessors (`getUser`, `getDriver`, `requireDriver`) instead of casting `c.get("user")`. The package root is for a server entrypoint, not for route handlers.
|
|
39
39
|
7. **Never read `process.env` at the top of a function file.** A module-scope read that comes back undefined throws at import time, and the loader reports that as a *skipped function* — the route simply 404s with no error attached to it. Read configuration inside the handler with `requireEnv(c, "NAME")`, or build a client once with `lazyResource(env => new Client(env.KEY))`.
|
|
40
40
|
8. **Work that outlives the response goes in `waitUntil(c, promise)`**, not a floating promise. A floating promise is dropped when the process shuts down mid-deploy; `waitUntil` is what a graceful shutdown waits for.
|
|
41
|
+
9. **Call your own routes from the browser with the client's `functions.invoke`**, never `fetch` with a token taken from `client.auth.getSession()`. The session is a snapshot that every renewal replaces, about hourly, so a kept token is refused once it expires and the app looks signed out. `invoke` renews before sending and retries once on a 401. For a request that is not to a function, ask for the token each time with `await client.auth.getAccessToken()`.
|
|
41
42
|
|
|
42
43
|
## Backend runtime (`runtime: "managed"` on Rebase Cloud)
|
|
43
44
|
|
|
@@ -48,6 +49,6 @@ This is a **headless** Rebase project: a REST API, auth, storage and realtime ov
|
|
|
48
49
|
- **Memory and disk belong to one instance, until the next deploy.** A module-level `new Map()` cache survives between requests on one instance, but is not shared between instances and is lost on every deploy and restart. `/tmp` is writable, with the same limits. Keep anything worth keeping in the database or in storage.
|
|
49
50
|
- **Requests:** a function times out after 30 seconds (`504 FUNCTION_TIMEOUT`, `REBASE_FUNCTIONS_TIMEOUT_MS`, at most 10 minutes), and a request body over 10 MiB gets a `413` (`REBASE_MAX_BODY_SIZE`). Pass `getSignal(c)` to `fetch`. Put longer work in a job or in `waitUntil`.
|
|
50
51
|
- **Instances:** at least one always runs; nothing scales a backend to zero.
|
|
51
|
-
- **Outbound network:** HTTP and HTTPS (ports 80 and 443) to anywhere, plus 465, 587 and 993 for mail. Every other port is blocked, so a database or Redis outside Rebase Cloud cannot be reached.
|
|
52
|
+
- **Outbound network:** HTTP and HTTPS (ports 80 and 443) to anywhere, plus 465, 587 and 993 for mail. Every other port is blocked, so a database or Redis outside Rebase Cloud cannot be reached. Outbound traffic comes from one fixed IP, shared by all projects and listed on that page, for third-party allowlists.
|
|
52
53
|
- **Configuration:** the human sets variables with `rebase cloud env set NAME=value` (`--secret` makes a value write-only). A change applies at the next deploy. Read variables inside the handler, with `requireEnv(c, "NAME")`.
|
|
53
54
|
- **Generated files** (audio, images, exports) go to storage: `rebase.storage.putObject({ file, key })`. A key under `public/` is served to anyone at `/api/storage/file/<key>`. Any other key needs a download token. The project needs `rebase cloud storage create` once, plus a `storageAuthorize` hook that allows the write.
|
|
@@ -2,6 +2,10 @@ packages:
|
|
|
2
2
|
- "backend"
|
|
3
3
|
- "config"
|
|
4
4
|
linkWorkspacePackages: true
|
|
5
|
+
# Without this, pnpm takes a higher version from the registry over a workspace
|
|
6
|
+
# package on a "*" range, and this project's own package names are free for
|
|
7
|
+
# anyone to publish.
|
|
8
|
+
preferWorkspacePackages: true
|
|
5
9
|
blockExoticSubdeps: false
|
|
6
10
|
minimumReleaseAge: 0
|
|
7
11
|
# See the note in templates/template/pnpm-workspace.yaml: pnpm 11 reads these
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# ╔══════════════════════════════════════════════════════════════════════════════╗
|
|
2
2
|
# ║ Rebase Environment Configuration ║
|
|
3
|
-
# ║
|
|
3
|
+
# ║ Reference only: `rebase init` wrote your .env. Do not copy this over it ║
|
|
4
4
|
# ╚══════════════════════════════════════════════════════════════════════════════╝
|
|
5
5
|
|
|
6
6
|
# ── Database ──────────────────────────────────────────────────────────────────
|