@guren/plugin-vercel 0.2.0 → 0.3.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/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # @guren/plugin-vercel
2
+
3
+ Deploy a [Guren](https://guren.dev/) SSR application to Vercel. The plugin assembles a [Build Output API v3](https://vercel.com/docs/build-output-api/v3) directory that runs on Vercel's Bun runtime.
4
+
5
+ ```bash
6
+ bunx guren plugin @guren/plugin-vercel
7
+ bun add @guren/plugin-vercel
8
+ ```
9
+
10
+ Installing scaffolds `src/vercel.ts`, `scripts/vercel-build.ts`, and `vercel.json`.
11
+
12
+ ## Build and deploy
13
+
14
+ ```bash
15
+ bun run vercel:build
16
+ vercel deploy --prebuilt
17
+ ```
18
+
19
+ ## API
20
+
21
+ - **`createVercelHandler(app)`** — boots a Guren `Application` and returns a `fetch` handler for the serverless function.
22
+
23
+ ```typescript
24
+ // src/vercel.ts
25
+ import app from './app.js'
26
+ import { createVercelHandler } from '@guren/plugin-vercel'
27
+
28
+ export default await createVercelHandler(app)
29
+ ```
30
+
31
+ - **`buildVercelOutput(options)`** — assembles `.vercel/output`: the bundled function, static assets, and the routing config. Reads the Vite manifests to inject the correct `GUREN_INERTIA_*` environment variables into the function.
32
+ - **`vercelPlugin()`** — the service provider factory, registered automatically by `guren plugin`.
33
+
34
+ ## Notes
35
+
36
+ - **SSR apps only.** The plugin reads Vite manifests to wire the Inertia SSR bundle. API-only apps should use Docker or Lambda instead.
37
+ - **SSR bundles must be self-contained.** Function directories ship without `node_modules`, so externalized `react`/`@inertiajs/react` imports fail at runtime and Inertia silently falls back to client-side rendering. The Guren Vite plugin defaults `ssr.noExternal: true` for SSR builds — leave it alone unless you know the target has those packages installed.
38
+ - **`NODE_ENV` is inlined at bundle time.** `bun build` bakes in `"development"` unless told otherwise, and a runtime `NODE_ENV=production` cannot override it. This plugin passes the right `--define` for you.
39
+
40
+ See the [deployment guide](https://guren.dev/docs/guides/deployment) for the full setup.
41
+
42
+ ## License
43
+
44
+ MIT
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ServiceProviderConstructor } from '@guren/core';
2
+ import { PathLike, DatabaseDialect } from '@guren/core/internal/deploy-build';
2
3
 
3
- type PathLike = string | URL;
4
4
  interface VercelAppLike {
5
5
  boot(): Promise<void>;
6
6
  fetch(request: Request): Response | Promise<Response>;
@@ -16,6 +16,13 @@ interface BuildVercelOutputOptions {
16
16
  docsDir?: PathLike;
17
17
  ssrDir?: PathLike;
18
18
  migrationsDir?: PathLike;
19
+ /**
20
+ * Databases this app connects to, overriding what is read from
21
+ * `config/database.ts`. Every other dialect's client is stubbed out of the
22
+ * bundle. Pass this when the config reaches a factory without naming it and
23
+ * the build reports that it could not tell.
24
+ */
25
+ databaseDialects?: readonly DatabaseDialect[];
19
26
  }
20
27
  /**
21
28
  * Configuration for the Vercel plugin. Currently empty — reserved so future
@@ -33,6 +40,6 @@ interface VercelPluginConfig {
33
40
  */
34
41
  declare function vercelPlugin(config?: VercelPluginConfig): ServiceProviderConstructor;
35
42
  declare function createVercelHandler(app: VercelAppLike): Promise<VercelHandler>;
36
- declare function buildVercelOutput(options?: BuildVercelOutputOptions): void;
43
+ declare function buildVercelOutput(options?: BuildVercelOutputOptions): Promise<void>;
37
44
 
38
45
  export { type BuildVercelOutputOptions, type VercelAppLike, type VercelHandler, type VercelPluginConfig, buildVercelOutput, createVercelHandler, vercelPlugin };
package/dist/index.js CHANGED
@@ -1,8 +1,20 @@
1
1
  // src/index.ts
2
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
2
+ import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
3
3
  import { basename, extname, resolve } from "path";
4
- import { fileURLToPath } from "url";
5
4
  import { definePlugin } from "@guren/core";
5
+ import {
6
+ assertOutputDirOutsideRoot,
7
+ DEV_ONLY_MODULES,
8
+ MCP_SDK_SUBPATH_PREFIX,
9
+ renderDevOnlyStub,
10
+ resetOutputDir,
11
+ resolveClientAssetEnv,
12
+ resolvePathLike,
13
+ resolveSsrEntryFile,
14
+ ssrRuntimePaths,
15
+ unusedSqlClients
16
+ } from "@guren/core/internal/deploy-build";
17
+ var LABEL = "Vercel build";
6
18
  var factory = definePlugin({
7
19
  name: "vercel",
8
20
  register() {
@@ -19,7 +31,7 @@ async function createVercelHandler(app) {
19
31
  }
20
32
  };
21
33
  }
22
- function buildVercelOutput(options = {}) {
34
+ async function buildVercelOutput(options = {}) {
23
35
  const root = resolvePathLike(options.rootDir ?? new URL("..", import.meta.url));
24
36
  const out = resolvePathLike(options.outputDir ?? resolve(root, ".vercel/output"));
25
37
  const funcDir = resolve(out, "functions/index.func");
@@ -29,12 +41,16 @@ function buildVercelOutput(options = {}) {
29
41
  const docsDir = resolvePathLike(options.docsDir ?? resolveNearestDocsDir(root) ?? resolve(root, "docs"));
30
42
  const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
31
43
  const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
32
- if (existsSync(out)) {
33
- rmSync(out, { recursive: true, force: true });
44
+ assertOutputDirOutsideRoot(out, root, LABEL);
45
+ if (!existsSync(entrypoint)) {
46
+ throw new Error(
47
+ `${LABEL}: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-vercel\` to scaffold src/vercel.ts, or pass "entrypoint".`
48
+ );
34
49
  }
50
+ const env = buildVercelEnvironment(publicDir, ssrDir);
51
+ resetOutputDir(out, root, LABEL);
35
52
  mkdirSync(funcDir, { recursive: true });
36
53
  mkdirSync(resolve(out, "static"), { recursive: true });
37
- const env = buildVercelEnvironment(root);
38
54
  writeFileSync(
39
55
  resolve(out, "config.json"),
40
56
  JSON.stringify(
@@ -73,28 +89,7 @@ function buildVercelOutput(options = {}) {
73
89
  2
74
90
  )
75
91
  );
76
- const result = Bun.spawnSync({
77
- // `bun build` inlines `process.env.NODE_ENV` at bundle time (defaulting to
78
- // "development"), so pin it to "production" for the deployed function.
79
- cmd: [
80
- "bun",
81
- "build",
82
- entrypoint,
83
- "--outdir",
84
- funcDir,
85
- "--target",
86
- "bun",
87
- "--minify",
88
- "--define",
89
- 'process.env.NODE_ENV="production"'
90
- ],
91
- cwd: root,
92
- stdout: "inherit",
93
- stderr: "inherit"
94
- });
95
- if (result.exitCode !== 0) {
96
- throw new Error("bun build failed");
97
- }
92
+ await bundleFunction({ entrypoint, funcDir, root, dialects: options.databaseDialects });
98
93
  if (existsSync(ssrDir)) {
99
94
  cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
100
95
  }
@@ -108,45 +103,102 @@ function buildVercelOutput(options = {}) {
108
103
  cpSync(publicDir, resolve(out, "static"), { recursive: true });
109
104
  }
110
105
  }
111
- function buildVercelEnvironment(root) {
106
+ var MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Vercel \u2014 it generates files on disk, and the function filesystem is read-only.";
107
+ var UNAVAILABLE_ON_VERCEL = {
108
+ sqlite: null,
109
+ vite: "The Vite dev server is unavailable on Vercel \u2014 assets are served from the static output directory.",
110
+ mcp: MCP_UNAVAILABLE
111
+ };
112
+ function stubbedModules(root, dialects) {
113
+ const devOnly = DEV_ONLY_MODULES.flatMap((module) => {
114
+ const message = UNAVAILABLE_ON_VERCEL[module.kind];
115
+ return message === null ? [] : [[module.specifier, renderDevOnlyStub(module, message)]];
116
+ });
117
+ const unused = unusedSqlClients({ root, label: LABEL, dialects }).map(({ module, message }) => [
118
+ module.specifier,
119
+ renderDevOnlyStub(module, message)
120
+ ]);
121
+ return Object.fromEntries([...devOnly, ...unused]);
122
+ }
123
+ var unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})
124
+ `;
125
+ async function bundleFunction(input) {
126
+ const stubs = stubbedModules(input.root, input.dialects);
127
+ const filter = new RegExp(
128
+ `^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`
129
+ );
130
+ const result = await Bun.build({
131
+ entrypoints: [input.entrypoint],
132
+ // `Bun.build` rejects with a bare "Bundle failed" AggregateError by
133
+ // default (Bun >= 1.2), which discards the one line that matters — the
134
+ // module it could not resolve. Opting out of that is what makes the
135
+ // `result.logs` report below reachable at all.
136
+ throw: false,
137
+ outdir: input.funcDir,
138
+ target: "bun",
139
+ // Whitespace and syntax only — never plain `minify: true`, which also
140
+ // mangles identifiers. Guren keys durable records on class names: the
141
+ // queue registry stores each job's wire name (its class name unless it
142
+ // declares a jobName) in every queued message, and notifications persist
143
+ // `constructor.name` as their `type`. Mangled, a job dispatched by one
144
+ // deploy resolves to nothing after the next.
145
+ //
146
+ // Not `keepNames`: as of Bun 1.3.14 it is accepted and silently leaves
147
+ // class names mangled, so it cannot replace this.
148
+ minify: { whitespace: true, syntax: true, identifiers: false },
149
+ define: {
150
+ // `bun build` inlines `process.env.NODE_ENV` at bundle time (defaulting
151
+ // to "development"), so pin it to "production" for the deployed function.
152
+ "process.env.NODE_ENV": '"production"'
153
+ },
154
+ plugins: [
155
+ {
156
+ name: "guren-vercel-stubs",
157
+ setup(build) {
158
+ build.onResolve({ filter }, (args) => ({ path: args.path, namespace: "guren-vercel-stub" }));
159
+ build.onLoad({ filter: /.*/, namespace: "guren-vercel-stub" }, (args) => ({
160
+ contents: stubs[args.path] ?? unlistedMcpStub,
161
+ loader: "js"
162
+ }));
163
+ }
164
+ }
165
+ ]
166
+ });
167
+ if (!result.success) {
168
+ throw new Error(`${LABEL}: bun build failed.
169
+ ${result.logs.map((log) => String(log)).join("\n")}`);
170
+ }
171
+ }
172
+ function escapeRegExp(value) {
173
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
174
+ }
175
+ function buildVercelEnvironment(publicDir, ssrDir) {
112
176
  const env = {
113
177
  NODE_ENV: "production",
114
178
  BUN_RUNTIME_TRANSPILER_CACHE_PATH: "/tmp/.bun-cache",
115
179
  BUN_INSTALL_CACHE_DIR: "/tmp/.bun-install-cache",
116
180
  TMPDIR: "/tmp"
117
181
  };
118
- const clientManifest = loadManifest(
119
- resolve(root, "public/assets/.vite/manifest.json"),
120
- resolve(root, "public/assets/manifest.json")
121
- );
122
- if (clientManifest) {
123
- const entry = clientManifest["resources/js/app.tsx"];
124
- if (entry?.file) {
125
- env.GUREN_INERTIA_ENTRY = `/assets/${entry.file}`;
126
- }
127
- if (entry?.css?.length) {
128
- env.GUREN_INERTIA_STYLES = entry.css.map((file) => `/assets/${file}`).join(",");
129
- }
182
+ const assetEnv = resolveClientAssetEnv(publicDir, "resources/js/app.tsx", LABEL);
183
+ if (assetEnv.entry) {
184
+ env.GUREN_INERTIA_ENTRY = assetEnv.entry;
130
185
  }
131
- const ssrManifest = loadManifest(
132
- resolve(root, ".guren/ssr/.vite/manifest.json"),
133
- resolve(root, ".guren/ssr/manifest.json")
134
- );
135
- if (ssrManifest) {
136
- const ssrEntry = ssrManifest["resources/js/ssr.tsx"];
137
- if (ssrEntry?.file) {
138
- env.GUREN_INERTIA_SSR_ENTRY = `./.guren/ssr/${ssrEntry.file}`;
186
+ if (assetEnv.styles) {
187
+ env.GUREN_INERTIA_STYLES = assetEnv.styles;
188
+ }
189
+ const ssrFile = resolveSsrEntryFile(ssrDir, "resources/js/ssr.tsx", LABEL);
190
+ if (ssrFile) {
191
+ const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
192
+ env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
193
+ if (ssrPaths.manifest) {
194
+ env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
139
195
  }
140
- env.GUREN_INERTIA_SSR_MANIFEST = "./.guren/ssr/.vite/manifest.json";
141
196
  }
142
197
  env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify({
143
198
  "@guren/inertia-client": "/vendor/inertia-client.tsx"
144
199
  });
145
200
  return env;
146
201
  }
147
- function resolvePathLike(value) {
148
- return value instanceof URL ? fileURLToPath(value) : resolve(String(value));
149
- }
150
202
  function resolveNearestDocsDir(startDir, maxDepth = 6) {
151
203
  let currentDir = startDir;
152
204
  for (let depth = 0; depth < maxDepth; depth += 1) {
@@ -162,19 +214,6 @@ function resolveNearestDocsDir(startDir, maxDepth = 6) {
162
214
  }
163
215
  return void 0;
164
216
  }
165
- function loadManifest(...paths) {
166
- for (const path of paths) {
167
- if (!existsSync(path)) {
168
- continue;
169
- }
170
- try {
171
- return JSON.parse(readFileSync(path, "utf8"));
172
- } catch {
173
- continue;
174
- }
175
- }
176
- return void 0;
177
- }
178
217
  export {
179
218
  buildVercelOutput,
180
219
  createVercelHandler,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-vercel",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -35,7 +35,7 @@
35
35
  "typecheck": "tsc --noEmit"
36
36
  },
37
37
  "dependencies": {
38
- "@guren/core": "^1.3.0"
38
+ "@guren/core": "^1.6.2"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^20.14.10",